Finding the next entity in a list python - python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!

You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Related

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Change in variable values upon recursion, Python 3

Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.

Need help shortening program (python beginner)

In response to the following task, "Create an algorithm/program that would allow a user to enter a 7 digit number and would then calculate the modulus 11 check digit. It should then show the complete 8-digit number to the user", my solution is:
number7= input("Enter a 7 digit number")
listnum= list(number7)
newnum=list(number7)
listnum[0]=int(listnum[0])*8
listnum[1]=int(listnum[1])*7
listnum[2]=int(listnum[2])*6
listnum[3]=int(listnum[3])*5
listnum[4]=int(listnum[4])*4
listnum[5]=int(listnum[5])*3
listnum[6]=int(listnum[6])*2
addednum= int(listnum[0])+int(listnum[1])+int(listnum[2])+int(listnum[3])+int(listnum[4])+int(listnum[5])+int(listnum[6])
modnum= addednum % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print(strnewnum)
(most likely not the most efficent way of doing it)
Basically, it is this: https://www.loc.gov/issn/check.html
Any help in shortening the program would be much appreciated. Thanks.
It might be worth it to do some kind of user input error checking as well.
if len(number7) != 7:
print ' error '
else:
//continue
Using a while loop for that top chunk might be a good starting point for you. Then you can sum the list and take the modulus in the same step. Not sure if you can make the rest more concise.
number7= input("Enter a 7 digit number: ")
listnum= list(number7)
newnum=list(number7)
count = 0
while count < 7:
listnum[0+count] = int(listnum[0+count])*(8-count)
count += 1
modnum= sum(listnum) % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print('New number:', strnewnum)
EDIT:
If you want it to print out in ISSN format, change your code after your if-else statement to this:
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
strnewnum = '-'.join([strnewnum[:4], strnewnum[4:]])
print('ISSN:', strnewnum)
You can convert the list to contain only int elements right after the input
number7 = int(input())
Then you can perform those operations in a loop.
for i in range(len(listnum)):
listnum[i] *= (8-i)
also the sum function does the trick of performing the addition of every element in the list (if possible)
EDIT:
addedNum = sum(listNum)

10 Integers and 1 input that is asked too soon in Python 3

I'm trying to create a program right now where the user insert 10 integers, and then gets the possibility to do the following:
program: "What would you like to do?: 1. Show me the biggest integer. 2. Show me the smallest integer. 3. Show me the average of all numbers combined with one decimal. 4. Show me all the entered integers. 5. Terminate this program."
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
z = int((input("What would you like to do? Please enter a number between 1 to 4. ")))
if z == 1:
print(s[0])
elif z== 2:
print(s[0])
elif z == 3:
print(s[0])
elif z == 4:
print(s[0])
else:
print("Please select a number between 1 to 4.")
This is how far I've come, and now I'm just stuck. When I get the "Please enter an Integer" I enter, let's say for example "1". Then I get the "Please enter a number between 1 to 4" directly after that. I would also like the "Please enter a number between 1 to 4" list several options but got: "TypeError: input expected at most 1 arguments, got 5". I also would like a fifth option to terminate the program. I tried "brake" but I guess it doesn't work like that?
I've re-formatted and added some bits to get this example working. Hopefully you can follow everything I've changed from the comments, but feel free to ask.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
#only calculate params after all numbers are entered (outside for loop)
s = [max(nr), min(nr), nr, sum(nr)/len(nr)]
while 1: #loop forever until user chooses "terminate this program"
#print options in a nicely formatted way
#triple quoted string allows newlines within literal definition (multiline strings)
print("""What would you like to do?:
1. Show me the biggest integer.
2. Show me the smallest integer.
3. Show me the average of all numbers combined with one decimal.
4. Show me all the entered integers.
5. Terminate this program.""")
#we don't specifically need an integer if we're just picking a choice from a list of options
z = input("input: ")
if z == "1": #choices are now strings so be sure to quote them
print(s[0]) #be sure to select proper element from our list 's'
elif z == "2":
print(s[1])
elif z == "3":
print(s[3])
elif z == "4":
print(s[2])
elif z == "5": #now that we are in a separate loop, break will bring us out of it
break
else:
print("Please select a number between 1 to 5.")
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
while True:
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = int((input("What would you like to do? Please enter a number between 1 to 4.\n1> Max Value\n2> Min Value\n3> Average\n4> Show All\n5> Terminate\n")))
if (z-1) in range(0,4):
print(s[z-1])
elif z == 5:
break
else:
print("Please select a number between 1 to 4.")
Here is the working version. I will explain each change to get you started on programming Python.
nr=[]
for i in range(10):
a=int(input("Please Enter an integer. "))
nr.append(a)
s = [max(nr), min(nr), sum(nr)/len(nr), nr]
z = 0
while not 1 <= z <= 5:
z = int((input("What would you like to do? (1) Max ; (2) Min; (3) Avg; (4) All; (5) None. ")))
if z != 5:
print(s[z-1])
Here are the changes I made:
As I originally said in the comments, we shift everything from the s = line to the left, to get it out of the input loop. Remember indentation is syntactically significant.
We swap the 3rd and 4th elements in your s array to conform to the description you had (option 3 is the average, option 4 prints the array)
We set up a while loop to keep asking for a legal option input (1 thru 5). Notice how in Python, you can do things like 1 <= z <= 5. This more natural notation is not something you find in many languages. Notice also how we had to set z = 0. We could have set z = 6 or z = 99 or whatever - basically, any value not between 1 and 5. Without that, z is initialized to the special Python value None - the null value that is nowhere in the set of integers, and will thus fail the 1 <= z <= 5 test.
We modify the message printed to the user just make the options clear
Last but not least, rather than having all the if statements, we take advantage of the fact that the option number is the same as the index in the array of calculations we did. Well, almost the same, except that arrays in Python start at index 0. So, we subtract one from the option number, and that indexes right to the place in the array holding the desired calculation. The only exception is option 5, which is meant to do nothing. So, we still have just one if statement, which tests for that option 5.

Python: Display and count divisors of two integers

Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :

Categories

Resources