How do I optimize nested if statements? I cannot use && here [closed] - python

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 2 years ago.
Improve this question
Is there a better way in which this can be written? I'm new to python coding and I want to improve below lines of code. I have included a few lines of my code here but the original code is much longer than this(multiple if statements). Any guidance/feedback would be helpful.
upperchar = #generate a char
pwdlist.append(upperchar)
if len(pwdlist) < length:
upperchar2 = #generate a char
pwdlist.append(upperchar2)
if len(pwdlist) < length:
lowerchar = #generate a char
pwdlist.append(lowerchar)
if len(pwdlist) < length:
lowerchar2 = #generate a char
pwdlist.append(lowerchar2)
if len(pwdlist) < length:
char3 = #generate a char
pwdlist.append(char3)
Posting my first question here so if you need anything more please ask me.

Assuming you are always generating a character the same way, then this would work
pwdlist = []
while len(pwdlist) < length:
pwdlist.append(generate_char())
Or
pwdlist = [generate_char() for _ in range(length)]
Then you can add logic into this generate function to return something based on random values, for example
def generate_char():
from random import randrange
x = randrange(4)
if x == 0:
return 'value a-z'
elif x == 1:
return 'value A-Z'
elif x == 2:
return 'value 0-9'
elif x == 3:
return 'punctuation'

Related

Function to find a continuous sub-array which adds up to a given number in python [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 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.

How to get list of palindrome in text? [closed]

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

How do I make a function read a row and a column with only zeros without using libraries [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 12 months ago.
This post was edited and submitted for review 12 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm new to programming in general... I have to check all the rows and columns of an matrix and in case any of them are complete with zeros, return a True value. I made this code in a silly attempt but it doesn't work for the purpose of the question itself. The matrix will always be a square and a list of lists.
def determinanteEhNulo(matriz):
contador = 0
for i in matriz:
for j in range(len(matriz)):
if i[j] == 0:
contador += 1
if contador >= int(len(matriz)):
return True
return False
This seems to do what you need.
def determinanteEhNulo(matriz):
for i in matriz:
if all(x==0 for x in i):
return True
for i in zip(*matriz):
if all(x==0 for x in i):
return True
return False
count = 0
def determinanteEhNulo(matrix):
global count
for i in matrix:
if all([j ==0 for j in i]):
count += 1
if count == len(matrix):
return True
else:
return False

Function that returns even numbers from a list and halves them [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 1 year ago.
The community is reviewing whether to reopen this question as of 1 year ago.
Improve this question
So I am having trouble concatenating this, I am not allowed to use .append(), and right now Im getting the error 'int' object not iterable.
def halveEvens(l):
num = []
for n in l:
if n % 2 == 0:
num += (n // 2)
return num
print(halveEvens([10,21,32,42,55]))```
sum(x//2 for x in numbers if x%2 == 0)
is probably how I would do it
if you just want to collect them (without summing them)
generator (x//2 for x in numbers if x%2 == 0) would be evaluated as you iterate it
or list comprehension that is evaluated immediatly
[x//2 for x in numbers if x%2 == 0]

How can I generate all possible words with a specified set of characters? [closed]

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 4 years ago.
Improve this question
I play to HackNet game and i have to guess a word to bypass a firewall.
The key makes 6 characters long and contains the letters K,K,K,U,A,N.
What is the simplest way to generate all possible combinations either in bash or in python ? (bonus point for bash)
Here is a backtracking-based solution in Python:
db = {"K" : 3, "U" : 1, "A" : 1, "N" : 1}
N = 6
def possibilities(v):
l = []
for k in db.keys():
if v.count(k) < db[k]:
l.append(k)
return l
def generateImpl(a):
if len(a) < N:
lst = []
for c in possibilities(a):
lst += generateImpl(a+[c])
return lst
else:
return [''.join(a)]
def generate():
return generateImpl([])
Just run generate() to obtain a list of possible words.
You have 6 letters and need to find a combination of 6 letters. If you are not using the same character in ['K','K','K','U','A','N'] again and again, then there is only 1 permutation.
If you can use the same character again and again, you can use the following code to generate all possible combinations.
import itertools
y = itertools.combinations_with_replacement(['K','U','A','N'],6)
for i in list(y):
print(i)

Categories