In: Computer Science
Write a Python program using functions and mainline logic which prompts the user to enter a number, then generates that number of random integers and stores them in a file. It should then display the following data to back to the user:
Please check out the code with the output... please do a comment for having any kind of doubt... thank...
please see the comments with the code for better understanding...
import random #for random function
def Read(fname): #for reading the data
f=open(fname) #opening file
R=f.read() #reading whole data as a string
f.close() #closing file
return R #returning the string
def ptr(list): #prints the list
print(list)
def lowest(list): #prints the lowest element in the list
print("lowest number in the list is ",min(list))
def highest(list): #prints the lowest element in the list
print("Highest number in the list is ",max(list))
def Sum(list): #prints the sum of elements on the list
print("Sum = ",sum(list))
return sum(list) #returns sum which is required for average
def avg(s,n): #prints the average of the list
print("Average is = ",float(s/n))
#start of main
x, y = [int(x) for x in input("Enter two value for range : ").split()] #taking range of random integer
n=int(input("Enter the number of random integers : ")) #number of random integer
fname=input("Enter the file name : ") #input file name where to store
f=open(fname,"w+") #opening file for writing
for i in range(n):
r=random.randint(x,y) #generates random number b/w x,y
f.write("%d "%r) #writing in file
f.close() #closing file
R=Read(fname) #reading the file as a string
list=[] #declearing a list
s=0 #s is required for calculating each of the number
for i in R:
if i!=' ': # if the current index is not a space
s=s*10+int(i) #calculating the integer number
else:
list.append(s) #i.e. if it is a space, then one integer is complete. so append it to list
s=0 #making s=0 again for next element
f.close() #closing file
ptr(list) #calling function
lowest(list)
highest(list)
s=Sum(list)
avg(s,n)
output
screen sort of code...