I'm trying to go through each index and check if it's greater than the next index or not, but I could not come up with any idea about how to do it. I tried using range and enumerate functions, but did not work so help would be much appreciated. This is my current code:
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
test = []
for the_index, the_item in enumerate(arrayList):
Here is what I tried earlier than this
user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
first_numbers = []
second_numbers = []
finalList = []
for i in arrayList:
the_index = arrayList.index(i)
if the_index % 2 != 0:
first_numbers.append(i)
if the_index % 2 == 0:
second_numbers.append(i)
first_numbers.append(second_numbers)
Not sure i got this clear but if you want to know if user's input was bigger / smaller than the previous choice, you can do this:
This may not be the shortest way to do it, but this is a dynamic snippet where you can decide ask as much as inputs you want the user to answer:
user_choice = input('Choose some numbers: ')
user_choice_listed = user_choice.split(',')
marked_choice = None # Uninitialized integer that would be assigned in the future
for t in user_choice_listed:
converted_t = int(t)
if marked_choice != None and marked_choice < converted_t:
print('{0} is Bigger than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice != None and marked_choice > converted_t:
print('{0} is Smaller than your previous choice, it was {1}'.format(t,marked_choice))
elif marked_choice == None:
print('This is your first Choice, nothing to compare with!')
marked_choice = converted_t # this is marking the previous answer of the user
NOTE: You can add a line to handle where the previous is equal to the current choice.
OUTPUT:
Choose some numbers: 1,3,5 # My Input
This is your first Choice, nothing to compare with!
3 is Bigger than your previous choice, it was 1
5 is Bigger than your previous choice, it was 3
Loop it through the indexes?
for i in range(len(arrayList)):
if arrayList[i] > arrayList[i + 1]:
//enter code here
Related
Looking on for some guidance on how to write a python code
that executes the following:
The program will ask for math problems to solve.
The program will asks for the number of problems.
And asks for how many attempts for each problem.
For example:
Enter amount of programs: 4
Enter amount of attempts: 5
what is: 4x3 =?
Your answer: 16
and so goes on to another attempt if wrong if correct moves onto another problem, just like before and exits when attempts or problems are finished.
I have this code but I want to it only do multiplication ONLY and would like to know how to integrate how to put additional code to limit how many time one can solve the question and how many questions it asks
import random
def display_separator():
print("-" * 24)
def get_user_input():
user_input = int(input("Enter your choice: "))
while user_input > 5 or user_input <= 0:
print("Invalid menu option.")
user_input = int(input("Please try again: "))
else:
return user_input
def get_user_solution(problem):
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
return result
def check_solution(user_solution, solution, count):
if user_solution == solution:
count = count + 1
print("Correct.")
return count
else:
print("Incorrect.")
return count
def menu_option(index, count):
number_one = random.randrange(1, 21)
number_two = random.randrange(1, 21)
problem = str(number_one) + " + " + str(number_two)
solution = number_one + number_two
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
def display_result(total, correct):
if total > 0:
result = correct / total
percentage = round((result * 100), 2)
if total == 0:
percentage = 0
print("You answered", total, "questions with", correct, "correct.")
print("Your score is ", percentage, "%. Thank you.", sep = "")
def main():
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
As far as making sure you're only allowing multiplication problems, the following function should work.
def valid_equation(user_input):
valid = True
for char in user_input:
if not(char.isnumeric() or char == "*"):
valid = False
return valid
Then after each user_input you can run this function and it will return True if the only things in the users string are numbers and the * sign and False otherwise. Then you just need to check the return value with a if statement that tells the user that their input is invalid if it returns False. You can add more "or" operations to the if statement if you want to allow other things. Like if you want to allow spaces (or char == " ").
As far as limiting the number of times a user can try to answer, and limiting the number of questions asked, you just need to store the values the user enters when you ask them these numbers. From there you can do nested while loops for the main game.
i = 0
user_failed = False
while ((i < number_of_questions) and (user_failed == False)):
j = 0
while ((j < number_of_attempts) and (user_correct == False)):
#Insert question asking code here
#In this case if the user is correct it would make user_correct = True.
j += 1
if j == number_of_attempts:
user_failed = True
i += 1
So in this situation, the outer while loop will iterate until all of the questions have been asked, or the user has failed the game. The inner loop will iterate until the user has used up all of their attempts for the question, or the user has passed the question. If the loop exits because the user used up all of their attempts, the for loop will trigger making the user lose and causing the outer loop to stop executing. If it does not it will add one to i, saying that another question has been asked, and continue.
These are just some ideas on how to solve the kinds of problems you're asking about. I'll leave the decision on how exactly to implement something like this into your code, or if you decide to change parts of your code to better facilitate systems like this up to you. Hope this helps and have a great one!
I am looking to see if any 2 indices add up to the inputed target number, and print the combination and index location of the respective pair. I honestly am not too sure how to approach this, my first reaction was using a for loop but due to inexperience i couldn't quite figure it out.
def length():
global lst_length
break_loop = False
while break_loop == False:
lst_length = int(input("Enter the length: "))
if lst_length >= 10 or lst_length <= 2:
print("Invalid list")
elif lst_length >= 2 and lst_length <= 10:
print('This list contains', lst_length, 'entries')
break_loop == True
break
def entries():
i = 0
x = 0
global lst
lst = []
while i < lst_length:
number = float(input("Enter the entry at index {0}:".format(x)))
if i < 0:
print('Invalid entry')
else:
lst = []
lst.append(number)
i += 1
x += 1
def target():
target_num = int(input("Enter the target number: "))
length()
entries()
target()
If I understand your question correctly, you want the user to insert numbers, and when finally two numbers match the wanted result, print them?
well, my code is pretty basic, and it gets the job done, please let me know if you meant something else.
for indices, I suppose you can fill in the gaps.
def check(wanted):
numbers_saved = []
checking = True
while checking:
x = float(input("enter a number: "))
if x < 0:
print("only numbers bigger than 0")
else:
for num in numbers_saved:
if num + x == wanted:
print(num, x)
checking = False
return
numbers_saved.append(x)
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!')
I don't understand why I cannot go out from simple loop.
Here is the code:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
elif b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
Thanks for your help.
This should solve your problem:
a = 1
#tip checking loop
while a != 0:
# tip value question - not defined as integer to be able to get empty value
b = input("Give me the tip quantinty which you gave to Johnnemy 'hundred' Collins :")
# loop checking if value has been given
if b:
#if b is given - checking how much it is
if int(b) >= 100:
print("\nJohnny says : SUPER!")
elif int(b) < 100:
print("\nJohnny says : Next time I spit in your soup")
if b == '0':
a = 0
else:
print("You need to tell how much you tipped")
print("\n\nZERO ? this is the end of this conversation")
the following condition
if b == '0':
a = 0
should be in the same scope as the if b: condition.
You cant break out of the loop because. actually, there is nobreak. You need to putbreak` command at the end of every loop branch where you would like to stop looping in order to break out of the loop.
Also, you could break out assigning a = 0 instead of the break.
nums = []
num = 0
valid_list = []
while num != '':
num = input('Enter numbers :')
nums.append(num)
nums2 = [(nums[i]) for i in range(0,len(nums))]
for i in range(len(nums2)):
if int(nums2[i]) < 101 and int(nums2[i]) > 0:
valid_list.append(nums2[i])
print(valid_list)
Sorry dont really know how to ask question corectly, but i hope those who get my idea will help, Thanks. So i am tryed to make program wich fills list with integers entered by user, than chech if they fit 1-101 and if they fit put those number in valid_list, The problem is while num != '': (BTW inters must be entered one by one, and it must stop when return is hited)
Without having actually tested it, I think this is what you want:
nums = []
num = 0
valid_list = []
while true:
num = input('Enter numbers :')
if not num:
break
nums.append(num)
nums2 = [(nums[i]) for i in range(0,len(nums))]
for i in range(len(nums2)):
if int(nums2[i]) < 101 and int(nums2[i]) > 0:
valid_list.append(nums2[i])
print(valid_list)
From Python 'If not' syntax the if not num syntax is explained as executing if num is any kind of zero or empty container, or False.