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'>
Related
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.
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])
I am working on my homework and I am a complete newbie to this.
Please help and explain in detail.
def conexclast(strlst):
output = ""
for elem in strlst:
strng = str(elem)
output = output+strng
return ' '.join(strlst([0:-1]))
print("Enter data: ")
strlst= raw_input()
print(conexclast(strlst))
I dont know how to get the solution.
def conexclast(strlst):
'''
function to concatenate all elements (except the last element)
of a given list into a string and return the string
'''
output = ""
for elem in strlst:
strng = str(elem)
output = output+strng
return ' '.join(strlst[0:-1])
print("Enter data: ")
strlst = raw_input().split()
print(conexclast(strlst))
The main correction is splitting the user's input raw_input().split() and:
return ' '.join(strlst[0:-1])
that slices the string, just need to remove the parentheses
See more for str.split() and string slicing
This sounds so simple, but I cannot find anything on how to do this on the internet. I've gone through documentation but that didn't help me.
I have to get inputs from the user to create a list. This is what I am using right now.
t = raw_input("Enter list items: ")
l = map(str,t.split())
But this is converting every element into a string. If I use int in map function, then every element would be converted to int.
What should I do? Is there any other function that I am missing?
You can use a list comprehension to only call int on the strings which contain nothing but numerical characters (this is determined by str.isdigit):
t = raw_input("Enter list items: ")
l = [int(x) if x.isdigit() else x for x in t.split()]
Demo:
>>> t = raw_input("Enter list items: ")
Enter list items: 1 hello 2 world
>>> l = [int(x) if x.isdigit() else x for x in t.split()]
>>> l
[1, 'hello', 2, 'world']
>>>
use try/except. Try to make it an int. If that fails, leave it as a string.
def operation(str):
try:
val = int(str)
except ValueError:
val = str
return val
t = raw_input("Enter list items: ")
l = map(operation,t.split())
print l
You can use a list comprehension rather than map for more "pythonic" code:
t = raw_input("Enter list items: ")
l = [operation(x) for x in t.split()]
Edit: I like iCodez's better... the isDigit test is nicer than try except.
I'm trying to do a for loop with [i] number of similar functions in Python:
i = int(raw_input())
for i in range (0, i):
myfunction[i] = str(raw_input())
And I'm getting an error that it isn't defined. So I'm defining it.... How do I define [i] number of similar functions?
larsmans answer can also be implemented this way:
def make_function(x):
def function(y):
return x + y
return function
functions = [make_function(i) for i in xrange(5)]
# prints [4, 5, 6, 7, 8]
print [f(4) for f in functions]
Updated
From the edit and all the comments it seems that you want to ask the user for a number N and then ask for N strings and have them put into a list.
i = int(raw_input('How many? '))
strings = [raw_input('Enter: ') for j in xrange(i)]
print strings
When run:
How many? 3
Enter: a
Enter: b
Enter: c
['a', 'b', 'c']
If the list comprehension seems unreadable to you, here's how you do it without it, with some comments:
i = int(raw_input('How many? '))
# create an empty list
strings = []
# run the indented block i times
for j in xrange(i):
# ask the user for a string and append it to the list
strings.append(raw_input('Enter: '))
print strings
You can't set list items by index, try:
myfunction = []
for i in range(0, 5):
myfunction.append(whatever)
I'm not sure what you want here, but from all that you said, it appears to me to be simply this:
def myfunction(j):
for i in range(j):
variable.append(raw_input('Input something: '))
I still think this may not be what you want. Correct me if I am wrong, and please be a little clear.
myfunction[i] is the i'th element of the list myfunction, which you have not already defined; hence the error.
If you want a sequence of functions, you can try something like this:
def myfunction(i,x):
if i==0:
return sin(x)
elif i==1:
return cos(x)
elif i==2:
return x**2
else:
print 'Index outside range'
return
If you need similar functions that have something to do with i, it gets simpler, like this example:
def myfunction(i,x):
return x**i