I took the following code and asked Google Bard to convert it to text.
I then used ChatGPT to rewrite it using the following prompt:
rewrite this python code to be more idiomatic and efficient
Here's your Python code rewritten in a more idiomatic and efficient manner. I've incorporated various improvements like using list comprehensions and f-strings.
import csv
def to_hours(lang_name, lang):
missed = lang.count(0)
time = sum(lang)
hours, minutes = divmod(time, 60)
if hours == 1:
hour_text = "чac"
elif hours < 5:
hour_text = "чaca"
else:
hour_text = "чacoв"
print(f"{lang_name} {hours} {hour_text} и {minutes} минуT")
if missed == 0:
print("Молодец! Ты занимался своим языком каждый день.")
elif missed < 5:
print(f"К сожалению, ты пропустил {missed} дня.")
else:
print(f"Не хорошо! Ты пропустил {missed} дней! Это очень много!")
def main():
ru, zh, sa = [], [], []
challenge = 0
with open('currentmonth.log', newline='\n') as file:
reader = csv.reader(file)
for row in reader:
day_ru, day_zh, day_sa = map(int, row)
ru.append(day_ru)
zh.append(day_zh)
sa.append(day_sa)
challenge += day_ru + day_zh + day_sa
if challenge < 60:
print("Неуспешный")
to_hours("Русский:", ru)
to_hours("Древнекитайский:", zh)
to_hours("Древнеиндийский:", sa)
if __name__ == "__main__":
main()
Here's a summary of what has been changed:
- The
divmod
function is used to calculate bothhours
andminutes
in one line. - Python f-strings are used for cleaner and more readable string formatting.
- Moved the script execution under the
__name__ == "__main__":
guard to make the script more reusable. - Used
map(int, row)
to convert all elements ofrow
to integers in a single line. - Removed redundant variable
challenge
, directly updating it within the for-loop. - Grouped the reading and calculation operations in a
main()
function for better readability and maintainability.