I want to write a program that asks for the list length and its integer elements. From the integer list though, the program needs to find out of there is a duplicate integer and if there is one: print "True" if a duplicate is found, other wise false.
This should be the sample output:
Enter list length: 3
Enter element 1: 100
Enter element 2: 2312
Enter element 3: 12312312
Has duplicate?: False
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
(this part ^ is just for the asking inputs)
for i in range(e):
if e.count(item) > 1:
print("Has duplicate?: True")
else:
print("Has duplicate?: False")
I keep getting an error though:
AttributeError Traceback (most recent call last) <ipython-input-7-d4356802d6f7> in <module> 8 9 for i in range(e): ---> 10 if e.count(item) > 1: 11 print("Has duplicate? True") 12 else: AttributeError: 'int' object has no attribute 'count' –
when you apply count function it should be like list_name.count(the_value_to_count)
but when you are doing e.count(item) e is basically a number not a list,set,tuple..
you can apply count function like this.
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
emp.append(e)
for i in set(emp):
#emp is a list. and i is the number. for which we have to count.
if emp.count(i) > 1:
print(str(i)+" Has duplicate?: True")
else:
print(str(i)+" Has duplicate?: False")
Output:
Enter the number of elements: 6
Enter element 1: 99
Enter element 2: 42
Enter element 3: 63
Enter element 4: 42
Enter element 5: 56
Enter element 6: 99
56 Has duplicate?: False
42 Has duplicate?: True
99 Has duplicate?: True
63 Has duplicate?: False
Note the list is not in order as i have applied set in for loop
Updated answer.
If you just wanted to check if list contains duplicate or not.
Using counter
from collections import Counter
emp = []
listLen = int(input("Enter the number of elements: "))
num = 1
for i in range(listLen):
e = int(input("Enter element %d: " % num))
num += 1
emp.append(e)
a=Counter(emp)
if max(a.values()) > 1:
print(" List Has duplicate?: True")
else:
print(" List Has duplicate?: False")
Output:
Enter the number of elements: 5
Enter element 1: 2
Enter element 2: 3
Enter element 3: 1
Enter element 4: 2
Enter element 5: 5
List Has duplicate?: True
Related
I have been trying to create a program that creates a list from user input. The program is meant to give an error message to the user input when the length of the list is more or less than nine (9)
For example:
"Please enter nine (9) numbers from 0 - 100: "
input
4 5 6 7 8 9
output
Sorry! Numbers should be up to nine.
or
input
5 67 8 2 90 65 3 45 2 7 1 0
"Sorry! Numbers should not be more than nine."
my code:
number = []
while True:
num = input("Please type numbers: ")
num = list(map(int, num.split()))
number.append(num)
if len(number) > 9:
print ("Numbers should not be more than 9!")
else:
break
print (number)
I don't know what I am doing wrong.
number = []
num = input("Please type numbers: ")
num = list(map(int, num.split()))
number.append(num)
while True:
if (len(number)) == 7:
print ("List is complete")
elif (len(number)) < 7:
print ("List is not complete")
else:
print ("List is more than 7")
break
this code works fine when I'm not asking for user input.
However it brings back the output
"List is not complete" whenever I run it without regard for the length of the string.
Your code creates a list within a list, like this
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]]
to solve this problem, you just have to replace number.append(num) by number = num or simply use directly the variable num like this
num = input("Please type numbers: ")
num = list(map(int, num.split()))
while True:
if (len(num)) == 7:
print ("List is complete")
elif (len(num)) < 7:
print ("List is not complete")
else:
print ("List is more than 7")
break
I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)
I am having an issue with Python validation. I was wondering if there was a simple way to put validation on two input numbers to check a few things:
If the inputs are ints
if neither of the inputs equals a certain number, they are not valid. (For example, this would mean one of them would have to be 5. So a = 1 b = 4, a = 3 b = 2, a = 1 b = 1 wouldn't work)
If the two numbers are the same number that is required it will not work (E.G. if a = 5 b = 5 will not work as 5 is the required number, however a = 1 b = 5 would work as 5 is only being inputted once).
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
val = int(a)
val1 = int(a)
if val1 != 5 or val != 5:
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
This is what I was trying to do, but I think I may be dreadfully wrong?
Any help appreciated!
Thanks.
Logical xor
You should continue the loop if exactly one a and b is equal to 5. It means you need a logical xor. Parens are needed to avoid comparing a to 5 ^ b:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
if (a != 5) ^ (b != 5):
print("I'm sorry but it must be a pos int and equal 5")
continue
break
except ValueError:
print("That's not an int")
It might not be very readable though.
Count 5's
You could count the number of ints equal to 5:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 1:
break
else:
print("Exactly one input should be equal to 5.")
except ValueError:
print("That's not an int")
If you want to differentiate between errors:
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a)
b = int(b)
count5 = [a, b].count(5)
if count5 == 2:
print("Inputs cannot both be equal to 5.")
elif count5 == 0:
print("At least one input should be equal to 5.")
else:
break
except ValueError:
print("That's not an int")
Here's an example:
Enter first input: 3
Enter second input: 1
At least one input should be equal to 5.
Enter first input: 5
Enter second input: 5
Inputs cannot both be equal to 5.
Enter first input: 3
Enter second input: 5
Logic... if True then break, False then print error message...
Two things... you want logical exclusive or so that True ^ True = False
You aren't storing b. The text you're printing doesn't explain what's happening.
while True:
a = input("Enter first input: ")
b = input("Enter second input: ")
try:
a = int(a) # like the readable code using a not val1...
b = int(b)
if (a != 5) ^ (b != 5): # added parens as suggested
break
else:
print("I'm sorry but it must be a pos int and equal 5")
continue
except ValueError:
print("That's not an int")
Output
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
Enter first input: 1
Enter second input: 5
runfile('...')
Enter first input: 5
Enter second input: 5
I'm sorry but it must be a pos int and equal 5
You could use:
(a == 5 and b != 5) or (a != 5 and b == 5)
Or this:
(a == 5) != (b == 5)
(!= is the boolean equivalent of bitwise xor)
I don't realize what is my mistake, this is how far I got now:
x = 1
e = 0
while x <= 50:
print "Please enter a number (from 1 to 9):"
b = float(raw_input())
asd = 0
if asd == 0:
h = b
l = b
asd = 1
if b < l:
l = b
elif b > h:
h = b
if 1 <= b or b <= 9:
x = x * b
print x
else:
print "Number is too large or too small."
e = e + 1
print "You have reached a value over 50."
print "Highest number entered:", h
print "Lowest number entered:", l
print "Entered numbers:", e
This is the program's output:
Please enter a number (from 1 to 9):
5
5.0
Please enter a number (from 1 to 9):
4
20.0
Please enter a number (from 1 to 9):
5
100.0
You have reached a value over 50.
Highest number entered: 5.0
Lowest number entered: 5.0
Entered numbers: 3
Why is the program giving me 5 instead of 4 as lowest number entered and how can I correct that?
You keep resetting asd each iteration, you need to set the variables outside the loop, I would use a list and that will enable you to get the min/max and number of valid inputs :
nums = [] # hold all nums outside the loop
limit = 1
while 50 >= limit:
num = float(raw_input("Please enter a number (from 1 to 9)")
if 1 <= num <= 9:
limit *= num
nums.append(num) # add all to list
else:
print "Number is too large or too small."
print "You have reached a value over 50."
print "Highest number entered:", max(nums)
print "Lowest number entered:", min(nums)
print "Entered numbers:", len(nums)
Everytime you go through the loop, you are setting asd to 0, causing the if statement below it to execute every single time, so you are always blindly updating l with the value the user just entered, which you have named as b
just for fun :)
def get_float_input(msg="Enter a Number:"):
while True:
try:
return float(raw_input(msg))
except ValueError:
print "Invalid Input Please Enter A Float!"
from itertools import takewhile
my_list = sorted(takewhile(lambda val:val < 50,iter(get_float_input,"Y")))
print "You Have Entered A # Greater than 50"
print "Min:",my_list[0]
print "Max:",my_list[-1]
print "Entered %d Numbers"%len(my_list)
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
for n in number:
a = int(n)
if len(number)!=5 or number>5 or number<0 :
print ('invalid input')
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
My program is checking the 5 digits which are inputted as if they are one number but I want my program to first make sure that 5 digits are inputed and then check if they are between 0 and 5 but the program combines all 5 digits into one number, I want the program to check each element of the list on it's own and before printing anything I want the program to check if the inputted number meets all the conditions and if does not to print (Invalid Input) and stop their
input_list = input("Enter numbers separated by spaces: ")
numbers = input_list.split()
if len(numbers) == 5 and all(0 <= int(n) <= 5 for n in numbers):
print("ok")
print("".join(numbers))
else:
print("invalid")
I use raw_input in python 2. input is fine for python 3.
input_list = raw_input("Enter numbers separated by spaces: ").split()
numbers = [int(n) for n in input_list if 0 <= int(n) <= 5]
if len(numbers) != 5:
print ('invalid input')
for a in numbers:
if a == 0:
print ('.')
else:
print ('x'* a)
input_list = input("Enter numbers separated by spaces: ")
number = input_list.split()
if len(number) == 5:
for n in number:
a = int(n)
if 0< a <=5:
print ('x'* a)
elif a == 0:
print ('.')
else:
print ("Number does not lie in the range 0 to 5.")
else:
print ("Invalid Input.")
Yes, the above works but is should check input first to make sure it is valid
number = raw_input("Enter numbers separated by spaces: ")
2 num_list = number.split()
3 for n in num_list:
4 a = 'True'
5 if int(n) <0 or int(n) >5:
6 a = 'False'
7 break
8 if (len(num_list) == 5) and a == 'True':
9 for n in num_list:
10 b = int(n)
11 if 0< b <=5:
12 print ('x'* b)
13 elif b == 0:
14 print ('.')
15 else:
16 print 'Invalid Input!'