How to duplicate numbers in string n times? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have this string (61,62,63,64) and i want to tranform the string into (61,61,62,62,62,62,63,64).
I want to duplicate the numbers in the string n times, the 61 i want to duplicate twice, the 62 i want to duplicate four times, how do i code something that duplicates a number in the string n times?
Can you possible do something like have annother string that tells the computer how many times to duplicate each number? (61, 62, 63, 64,) (2,4,1,1)

if both your inputs are strings:
a = '(61, 62, 63, 64,)'
b = '(2,4,1,1)'
a = [i for i in a[1:-1].strip().replace(" ","").split(",")]
a.remove('')
b = [int(i) for i in b[1:-1].strip().replace(" ","").split(",")]
result = "("
for i in range(len(b)):
for j in range(b[i]):
result += a[i]
result += ", "
result = result.strip()[:-1]+")"
print(result)

Here is a possible solution (if rep is a string and not a tuple, you just need to do rep = eval(rep)):
s = "(61,62,63,64)"
rep = (2,4,1,1)
# convert the string to a tuple
t = eval(s)
# compute the result as a tuple
result = tuple(x for i, x in enumerate(t) for _ in range(rep[i]))
# convert the result into a string
result = str(result)
If you want something more compact:
s = "(61,62,63,64)"
rep = (2,4,1,1)
result = str(tuple(x for i, x in enumerate(eval(s)) for _ in range(rep[i])))
Be careful with using eval!! Check this question for more info.

Related

PYTHON- Return minimum three digits [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I want to return minium three digits maximum whatever it has it should return.
I have tried following function,
def get_code(model, prefix):
content = model.objects.filter(code__startswith=prefix).last()
last = None
code_prefix = prefix
if content:
a_string = content.code
split_strings = []
n = len(prefix)
for index in range(0, len(a_string), n):
split_strings.append(a_string[index: index + n])
last = int(split_strings[1])
if last is not None:
suggested = last + 1
else:
suggested = 1
return "{}{:03d}".format(code_prefix, suggested)
Above code returns threedigits only if i have 4 didits it skips for calculation also. it takes only three digits for calucualtion also. how can i fix this???
If you replace the last line with
while len(""+suggested)<3:
suggested="0"+suggested
return code_prefix+suggested
I think you will have the formatting that you want.
We have to concatenate to a string to use len and to keep the 0's.
here my answer,
def get_code(model, prefix):
content = model.objects.filter(code__startswith=prefix).last()
def text_num_split(item):
for index, letter in enumerate(item, 0):
if letter.isdigit():
return [item[:index], item[index:]]
last = None
code_prefix = prefix
if content:
a_string = content.code
pre_code = text_num_split(a_string)
last = int(pre_code[-1])
if last is not None:
suggested = last + 1
else:
suggested = 1
return "{}{:03d}".format(code_prefix, suggested

How to place random dots in string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have code
import random
lst = ['.']
string = 'o3oyrwrj0jtirvwp5sh57oed67d5zy'
print ''.join('%s%s' % (x, random.choice(lst) if random.random() > 0.5 else '') for x in string)
It generates string with random dots between symbols:
o3.oy.r.wrj.0jt.i.rv.w.p5sh57.oe.d6.7.d.5z.y
o3oyr.wr.j.0.j.ti.rvw.p5sh5.7o.e.d6.7.d5zy
o.3o.y.rw.r.j.0.jt.i.r.v.wp.5sh.5.7.oe.d6.7.d5.zy
I need to generate string with number of dots from 1 to 10, and except results
dot at the end 'o.3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy.'
dot in the begin 'o.3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy'
double+ dot 'o..3.oyrwrj.0.jt.irv.wp.5.s.h57oe.d.67.d.5.zy'
I need only from 1 up to 10dots (not 10+)
You can use random.sample to select a random set of indices at which you will insert a dot instead of drawing at each index.
Forming slices out of these indices and joining with '.'.join will prevent pairs of dots as well as heading and trailing dots if you exclude first and last indices.
from random import sample
def insert_dots(s, k):
indices = sorted(sample(range(1, len(s) - 1), k))
intervals = []
for i, j in zip([0] + indices, indices + [len(s)]):
intervals.append(s[i:j])
return '.'.join(intervals)
Example
s = 'foobar'
for _ in range(5):
print (insert_dots(s, 3))
Output
fo.o.ba.r
fo.ob.a.r
f.oob.a.r
fo.o.b.ar
fo.o.ba.r
If you need a random number of dots, you can then do this.
insert_dots(s, randint(1, 10))
You can use this if statement:
if string.startswith('.')
# Raise dot at the beginning exception
elif string.endswith('.'):
# Raise dot at the end exception
elif '..' in string:
# Raise double dot exception

In Python how do I extract all substrings that cross a certain index in a longer string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Say I have a string (mystring). I want to extract all possible substrings of mystring so long as the substrings are lengths 8-15. I've been able to do that with no problem (see code below). However, what if I want to only extract these substrings if they overlap a certain part of mystring? The overlap is defined by the position in mystring rather than a certain letter of mystring, as the letters are not unique across mystring.
In the example below, I might want my substrings to include zero-based index 11.
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length:
substrings.add(ss)
Simple answer
You could check that 11 is included in [i, i + length) by checking i <= 11 < i + length:
mystring = "JACKANDJILLRANUPTHEHILLFORWATER"
substrings = set()
for i in range(0, len(mystring)):
for length in range(8,16):
ss = mystring[i:i+length]
if len(ss) == length and i <= 11 < i + length:
substrings.add(ss)
As set comprehension
You could do it like this:
substrings = {mystring[i:j]
for i in range(0, len(mystring))
for j in range(i + 8, min(i + 16, len(mystring)))
if i <= 11 < j}

Multiply digits in list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Let's say we have list of numbers and we want to multiply all numbers in it as long as product is digit.
For Example:
[2,2,5] => [4,5]
[3,3,7] => [9,7]
[5,5,5,5,5] => [5,5,5,5,5]
Can I somehow use functools.reduce here? What's pythonic way to solve this problem?
This can be solved easily by a simple stateful algorithm:
def multiply_digits(lst):
res = []
for x in lst:
if res and res[-1] * x < 10:
res[-1] *= x
else:
res.append(x)
return res
While there is an equivalent functional way (with reduce), that will not be as simple since you either need to reassemble the result list in each step, or carry the current number value separately.
This might do the trick:
def process(lst):
lst = sorted(lst)
last = 1
result = []
for el in lst:
if last * el >= 10:
result.append(last)
last = el
continue
last *= el
result.append(last)
return result
This is better I guess:
from numpy import product
reduce(lambda x , y : (x[0:-1]+[y*x[-1]] if product(x+[y])<10 else x+[y]) if len(x)>0 else [y] ,[21,1,2,3,4,5,6],[])

Python : Subtracting inside an array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to subtract the values in an array with 10 values that the user inputs. So far I can't find how to do that. This is what I have...
g = 0
q = []
for s in range(9):
while g < 10:
n = input()
q.append(int(n))
g = g+1
add = sum(Q)
sub =
There are more succinct ways to do this; I've opted instead for readability:
# get our initial input:
n = input()
result = int(n)
# subtract the rest of the user's inputs:
for x in range(9):
n = input()
result -= int(n)
# ... do something with the result ...
You don't need to assign all of those to individual variables. At each iteration of the loop, you could just append the newly input value to the array:
q = []
g = 0
while g < 10:
n = input()
q.append(int(n))
g = g + 1
At the end of this loop, q will contain the 10 values that the user entered.
It's not clear to me what needs to be subtracted from what, but that might get you a little closer to where you need to be.
Be pythonic
a = [int(input()) for x in range(10)]
Or for python 2.X
a = [int(raw_input()) for x in xrange(10)]
This gives you a list containing 10 integers.
Then you can
q = map(lambda x: x-sum(a), q),
which subtracts the sum of user inputs
Just use python API
li = []
for x in xrage(10):
li.append(input())
result = reduce(lambda x, y: x - y, li)

Categories