Passing an individual element value to a list using function - python-3.x

I am trying to pass an value on an "Empty" list(myUniqueList = []) using a user- defined function,
where I need to design it in a manner that in case I passed a value that is already existing in my
"empty" list, that value will then be added or append to the other "empty" list(myLeftovers = [] ).
def append_1(value):
myUniqueList.append(value)
def append_2(value):
myLeftovers.append(value)
myUniqueList = []
myLeftovers = []
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
for item in myUniqueList:
if item == value:
append_2(value)
else:
append_1(value)
print(myUniqueList)
print(myLeftovers)

myUniqueList = []
myLeftovers = []
def append_1(value):
myUniqueList.append(value)
def append_2(value):
myLeftovers.append(value)
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
if not value in myUniqueList:
append_1(value)
else:
append_2(value)
print(myUniqueList)
print(myLeftovers)
This should be what you are looking for. If you write the code without the two functions i think is better. Hope this will be helpful!
myUniqueList = []
myLeftovers = []
n = int(input("Enter number of elements: "))
for i in range(n):
value = input("Enter a value: ")
if not value in myUniqueList:
myUniqueList.append(value)
else:
myLeftovers.append(value)
print(myUniqueList)
print(myLeftovers)

Related

Sumlist and appending problems

I am trying to create a program that takes in four numbers they can be negative or positive and it should sum all the numbers together and then print the sum.
My problem comes with the append line, I am trying to place it inside the list but it keeps coming up with an error and I am unsure why.
Here is the Code:
def sumList(NumList, list):
sum = 0
for num in list:
sum = sum + num
return sum
NumList = []
while (True):
number = int(input("please enter a number: "))
if (number != 0):
number.append(number, NumList) #Here keeps coming up as an error
else:
sumList()
break
print(NumList)
Thank you for having the time to read this.
Honestly, your code is a mess. This works:
numlist = []
number = int(input("please enter a number: "))
while number != 0:
numlist.append(number)
number = int(input("please enter a number: "))
print(sum(numlist))
To sum the values of an iterable, you can simply use the builtin sum function. And to append something to a list, use list.append(value)
It should be NumList.append(number) or NumList.extend(number)
code snippet:
def sumList(NumList, list):
sum = 0
for num in list:
sum = sum + num
return sum
NumList = []
while (True):
number = int(input("please enter a number: "))
if (number != 0):
NumList.append(number) #correct this
else:
sumList()
break
print(NumList)

Is it possible to not have to replicate code for each iteration of the function

def math():
x = str('y')
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
print(a)
print(b)
print(c)
print(d)
x == str(input("Would you like to continue"))
math()
Hello I'm new to programming and I was just casually doing this to make an easy calculator for my homework assignment and I wanted to know instead of replicating the code for each variable if there was a way to do the math one time and just keep reassigning values to the variable for the math. This might be dumb a question and it's not serious or anything I just was curious if there are better way's to do this.
Comments and suggestions:
def math():
x = str('y')
'y' is a string, so there is no need to convert it to a string using str(). x = 'y' is sufficient.
while x == 'y':
a = float(input("Please enter a number: "))
a = (((4*a)+1)/(a-3))
b = float(input("Please enter a number: "))
b = (((4*b)+1)/(b-3))
c = float(input("Please enter a number: "))
c = (((4*c)+1)/(c-3))
d = float(input("Please enter a number: "))
d = (((4*d)+1)/(d-3))
DRY - don't repeat yourself.
Define a function which takes an input and returns the computed results:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
and call this function n times:
result_list = compute(4) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
ask user if they wish to continue:
x == input("Would you like to continue? ")
run your function:
math()
Conclusion:
def compute(n_times):
results = [] # initialize results, empty list
for repetition in range(n_times): # repeat n times
inp = float(input("Please enter a number: "))
results.append(((4 * inp) + 1) / (inp - 3)) # append result to list
return results # return filled list
def math():
how_often = 4
answer = 'y'
while answer == 'y':
result_list = compute(how_often) # compute() returns a list with results
for result in result_list: # iterate through list
print(result)
answer == input("Would you like to continue? (y/n): ")
math()

name, *line = input().split() in here can i use *line as a list?

I was doing a question on python and i got "name, *line = input().split() " this line in the code section. Then i searched and found that this line grabs the rest of the input as a list. Now, i want to use *line as a list for my furthur code. I have two question here.
Is *line actual a list?
How Can i use it as a list for furthur calculation?
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
Annotated code:
if __name__ == '__main__':
n = int(input('Enter number of students: '))
student_marks = {}
for _ in range(n): # _ character ignores the value returned by the generator
# split on whitespace, first argument goes to name, remaining go to line
name, *line = input('Enter record(name mrks1 mrks2 ...): ').split()
# line is indeed a list
print(type(line))
# parse the list "line" containing strings into floats/real numbers
scores = list(map(float, line))
# add it to the student dictionary, with value in "name" as the key
student_marks[name] = scores
query_name = input()

I was supposed to count the unique digits in a number but getting this int object not iterable on 4th line and not sure how to fix it

x = int(input("Enter the number: "))
count = 0
for elements in range(0,10):
for i in (x):
if elements == i:
count += 1
break
print()
That error raise because an integer is not an iterate object unlike strings, list, etc. So what you can do it's just work with a string, then use set (which get the unique values) and then get the length of it and you won't need to traverse with a for loop as below:
x = input("Enter the number: ")
unique_digits = set(x)
print(len(unique_digits))
Hope it will help you :)
x = input("Enter number: ")
count = 0
for elements in range(10):
for t in x:
if (int(t)==elements):
count += 1
break
print(count)

Program: finding the percentage / hackerrank

I am using below python code:
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(l)
print(no)
s = sum(l)
print(s)
ss = s/no
print(ss)
But, i am getting an error while input the query_name during the run of code.
source: https://www.hackerrank.com/challenges/finding-the-percentage/problem
you can try to do
n = int(input('enter the number:'))
student_marks = {}
for i in range(n):
name, *line = input("enter name and scroe (spared by space): ").split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input('enter the name:')
list_1 = list(student_marks[query_name])
no = len(list_1)
print("the numer of scores {}".format(no))
s = sum(list_1)
print("The sum of all scores {}".format(s))
ss = s/no
print("The average score {}".format(ss))
if __name__ == '__main__':
n = int(input())
student_marks = {}
count = 0
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
for i in student_marks[query_name]:
count += i
average = count / len(student_marks[query_name])
print("%.2f" %average)
You can try this solution:
--------------------------
from decimal import Decimal
# Main function (like Java main() method)
if __name__ == '__main__':
# Taking number of times input will be taken from console and converting it into int type
n = int(input())
# creating an empty dictionary
student_marks = {}
# Iterate from: 0 to n-1 times
for _ in range(n):
# Taking the first argument as name and all other numbers inside line var
name, *line = input().split()
# Converting the numbers contained in line variable to a map then, converting into list
scores = list(map(float, line))
# Inserting into dictionary as key - value pair
student_marks[name] = scores
# Taking the student name from console and store into query_name
query_name = input()
# Fetch student marks using student name
query_scores = student_marks[query_name]
# Sum all the marks
total_scores = sum(query_scores)
# Find average of the marks
avg = Decimal(total_scores/3)
# print the average upto two decimal point
print(round(avg, 2))

Resources