List not concatenating properly in python - python

My code all work fine apart from the list at the very bottom "newList = [i + j for i, j in zip(numberString, products)]". I expected it to add all the elements within the two list without fault, sort of like this: [a9, b7, c5, d3, e1].
Instead i got this: "['[a', '[b', '9c', ',d', ' e']". Both lists are strings, so i'm not sure why they aren't concatenating properly.
# create an empty list for your products.
products = []
# Asking for the number of elements to be inputted.
n = int(input("Enter number of products you're buying : "))
# Some UI for the customer.
print("What are these products?")
# iterating until the range that has been chosen.
for i in range(0, n):
ele = input()
products.append(ele) # adding the element
def sort_numbers(number_list):
# sorts a list of valid numbers in descending numerical order
swaps = True
loopcount = len(number_list) - 1
while loopcount > 0 and swaps:
swaps = False
for i in range(loopcount):
if number_list[i] < number_list[i + 1]:
number_list[i], number_list[i + 1] = number_list[i + 1], number_list[i]
swaps = True
loopcount = loopcount - 1
def input_numbers(number_list):
# inputs shopping items and costs and stores them in two lists
user_input = input('Input a number of type Q to quit ')
while user_input.upper() != 'Q':
valid_number = False
while valid_number == False:
# use an exception handler to cover non-numeric input
try:
number_list.append(int(user_input))
valid_number = True
except ValueError:
print('Please enter a valid number')
user_input = input('Input a number or type Q to quit ')
user_input = input('input a number or type Q to quit ')
def totalise_numbers(number_list):
# sums us the list of numbers
total = 0
for i in range(len(number_list)):
total = total + number_list[i]
print('The total of the numbers is ', total)
print('The total of the numbers minus the smallest number is ', total - number_list[0])
# initialise the list
numbers = []
# call the function to create the list of numbers
input_numbers(numbers)
# sort the list in ascending order
sort_numbers(numbers)
# Totalise the numbers
totalise_numbers(numbers)
numberString = str([numbers])
# print the list of numbers
newList = [i + j for i, j in zip(numberString, products)]
print(newList)
print(numbers)

Replace the few bottom lines with this code.
numberString = numbers
# print the list of numbers
newList = [str(i) + j for i, j in zip(numberString, products)]
print(newList)
print(numbers)

Related

how to add an element in list using for loop and also without using append and also ask the position in which the number should be added

i somehow used it in for loop to add an element using the user inputed position but i somehow get the last element of the list get deleted,
list1 = [int(item) for item in input("Enter the list(leave space for an element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter the number that should be inserted: "))
pos = int(input("Enter the position of that number should be inserted: "))
for i in range(n-1):
if(pos - 1 == i):
for j in range(n-1, i-1, -1):
list1[j]=list1[j - 1]
list1[i]=add
n += 1
print(list1)
can you guys please help me identify the problem
list1 = [int(item) for item in input("Enter the list (leave space between each element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter number to be inserted: "))
pos = int(input("Enter position to be inserted: "))
pos = pos -1
for i in range(n):
if(pos == i):
list1.insert(pos,add)
print(list1)

Divide an element in a list with every other element in the list

I would like to take a list of numbers and a value (v) from user and see whether an element divided by another element in the list is equal to v:
e.g.
user input:[ 9, 5, 8, 1 ], v = 10, result: false
user input:[ 2, 4, 5, 7 ], v = 2, result: 2 and 4
user input: [ 3, 5, 15, 20 ] v = 4, result: 5 and 20
below is what I have now:
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = listnum.split()
for num in listnum:
list1.append(num)
for a in range(len(list1)):
for b in range(len(list1)):
if int(list1[a])/int(list1[b]) == v:
print(list1[b], list1[a])
else:
print('False')
but my output is like:
Enter a list of numbers: 2 4 5 7
Enter the value of v: 2
2 4
False
how could I adjust the code? Thanks!
Here goes:
from itertools import combinations
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = map(int, listnum.split())
combs = combinations(listnum, 2)
divisors = [(n1, n2) for n1, n2 in combs if n1/n2 == v or n2/n1 == v]
if len(divisors) == 0:
print(False)
else:
print(divisors)
Enter a list of numbers: 3 5 15 20
Enter the value of v: 4
[(5, 20)]
A bit optimized version:
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = sorted(list(map(int, listnum.split())), reverse=True)
if(v<2): print("False")
else:
for i in range(len(listnum)):
if(listnum[i]%v==0):
for j in range(i+1, len(listnum)):
if(listnum[i] == v*listnum[j]):
list1.append((listnum[i], listnum[j]))
if(len(list1)==0): print("False")
else: print(list1)
Few notes - what I do here:
(1) to make it easier - sort the input array in a descending order. Thanks to this you won't have to run over the whole list twice, but just run over the reminder in the second step (which is still O(n^2), yet it's 2x less operations).
(2) you only need to execute the lookup through reminder, if v is a divisor of the bigger number - otherwise you won't find the smaller one anyways.
In total - depending on the input sample - you should see some major performance improvements with this code.
You have an indentation problem, your else condition isn't working as you're expecting.
If what you want to do is print False when no result are found, then you can do something like:
exists = False
for a in range(len(list1)):
for b in range(len(list1)):
if int(list1[a])/int(list1[b]) == v:
print(list1[b], list1[a])
exists = True
if not exists:
print('False')
Try this :
listnum = input("Enter a list of numbers: ")
list1 = []
v = int(input("Enter the value of v: "))
listnum = listnum.split()
for num in listnum:
list1.append(int(num))
found=False
for a in list1:
for b in list1:
if a/b == v:
print(b,a)
found=True
break
if found:
break
else:
print('False')
Note :
You can just loop through list1 without explicitly using the index.
You will need a break statement inside the for loop. The associated else part will be executed only if the for loop is not terminated by any break statement.
Please notice that even if there are multiple pairs which can result in producing v after division, the above snippet will only print the first pair.
You can use a flag to decide whether an element divided by another element in the list is equal to v, like this way
listnum = input("Enter a list of numbers: ")
v = int(input("Enter the value of v: "))
listnum = listnum.split()
isDevided=False
for a in range(len(listnum)):
for b in range(len(listnum)):
if int(listnum[a])/int(listnum[b]) == v:
print(listnum[b], listnum[a])
isDevided=True
if isDevided==False:
print ("False")
Another thing i want to mention that is you are using list1 as an extra variable and an extra for loop which may decrease the performance, Above code is little bit more optimized, memory and computation wise.
Try this
a=input("Enter list of numbers Like 2 4 5 1: ")
v= float(input("Enter the value of v: "))
a= a.split()
b = [int(a[i]) for i in range(len(a))]
b = sorted(b)
final_list = []
for i in b:
if i not in final_list:
final_list.append(i)
count = 0
for i in range(len(final_list)):
for j in final_list[i+1:]:
if int(j) / int(final_list[i]) == v:
print(final_list[i], " and ", j)
count += 1
if count == 0:
print(False)
...
You can do this in a much more compact way using list comprehensions. By computing a list of resulting products (number * v) you can use a set to only go throuh the list twice instead of going through it for every single number in it. This will give you an O(n) complexity instead of O(n^2).
numbers = input("Enter a list of numbers: ")
numbers = list(map(int,numbers.split(",")))
value = int(input("Enter the value of v: "))
products = { divisor*value for divisor in numbers }
matches = [ number for number in numbers if number in products ]
print( ", ".join(f"{prod}/{prod//value}" for prod in matches) or "False")
sample runs:
Enter a list of numbers: 9,5,8,1
Enter the value of v: 10
False
Enter a list of numbers: 2,4,5,7
Enter the value of v: 2
4/2
Enter a list of numbers: 3,5,15,20
Enter the value of v: 4
20/5
Enter a list of numbers: 5,10,15,30,45
Enter the value of v: 3
15/5, 30/10, 45/15
note that some special cases would need to be adressed (zeroes or repetitions in the list or v == 1) but since your original code didn't bother with those I assumed they are not part of the problem statement
Here's an even more condensed version:
nums = map(int,input("Enter a list of numbers: ").split(","))
v = int(input("Enter the value of v: "))
print(*([f"{n}/{n//v}" for s in [set(nums)] for n in s if n//v in s] or "False"))

Lists, Loops, Average Python

I'm currently having an issue with my code. The program works properly but for some reason when I enter all positive numbers I receive an error for the last function. The last function is removing all the negative numbers from the list.
i=0
numList = []
x = int(input("Please enter number from -9999 to end:"))
while x > -9999:
i = i + 1
numList.insert(i,x)
x = int(input("Please enter number from -9999 to end:"))
if x == -9999:
print("The list of numbers entered:",(numList))
newList = numList[:]
secList = numList[:]
def posNumAvg(newList):
for e in newList[:]:
if e < 0:
newList.remove(e)
def negNumAvg(secList):
for y in secList[:]:
if y > 0:
secList.remove(y)
posNumAvg(newList)
negNumAvg(secList)
mydict = {'AvgPositive':(sum(newList)//len(newList)),'AvgNonPos': (sum(secList)//len(secList)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
You are trying to compute the average of an empty list, which is not defined (specifically, the list's length is zero so you end up dividing by zero).
You need to decide what you want to do in that case and handle it specifically.
As an aside, you can rewrite
for e in newList[:]:
if e < 0:
newList.remove(e)
as
newList = [e for e in newList if e >= 0]
NOte: Never modify the list when you iterating over it. Let me make some changes to your code
numList = []
while True:
x = int(input("Please enter number from -9999 to end:")
if x == -9999:
print("The list of numbers entered:",(numList))
break
# you don't need i here, used append to insert element at last of list
# insert is used to insert a element at specific position
numList.append(x)
def posNumAvg(gotList):
list_negative = [] # will contain negative number
for e in gotList:
if e < 0:
list_negative.append(e)
return list_negative
def negNumAvg(gotList):
list_positive = [] # will contain positive number
for y in gotList:
if y >= 0:
list_positive.append(y)
return list_positive
list_positive = posNumAvg(numList)
list_negative = negNumAvg(numList)
mydict = {'AvgPositive':(sum(list_positive)//len(list_positive)),'AvgNonPos': (sum(list_negative)//len(list_negative)),'AvgAllNum':(sum(numList)//len(numList))}
print("The dictionary with averages is:",mydict)
you can get positive and negative number from one function: see this code
def neg_poss(gotList):
list_positive = [] # will contain positive number
list_negative = [] # will contain negative number
for y in gotList:
if y >= 0:
list_positive.append(y)
else:list_negative.append(y)
return list_positive,list_negative
list_positive,list_negative = neg_post(numList)

(Python) Stuck on skipping range values for the sum of a randint list

I need to make a program in python that generates ten random numbers from 1-100 that stores it in a list using a loop. Then a second loop should display said list, then calculate the sums of the even and odd elements to display them. This is what I have so far, any help is greatly appreciated. Thanks
import random
def main():
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print(numlist)
list_length = len(numlist)
print('The number of elements in the list is', list_length)
More specifically this is the part I'm stuck on. I have to add the sums of the odd and then even elements. Every work around I've tryed has only given me the sum of the total elements.
for x in range(0, 10, 2):
numlist[x] = numlist
print('The Sum of the odd numbers is ', sum(numlist))
main()
import random
nums = [random.randint(1,100) for _ in range(10)]
You can use lambdas and filter
evenSum = sum(filter(lambda i : i%2 == 0, nums))
oddSum = sum(filter(lambda i : i%2, nums))
Or make some quick helper functions
def isEven(x):
return x % 2 == 0
def isOdd(x):
return x % 2 == 1
evenSum = sum(filter(isEven, nums))
oddSum = sum(filter(isOdd, nums))
Using your own code:
def main():
numlist = [] # create empty list to add randints to
for r in range(10):
numlist.append(random.randint(1,100)) # append to the list
list_length = len(numlist)
print('The number of elements in the list is', list_length)
odd = 0
even = 0
for num in numlist:
if num % 2: # if num mod 2 has a remainder, num is odd
odd += num
else: # else num is even
even += num
print('The Sum of the odd numbers is {} and even numbers is {}'.format(odd,even))
You can replace the first loop with a list comp:
numlist = [random.randint(1,100) for _ in range(10)]
Can't Understand the actual problem (hahehehe !)
As far as I have understood, you want to print the sum of odd and even numbers of the list that is generated from randint(). Well I have just edited your code ;)
so here is the simple done code !
Vote If It Helps !
import random
def main():
odd_sum=0
even_sum=0
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print numlist
list_length = len(numlist)
print('The number of elements in the list is', list_length)
for i in numlist:
if (i%2 == 1): #the remainder is 1 if the number is odd
odd_sum = odd_sum + i #add the odd_numbers
elif(i%2 == 0): #the remainder is 0 if the number is even
even_sum = even_sum + i #add the even_numbers
else:
print "No need of this else part !"
print "Odd_sum = ",odd_sum
print "Even_sum = ",even_sum
main()

Beginners python program

Decided to help out with doing a lab for my buddy, first time ever doing this so please don't make fun of my code lol. I have to get a number "num" of how many numbers to add to array, then a total number. Then from that I want to add user defined numbers from the size of the array. Then if any of those numbers adds up to the total then print them out, else print sorry. Can't understand why it doesn't work :(
EXTRA EDIT: Problem is, my script does not show the numbers that add up to the total value, only the print('sorry')
edit: I learned prior to this java and C, couldn't figure out the foor loops or how variable types are instantiated.
num = int(input('Please enter the amount of numbers you wish to use: '))
total = int(input('Please the total wild card number: '))
hasValue = int(0)
ar = []
i = int(0)
j = int(0)
k = int(0)
l = int(0)
m = int(0)
while (i < num):
j = i + 1
inNum = input('Please enter number %d:' %j)
ar.append(inNum)
i = i + 1
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
if (hasValue == 0):
print('sorry, there no such pair of values')
As I got it, your current script is looking for two consequent numbers where sum equal to total, but should search for any pair in array, right? So if we have
ar = [1, 2, 3]
and
total = 5
program should display 2, 3 pair. But it will not find 1+3 for total=4.
Here are some general advices:
There is error in print invocation, where pair is printed (string should go first in str+int concatenation). Use format
print('%d, %d'.format(ar[k], ar[k])
or print result as tuple
print(ar[k], ar[l])
Use for k in range(num) instead of while
hasValue is better to be boolean value
Well, here is my solution (python2.7)
num = int(input("Array size: "))
sum = int(input("Search for: "))
a = []
found = False
# Fill array
for i in range(num):
a.append(int(input("Enter number #{}: ".format(i+1))))
# More effective algorithm - does not check same numbers twice
for i in range(num):
for j in range(i+1, num):
if a[i] + a[j] == sum:
print "{}, {}".format(a[i], a[j])
found = True
if not found:
print "Sorry..."
This is how to do for-loops in python:
for x in range(10):
# code for the for loop goes here
This is equivalent to:
for (int x = 0; x < 10; x++) {
// code for the for loop goes here
}
... in C++
(Notice how there is no initializing the variable 'x'. When you do a for loop, python automatically initializes it.
Here is what I think you wish to do:
def main():
num = int(input("Enter the amount of numbers: "))
total = int(input("Enter the total: "))
array = []
counter, elem = 0, 0
for user_numbers in range(num):
array.append(int(input("Please enter number: ")))
for each_element in array:
counter += each_element
elem += 1
if counter == total:
print(array[:elem])
break
if counter != total:
print("sorry...")
main()
while (k < num):
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
Apart from the fact that the loops are not "pythonic", you need to initialize l = 0 within the k loop.
while (k < num):
l = 0
while(l < num):
if ((ar[k]+ar[l])==total):
print(ar[k] +' , '+ ar[l])
hasValue = hasValue + 1
l = l +1
k = k + 1
or slightly more python way:
for num1 in ar:
for num2 in ar:
if num1+num2==total:
print(num1 +' , '+ num2) # not sure about this syntax. I am a python beginner myself!
hasValue = hasValue + 1

Categories

Resources