How to count and store an unknown number of inputs Python - python

I need to take in an unknown number of strings, each on a new line, count them and determine if they were entered in alphabetical order.
I have to do this without using lists or dictionaries.
I’m lost. I tried assigning each to a variable but realized that without knowing the number of inputs that was not going to work without a loop of some kind that ends when there is no additional input. I have tried that but can’t figure out how to assign a new variable in the loop

try this one:
count = 0
prev = ''
isAlphabetical = True
while True:
curr = input('Enter string:')
if curr == '': # this is the ending condition. you may want to change it.
break
count+=1
if curr < prev:
isAlphabetical = False
prev = curr
print('count =',count)
if isAlphabetical:
print('they are in alphabetical order')
else:
print('they are not in alphabetical order')
the above code takes the inputs until the user enters nothing and press the enter button. it takes track of the order of the inputs and the number of them.

Related

How do I take an input, add it to a list, and use loops and if elif else statements to check if any two values are the same?

I am trying to make a simple program that uses for loops, if-elif-else statements, and input to take three "employees" salaries and compare them to see if A, any of them have the same salary. Or B if non of them have the same salary. So far, this is what I got but both strategies I've tried haven't been successful and I don't understand why :(. All help is appreciated, and spare me for I'm still new to coding and I'm trying to teach myself through these exercises. Thank you kindly!
salarylist = []
salarylist = list(map(int, salarylist))
maxLengthList = 3
while len(salarylist) < maxLengthList:
salary_of_employee = int(input("Enter your salary: "))
salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
print('non of the salaries are the same.')
############################################################################
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]
if empOne == salarylist[0]:
print("these are the same salary.")
elif empTwo == salarylist[1]:
print('these are the same salary')
elif empThree == salarylist[2]:
print('these are the same salary')
else:
print('non of the salaries are the same.')
I have tried running your code and it gives a horrible error.
I clearly understood your desire. Most of your logic don't meet it.
So I decided to RE-Code everything based upon your requirements {for loops, if, elif, else statement, 3 employees etc..}
MAX_LEN = 3
COUNTER = 1
LIST_SAL = []
while MAX_LEN >= COUNTER:
ASK_SAL = int(input('Enter your salary :'))
LIST_SAL.append(ASK_SAL)
COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
if LIST_SAL.count(check)>1:
print('Same salaries presented in the list')
break
else:
print('Salaries of employees are unique!')
break
Okay so ..
I created a variable max_len = 3 which is the total number of employees and then I initiated the variable COUNTER to 1 so that it iterates in the while loop and gets incremented by 1 each time.
Therafter a variable named ask_sal asks the user for salaries {3 times} and appends each input to the LIST_SAL variable {a list}. And then I printed the list for visualisation.
There after I accessed the elements in the list {list_sal} by a for loop with the variable check which looks for the number of time an element repeats in the list all by the help of count() function Which, IF greater then one prints "SAME salaries presented" OR else prints "Unique salary"..
You might be wondering why have I used 2 break statements..
Well they are used to break the further iteration as the if or else condition are met in the first iteration.
If you try removing the break statements, the print function will work the number of times the same salaries occur in the list.
Hope I helped you.. I am too , a newbie in programming yet I love it and practice a lot .
Keep grinding and Working hard
When you have the list of salaries, create a set from that list and compare the length, if same length then salaries will be unique, otherwise there will be at least one common salary
lst2 = set(salarylist)
if(len(lst2) == len(salarylist)):
print("Non of the salaries are the same.")
else:
print("Same salaries found")
To find the same salaries loop through the the set and check count of elements in the list, if greater than one, then duplicate.
for sal in lst2:
if(salarylist.count(sal) > 1):
print("Duplicate here")

Finding whether element entering in a list is duplicate or unique, while the program is running

so, I came across this question, where I have to create a list, take the elements as input from the user. After doing so, I have to check whether the elements entered by the user are 'Unique' or 'Duplicate', and this has to be done while the program is running. i.e if the input entered is duplicate, then I have to terminate the program then and there, otherwise proceed.
I have written the following code (Python):
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0,num):
q = int(input('element %d: '%(i+1)))
list.append(q)
print(list)
cnt = 0
for i in range(0,num):
if(list[i]==q):
cnt = cnt+1
if(cnt>1):
print('Duplicate')
else:
cnt = cnt+0
if(cnt==0):
print('Unique')
print('\nProgram Terminated!')
The thing is that, I know that I might have to use the break statement in the loop where I check whether the values are equal, but I somehow can't place it correctly.
Thank you! :)
If you want to check each time the user puts in a new element, i think this is the solution to your question:
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0, num):
q = int(input('element %d: ' % (i+1)))
if q not in list:
print('Unique')
list.append(q)
else:
print('Duplicate')
break
print(list)
print('\nProgram Terminated!')

Phone number lookup program: (index) and while loop

Can anybody please explain this code a little bit for me about why are we using the (index) and while loop?
def main():
people = ['todd','david','angela','steve','bob','josh','ben']
phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6990','911-9111']
found = False
index = 0
searchValue = raw_input('Enter a name to search for phone number: ')
while found == False and index < len(people):
if people[index] == searchValue:
found = True
else:
index = index + 1
if found:
print('the phone number is: ',phoneNumbers[index])
else:
print('that name was not found')
main()
Your program is looping through the whole list of phoneNumbers and people. Each item on a list has its own index value. In python, the first item in the list has an index of 0. According to your question, indexes were used to find at which position the person's name is. Then the same index position is used to find what is the phone number in the other list. But to determine this, we have builtin method to find the index position of an item in a list. I have made modifications to your code and now it is optimized.people.index(searchValue)returns the index position of the searchValue. For example, if the searchValue is steve, then the index position we get will be 3. We need to use this index position to find the phone number in the other list. So to do that we can simply do phoneNumbers[people.index(searchValue)] that simply means phoneNumbers[3]. This returns the 4th item which is 789-5489 that is the phone number.
NOTE:
Index of a list always starts with 0
listName.index(item) returns the index position
listName[index] returns the item
def main():
people = ['todd','david','angela','steve','bob','josh','ben']
phoneNumbers = ['234-7654','567-1234','888-8745','789-5489','009-7566','444-6990','911-9111']
searchValue = input('Enter a name to search for phone number: ')
if searchValue in people:
print(f"The phone number is {phoneNumbers[people.index(searchValue)]}")
else:
print('that name was not found')
main()
Some information about the logic:
while found == False means until the name is found in the list
and index < len(people) means the number of iterations that should
take place in the list people
if people[index] == searchValue checks if the person in the list is
same as the person the user searched for
found = True means that the person that we are looking for has been found. This will quit from the while loop because we mentioned that we
need to execute the code only when found = false. But now it is
true. So it will quit from the while loop
else: index = index + 1 is to shift to the next position. We
already completed checking if the first item is equivalent to the
user input. If it is not equal, then we need to check if the next
name in the list is equal to the user input.
Keep in mind that only one of if or else will occur. That means when the condition for if is satisfied, only the if part will occur and the else part is not to be bothered. When the condition for if is not satisfied, only else will occur. Therefore, if the name is not found only we are checking the next item. If we found it, we are just going to quit from the while loop.
In while found == False and index < len(people):, found == False means run until find a name, and index < len(people) means searched every name from list.
And the reason using index is phone number locates at same index in phonenumbers.

Finding the next entity in a list 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

Creating a list with inputs prompted by the user?

I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.

Categories

Resources