Linear Search - Matching integer with list - python

Hi am new to python here is what am trying to do , i have this below list.
x= [1,2,3,4,5,6,7,8,9]
and here is my python code:
length = len(x)
c = input("Enter a no\n")
for i in range (length):
if x[i] == c:
print ("Found at position ", i)
else:
print("not found")
and the output am receiving.
Enter a no
2
not found
not found
not found
not found
not found
not found
not found
not found
not found
Now with my very few little knowledge what i figured out is this multiple not found is happening because every time loop takes a no checks with the list and if its not available its moving to else part due to lack no proper beak statement but what am not able to figure out that when it takes to in x[i] its matching then output should be Found at position 1 . i read somewhere need to use if c in x[i] but it didn't work. on the hand i re-wrote the code.
def ls():
t = int(input("Enter your search no \n"))
for i in x:
if i!= t:
continue
print("Your value is present in ")
break
else:
print ("parrrrrrrrrrr")
ls()
which is working all good. It will be of help if i can get to know:
with 1st program why its showing not found even the input is present in the list
the part where c in x[i] was entered same issue happened as per my knowing (which now makes no-sense) it should also work
if it is the case of integer vs list then how my 2nd code is working
-is it the rigt way to do linear search.

Because input returns you a str object and then compared with int object without implicit conversion, so the expression always be False.
c in x where x is a list works, but x[i] is an integer in your case
2nd code is working because you convert the input into int implicitly
The most elegant way in my opinion is:
c = input("Enter a no\n")
items = [1,2,3]
print(items.index(int(c)) if int(c) in items else 'Not found')
And of course dont forget to catch ValueError if input is not convertable into integer

Related

Is list comprehension possible in this line of code of mine

I am still fairly new to Python, but I am getting more and more obsessed with shortening my code as much as possible, but I cannot figure out how to do that with this piece of code of mine. Is it possible to use list comprehension to shorten the following code at all? Also how do i edit my code so that the spaces and indentation show properly on stack overflow?
user_input = input("Please guess a number: ")
correct_number_list = [4,5,7,1]
if user_input[0] in correct_number_list and user_input[1] in correct_number_list\
and user_input[2] in correct_number_list and user_input[3] in correct_number_list :
in_range = True
else:
in_range = False
This is only a small portion of the code but it is hurting my eyes as I know there must be a better way to write this. In my original code I randomly generate 4 random numbers and store them in a list and have the user guess the numbers.
Any help or suggestions on how to shorten this code even if it does not relate to list comprehension will be great. Thank you in advance
in_range = all(x in correct_number_list for x in user_input)
Note that similar to your original code this does not correctly check the result because the player wins if they get one of the digits correct and use it for all digits of the number to guess.
Also, the value from input() is str so comparison with number is going to always be False if your generated number is a list of int such as if you do:
correct_number_list = [4,5,7,1]
Instead, you can sort the char in the strings then check that the strings match:
rand_number = sorted(str(generate_number_4digits()))
guess = sorted(input('Enter 4 digit num: '))
win = guess == rand_number

basic encryption in python using loop and if elif

I am trying to make a caesar cipher encryption program in python using loop and if/elif, but I my program returns unwanted results. There may be a little error in my programming logic and maybe someone wants to help me to fix it.
this input :
caesar
2
and should show an output:
ecguct
but my program show output : caesar #thats wrong
This my code I'm trying:
x = []
ch = ""
i = 0
x = input(" enter words : ")
y = int(input("enter number : "))
for i in range(len(x)):
i+1
ch = x[i]
if(ord(ch)>=ord('a') and ord(ch)<=ord('z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('z')):
(ord(ch)- ord('z')-ord('a')-1)
x[i]=ch
elif(ord(ch)>=ord('A') and ch<=ord('Z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('Z')):
(ord(ch)- ord('Z')+ord('A')-1)
x[i]=ch
print(x)
I feel unsure about iteration that I made i+1 , and also x[i]=ch it's right syntax?. Also I use ord() to change value string to integer. I need your opinion to fix it.
You got several bugs in your code. First of all you have to turn your calculations to char again using the chr() function. Sometimes you do, sometimes you don't. Then you can't index strings - here x[i]=ch. Instead you have to assign your result to a new string using += operator or some other append method. At last your if and elif does not cover the overflows it should. In case you input a string with a letter y, z, Y or Z it will overflow. The if-questions covering those overflows need to be nested inside the top level if-elif which processes the different upper case and lower case letters.
There is also a minor bug within the overflow calculation where you use a - minus instead of a + plus operation.
Here is the slightly fixed version of your code:
x = input(" enter words : ")
y = int(input("enter number : "))
y = y % 26 # limit y to the amount of possible letters
result = ""
for ch in x:
if(ch>='a' and ch<='z'):
ch = chr(ord(ch)+y)
if(ch>'z'):
ch = chr(ord(ch)- ord('z')+ord('a')-1)
elif(ch>='A' and ch<='Z'):
ch = chr(ord(ch)+y)
if(ch>'Z'):
ch = chr(ord(ch)- ord('Z')+ord('A')-1)
result += ch
print("input:", x)
print("output:", result)
You also can iterate directly over the letters of a string like 'for ch in x' does without the need of extra indexing with x[i]. The ord(...) function is not required for comparison of characters.
Some further shrinking:
x = input(" enter words : ")
y = int(input("enter number : "))
result = "".join ( [ [ # encrypting a string by adding a number to all letters
c, chr((ord(c)-ord('Aa'[c.islower()])+y)%26+ord('Aa'[c.islower()]))
] [ c.isalpha() ] for c in x ] )
print("output:", result)
This code is harder to read and should cover some remarks on what it actually does. If you have some more code, shrinking might make it easier to understand because otherwise you have tons of files and modules within a project.

finding an element in an array based on user input [duplicate]

This question already has answers here:
Finding the index of an item in a list
(43 answers)
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
Hi new to python and programming in general
I'm trying to find an element in an array based on user input
here's what i've done
a =[31,41,59,26,41,58]
input = input("Enter number : ")
for i in range(1,len(a),1) :
if input == a[i] :
print(i)
problem is that it doesn't print out anything.
what am I doing wrong here?
input returns a string. To make them integers wrap them in int.
inp=int(input('enter :'))
for i in range(0,len(a)-1):
if inp==a[i]:
print(i)
Indices in list start from 0 to len(list)-1.
Instead of using range(0,len(a)-1) it's preferred to use enumerate.
for idx,val in enumerate(a):
if inp==val:
print(idx)
To check if a inp is in a you can this.
>>> inp in a
True #if it exists or else False
You can use try-except also.
try:
print(a.index(inp))
except ValueError:
print('Element not Found')
input returns a string; a contains integers.
Your loop starts at 1, so it will never test against a[0] (in this case, 31).
And you shouldn't re-define the name input.
Please don't declare a variable input is not a good practise and Space is very important in Python
a =[31,41,59,26,41,58]
b = input("Enter number : ")
for i in range(1,len(a),1):
if int(b) == a[i] :
print(i)
I think you want to check a value from your list so your input need to be a Int. But input takes it as String. That's you need to convert it into int.
input is providing you a str but you are comparing a list of ints. That and your loop starts at 1 but your index starts at 0

python help! If/else statement

I have been learning python through code academy. It asked me to create a if else statement that prints the users input, but if there is no input print "empty". I did pass the tutorial but when there is a user input it prints both the users input and "empty".
here is my code:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len("original")
if length > 0:
print original
else: length < 0
print "empty"
Notice that print under else is not indented. I thought you had to indented it, but when i do it gives me an error.
You seem to have a couple issues with your code. First I believe you should change your assignment of length to:
length = len(original)
That way you get the correct length of the string you binded to the name original. If you use len("original"), you will pass the string "original" to the len() function, and it will just count the characters in that string. Regardless of what the user of your program inputted, your length will always be 8, since that's how many characters are in the string "original"
Also keep in mind that the len() function will never return a negative value. So testing if length < 0 doesn't make sense. You probably wanted to test if it equals 0. It seems as if you were trying to use an elif statement.
Try:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
elif length == 0:
print "empty"
elif statements let you test conditions just like if statements. elif is short for "else if".
Furthermore, as #chepner pointed out in the comments, there is no need to even test the second condition at all. You can just as easily go with:
else:
print "empty"
The else syntax is not followed by any condition. It automatically enters the indented block of code if the other conditions evaluate to False.
Was the length < 0 intended to be a comment? You need the comment character #.
else: # length < 0
print "empty"
It's wrong anyway, it should be length <= 0.
Without a comment character it was being interpreted as the statement to use as the else clause. It didn't create an error since length < 0 just generates a boolean result that you didn't do anything with, but it prevented you from having another statement as part of the else.
else: length < 0
print "empty"
should be
elif length == 0:
print "empty"
Python has significant whitespace, things that are indented the same are in the same scope.
First off, it is not len("original") it is len(original). If you use quotes you are making it a constant value, "original", rather than a variable named original.
Second, instead of checking the length of the string you should use this
if original:
# Type here what happens if the string is not empty
else:
# Here what happens if the string is empty
By Python standard any collection, including strings, equals false if it is empty(aka contains no elements) and true if it contains any elements.
There is a a statement after else.
else: length < 0
print "empty"
Maybe you are looking for an (elif is another way to check another condition after the if if the previous if fails.)
elif length <= 0:
or just a plain
else:
print "empty"
it will never go past zero anyways you could have a == conditional for zero and it would work.
elif length == 0:
this is probably the best way there is no need to check another condition.
if length > 0:
print original
else:
print "empty"
also just a side note length = len("original")
there is not suppose to be quotation marks around original because its a variable :). You will just be getting the string "original" not the actual stuff inside of the variable.
The end result ..
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
length = len(original)
if length > 0:
print original
else:
print "empty"
To check if there is an item in a list, simply do this:
if List_name:
{code here}
...
So, your code should very simply look like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("what is your name?")
if original:
print original
else:
print "Empty"
It's that easy :D

Advice on python program

So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounded by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { } is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once
and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")

Categories