Python Change variable inside a loop while looping through it - python

I just startet with Python and wanted to make a little countdown app, i am able to do it with seconds but when i try to do it with minutes it just goes into the negatives, i tried it with a if statement but instead it goes into the negatives. Any Ideas? Also anything I should change to make my code cleaner? Thanks in advance :)
import winsound
frequency = 1000
duration = 1000
def calc(num):
if dictionary["unit"] == "seconds":
for i in range(num):
print(num)
time.sleep(1)
num = num - 1
if num == 0:
winsound.Beep(frequency, duration)
elif dictionary["unit"] == "minutes":
num2 = 60
sum = 60
for i in range(num*60):
num2 = num2 -1
print(f"{num} Minutes {num2}")
time.sleep(0.005)
if num2 == 0:
num -1
num2 +60
def validation():
try:
number = int(dictionary["time"])
if number > 0:
calc(number)
except ValueError:
print("Do it again")
user = (input("Enter your Time\n"))
splitet = user.split()
dictionary = {"time": splitet[0], "unit": splitet[1]}
validation()

You can convert the minutes to seconds and do while loop for counting down. in for range loop, i already acts like a count down so you don't need to check if num is 0.
import time
import winsound
frequency = 1000
duration = 1000
def parse_time(input_str):
parts = input_str.split()
if len(parts) != 2:
raise ValueError("Wrong format.")
try:
number = int(parts[0])
except ValueError:
raise ValueError("Time is not integer")
if number <= 0:
raise ValueError("Negative Time")
return number, parts[1]
def calculate_seconds(count, measure):
if measure == "seconds":
return count
if measure == "minutes":
return 60 * count
def countdown(n_sec):
# A reversed range loop to count down
# i will decrease from n_sec to 0 in each iteration
for i in reversed(range(n_sec)):
print("%d minutes %d seconds" % (i / 60, i %60))
time.sleep(1)
winsound.Beep(frequency, duration)
if __name__ == "__main__":
# Use raw_input for raw string input.
input_str = raw_input("Enter your Time\n")
count, measure = parse_time(input_str)
seconds = calculate_seconds(count, measure)
countdown(seconds)

Related

How to modify this shortest-remaining-time-fisrt algorithm? (python lang)

The code has successfully able to compute same value of arrival times given by user input. However, its calculations are inaccurate. I do think the code messed up its computation in the initialisation part of priority queue. Please help me to modify it where it can accurately solve/compute with same value of arrival times as well as burst times.
Here is the code:
import sys
import pandas as pd
def srtf():
num_processes = []
# Get number of processes from user (between 5 and 10)
while True:
try:
num_processes = int(input("Enter the number of processes (minimum of 5 and maximum of 10): "))
if 5 <= num_processes <= 10:
break
else:
print("Invalid input. Number of processes must be between 5 and 10.")
except ValueError:
print("Invalid input. Only integers are allowed.")
print("\n")
# Get burst times and arrival times for each process
burst_times = []
for i in range(num_processes):
while True:
try:
burst_time = int(input("Enter burst time for process {} (minimum of 5 and maximum of 15): ".format(i+1)))
if 5 <= burst_time <= 15:
burst_times.append(burst_time)
break
else:
print("\nInvalid input. Burst time must be between 5 and 15.")
except ValueError:
print("\nInvalid input. Only integers are allowed.")
print("\n")
arrival_times = []
for i in range(num_processes):
while True:
try:
arrival_time = int(input("Enter arrival time for process {} (minimum of 0 and maximum of 12): ".format(i+1)))
if 0 <= arrival_time <= 12:
arrival_times.append(arrival_time)
break
else:
print("\nInvalid input. Arrival time must be between 0 and 12.")
except ValueError:
print("\nInvalid input. Only integers are allowed.")
# Initialize variables
process_id = [i+1 for i in range(num_processes)]
remaining_time = burst_times.copy()
completion_time = [0 for i in range(num_processes)]
waiting_time = [0 for i in range(num_processes)]
turnaround_time = [0 for i in range(num_processes)]
response_time = [0 for i in range(num_processes)]
current_time = 0
completed_processes = 0
import heapq
...
# Initialize the priority queue
priority_queue = []
...
while completed_processes != num_processes:
# Add all processes that have arrived to the priority queue
for i in range(num_processes):
if arrival_times[i] <= current_time and remaining_time[i] > 0:
heapq.heappush(priority_queue, (remaining_time[i], i))
if priority_queue:
remaining_time[priority_queue[0][1]] -= 1
current_time += 1
if response_time[priority_queue[0][1]] == 0: # first time process runs
response_time[priority_queue[0][1]] = current_time - arrival_times[priority_queue[0][1]]
if remaining_time[priority_queue[0][1]] == 0:
completed_processes += 1
completion_time[priority_queue[0][1]] = current_time
heapq.heappop(priority_queue)
else:
current_time += 1
# Calculate waiting time and turnaround time
for i in range(num_processes):
waiting_time[i]= completion_time[i] - burst_times[i] - arrival_times[i]
turnaround_time[i] = completion_time[i] - arrival_times[i]
# Calculate average waiting time, average turnaround time and average response time
avg_waiting_time = sum(waiting_time) / len(waiting_time)
avg_turnaround_time = sum(turnaround_time) / len(turnaround_time)
# Create a table with the results
results = {"Process ID": process_id, "Burst Time": burst_times, "Arrival Time": arrival_times,
"Completion Time": completion_time, "Waiting Time": waiting_time, "Turnaround Time": turnaround_time, "Response Time": response_time}
df = pd.DataFrame(results)
# Print the table
print("\n", df)
# Print the average turnaround time, waiting time and response time
print("\n")
print("Average Turnaround Time: ", "{:.2f}".format(avg_turnaround_time))
print("Average Waiting Time: ", "{:.2f}".format(avg_waiting_time))
return df, avg_turnaround_time, avg_waiting_time
srtf()
This is an example of the output(inaccurate) from the terminal:

While loop not breaking even with the 'break' statement

I'm a beginner at python and programming in general so I've no idea what's wrong with my code. I'm trying to break out of the while loop but it's not working. Also, the fibonacci number code is not working as well. All the numbers between 1 to 1000 are interpreted as FIB numbers.
import collections
import threading
def main():
my_list = []
i = 0
time_second = int(input("Please input seconds\n"))
def sample():
threading.Timer(time_second, sample).start()
# Counts the frequency of number in a list
ctr = collections.Counter(my_list)
print(ctr)
sample()
first_number = int(input("Please enter the first number\n"))
my_list.append(first_number)
while True:
user_input = input("Enter number\n")
if user_input.isnumeric():
user_input = int(user_input)
# check for Fibonacci number
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
elif n > 2:
return fibonacci(n - 1) + fibonacci(n - 2)
if user_input in range(1, 1001):
print("FIB")
my_list.append(user_input)
if user_input == 'q':
print("Bye")
break
main()
Your function is in an odd place and I recommend you place it outside of the while loop.
There are a few ways to exit a loop. One of these ways is by satisfying a condition for the while loop to exit from.
import time
def in_loop(count):
print(f"Still in loop... on the {count} cycle")
def exited_the_loop():
print("Exited the loop")
count = 0
while count < 10:
time.sleep(.3)
count += 1
in_loop(count)
exited_the_loop()
Another way is to use python's break when a certain condition has been met within the loop. In this case I've used an if statement to check for this condition.
import time
def in_loop(count):
print(f"Still in loop... on the {count} cycle")
def exited_the_loop():
print("Exited the loop")
count = 0
while True:
time.sleep(.3)
count += 1
in_loop(count)
if count > 10:
break
exited_the_loop()

Python Credit Card Validation

I'm a beginner Python learner and I'm currently working on Luhn Algorithm to check credit card validation. I wrote most of the code, but I'm stuck with 2 errors I get 1st one is num is referenced before assignment. 2nd one I'm getting is object of type '_io.TextIOWrapper' has no len(). Further help/ guidance will be greatly appreciated.
These are the steps for Luhn Algorithm (Mod10 Check)
Double every second digit from right to left. If this “doubling” results in a two-digit number, add the two-digit
number to get a single digit.
Now add all single digit numbers from step 1.
Add all digits in the odd places from right to left in the credit card number.
Sum the results from steps 2 & 3.
If the result from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
Here's what my output is supposed to be
Card Number Valid / Invalid
--------------------------------------
3710293 Invalid
5190990281925290 Invalid
3716820019271998 Valid
37168200192719989 Invalid
8102966371298364 Invalid
6823119834248189 Valid
And here is the code.
def checkSecondDigits(num):
length = len(num)
sum = 0
for i in range(length-2,-1,-2):
number = eval(num[i])
number = number * 2
if number > 9:
strNumber = str(number)
number = eval(strNumber[0]) + eval(strNumber[1])
sum += number
return sum
def odd_digits(num):
length = len(num)
sumOdd = 0
for i in range(length-1,-1,-2):
num += eval(num[i])
return sumOdd
def c_length(num):
length = len(num)
if num >= 13 and num <= 16:
if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"):
return True
else:
return False
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
main()
You just forgot to initialize num
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
# initialize num here
num = cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = cc = (infile.readline().strip())
First, maybe you should remove the extra characters:
def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(r"\D", "", card_num)
After check if credit card is valid using the Luhn algorithm:
def validate_card(formated_card_num):
"""
Input: Card number, integer or string
Output: Valid?, boolean
"""
double = 0
total = 0
digits = str(card_num)
for i in range(len(digits) - 1, -1, -1):
for c in str((double + 1) * int(digits[i])):
total += int(c)
double = (double + 1) % 2
return (total % 10) == 0
This is a very simpler version of code it is based on lunh's algorithm
def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
print('This a valid credit card')
else:
print('This is not valid credit card')
def cardnumber():
result=''
while True:
try:
result = input('Please enter the 16 digit credit card number : ')
if not (len(result) == 16) or not type(int(result) == int) :
raise Exception
except Exception:
print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.')
continue
else:
break
return result
def goagain():
return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y'
def main():
while True:
result = cardnumber()
validator(result)
if not goagain():
break
if __name__ == '__main__':
main()
Old thread but the answer concerns me... and the real issue wasn't identified.
Actually, the error is that you have used the identifier (num) for the parameter when defining checkSecondDigits as the identifier/name of the argument when calling the function in the mainline. The function should be called in main() by
even = checkSecondDigits(cc) so the value in cc (which is the argument) is passed into num (as the parameter) for use within the function.
The same rookie error is made with odd_digits and cc_length.
This question (and the initially suggested answer) demonstrates a fundamental mis-understanding of passing arguments to parameters...
The suggested 'declaring' of num just hides this error/misunderstanding and also obfuscates the local and global scopes of num (which should only be local) and cc (which is global) so whilst the suggestion works in this case, it works for the wrong reason and is poor style and bad programming.
Further,
num should not appear anywhere in main() as it should be local to (only appear inside of) the functions called...
The last line in this code should be the same as the first, but the last line incorrectly assigns the data to num instead of cc
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
you can use my code for card validation it is 100% dynamic because of the card structure is stored in CSV file, so it is easy to update here is the code on GitHub profile, python file link, code explanation file link and CSV for datafile link
python code:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:55:30 2019
#author: Preyash2047#gmail.com
"""
import csv
import numpy as np
#csv file imported and storf in reader
reader = csv.DictReader(open("card_data.csv"))
#input card number
card_number = input("Enter the card No: ")
#global variable declaration
min_digits=0
max_digits=0
card_number_list = list(card_number)
card_number_list_reverse=card_number_list[::-1]
card_number_length=len(card_number_list)
first_digit = int(card_number_list[0])
#global variable for final output
card_provider_list_number = 0
result_found = False
card_number_digits = 0
mit_name=""
#list
start=[]
end=[]
name=[]
c_d=[]
number_length=[]
min_max_digits_list=[]
#append the list from csv
for raw in reader:
start.append(raw['start'])
end.append(raw['end'])
name.append(raw['name'])
c_d.append(raw['c_d'])
number_length.append(raw['number_length'])
#initialize the value of min_digits & max_digits
def min_max_digits():
global min_digits
global max_digits
for i in range(len(start)):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
min_max_digits_list.append(available_length[j])
min_max_digits_array = np.array(min_max_digits_list)
np.unique(min_max_digits_array)
min_digits=int(min(min_max_digits_array))
max_digits=int(max(min_max_digits_array))
#list to int
def list_to_int(noofdigits):
str1 = ""
return int(str1.join(noofdigits))
#card validation
def iin_identifier():
first_six_digit = list_to_int(card_number_list[0:6])
for i in range(len(start)):
if(first_six_digit >= int(start[i]) and first_six_digit <= int(end[i])):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
if(card_number_length == int(available_length[j])):
global card_provider_list_number
card_provider_list_number = i
global card_number_digits
card_number_digits = available_length[j]
global result_found
result_found = True
#Major Industry Identifier (MII) identification
def mit_identifier():
global first_digit
global mit_name
switcher = {
1: "Airlines",
2: "Airlines",
3: "Travel and Entertainment",
4: "Banking and Financial Services",
5: "Banking and Financial Services",
6: "Merchandising and Banking",
7: "Petroleum",
8: "Health care, Telecommunications",
9: "National Assignment"
}
mit_name=switcher.get(first_digit, "MIT Identifier Not Found")
#Luhn Algorithm or modulo-10 Algorithm
def luhn_algorithm():
for i in range(card_number_length):
if(i%2!=0 and i!=0):
card_number_list_reverse[i]=int(card_number_list_reverse[i])*2
#print(str(i)+" "+ str(card_number_list_reverse[i]))
if(len(str(card_number_list_reverse[i]))==2):
even_number_2=list(str(card_number_list_reverse[i]))
card_number_list_reverse[i] = int(even_number_2[0])+int(even_number_2[1])
#print("\tsubsum "+str(i)+" "+str(card_number_list_reverse[i]))
else:
card_number_list_reverse[i]=int(card_number_list_reverse[i])
division_int = int(sum(card_number_list_reverse)/10)
division_float=sum(card_number_list_reverse)/10
if(division_int-division_float==0):
return True
#initial level number length validation
def card_number_validation():
min_max_digits()
if(card_number_length>= min_digits and card_number_length <= max_digits and first_digit != 0):
iin_identifier()
mit_identifier()
if(result_found and luhn_algorithm()):
print("\nEntered Details are Correct\n")
print("\nHere are the some details we know about you card")
print("\nNo: "+card_number)
print("\nIssuing Network: "+name[card_provider_list_number])
print("\nType: "+c_d[card_provider_list_number]+" Card")
print("\nCategory of the entity which issued the Card: "+mit_name)
else:
print("\nCard Number is Invalid\nPlease renter the number!\n")
else:
print("\nCard Number is Invalid\n")
#method called to run program
card_number_validation()
n = input("Enter 16-digit Credit Card Number:")
lst = []
for i in range(16):
lst.append(n[i])
# print(lst)
# list1 = n.split()
# print(list1)
def validate_credit_card():
global lst
if len(lst) == 16:
for i in range(0, len(lst)):
lst[i] = int(lst[i])
# print(lst)
last = lst[15]
first = lst[:15]
# print(first)
# print(last)
first = first[::-1]
# print(first)
for i in range(len(first)):
if i % 2 == 0:
first[i] = first[i] * 2
if first[i] > 9:
first[i] -= 9
sum_all = sum(first)
# print(first)
# print(sum_all)
t1 = sum_all % 10
t2 = t1 + last
if t2 % 10 is 0:
print("Valid Credit Card")
else:
print("Invalid Credit Card!")
else:
print("Credit Card number limit Exceeded!!!!")
exit()
if __name__ == "__main__":
validate_credit_card()

Trying to find the next prime number

MyFunctions file file -
def factList(p,n1):
counter = 1
while counter <= n1:
if n1 % counter == 0:
p.append(counter)
counter = counter + 1
def isPrime(lst1,nbr):
factList(lst1, nbr)
if len(lst1) == 2:
return True
else:
return False
def nextPrime(nbr1):
cnt1 = 1
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 = 0
Filetester file -
nbr1 = 13
nextPrime(nbr1)
print nbr1
My isPrime function already works I'm tring to use my isPrime function for my nextPrime function, when I run this I get
">>>
13
" (when using 13)
">>> " (When using 14)
I am supposed to get 17 not 13. And if I change it to a composite number in function tester it gets back in a infinite loop. Please only use simple functions (the ones I have used in my code).
This is NOT the right way to do this, but this is the closest adaptation of your code that I could do:
def list_factors_pythonic(number):
"""For a given number, return a list of factors."""
factors = []
for x in range(1, number + 1):
if number % x == 0:
factors.append(x)
return factors
def list_factors(number):
"""Alternate list_factors implementation."""
factors = []
counter = 1
while counter <= number:
if number % counter == 0:
factors.append(counter)
return factors
def is_prime(number):
"""Return true if the number is a prime, else false."""
return len(list_factors(number)) == 2
def next_prime(number):
"""Return the next prime."""
next_number = number + 1
while not is_prime(next_number):
next_number += 1
return next_number
This would be helpful:
def nextPrime(number):
for i in range(2,number):
if number%i == 0:
return False
sqr=i*i
if sqr>number:
break
return True
number = int(input("Enter the num: ")) + 1
while(True):
res=nextPrime(number)
if res:
print("The next number number is: ",number)
break
number += 1
I don't know python but if it's anything like C then you are not assigning anything to your variables, merely testing for equality.
while cnt1 == 1:
nbr1 == nbr1 + 1
if isPrime(lst2,nbr1):
cnt1 == cnt1 + 1
Should become
while cnt1 == 1:
nbr1 = nbr1 + 1 << changed here
if isPrime(lst2,nbr1):
cnt1 = cnt1 + 1 << and here
Well this code help you
n=int(input())
p=n+1
while(p>n):
c=0
for i in range(2,p):
if(p%i==0):
break
else:c+=1
if(c>=p-2):
print(p)
break
p+=1
this code optimized for finding sudden next prime number of a given number.it takes about 6.750761032104492 seconds
def k(x):
return pow(2,x-1,x)==1
n=int(input())+1
while(1):
if k(n)==True:
print(n)
break
n=n+1

How can i speed up this python code?

So I recently coded this as a little challenge to see how quick I could do it. Now since its working an such I want to speed it up. It finds all the proper devisors of a number, the highest proper devisor and times how long it all takes. The problem is with number like 5000 it takes 0.05 secs but with numbers like 99999999999 it takes 1567.98 secs.
this the old code I have made a new and improved version below
import time
def clearfile(name):
file = open(name + ".txt", "r")
filedata = file.read()
file.close()
text_file = open(name + ".txt", "w")
text_file.write("")
text_file.close()
def start():
num = input("Enter your Number: ")
check(num)
def check(num):
try:
intnum = int(num)
except ValueError:
error(error = "NON VALID NUMBER")
if(intnum < 0):
error(error = "POSITIVE NUMBERS ONLY")
else:
finddivisor(intnum)
def finddivisor(intnum):
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
print(i)
file = open("numbers.txt", "r")
filedata = file.read()
file.close()
text_file = open("numbers.txt", "w")
text_file.write(str(i) +"\n"+ filedata)
text_file.close()
i += 1
properdivisor(starttimer)
def properdivisor(starttimer):
file = open("numbers.txt", "r")
highest = file.readlines()
print("\nThe Highest Proper Divisor Is\n--------\n" + highest[1] + "--------" + "\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
restart(errorrestart = "false")
def restart(errorrestart):
if errorrestart == "false":
input("Do You Want Restart?\nPress Enter To Restart Or Close The Programe To Leave")
start()
elif errorrestart == "true":
input("\nThere Was An Error Detected.\nPress Enter To Restart Or Close The Programe To Leave")
start()
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------")
restart(errorrestart = "true")
clearfile(name = "numbers")
start()
Can someone speed it up for me
EDIT 1
so after looking over it I have now edited it to be moving it away from a file to an array
import time
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
except ValueError:
error("NOT VALID NUMBER")
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
numbers.insert(0,i)
print(i)
i += 1
print("\nThe Highest Proper Divisor Is\n--------\n" + str(numbers[1]) + "\n--------" + "\n\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running == True):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
New Edit
import time, math
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= math.sqrt(intnum):
if (intnum % i) == 0:
numbers.insert(0,i)
numbers.insert(0,int(intnum/i))
print(i,":", int(intnum/i))
i += 1
numbers = sorted(numbers, reverse = True)
print("The Highest Proper Divisor Is\n--------\n",str(numbers[1]) , "\n--------\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors." )
except ValueError:
error("NOT VALID NUMBER")
except OverflowError:
error("NUMBER IS TO LARGE")
except:
error("UNKNOWN ERROR")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
If you have divisor a of number n then you can tell one more divisor of n b = n / a. Moreover if a <= sqrt(n) then b >= sqrt(n) and vice versa. It means in your finddivisor function you can iterate while i * i <= n and print both divisors i and n / i.
By the way, you shouldn't open, read and close files in cycle. Open it once before cycle and close after if you need to read/write several times.
You don't need to read and rewrite the entire file every time you want to put a single entry into it. You can just do it once when you know what change you want. Also you could just append to it. Maybe something like this:
def finddivisor(intnum):
starttimer = time.time()
print("\nThe divisors of your number are:")
divs = set()
for i in range(1, int(math.sqrt(intnum)) +1):
if intnum % i == 0:
print(i)
divs.add(i)
divs.add(intnum // i)
with open("numbers.txt", "a") as file:
file.writelines("{}\n".format(ln) for ln in sorted(divs, reverse=True))
also your program flow is building a very deep stack. Try and flatten it with something like
def start():
clearfile()
while True:
n = get_number()
starttimer = time.time()
finddivisor(n)
properdivisor(starttimer)
input("Press Enter To Restart Or Close The Programe To Leave")
in properdivisor you dont need to read the whole file either, you just need the first line. so maybe something like:
def properdivisor(starttimer):
with open(FILENAME, "r") as file:
highest = file.readline().strip()
print "\nThe Highest Proper Divisor Is"
print "--------%s--------" % highest
print "It took %0.2f seconds to finish finding the divisors.\n" % (time.time() - starttimer)
AFTER EDIT
Something like this is how I would do it, and it runs less then a second on my box:
import math
def get_divisors(n):
yield 1
sqroot = int(math.sqrt(n))
for x in xrange(2, sqroot):
if n % x == 0:
yield x
yield n / x
if sqroot**2 == n:
yield sqroot
divisors = sorted(get_divisors(999999999999))
print divisors

Categories