Want to make this code with input () of a list.
from statistics import mean
def Average(lst):
return mean(lst)
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst)
print("Average of the list =", round(average, 2))
I have tried to replace the lst part with input and int as well as empty list.
making statistics for mean with function and input as well as import.
One possible solution could be make a loop and input the user to enter a number. If the user wants to finish the inputting, he/she just hits Enter:
from statistics import mean
def Average(lst):
return mean(lst)
lst = []
while True:
num = input("Please input a number (just Enter to finish input): ")
if num.strip() == "":
break
lst.append(int(num))
average = Average(lst)
print("Average of the list =", round(average, 2))
Prints (for example):
Please input a number (just Enter to finish input): 10
Please input a number (just Enter to finish input): 20
Please input a number (just Enter to finish input): 30
Please input a number (just Enter to finish input):
Average of the list = 20
Related
def removal(DataList, n):
if len(DataList) < 2*n:
print "Not enough elements!"
for i in range(n):
DataList.remove(min(DataList))
DataList.remove(max(DataList))
return sorted(DataList)
def main():
inputs = []
while True:
inp = raw_input("Please enter a new integer, press ENTER if you want to stop: ")
if inp == "":
break
else:
inputs.append(inp)
removal(inputs,2)
if __name__=='__main__':
main()
main()
I got a ValueError: min() arg is an empty sequence
At a meanwhile, if I do not write my code in the main() and if name=='main', I'd be fine with the following code.
def removal(DataList, n):
#return to a sorted list with n smallest and n largest numbers removed.
for i in range(n):
DataList.remove(min(DataList))
DataList.remove(max(DataList))
return sorted(DataList)
inputs = []
while True:
inp = raw_input("Please enter a new integer, press ENTER if you want to stop: ")
if inp == "":
break
else:
inputs.append(inp)
removal(inputs,2)
Could somebody explain why it doesn't work in former and how should I make it work?
With:
if __name__=='__main__':
main()
main()
You're calling the main function twice (when your program is run as the main program), so after you enter a series of numbers and press another Enter to end the input, main calls removal to do the intended operations, which do not produce any output, and returns to the main program to start another call to main, which prompts for another series of number input. If at this point you simply press another Enter, you would end up with an empty list for the inputs list, which your removal function does not handle properly and would call min with the empty list, causing the said exception of ValueError: min() arg is an empty sequence.
I have a query relating to return only the last results, so here is my code:
import random
def Step_1():
Start_Game = raw_input("Enter \'Start' to continue \n")
if Start_Game == 'start':
print "Let the Lottery begin"
else:
return Step_1()
#-------------------------------------------------------------------
def Step_2():
random_list = []
for i in range(10):
while len(random_list) < 6:
random_number = random.randint(1,59)
while random_number not in random_list:
random_list.append(random_number)
print random_list
Step_1()
Step_2()
When i run this it gives me the below result,
Enter 'Start' to continue
start
Let the Lottery begin
[56]
[56, 20]
[56, 20, 32]
[56, 20, 32, 2]
[56, 20, 32, 2, 23]
[56, 20, 32, 2, 23, 30]
However how can i just display the last result generated and discard the previous 5. I know i need to change the last bit "print" within my Step_2 function, but what do I need to add?
Thanks .
A one liner:
random.sample(range(1, 59), 6) # genrates 6 unique random no's in the range
OR to modify existing code, use a list to store previously generated random no's
def Step_2():
random_list=[]
for i in range(6):
random_number = random.randint(1,59)
while random_number in random_list:
random_number = random.randint(1,59)
print random_number
list.append(random_number )
For your step2() function you will probably want to use a while loop, since you do not really know, how many random numbers you need to generate until you have 6 unique numbers.
def step2():
# Declare an empty list to hold the random numbers
numbers = []
# While we do not have 6 numbers in our list
while len(numbers) < 6:
# Generate a random number
rndnum = random.randint(1,59)
# If that random number is not yet in our list
if rndnum not in numbers:
# Append it to the list
numbers.append(rndnum)
return numbers
What I am trying to do is write a program that opens a .txt file with movie reviews where the rating is a number from 0-4 followed by a short review of the movie. The program then prompts the user to open a second text file with words that will be matched against the reviews and given a number value based on the review.
For example, with these two sample reviews how they would appear in the .txt file:
4 A comedy-drama of nearly epic proportions rooted in a sincere performance by the title character undergoing midlife crisis . 2 Massoud 's story is an epic , but also a tragedy , the record of a tenacious , humane fighter who was also the prisoner -LRB- and ultimately the victim -RRB- of history .
So, if I were looking for the word "epic", it would increment the count for that word by 2 (which I already have figured out) since it appears twice, and then append the values 4 and 2 to a list of ratings for that word.
How do I append those ints to a list or dictionary related to that word? Keep in mind that I need to create a new list or dicitonary key for every word in a list of words.
Please and thank you. And sorry if this was poorly worded, programming isn't my forte.
All of my code:
def menu_validate(prompt, min_val, max_val):
""" produces a prompt, gets input, validates the input and returns a value. """
while True:
try:
menu = int(input(prompt))
if menu >= min_val and menu <= max_val:
return menu
break
elif menu.lower == "quit" or menu.lower == "q":
quit()
print("You must enter a number value from {} to {}.".format(min_val, max_val))
except ValueError:
print("You must enter a number value from {} to {}.".format(min_val, max_val))
def open_file(prompt):
""" opens a file """
while True:
try:
file_name = str(input(prompt))
if ".txt" in file_name:
input_file = open(file_name, 'r')
return input_file
else:
input_file = open(file_name+".txt", 'r')
return input_file
except FileNotFoundError:
print("You must enter a valid file name. Make sure the file you would like to open is in this programs root folder.")
def make_list(file):
lst = []
for line in file:
lst2 = line.split(' ')
del lst2[-1]
lst.append(lst2)
return lst
def rating_list(lst):
'''iterates through a list of lists and appends the first value in each list to a second list'''
rating_list = []
for list in lst:
rating_list.append(list[0])
return rating_list
def word_cnt(lst, word : str):
cnt = 0
for list in lst:
for word in list:
cnt += 1
return cnt
def words_list(file):
lst = []
for word in file:
lst.append(word)
return lst
##def sort(words, occurrences, avg_scores, std_dev):
## '''sorts and prints the output'''
## menu = menu_validate("You must choose one of the valid choices of 1, 2, 3, 4 \n Sort Options\n 1. Sort by Avg Ascending\n 2. Sort by Avg Descending\n 3. Sort by Std Deviation Ascending\n 4. Sort by Std Deviation Descending", 1, 4)
## print ("{}{}{}{}\n{}".format("Word", "Occurence", "Avg. Score", "Std. Dev.", "="*51))
## if menu == 1:
## for i in range (len(word_list)):
## print ("{}{}{}{}".format(cnt_list.sorted[i],)
def make_odict(lst1, lst2):
'''makes an ordered dictionary of keys/values from 2 lists of equal length'''
dic = OrderedDict()
for i in range (len(word_list)):
dic[lst2[i]] = lst2[i]
return dic
cnt_list = []
while True:
menu = menu_validate("1. Get sentiment for all words in a file? \nQ. Quit \n", 1, 1)
if menu == True:
ratings_file = open("sample.txt")
ratings_list = make_list(ratings_file)
word_file = open_file("Enter the name of the file with words to score \n")
word_list = words_list(word_file)
for word in word_list:
cnt = word_cnt(ratings_list, word)
cnt_list.append(word_cnt(ratings_list, word))
Sorry, I know it's messy and very incomplete.
I think you mean:
import collections
counts = collections.defaultdict(int)
word = 'epic'
counts[word] += 1
Obviously, you can do more with word than I have, but you aren't showing us any code, so ...
EDIT
Okay, looking at your code, I'd suggest you make the separation between rating and text explicit. Take this:
def make_list(file):
lst = []
for line in file:
lst2 = line.split(' ')
del lst2[-1]
lst.append(lst2)
return lst
And convert it to this:
def parse_ratings(file):
"""
Given a file of lines, each with a numeric rating at the start,
parse the lines into score/text tuples, one per line. Return the
list of parsed tuples.
"""
ratings = []
for line in file:
text = line.strip().split()
if text:
score = text[0]
ratings.append((score,text[1:]))
return ratings
Then you can compute both values together:
def match_reviews(word, ratings):
cnt = 0
scores = []
for score,text in ratings:
n = text.count(word)
if n:
cnt += n
scores.append(score)
return (cnt, scores)
What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break
I have to write a program that accepts a sequence of average daily temperatures and put those temperatures into a list, but I can't figure out how. What I tried below does not work. Instead of giving me a list it just gives me the last input.
def main():
#create a list to store the temperatures.
tempList = []
while True:
dailyTemp = raw_input(
"Enter average daily temperature or -100 to quit: ")
# assign dailyTemo to tempList list
tempList = [dailyTemp]
print tempList
if dailyTemp == '-100':
break
main()
To append to a list, you have to do templist.append('thingtoappend').
In your case, you'd want something like this:
tempList = []
while True:
dailyTemp = raw_input("Enter average daily temperature or -100 to quit: ")
tempList = tempList.append(dailyTemp)
What the code that you posted does instead is, it says that the temperature that the user entered, is the list - so each time they enter a new temperature, it replaces the last one they entered.
The answer above does not work correctly because instead of append the new value to the list in this line tempList = tempList.append(dailyTemp), it will try to append the value to an NoneType object and raise an error.
To fix it, you must just use tempList.append(dailyTemp)
The entire solution is:
tempList = []
while True:
dailyTemp = raw_input("Enter average daily temperature or -100 to quit: ")
tempList.append(dailyTemp)