Python combine function - python

Today i'll publish a riddle.
The best answer will be the shortest code.
Write a one liner function that accepts a currency and a list of numbers. The function needs to return a string where each number from the list is attached with its currency.
Here's an example for a simple way to solve it.
def combine_coin(coin, numbers):
coins_str = ''
for num in numbers:
coins_str += coin + str(num) + ', '
return coins_str[:-2]
print(combine_coin('$', range(5)))

def combine_coin(coin, numbers):
return ', '.join([f'{coin}{k}' for k in numbers])

print(','.join(list(map(lambda num:"$"+num,input("enter the values <sep by space>").split()))))
Okay splitting this long line, we get 1)
','.join(list( - this will join the list we get with a comma
2)map- maps a function to all values in a list and returns a map object containing the return value of the function
3)lambda num:'$'+str(num) - takes a number and returns its string with a '$' example: '$1'
4)input().split()- splits the input by space

Codegolf is fun:
def combine_coin(c, n):
return ', '.join(c+str(k) for k in n)

Related

Problem with the multiplication table of a number

I am trying to write a function that shows me the multiplication table of a number:
def tabellina(n):
for i in range (1,11):
print(n*i)
If I write the function in this way, it works fine.
If I put 4 instead of n, it prints:
4,8,12,16,20,24,28...40
But if I use return instead of print, it does not work anymore, and it just returns me the n value.
I have to use the return and I can’t use the print
What should I do? (I MUST use return NOT print)
The reason it returns the n value if you use return is because the loop doesn't run fully. When you use return, it returns the value, which exits the function. The rest of the loop never executes.
What you want instead is to return an array. The easiest way is probably a list comprehension:
def tabellina(n):
return [n*i for i in range(11)]
you could save the output in a string and then return that. for example:
def tabellina(n):
table = ''
for i in range (1,11):
table += ((n*i) + ' ')
return table
you could replace ' ' with any devider (like ',') as you want.
Try the following script:
def tabellina(n):
joint = ""
for i in range (1,11):
joint = joint + (" %s" % n*i)
return joint

how to find the length of a list in python without using len() [duplicate]

This question already has answers here:
String length without len function
(17 answers)
Closed 6 months ago.
I want to write a function which will find out the length of a list based on user input. I don't want to use the in-built function len().
Function which i have written is working for strings but for lists it is failing.
#function for finding out the length
def string_length(a):
for i in a:
j+=1
return j
#taking user input
a = input("enter string :")
length = string_length(a)
print("length is ", length)
You probably need to initialize your variable j (here under renamed counter):
def string_length(my_string):
"""returns the length of a string
"""
counter = 0
for char in my_string:
counter += 1
return counter
# taking user input
string_input = input("enter string :")
length = string_length(string_input)
print("length is ", length)
This could also be done in one "pythonic" line using a generator expression, as zondo has pointed out:
def string_length(my_string):
"""returns the length of a string
"""
return sum(1 for _ in my_string)
It's quite simple:
def string_length(string):
return sum(1 for char in string)
1 for char in string is a generator expression that generates a 1 for each character in the string. We pass that generator to sum() which adds them all up. The problem with what you had is that you didn't define j before you added to it. You would need to put j = 0 before the loop. There's another way that isn't as nice as what I put above:
from functools import reduce # reduce() is built-in in Python 2.
def string_length(string):
return reduce(lambda x,y: x+1, string, 0)
It works because reduce() calls the lambda function first with the initial argument, 0, and the first character in the string. The lambda function returns its first argument, 0, plus one. reduce() then calls the function again with the result, 1, and the next character in the string. It continues like this until it has passed every character in the string. The result: the length of the string.
you can also do like this:
a=[1,2,2,3,1,3,3,]
pos=0
for i in a:
pos+=1
print(pos)
Just a simple answer:
def mylen(lst):
a = 0
for l in lst: a+=1
return a
print(mylen(["a","b",1,2,3,4,5,6,67,8,910]))

writing a function that return the reversed number

I am trying to write a Python function that get a number as input and returns its reversed number as output. for example: 1234 returns 4321.
this is what I try, but it return only ''
def reverse(num):
L=[]
x=str(num)
L1=list(x)
for i in L1:
L.insert(0,i)
print 'the reversed num is:'
x=''
for i in L:
x.join(i)
return x
any ideas?
def reverse(num):
return str(num)[::-1]
or one line:
lambda x: str(x)[::-1]
Well, the easy solution is this one:
>>> int(str(1234)[::-1])
4321
Your code can be fixed by changing the part
for i in L:
x.join(i)
return x
to
for i in L:
x += i
return x
Alternatively, just replace that section by
return ''.join(L)
What was wrong with your code? Because of wrong indentation, you returned in the first iteration of the for loop. You never assigned a name to x.join(i) so the return value was lost. What you expected join to do I do not know.
First, there is an easier way by converting to string, slicing the string and converting it back to a number.
def reverse(num):
return int(str(num)[::-1])
Second, there are multiple errors in your code:
1) your return statement is in the loop, so it will return after the first iteration;
2) x does not change because x.join() creates a new string and does not modify the string x (which is immutable by the way)
3) no need to convert the string into a list since you can directly iterate over the string (for i in x: ...)
4) join() takes an iterator as an argument. No need for the second loop: return ''.join(L)
thank you all for the helpful ideas.
here is my solution:
def reverse(n):
reverse=0
while(n>0):
dig=n%10
reverse=reverse*10
reverse=reverse+dig
n=n/10
return reverse
def reverse(num)
return str(num)[::-1]
Reverse a string in Python
Other users already gave good answers. Here is a different one, for study purposes.
num = 1234
print "".join(reversed(str(num)))
# 4321
You can convert to int afterwards.

Python - making a function that would add "-" between letters

I'm trying to make a function, f(x), that would add a "-" between each letter:
For example:
f("James")
should output as:
J-a-m-e-s-
I would love it if you could use simple python functions as I am new to programming. Thanks in advance. Also, please use the "for" function because it is what I'm trying to learn.
Edit:
yes, I do want the "-" after the "s".
Can I try like this:
>>> def f(n):
... return '-'.join(n)
...
>>> f('james')
'j-a-m-e-s'
>>>
Not really sure if you require the last 'hyphen'.
Edit:
Even if you want suffixed '-', then can do like
def f(n):
return '-'.join(n) + '-'
As being learner, it is important to understand for your that "better to concat more than two strings in python" would be using str.join(iterable), whereas + operator is fine to append one string with another.
Please read following posts to explore further:
Any reason not to use + to concatenate two strings?
which is better to concat string in python?
How slow is Python's string concatenation vs. str.join?
Also, please use the "for" function because it is what I'm trying to learn
>>> def f(s):
m = s[0]
for i in s[1:]:
m += '-' + i
return m
>>> f("James")
'J-a-m-e-s'
m = s[0] character at the index 0 is assigned to the variable m
for i in s[1:]: iterate from the second character and
m += '-' + i append - + char to the variable m
Finally return the value of variable m
If you want - at the last then you could do like this.
>>> def f(s):
m = ""
for i in s:
m += i + '-'
return m
>>> f("James")
'J-a-m-e-s-'
text_list = [c+"-" for c in text]
text_strung = "".join(text_list)
As a function, takes a string as input.
def dashify(input):
output = ""
for ch in input:
output = output + ch + "-"
return output
Given you asked for a solution that uses for and a final -, simply iterate over the message and add the character and '-' to an intermediate list, then join it up. This avoids the use of string concatenations:
>>> def f(message)
l = []
for c in message:
l.append(c)
l.append('-')
return "".join(l)
>>> print(f('James'))
J-a-m-e-s-
I'm sorry, but I just have to take Alexander Ravikovich's answer a step further:
f = lambda text: "".join([c+"-" for c in text])
print(f('James')) # J-a-m-e-s-
It is never too early to learn about list comprehension.
"".join(a_list) is self-explanatory: glueing elements of a list together with a string (empty string in this example).
lambda... well that's just a way to define a function in a line. Think
square = lambda x: x**2
square(2) # returns 4
square(3) # returns 9
Python is fun, it's not {enter-a-boring-programming-language-here}.

Higher order function in Python exercise

I learning Python and during solution an exercise, function filter() returns empty list and i can't understand why. Here is my source code:
"""
Using the higher order function filter(), define a function filter_long_words()
that takes a list of words and an integer n and returns
the list of words that are longer than n.
"""
def filter_long_words(input_list, n):
print 'n = ', n
lengths = map(len, input_list)
print 'lengths = ', lengths
dictionary = dict(zip(lengths, input_list))
filtered_lengths = filter(lambda x: x > n, lengths) #i think error is here
print 'filtered_lengths = ', filtered_lengths
print 'dict = ',dictionary
result = [dictionary[i] for i in filtered_lengths]
return result
input_string = raw_input("Enter a list of words\n")
input_list = []
input_list = input_string.split(' ')
n = raw_input("Display words, that longer than...\n")
print filter_long_words(input_list, n)
Your function filter_long_words works fine, but the error stems from the fact that when you do:
n = raw_input("Display words, that longer than...\n")
print filter_long_words(input_list, n)
n is a string, not an integer.
Unfortunately, a string is always "greater" than an integer in Python (but you shouldn't compare them anyway!):
>>> 2 > '0'
False
If you're curious why, this question has the answer: How does Python compare string and int?
Regarding the rest of your code, you should not create a dictionary that maps the lengths of the strings to the strings themselves.
What happens when you have two strings of equal length? You should map the other way around: strings to their length.
But better yet: you don't even need to create a dictionary:
filtered_words = filter(lambda: len(word) > n, words)
n is a string. Convert it to an int before using it:
n = int(raw_input("Display words, that longer than...\n"))
Python 2.x will attempt to produce a consistent-but-arbitrary ordering for objects with no meaningful ordering relationship to make sorting easier. This was deemed a mistake and changed in the backwards-incompatible 3.x releases; in 3.x, this would have raised a TypeError.
I don't know what your function does, or what you think it does, just looking at it gives me a headache.
Here's a correct answer to your exercise:
def filter_long_words(input_list, n):
return filter(lambda s: len(s) > n, input_list)
My answer:
def filter_long_words():
a = raw_input("Please give a list of word's and a number: ").split()
print "You word's without your Number...", filter(lambda x: x != a, a)[:-1]
filter_long_words()

Categories

Resources