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
Related
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 month.
Improve this question
I want to know what's wrong in the below code. Will it consume more time to in some certain scenarios?
Expected time complexity: O(n)
def subArraySum(self,arr, n, s):
if sum(arr[0:n]) == s:
return [1, n]
if sum(arr[0:n]) < s:
return [-1]
start = 0
i =1
sum_elements = 0
while i < n:
sum_elements = sum(arr[start:i+1])
if sum_elements == s:
return [start+1, i+1]
if sum_elements < s:
i += 1
continue
if sum_elements > s:
start += 1
continue
if sum_elements < s:
return [-1]
Instead of running sum(arr[start:i+1]) in each iteration of the while loop, you should use a variable and add or subtract the respective value that is included or excluded from the subarray in each iteration. That way you can avoid the O(n^2) complexity and stay within O(n).
Currently there is a lot of overhead for calculating the sum of a (potentially large) subarray that has only changed by one single value at the beginning or the end during each iteration.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
I have the following interview question that may require traversing through the entire string.
Problem I searched about find Problem and most people do it like this def palindrome(s): return s==s[::-1] But this task is diffrent?
palindrome is a word the can read from both directions like 'mam', 'dad'. Your task is to get a list of palindrome in a given string.
def palindrome(s):
stack = []
return ['aaa']
exampls
palindrome('aaa') #['aaa']
palindrome('abcbaaaa') #['abcba','aaaa']
palindrome('xrlgabccbaxrlg') #['abccba']
palindrome('abcde') #['']
Let's try to avoid checking all the possible combinations :). My idea is, start from the extremities and converge:
def palindrome(s):
out = [''] #we need the list to not be empty for the following check
for main_start in range(len(s) - 1):
for main_end in range(len(s) - 1, main_start, -1):
start = main_start
end = main_end
while (end - start) > 0:
if s[start] == s[end]: ##may be palindrome
start += 1
end -= 1
else:
break
else:
if s[main_start:main_end + 1] not in out[-1]: #ignore shorter ("inner") findings
out.append(s[main_start:main_end + 1])
return out[1:] #skip the dummy item
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 1 year ago.
Improve this question
Let s = "%2ABCDE" - get first 2 characters from string
then output should be "AB".
Need to get characters from string specified by numeral in string.
E.g. s1="%12ABCDERTYUIOPLKHGF" - get first 12 characters from string.
I tried to get digit using re.findall('\d+', string ), but this creates problem if my string would be "%2ABCD1".
Please suggest
s = "%2ABCDE"
number = ""
offset = 0
for i in range(len(s)):
if s[i] == "%":
continue
elif s[i].isdigit():
number += s[i]
else:
offset = i
break
print(s[offset:int(number) + offset])
Output: AB
A simpler way of doing this would be to do the following:
txt = "%2ABCDE"
number_list = [s for s in txt if s.isdigit()]
number_concate = int("".join(number_list))
txt_filtered = txt[len(number_list)+1:]
print(txt_filtered[:number_concate])
Outputs AB for string "%2ABCDE"
Outputs ABCDERTYUIOP for string "%12ABCDERTYUIOPLKHGF"
You are taking your string, doing a list comprehension of the string if the digit exists, then joining the list and changing this to an integer to allow for you to filter your string accordingly. Then you strip the string to only the characters and you have your answer printed out.
import re
s = '%2ABCDERTYUIOPLKHGF'
numeral_instruction = re.search(r'%\d+',s).group(0)
start = len(numeral_instruction)
stop = start + int(numeral_instruction[1:])
s[start:stop]
outputs
AB
You can get the position of the first non-digit character in the string (skipping the %) and use that as the basis to get the length and form a substring:
s1="%12ABCDERTYUIOPLKHGF"
i = next(i for i,c in enumerate(s1[1:],1) if not c.isdigit())
result = s1[i:i+int(s1[1:i])]
print(result)
ABCDERTYUIOP
If the first number in the string is not always at index 1, you can skip a variable number of characters using the same technique:
s1="*:%12ABCDERTYUIOPLKHGF"
start = next(i for i,c in enumerate(s1) if c.isdigit())
end = next(i for i,c in enumerate(s1[start:],start) if not c.isdigit())
result = s1[end:end+int(s1[start:end])]
print(result)
ABCDERTYUIOP
If you want to use the re module, you only need the first occurrence of a number, so use re.search() instead of re.findall():
import re
m = re.search(r"\d+",s1)
result = s1[m.end():m.end()+int(m.group())]
print(result)
ABCDERTYUIOP
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.
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'm learning python and in a test, I made a class that have a list of numbers, in other class, a list of previous class. In the second class, I wrote a method for put the numbers dinamically but it put the numbers x times for the length of the list of previous class.
def make_connection(self, number):
if not self.__has_con:
for i in range(number):
self.__weight.append(1)
self.__has_con = True
The method above is from the first class, to get n numbers.
inp = len(self.__inputs)
for n in self.__hidden:
n.make_connection(inp)
This is from the second class. If __hidden has 9 objects, it put the inp 9 times for all the 9 elements.
init of second class
def __init__(self, array):
if isinstance(array, list):
if len(array) > 2:
inps = []
hidd = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[len(array)-1]):
k = kn(kn.OUTPUT)
outs.append(k)
a = array[1:]
h = a[:len(a)-1]
if len(h) > 1:
for i in h:
hd = []
for p in range(i):
k = kn(kn.HIDDEN)
hd.append(k)
hidd.append(hd)
else:
for p in range(h[0]):
k = kn(kn.HIDDEN)
hidd.append(k)
self.__inputs = inps
self.__hidden = hidd
self.__output = outs
else:
inps = []
outs = []
for i in range(array[0]):
k = kn(kn.INPUT)
inps.append(k)
for i in range(array[0]):
k = kn(kn.OUTPUT)
outs.append(k)
self.__inputs = inps
self.__output = outs
The for var in collection syntax in Python uses an iterator. Instead of a for loop where you specify a starting value, an increment and a terminating value, it says iterate over all the values in the collection.
So when you say this in Python:
for x in range(4):
print x
it's like saying this in other languages:
for (x = 0; x < 4; ++x) {
print(x);
}
Python's range returns a iterator over 0..4 in this case. In your example, Python gives you each element of your collection.
See, for more details: https://www.w3schools.com/python/python_iterators.asp
In python Use the for loop like that:
for str in str_list
print (str)