How do I make 'i' number of functions in python? - python

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

Related

String to int function

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'>

Hacker rank string separated challenge

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])

How to input a list in Python?

Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!
Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.
In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.

how can i compare string within a list to an integer number?

my task today is to create a function which takes a list of string and an integer number. If the string within the list is larger then the integer value it is then discarded and deleted from the list. This is what i have so far:
def main(L,n):
i=0
while i<(len(L)):
if L[i]>n:
L.pop(i)
else:
i=i+1
return L
#MAIN PROGRAM
L = ["bob", "dave", "buddy", "tujour"]
n = int (input("enter an integer value)
main(L,n)
So really what im trying to do here is to let the user enter a number to then be compared to the list of string values. For example, if the user enters in the number 3 then dave, buddy, and tujour will then be deleted from the list leaving only bob to be printed at the end.
Thanks a million!
Looks like you are doing to much here. Just return a list comprehension that makes use of the appropriate conditional.
def main(L,n):
return([x for x in L if len(x) <= n])
Just use the built-in filter method, where n is the cut off length:
newList = filter(lambda i:len(i) <= n, oldList)
You should not remove elements from a list you are iterating over, you need to copy or use reversed:
L = ["bob", "dave", "buddy", "tujour"]
n = int(input("enter an integer value"))
for name in reversed(L):
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
Making a copy using [:] syntax:
for name in l[:]:
# compare length of name vs n
if len(name) > n:
# remove name if length is > n
L.remove(ele)
print(L)
This is a simple solution where you can print L after calling the main function. Hope this helps.
def main(L,n):
l=len(L)
x=0
while x<l:
#if length is greater than n, remove the element and decrease the list size by 1
if len(L[x])>n:
L.remove(L[x])
l=l-1
#else move to the next element in the list
else:
x=x+1

Python: Adding numbers in a list

The question is to iterate through the list and calculate and return the sum of any numeric values in the list.
That's all I've written so far...
def main():
my_list = input("Enter a list: ")
total(my_list)
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
print list_sum
main()
If you check to see whether the list item is an int, you can use a generator:
>>> a = [1, 2, 3, 'a']
>>> sum(x for x in a if isinstance(x, int))
6
You can use a generator expression such that:
from numbers import Number
a = [1,2,3,'sss']
sum(x for x in a if isinstance(x,Number)) # 6
This will iterate over the list and check whether each element is int/float using isinstance()
Maybe try and catch numerical
this seams to work:
data = [1,2,3,4,5, "hfhf", 6, 4]
result= []
for d in data:
try:
if float(d):
result.append(d)
except:
pass
print sum(result) #25, it is equal to 1+2+3+4+5+6+4
Using the generator removes the need for the below line but as a side note, when you do something like this for this:
try:
for number in my_list1:
list_sum += number
except ValueError:
#don't know what to do here
You need to call float() on the number to force a ValueError when a string is evaluated. Also, something needs to follow your except which could simply be pass or a print statement. This way of doing it will only escape the current loop and not continue counting. As mentioned previously, using generators is the way to go if you just want to ignore the strings.
def main():
my_list = input("Enter a list: ")
total(my_list)
return
def total(my_list1):
list_sum = 0
try:
for number in my_list1:
list_sum += float(number)
except ValueError:
print "Error"
return list_sum
if __name__ == "__main__":
main()

Categories

Resources