linear search in python programming - python

I have wriiten a code for linear search in python language. The code is working fine for single digit numbers but its not working for double digit numbers or for numbers more than that. Here is my code.
def linear_search(x,sort_lst):
i = 0
c= 0
for i in range(len(sort_lst)):
if sort_lst[i] == x :
c= c+1
if (c > 0):
print ("item found")
else :
print ("not found")
sort_lst= input("enter an array of numbers:")
item= input("enter the number to searched :")
linear_search(item,sort_lst)
any suggestions ?

Replace
sort_lst= input("enter an array of numbers:")
with:
print 'enter an array of numbers:'
sort_lst= map(int, raw_input().strip().split(' '))

If all you want is a substring search, you can just use this
print("item found" if x in sort_lst else "not found")
If you want to get more complicated, then you need to convert your input from a string to an actual list.
(assuming space separated values)
sort_lst= input("enter an array of numbers:").split()
Then, that's actually a list of strings, not integers, but as long as you compare strings to strings, then your logic should work
Note: the print statement above will still work in both cases

This may be a case of confusion between behavior in python 2.x and python 3.x, as the behavior of the input function has changed. In python 2, input would produce a tuple (12, 34) if you entered 12, 34. However, in python 3, this same function call and input produces "12, 34". Based on the parenthesis in your prints and the problem you're having, it seems clear you're using python 3 :-)
Thus when you iterate using for i in range(len(sort_lst)):, and then looking up the element to match using sort_lst[i], you're actually looking at each character in the string "12, 34" (so "1", then "2", then ",", then " ", etc.).
To get the behavior you're after, you first need to convert the string to an actual list of numbers (and also convert the input you're matching against to a string of numbers).
Assuming you use commas to separate the numbers you enter, you can convert the list using:
sorted_int_list = []
for number_string in sort_list.split(","):
sorted_int_list = int(number_string.strip())
If you are familiar with list comprehensions, this can be shortened to:
sorted_int_list = [int(number_string.strip()) for number_string in sort_list.spit(",")]
You'll also need:
item = int(item.strip())
To convert the thing you're comparing against from string to int.
And I'm assuming you're doing this to learn some programming and not just some python, but once you've applied the above conversions you can in fact check whether item is in sorted_int_list by simply doing:
is_found = item in sorted_int_list
if is_found:
print ("Found it")
else:
print ("Didn't find it :-(")
Notes:
"12, 34".split(",") produces ["12", " 34"], as the split function on strings breaks the string up into a list of strings, breaking between elements using the string you pass into it (in this case, ","). See the docs
" 12 ".strip() trims whitespace from the ends of a string

Related

User Input Slice String

stringinput = (str(input("Enter a word to start: ")))
removeinput = (str(input("How many character's do you want to remove?")))
if (str)(removeinput) > (str)(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[-1,-removeinput,1]
print((str)(removed))
Traceback (most recent call last):
File "C:\Users\x\PycharmProjects\pythonProject\Pynative Beginner Tasks.py", line 110, in <module>
removed = stringinput[-1,-removeinput,1]
TypeError: bad operand type for unary -: 'str'
I am doing an exercise to create an input that slices a string.
I understand that removeinput needs to be converted to a string to be part of the slice but I don't know how to convert it in the else statement.
I also need it to be a string to make a comparison incase the user inputs a number greater than the amount of chars in stringinput
It looks like you might be trying to take a slice from anywhere in the string, in which case you would need to get an input for the starting index and an ending index. In the example below I wrote it to remove the number of characters from the end of the string so if you input "hello" and "2" you are left with "hel". This behavior could be modified using the tutorial I have attached below.
Here's a modified version of your code with comments to explain the changes:
stringinput = input("Enter a word to start: ")
removeinput = int(input("How many character's do you want to remove? ")) // the int() function converts the input (a string) into an integer
if removeinput > len(stringinput):
print("Cannot remove more chars than there are chars, try again")
else:
removed = stringinput[:-removeinput] // remove the last characters based on the input
print(removed)
In your code you use (str)(removeinput) and (str)(stringinput). It looks like you are trying to cast the variables as strings, but this is not necessary as both of them are already strings by default. In the modified code I converted the input into an integer using int(). This is because your input is not an integer, it is the string version of the integer. By using int(), we are comparing the integer version of the input.
To address the error that you were getting, the syntax that you are using is not correct. Strings are indexed using colons in Python, not commas. Here is a tutorial that might help you: https://www.digitalocean.com/community/tutorials/how-to-index-and-slice-strings-in-python-3
I hope this helps!

Part 2, Remove All From String problem in python

I can't figure out what I need to add to make my code work, this is what I have:
my_string = input("Enter a word: ")
part_to_remove = input("Enter a part of the word to remove: ")
def remove_all_from_string(my_string):
while my_string != "bas":
index = my_string.find(part_to_remove)
return index
print remove_all_from_string(my_string)
I can't figure out what to add next, the test cases tells me to
Use the find function
Use a while loop
Use string concatenation
Use string indexing
Use the len function
Test the code with "bananas"
Test the code by replacing "na"
With the specified test info your code should return "bas"
I don't know what I could possibly do to match these and still make the code work
You can simply use the replace function of strings:
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
my_string = my_string.replace(paet_to_remove, "")
I am not going to write that code for you, but I will try to clarify some of the pointers:
use find and string indexing (actually string slicing) to get the part of the string before the part to remove
use find, len, and string slicing to get the part after the part to remove
use string concatenation to combine them and replace the original string
use while and find to continue while the part to remove exists in the string
test the function with parameters "bananas" and "na", and compare the result to "bas", but do not "hard-code" any of that into your function
With those steps, you should be able to write the function on your own.
Similar to the answer of #kevin
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
print( ''.join(my_string.split(paet_to_remove)) )

How to return an ordered string from an unordered one?

I am trying to solve a problem but struggling with the logic approach to it. The problem is as follows:
"Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers."
For e.g. "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
I have tried the following so far:
def order(sentence):
my_string = "is2 Thi1s T4est 3a"
new_string = " "
for i in my_string:
if i in my_string == none
return new_string = " "
else:
if i in my_string
return new_string
But stuck on continuing the next bit. How can I put "put words into order starting from 1" into python code into my for loop?
I'm a beginner in python and programming so I am not entirely sure if the approach I'm making is the best logical way to do so, by creating an empty string new_string and then sorting my_string into that. Is this a good way of approaching this? I am stuck on which direction to go after this.
you could do :
r = "is2 Thi1s T4est 3a"
def get_number(w) :
for x in w :
try :
i = int(x)
return i
except :
pass
return None
ordered_list = " ".join((sorted( s.split(' ') , key = get_number)))
the function get_number allows to get the first number appearing in a word, so we split the sentence to get the words it's made of , r.split(' ') gives ['is2', 'Thi1s', 'T4est', '3a'], we order then the list using ordered builtin function , it takes a list and a function that yields the keys over which we want to order the list, and outputs the ordered list, we then use the builtin function join to join the list using a space separator.
Output :
Out[425]: 'Thi1s is2 3a T4est'

char is getting printed instead of integer in python

Hey guys I'm a newbie in python programming. As the title suggests char is getting printed instead of integer for the following code snippet. Thanks.
nl=[]
inp=raw_input()
if inp.isdigit():
list=inp.split()
for s in list:
nl.append(int(s))
print nl
For example if I give an input as 1 2 3 the output obtained is ['1','2','3'] but the expected output is [1,2,3]. I want to print the answer in a list form.
Try this:
nl = [int(n) for n in raw_input().split(' ') if n.isdigit()]
print nl
You have to split the input before to use str.isdigit() because '1 2 3' is not a digit.
Warning: if the numbers can be floating point numbers, you should use a regex instead of str.isdigit()
Being a novice myself, I can somewhat understand your situation.
So lets solve all the issues here:
inp will take a string from the user. Ex: "12345", "12 45" etc.
inp.isdigit() checks whether the string inp is composed of digits or not. Mind you, we are strictly speaking about digits (no other special characters).
Ex: "12345".isdigit() returns True while "12 45".isdigit() returns False.
inp.split() will return a list of words (or items) separated by a white space. Since, isdigit() and split() are contradicting each other, you are not getting a correct answer for "12 45" (or anything like this).
Hope you get my point.
Tip : Don't use list are a variable name. The code may work fine but it is not conventional.
I like the list comprehension above but here's the same thing (without the use of isdigit) using a for loop-
nl = []
inp = raw_input()
lst = inp.split(' ')
for s in lst:
nl.append(int(s))
print nl
A couple of quick points. Spaces before and after the equal sign (=) improves readability. You probably should avoid using list as a variable name since list is a built-in function. raw_input returns a string so "if inp.isdigit()" will always return false in your code.

split string update numbers only

I have a function using raw_input getting a sentence from user. Then my second function splits the sentence so I am only trying to update the numbers on the sentence. This is the split sentence:
['You', 'are', '42', 'this', 'year']
I am trying to update 42 to 43 do a return and print 'You are 43 this year'
I am able to pull the number by using isdigit() but I can't increase it. This is what I have so far:
def GetDigits(sentence):
for i in sentence:
if i.isindigit():
i = i +1
return sentence
Numbers in Python are immutable objects, so when you do i = i+1, you are creating a new object. This new object is not part of your original sentence object. Also, '42' is a string. You can't apply numeric add operation on it. You need to convert it to an integer first.
This is what you need -
def GetDigits(sentence):
for idx, value in enumerate(sentence):
if value.isdigit():
sentence[idx] = int(value) +1
return sentence
There is a built in method for strings that would be much better for this, format()
age = raw_input('How old are you?')
sentence = 'You are {} this year'
print(sentence.format(age))
If you need to update it you can:
print(sentence.format(int(age) + 1))
Alternatively as function utilizing a generator comprehension:
def get_digits(sentence):
return ' '.join(str(int(word) + 1) if word.isdigit() else word for word in sentence.split())
Another hacky way through regex using re module,
import re
sentence = input("Enter the sentence : \n")
def GetDigits(sentence):
L = []
for i in sentence.split():
if re.match(r'\d+$', i):
i = int(i)+1
L.append(str(i))
else:
L.append(i)
sentence = ' '.join(L)
return(sentence)
print(GetDigits(sentence))
Output:
Enter the sentence :
You are 42 this year
You are 43 this year
You're trying to add 1 to a string, as '42' isn't the same as 42.
You need to change '42' to an int first using int(v), then increase it.
def GetDigits(sentence):
for i, v in enumerate(sentence):
if v.isdigit():
sentence[i] = str(int(v) + 1)
return sentence
The key issue here is that you're trying to find a function that lets you know when it's safe/correct to convert a string to an int—but there is no such function. There are various approximations, but the simplest thing to do is just try to convert the string. This is a general principle in Python, EAFP: Easier to Ask Forgiveness than Permission. The language has been designed around the fact that the way to check whether something will work is to just do it, then handle the case where it didn't work (normally meaning an exception). Trying to fight that design is just going to make your life harder.
But that's not the only issue; there are multiple problems here.
isindigit isn't a method of strings. Maybe you meant isdigit?
isdigit doesn't give you the right answer for, say, -3—or, for that matter, integers in non-Western scripts (which may return true for isdigit but not actually be interpretable as integers by Python).
Just because i is a string representing an integer doesn't mean it's an integer; it's still a string, and i + 1 is still a TypeError. You need to call int(i) to get its value as a number.
Just reassigning to i doesn't affect sentence at all. All you're doing is making the local variable i into a name for a different value. You need to do something with that i—either build a new sentence, or modify the sentence in-place (e.g., by using enumerate to keep track of the index, so you can do sentence[index] = …).
While it isn't clear what you're doing with the results, I'll bet you actually want to get strings back, not a mix of strings and integers, so you'll probably want to convert back to str after adding 1.
So, what you want is something like this:
def GetDigits(sentence):
new_sentence = []
for i in sentence:
try:
i = str(int(i) + 1)
except ValueError:
pass
new_sentence.append(i)
return new_sentence
However, this might be a little too clever as written. If i doesn't represent an integer, int(i) will raise a ValueError, meaning i is still referring to the original string, which we add to new_sentence. Otherwise, we'll convert it to an integer, add 1, convert back to a string, and make i refer to this new string, which we add to new_sentence. If you don't understand why new_sentence.append(i) always does the right thing, you should rewrite it more explicitly.

Categories

Resources