I am supposed to write a function that lets the user put in any string of numbers and then turns that input into an int list (e.g "12635 1657 132651627"). However, I don't know how to change this bit of code so that the user can actually put something into the console. When I try to introduce a new variable Python says that there is no value assigned to it, and I do not know how to work around that. I want everything to be within the function. I managed to introduce a new variable before the start of the function but that's not really my aim here.
def Int_Split(a):
List = []
last = 0
max = len(a)
for i in range (max):
if a[i] =="":
nmbr = a[last:i]
last = i+1
List.append(int(nbmr))
nmbr = a[last:]
List.append(int(nmbr))
return List
print(List)
It isn't clear what your issue is with adding a variable, or entirely what you're after. But if you are after converting "12635 1657 132651627" to [12635, 1657, 132651627], that can be done very simply with:
s = "12635 1657 132651627"
l = [int(x) for x in s.split()]
print(l)
Which yields:
[12635, 1657, 132651627]
Here is an example in a function:
def main():
print("input some numbers:")
s = input()
print([int(x) for x in s.split()])
if __name__ == "__main__":
main()
Here we print the request for input, set the value given to s, then use a list comprehension to say: split a string on any whitespace, then give the integer value for each.
Here is a method without using string.split():
def sep(s):
words = []
word = ""
for c in s:
if c != " ":
word += c
continue
words.append(word)
word = ""
else:
words.append(word)
return words
def main():
print("input some numbers:")
s = input()
print([int(x) for x in sep(s)])
if __name__ == "__main__":
main()
Here we have written a function called sep, which just iterates over characters in the given string until it finds a space or the end, each time adding that group of characters to a list of strings.
Related
I have a (somewhat long) list of words. And a function 1 (linsok(lista, elem)) which asks the user for a word, and if the user-inputted word exists in the list, we get a confirmation in the form of exists/does not exist.
I then have a 2nd function which for any word in the list will create 4 variations of it (creating 4 concatenations of each word) and append these new words to another list. This function will come in handy in my third function, which I am having trouble constructing.
My third function will compare the words in my original list, to the list of my concatenated words. If any word in the concatenated list exists in my orginal list, the function should yield these matches in a list (in the form of [original word, concatenated word] where both are present in the original list). All with the caveat that this third function is to include a function call for the 1st function which asks for user input of a word and produces a confirmation of the word's existence.
I have tried to write the function in the form of for item1 in list 2 and for item2 in list 2 but honestly in pretty lost as to how to construct the function. Especially how/where I am to insert my function call to the first function.
This is the code as it stands now:
`
########## UPPGIFT 1 ##########
#fil = open('ordlista.txt')
lista = open('ordlista.txt').read().split()
#print(lista[::100])
########## UPPGIFT 2 #########
def linsok(lista, elem): #function 1 which returns whether or not a word is present in list
if elem in lista:
print(elem + ' exists')
return True
else:
print(elem + ' exists not')
return False
########## UPPGIFT 3 ##########
def kupering(ord): #function which concatenates the words in question
nylista = []
if ord in lista:
for i in range(len(ord)):
nylista.append((ord[i:len(ord)] + ord[:i]))
#nylista=nylista[1:]
#print(nylista)
return nylista
#def linsok_kup(lista): #funtion 3 which i have trouble with
# def main():
# while elem := input('Ditt ord: '):
# linsok(lista,elem) #u2
#
# #where i would insert my 3rd function
#
# if __name__ == '__main__':
# main()
`
Your explanation is a little unclear but here goes.
Assuming concantenation as in your function is correct.
cat -> [(catc),(catca),(catcat)]
You can simply use a dict to save a lot of time.
def kupering(ord,mydict):
nylista = []
if ord in lista:
for i in range(min(len(ord),3)):
nylista.append(ord[i:len(ord)] + ord[:i])
try:
mydict[ord[i:len(ord)] + ord[:i]].append(ord) #child has not been made before
except:
mydict[ord[i:len(ord)] + ord[:i]] = [ord] #concantenated word has been made before
return nylista, mydict #we return your 'list' and also our 'dict of children and their parents'
The dict now contains all your 'root' words and their children.
This then forces the condition that if the child exists, yield result IFF parent exists.
def new_function(user_input, mydict,lista):
test = linsok(user_input,lista) #use your function to see if word exist
if test == True:
#I guess we want if this is true
eval = mydict[user_input]
if len(eval)==0: #Case were it doesnt exist in 'concantenated words"
print("I do not exist in children")
return None #leave the fucntion with nothing
outputs = []
for word in eval: #alternate case is if it does exist
result = linsok(lista,word) #do parent of word exist in lista
if result == True:
print([eval,user_input]) #if yes we add to our outputs
output.append([eval,user_input])
return output
else:
return None
#Covers scenario where a child can have multiple parents I think. abab -> ababa,ababab... , aba -> abab, ababa,ababab....
From your description, I'm not sure what the result of linsok() in the third functions is used for.
I also assume that all the words in lista are at least four characters long, since a word with less than four characters would not give 4 variations.
lista = ["hello", "dogs", "cars", "scar"]
concact_lst = kupering("cars")
def third_func(concact_lst):
user_input = input("Enter word: ")
word_exists = linsok(lista, user_input)
result = []
for i in range(len(concact_lst)):
for j in range(len(lista)):
if concact_lst[i] == lista[j]:
result.append([lista[j], concact_lst[i]])
return result
print(third_func(concact_lst))
output: [['cars', 'cars'], ['scar', 'scar']]
I had the assignment to create a function which would allow the user to input a string of numbers and then receive that string as an int list. I was also supposed to use string slicing for this particular function. That being said I couldn't come up with anything fancy and this is what I wrote:
def Split_to_Integers():
print("Put in a string:")
Input = str(input())
List = []
List.append(Input)
print(List)
It is nothing fancy but it somehow got the job done. However, I also have the official solution which looks as follows:
def split_to_integers(inputstr):
res = []
last = 0
max = len(inputstr)
for i in range(max):
if inputstr[i] == " ":
nmbr = inputstr[last:i]
last = i+1
res.append(int(nmbr))
nmbr = inputstr[last:]
res.append(int(nmbr))
return res
The second function works when I put in one integer, however, as soon as I put in a second one, the function crashes, and I dont know where the Problem is.
You can use the split function of strings. Like so:
def list_from_string(number_string: str):
ints = [int(item) for item in number_string.split(" ")]
return ints
if __name__ == "__main__":
s = input("Enter the string: ")
result = list_from_string(s)
print(result, type(result))
This is the behavior in a console:
Enter the string: 6 5 4
[6, 5, 4] <class 'list'>
So i was solving a question that is in my Lab practical Syllabus. Below is the question:-
Write a python class to reverse a sentence (initialized via
constructor) word by word. Example: “I am here” should be reversed as
“here am I”. Create instances of this class for each of the three
strings input by the user and display the reversed string for each, in
descending order of number of vowels in the string.
Below is code for the implementation of above question:-
class sentenceReverser:
vowels = ['a','e','i','o','u']
vowelCount =0
sentence=""
reversed_string = ""
def __init__(self,sentence):
self.sentence = sentence
self.reverser()
def reverser(self):
self.reversed_string = " ".join(reversed(self.sentence.split()))
return self.reversed_string
def getVowelCount(self):
for i in self.sentence:
if i.lower() in self.vowels:
self.vowelCount += 1
return self.vowelCount
inp = []
for i in range(2):
temp = input("Enter string:- ")
ob = sentenceReverser(temp)
inp.append(ob)
sorted_item = sorted(inp,key = lambda inp:inp.getVowelCount(),reverse=True)
for i in range (len(sorted_item)):
print('Reversed String: ',sorted_item[i].reverser(),'Vowel count: ',sorted_item[i].getVowelCount())
Below is output i am getting for the above code:-
issue:-
Could someone tell me why i am getting double the vowel count???
Any help would be appreciated!!
You are calling getVowelCount() twice. Instead you can use the variable instead of calling in the print command
for i in range (len(sorted_item)):
print('Reversed String: ',sorted_item[i].reverser(),'Vowel count: ',sorted_item[i].vowelCount)
This is because you don't reset vowel count in the method. So if you execute the method once (here in sort), you'll get correct count. If you execute it twice (in printing), you will get twice as much. If you execute it once more, you'll get 3x correct amount. And so on.
The solution is to reset the number:
def getVowelCount(self):
self.vowelCount = 0
for i in self.sentence:
if i.lower() in self.vowels:
self.vowelCount += 1
return self.vowelCount
Or to calculate it only once - set it to None, then calculate only if self.vowelCount is None, otherwise return existing value.
I'm trying to solve a hacker rank challenge:
Given a string, s , of length n that is indexed from 0 to n-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings. on a single line (see the Sample below for more detail)
link: https://www.hackerrank.com/challenges/30-review-loop/problem
Error:
for example:
The input "adbecf" should output "abc def"
When I run python Visualizer my code seem to have the correct output.. but on hacker rank it's saying I have the wrong answer. Does anyone know what might be wrong with my code.
This is the code I tried -
class OddEven:
def __init__(self, input_statement):
self.user_input = input_statement
def user_list(self):
main_list = list(user_input)
even = []
odd = []
space = [" "]
for i in range(len(main_list)):
if (i%2) == 0:
even.append(main_list[i])
else:
odd.append(main_list[i])
full_string = even + space + odd
return(full_string)
def listToString(self):
my_string = self.user_list()
return(''.join(my_string))
if __name__ == "__main__":
user_input = str(input ())
p = OddEven(user_input)
print(p.listToString())
First of all, input is always string, you don't need to convert it here.
user_input = str(input())
Each line is provided to you as separate input. Number of strings equal to num in the first line. In this case 2, so...
count = input()
for s in range(int(count)):
...
user_input variable inside user_list function should be accessed as self.user_input, it's a property of an object, which you pass to function as self.
Also you can iterate over list directly.
Here:
full_string = even + space + odd
you're trying to concatenate list, which is not a good idea, you'll still get a list.
You can join list with separating them with some string using join string method.
' '.join(list1, list2, ..., listN)
It's better do define odd and even as empty strings.
And then join them the using concatenation (+).
Here:
if (i%2) == 0
you don't have to compare with 0. Python will evaluate what's to the right from condition as True or False. So:
if i % 2:
...
There is simpler solution:
def divide(self):
odd = even = ''
for i, c in enumerate(self.user_input):
if i % 2:
odd += c
else:
even += c
return even + ' ' + odd
Here is the simple code for this problem:)
T=int(input())
for i in range(0,T):
S=input()
print(S[0::2],S[1::2])
So I'm a little confused as far as putting this small code together. My teacher gave me this info:
Iterate over the string and remove any triplicated letters (e.g.
"byeee mmmy friiiennd" becomes "bye my friennd"). You may assume any
immediate following same letters are a triplicate.
I've mostly only seen examples for duplicates, so how do I remove triplicates? My code doesn't return anything when I run it.
def removeTriplicateLetters(i):
result = ''
for i in result:
if i not in result:
result.append(i)
return result
def main():
print(removeTriplicateLetters('byeee mmmy friiiennd'))
main()
I have generalized the scenario with "n". In your case, you can pass n=3 as below
def remove_n_plicates(input_string, n):
i=0
final_string = ''
if not input_string:
return final_string
while(True):
final_string += input_string[i]
if input_string[i:i+n] == input_string[i]*n:
i += n
else:
i += 1
if i >= len(input_string):
break
return final_string
input_string = "byeee mmmy friiiennd"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
# bye my friennd
You can use this for any "n" value now (where n > 0 and n < length of input string)
Your code returns an empty string because that's exactly what you coded:
result = ''
for i in result:
...
return result
Since result is an empty string, you don't enter the loop at all.
If you did enter the loop you couldn't return anything:
for i in result:
if i not in result:
The if makes no sense: to get to that statement, i must be in result
Instead, do as #newbie showed you. Iterate through the string, looking at a 3-character slice. If the slice is equal to 3 copies of the first character, then you've identified a triplet.
if input_string[i:i+n] == input_string[i]*n:
Without going in to writing the code to resolve the problem.
When you iterate over the string, add that iteration to a new string.
If the next iteration is the same as the previous iteration then do not add that to the new string.
This will catch both the triple and the double characters in your problem.
Tweaked a previous answer to remove a few lines that were not needed.
def remove_n_plicates(input_string, n):
i=0
result = ''
while(True):
result += input_string[i]
if input_string[i:i+n] == input_string[i]*n:
i += n
else:
i += 1
if i >= len(input_string):
break
return result
input_string = "byeee mmmy friiiennd"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
# bye my friennd
Here's a fun way using itertools.groupby:
def removeTriplicateLetters(s):
return ''.join(k*(l//3+l%3) for k,l in ((k,len(list(g))) for k, g in groupby(s)))
>>> removeTriplicateLetters('byeee mmmy friiiennd')
'bye my friennd'
just modifying #newbie solution and using stack data structure as solution
def remove_n_plicates(input_string, n):
if input_string =='' or n<1:
return None
w = ''
c = 0
if input_string!='':
tmp =[]
for i in range(len(input_string)):
if c==n:
w+=str(tmp[-1])
tmp=[]
c =0
if tmp==[]:
tmp.append(input_string[i])
c = 1
else:
if input_string[i]==tmp[-1]:
tmp.append(input_string[i])
c+=1
elif input_string[i]!=tmp[-1]:
w+=str(''.join(tmp))
tmp=[input_string[i]]
c = 1
w+=''.join(tmp)
return w
input_string = "byeee mmmy friiiennd nnnn"
output_string = remove_n_plicates(input_string, 3)
print(output_string)
output
bye my friennd nn
so this is a bit dirty but it's short and works
def removeTriplicateLetters(i):
result,string = i[:2],i[2:]
for k in string:
if result[-1]==k and result[-2]==k:
result=result[:-1]
else:
result+=k
return result
print(removeTriplicateLetters('byeee mmmy friiiennd'))
bye my friennd
You have already got a working solution. But here, I come with another way to achieve your goal.
def removeTriplicateLetters(sentence):
"""
:param sentence: The sentence to transform.
:param words: The words in the sentence.
:param new_words: The list of the final words of the new sentence.
"""
words = sentence.split(" ") # split the sentence into words
new_words = []
for word in words: # loop through words of the sentence
new_word = []
for char in word: # loop through characters in a word
position = word.index(char)
if word.count(char) >= 3:
new_word = [i for i in word if i != char]
new_word.insert(position, char)
new_words.append(''.join(new_word))
return ' '.join(new_words)
def main():
print(removeTriplicateLetters('byeee mmmy friiiennd'))
main()
Output: bye my friennd