Repeat a number 3 times for output - python

I need to define a function which repeats a number 3 times. I can only get it to work as a list where the output is [1, 1, 1] if the input is 1. However I need the output to be 111
This is what I have
def repeat_number(num):
if not type(num) is int:
return None
list_1 = []
x = list_1.append(num)
y = list_1*3
for i in y:
return i,i,i
a = 12
print (repeat_number(a))
and again I want the output to be 121212

def repeat_number3(a):
return str(a)*3

You can use a simple str.join for this, and create a general function:
def repeat(something, times, separator):
return separator.join([str(something) for _ in range(times)])
And now use it to create your specific function:
def repeat_three_times(something):
return repeat(something, 3, '')
Output:
>>> repeat_three_times(1)
'111'
Few things to note:
I've used str to cast the expected integer to a string
I've used a list comprehension to create an iterable which is what str.join expects
I've used str.join to create a string which is a concatenation of the strings in the list (see 2).
Here is an example of using the more general function in a different way:
>>> repeat(1, 4, ',')
'1,1,1,1'

If the output is [1, 1, 1] and you were looking for 111, you can do the following:
print (*repeat_number(a), sep='')
However, I'd recommend doing the following with your function:
def repeat_number(num):
if type(num) != int: return
return int(str(num)*3)
And then all you have to do is:
print (repeat_number(a))
as you originally attempted. Plus, this function returns an actual number, which is probably good.

You can cast the number as a string and multiply.
def repeat(num):
return str(num)*3
a = 12
print(repeat(a))

def repeat_num(x):
return str(x)*3

Related

Python 3, *args, print the output in a list

def even_number(*args):
for even in args:
if even%2==0:
even
print(list(str(even)),end='')
I want to print the output in a list as [8,6,4], but rather it prints it out as [8],[6],[4]. If I put out the last print statement and just print(even), it obviously doesn't list out the output.
Your problem is that you print every time you enter in your if.
Instead, you want to add your number to a list every time you enter the loop and then print it :
def even_number(*args):
my_list = list()
for even in args:
if even%2==0:
my_list.append(even)
print(my_list)
EDIT :
The others answer are correct by the way. It's better to use the comprehension list. I don't remove my answer so you get to understand what your mistake was.
def even_number(*args):
print([i for i in args if i % 2 == 0])
You need to collect the result before printing it if you want to print it as a list, i.e.:
def even_number(*args):
evens = [a for a in args if a % 2 == 0]
print(evens)
# test:
even_number(*range(10)) # [0, 2, 4, 6, 8]
Just use a list comprehension with:
def even_number(*args):
even = [n for n in args if n % 2 == 0]
print(even)
Simple code
def even_number(*args):
result = []
for even in args:
if even % 2 == 0:
result.append(even)
return result
with comprehension list
def even_number(*args):
result = [x for x in args if x%2==0]
return result
for to use function even_number
print even_number(range(10))

Python: can a function return a string?

I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
def lsubstr(x):
a= ''
b= ''
if x == '':
return ''
else:
a = a + x[0:]
b = b + x[1:]
lsubstr(x[2:])
#print (a,b)
return a and b
lsubstr('hweolrllod')
so I changed my code to this:
def lsubstr(x):
if len(x) <1:
return x
else:
return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')
and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
the error I get is
TypeError: Can't convert 'tuple' object to str implicitly
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.
The and keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
...
return (a, b)
And then you can access the values using the indexing operator like this:
a = lsubstr( ... )
a[0]
a[1]
Or:
word1, word2 = lsubstr( ... )

list to integer

I'm trying to write a recursive python function that takes in a list for example [1,2,3,4] and returns an integer 1234. Any help on how to do this
def listtoint(lst):
if lst==[]:
return 0
return lst[-1:]+clti(lst/10)
I know you can't divide the list but I would like a way to get around it
def listtoint(lst):
if lst == []:
return 0
s = ''.join([str(i) for i in lst])
return int(s)
How this works is: ''.join(some_list) takes every element of the list and concatenates them into one long string. every element of some_list here must already be a string, thus the list comprehension in the code above.
int is then used to turn the resulting string into an integer.
There should be error checking but you can deal with that. Also, this isn't recursive and doesn't need to be.
To do this recursively...
def listtoint(lst):
if lst==[]:
return 0
iPower = 10**(len(lst)-1)
return lst[0]*iPower + listtoint(lst[1:])

Print a list of values from these functions

Hello so I was wondering how can I 'print' the list of numbers generated by these functions that take the values from the list and squares them. Thanks!!!
def square(list):
return [i ** 2 for i in list]
def square(list):
return map(lambda x: x ** 2, list)
def square(list):
for i in list:
yield i ** 2
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
Printing a list by using print, for example:
print(', '.join(map(str, square([5,3,2]))
First off, you need different function names, or else when you call it, python will only take the last one.
To answer your question, it is as easy as using a print statement. Simply print the return of the function while using a list as the argument.
square_list = [1,2,3]
print square(square_list)
If you wanted to try a different way, putting the print statement in the function also works.
For example:
def square(list):
print [i ** 2 for i in list] # Instead of return
The downside of this is you cannot store it as a variable or append it to a list later on.
Happy coding!

How to count the number of letters in a string with a list of sample?

value = 'bcdjbcdscv'
value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
How to count the number of letters in a string with a list of sample? I get nothing in my python shell when I wrote the above code in my python file.
There is a built-in method for this:
value.count('c')
functions need to be called, and the return values need to be printed to the stdout:
In [984]: value = 'bcvfdvdfvcdjbcdscv'
In [985]: count_letters(value, 'b')
Out[985]: 2
In [987]: ds=count_letters(value, 'd') #if you assign the return value to some variable, print it out:
In [988]: print ds
4
EDIT:
On calculating the length of the string, use python builtin function len:
In [1024]: s='abcdefghij'
In [1025]: len(s)
Out[1025]: 10
You'd better google it with some keywords like "python get length of a string" before you ask on SO, it's much time saving :)
EDIT2:
How to calculate the length of several strings with one function call?
use var-positional parameter *args, which accepts an arbitrary sequence of positional arguments:
In [1048]: def get_lengths(*args):
...: return [len(i) for i in args]
In [1049]: get_lengths('abcd', 'efg', '1234567')
Out[1049]: [4, 3, 7]
First you should probably look at correct indenting and only send in value. Also value is being overwritten so the last one will be the actual reference.
Second you need to call the function that you have defined.
#value = 'bcdjbcdscv'
#value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
x = count_letters(value, 'b')
print x
# 2
This should produce the result you are looking for. You could also just call:
print value.count('b')
# 2
In python, there is a built-in method to do this. Simply type:
value = 'bcdjbcdscv'
value.count('c')

Categories