so I was basically messing around with some exercises (started coding 4 months ago) and I came with an interesting exercise which I wanted to exploit a little bit more. What I want the program to do is quite simple:
Create random lists and check for it to be a palindrome, if it is, break and print the list, time taken and tries needed. I could clean the code up to this but I want to know if there is any cleaner or faster way to perform. I tried with a function but I couldn't make it work faster so I discarded it.
I've added a timer so after 10 seconds, it will stop and tell me the tries, for this I used:
- A list of 2 values,
- From 1
- Up to 999,999,999
so it will never find it in under 10 seconds. 3,150,000 tries was my best.
Thank you in advance! Hope you guys can teach me some more!
import random
is_same = False
from timeit import default_timer
import random
is_same = False
print("\n**Check how many tries it requires to find a palindrome list**\n")
r2 = int(input("How long would you like the list to be? "))
a1 = int(input("From what number?: "))
a2 = int(input("Up to?: "))
t1_start = default_timer()
limit1 = 10
c = 0
while not is_same:
while default_timer() < t1_start+10:
list1 = [random.randint(a1, a2) for x in range(1, r2+1)]
c += 1
if list1 == list1[::-1]:
is_same = True
print(f"\n'{len(list1)}' Elements in list\n")
print(list1)
print(f"¡Palindrome!")
break
break
t1_stop = default_timer()
print("\n\nIt took around ", t1_stop-t1_start, "seconds.")
print(F"\nTries that had to be performed were: {c:,}\n")```
Aucun commentaire:
Enregistrer un commentaire