I am trying to create a rhombus made out of letters that a user selects, using Python 3. So if a user selects "B" then the rhombus is
A
B B
A
If the user selects "D" the rhombus would be:
A
B B
C C C
D D D D
C C C
B B
A
Can anyone help me get started on this? As of now, I am thinking if a user selects D then that corresponds to 4 and you would use the equation 2k-1 to determine the size of the "square." I would also create a linked list containing all the letters
so letter = ['A', 'B', 'C', 'D'.... 'Z'] (or would a dictionary be better?)
so:
def rhombus(n):
squareSize = 2n-1
for i in range(1,squareSize):
for l in letter:
print l + "/n"
golfing time \o/
edit: there's of course an SE for code golf and i'll do as in rome
Python 3, 106 bytes
n=26
for x in range(-n, n):
x = abs(x)
print(' '*x+' '.join([chr(64+n-x) for _ in range(n-x)]))
Try it online!
explanation
for x in range(-n, n): generate the rows
' '*x: generate the space before each first letter in the row
chr(64+n-x): display the letter, with chr(65) = "A"
' '.join: join all letters with three spaces between each of them
for _ in range(n-x): will generate the right number of letters. the value itself is useless.
output for n=4:
A
B B
C C C
D D D D
C C C
B B
A
domochevski's answer is great but we don't actually need those imports.
def rhombus(char):
A = 64
Z = A + 26
try:
val = ord(char)
if val < A or val > Z:
return None
except:
return None
L = [ ''.join(([chr(x)]*(x-A))) for x in range(A,val+1) ]
L = [' '.join(list(x)) for x in L]
max_len = max(len(x) for x in L)
L = [x.center(max_len) for x in L]
L += L[-2::-1]
return '\n'.join(L)
print(rhombus('Z'))
Well that was an interesting question. Here is some quick and dirty way to do it:
from string import ascii_uppercase
def rhombus(c): # Where c is the chosen character
# Get the position (1-based)
n = ascii_uppercase.find(c.upper()) + 1
if 0 < n <= 26:
# Get the strings for the top of the rhombus without spaces
l = [ascii_uppercase[i] * ((i)+1) for i in range(n)]
# Add in the spaces
l = [' '.join(list(e)) for e in l]
# Align everything
max_len = max(len(e) for e in l)
l = [e.center(max_len) for e in l]
# Get the bottom from the top
l += l[-2::-1]
# Print the rhombus
for e in l:
print(e)
As I mentioned this is not beautiful code but it should work.
Related
I want to make a code breaker that can break codes.
I don't understand how to put the (n) letter of the code into a string and turn it back into a list and print it out into the terminal.
#This is python code
alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z".split() #needs double alphabet as code will add up: w --> h, or the list will be out of range
while True:
saves = []
crack = ""
totalSaves = []
code = input("Enter code >")
codeIndex = 0
for i in range(26): #Length of alphabet
for i in range(len(code)): #length of code
#get the first letter of code into the saves code in here
#use saves[codeIndex] if possible
#I want the code breaker to be sort of like this: a --> c. At this case, I want codeIndex to be 2. If possible, I want to put the letters into saves[].
crack = "".join(saves) #unsure about this use
totalSaves.append(crack)
saves = []
crack = ""
printIndex = 0
for i in range(26):
print(totalSaves[printIndex])
totalSaves += 1
I'm sorry if you don't understand.
If you want to break and combine the alphabets in the list, you can do like this.
alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z a b c d e f g h i j k l m n o p q r s t u v w x y z"
alphabet_list = alphabet.split()
split_n = 5
result = []
for i in range(0, len(alphabet_list), split_n):
result.append("".join(alphabet_list[i:i+split_n]))
print(result)
You will get output: ['abcde', 'fghij', 'klmno', 'pqrst', 'uvwxy', 'zabcd', 'efghi', 'jklmn', 'opqrs', 'tuvwx', 'yz']
I would like to add a string (not replace) based on the nth occurence of multiple strings.
Example:
tablespecs = "l c d r c l"
Now assuming I want to add the third appearance of l, c and r the string "here: ", the desired output should be:
desired_tablespecs = "l c d here: r c l"
So solely considering l, c and r, ignoring d.
I solely cames as close, as the following, instead of adding the copde the code replaces the match, so it delivers "l c d here: c l".
tablespecs = "l c d r c l"
def replacenth(string, sub, wanted, n):
pattern = re.compile(sub)
where = [m for m in pattern.finditer(string)][n-1]
before = string[:where.start()]
after = string[where.end():]
newString = before + wanted + after
return newString
#Source of code chunk https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string
replacenth(tablespecs, "[lcr]", "[here:]", 3)
#wrong_output: 'l c d [here:] c l'
You can set after to start at where.start() instead of where.end(), so that it includes that character.
tablespecs = "l c d r c l"
def replacenth(string, sub, wanted, n):
pattern = re.compile(sub)
where = [m for m in pattern.finditer(string)][n-1]
before = string[:where.start()]
after = string[where.start():]
newString = before + wanted + after
return newString
replacenth(tablespecs, "[lcr]", "here: ", 3)
This outputs 'l c d here: r c l'.
A slightly different approach:
tablespecs = "l c d r c l"
def replacenth(string, sub, wanted, n):
count = 0
out = ""
for c in string:
if c in sub:
count += 1
if count == n:
out += wanted
count = 0
out += c
return out
res = replacenth(tablespecs, "lcr", "here: ", 3)
assert res == "l c d here: r c l", res
I would like to make a alphabetical list for an application similar to an excel worksheet.
A user would input number of cells and I would like to generate list.
For example a user needs 54 cells. Then I would generate
'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'
I can generate the list from [ref]
from string import ascii_lowercase
L = list(ascii_lowercase)
How do i stitch it together?
A similar question for PHP has been asked here. Does some one have the python equivalent?
Use itertools.product.
from string import ascii_lowercase
import itertools
def iter_all_strings():
for size in itertools.count(1):
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
for s in iter_all_strings():
print(s)
if s == 'bb':
break
Result:
a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb
This has the added benefit of going well beyond two-letter combinations. If you need a million strings, it will happily give you three and four and five letter strings.
Bonus style tip: if you don't like having an explicit break inside the bottom loop, you can use islice to make the loop terminate on its own:
for s in itertools.islice(iter_all_strings(), 54):
print s
You can use a list comprehension.
from string import ascii_lowercase
L = list(ascii_lowercase) + [letter1+letter2 for letter1 in ascii_lowercase for letter2 in ascii_lowercase]
Following #Kevin 's answer :
from string import ascii_lowercase
import itertools
# define the generator itself
def iter_all_strings():
size = 1
while True:
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
size +=1
The code below enables one to generate strings, that can be used to generate unique labels for example.
# define the generator handler
gen = iter_all_strings()
def label_gen():
for s in gen:
return s
# call it whenever needed
print label_gen()
print label_gen()
print label_gen()
I've ended up doing my own.
I think it can create any number of letters.
def AA(n, s):
r = n % 26
r = r if r > 0 else 26
n = (n - r) / 26
s = chr(64 + r) + s
if n > 26:
s = AA(n, s)
elif n > 0:
s = chr(64 + n) + s
return s
n = quantity | r = remaining (26 letters A-Z) | s = string
To print the list :
def uprint(nc):
for x in range(1, nc + 1):
print AA(x,'').lower()
Used VBA before convert to python :
Function AA(n, s)
r = n Mod 26
r = IIf(r > 0, r, 26)
n = (n - r) / 26
s = Chr(64 + r) & s
If n > 26 Then
s = AA(n, s)
ElseIf n > 0 Then
s = Chr(64 + n) & s
End If
AA = s
End Function
Using neo's insight on a while loop.
For a given iterable with chars in ascending order. 'abcd...'.
n is the Nth position of the representation starting with 1 as the first position.
def char_label(n, chars):
indexes = []
while n:
residual = n % len(chars)
if residual == 0:
residual = len(chars)
indexes.append(residual)
n = (n - residual)
n = n // len(chars)
indexes.reverse()
label = ''
for i in indexes:
label += chars[i-1]
return label
Later you can print a list of the range n of the 'labels' you need using a for loop:
my_chrs = 'abc'
n = 15
for i in range(1, n+1):
print(char_label(i, my_chrs))
or build a list comprehension etc...
Print the set of xl cell range of lowercase and uppercase charterers
Upper_case:
from string import ascii_uppercase
import itertools
def iter_range_strings(start_colu):
for size in itertools.count(1):
for string in itertools.product(ascii_uppercase, repeat=size):
yield "".join(string)
input_colume_range = ['A', 'B']
input_row_range= [1,2]
for row in iter_range_strings(input_colume_range[0]):
for colum in range(int(input_row_range[0]), int(input_row_range[1]+1)):
print(str(row)+ str(colum))
if row == input_colume_range[1]:
break
Result:
A1
A2
B1
B2
In two lines (plus an import):
from string import ascii_uppercase as ABC
count = 100
ABC+=' '
[(ABC[x[0]] + ABC[x[1]]).strip() for i in range(count) if (x:= divmod(i-26, 26))]
Wrap it in a function/lambda if you need to reuse.
code:
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in range(len(alphabet)):
for a in range(len(alphabet)):
print(alphabet[i] + alphabet[a])
result:
aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
...
a = ["000000001111111110101010","111111110000111111000011"]
what I need to do is check my list(a),
for item in a:
for elements in range(len(a[item])):
if "0" in a or "1" in a:
random change one elements in a[item](0 change to 1 or 1 change to 0) just one element,how can I do this
in my question if all elements changed should be:
a = ["111111110000000001010101","000000001111000000111100"]
if just one elements changed should be:
a =["000000001111101110101010","111111110000111111001011"]
just random pick 0 or 1 to change to 1 or 0
The source code below works for me:
a = ['000000001111111110101010',"111111110000111111000011"]
print(a)
ret = []
for item in a:
r = ''
for i in item:
b = int(i, base=2)
c = str(int(not b))
r = r + c
ret.append(r)
print(ret)
And the output is:
['000000001111111110101010', '111111110000111111000011']
['111111110000000001010101', '000000001111000000111100']
Here are both, flipping all digits and flipping one random digit:
import random
def flip_all(s):
s = list(s)
return ''.join([str(1 - int(c)) for c in s])
def flip_one(s):
s = list(s)
rand_i = random.randint(0, len(s)-1)
s[rand_i] = str(1 - int(s[rand_i]))
return ''.join(s)
a = ["000000001111111110101010","111111110000111111000011"]
print("a: ", a)
print("flip all: ", [flip_all(word) for word in a])
print("flip one: ", [flip_one(word) for word in a])
Output:
a: ['000000001111111110101010', '111111110000111111000011']
flip all: ['111111110000000001010101', '000000001111000000111100']
flip one: ['000000001101111110101010', '111111110000111110000011']
I would like to make a alphabetical list for an application similar to an excel worksheet.
A user would input number of cells and I would like to generate list.
For example a user needs 54 cells. Then I would generate
'a','b','c',...,'z','aa','ab','ac',...,'az', 'ba','bb'
I can generate the list from [ref]
from string import ascii_lowercase
L = list(ascii_lowercase)
How do i stitch it together?
A similar question for PHP has been asked here. Does some one have the python equivalent?
Use itertools.product.
from string import ascii_lowercase
import itertools
def iter_all_strings():
for size in itertools.count(1):
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
for s in iter_all_strings():
print(s)
if s == 'bb':
break
Result:
a
b
c
d
e
...
y
z
aa
ab
ac
...
ay
az
ba
bb
This has the added benefit of going well beyond two-letter combinations. If you need a million strings, it will happily give you three and four and five letter strings.
Bonus style tip: if you don't like having an explicit break inside the bottom loop, you can use islice to make the loop terminate on its own:
for s in itertools.islice(iter_all_strings(), 54):
print s
You can use a list comprehension.
from string import ascii_lowercase
L = list(ascii_lowercase) + [letter1+letter2 for letter1 in ascii_lowercase for letter2 in ascii_lowercase]
Following #Kevin 's answer :
from string import ascii_lowercase
import itertools
# define the generator itself
def iter_all_strings():
size = 1
while True:
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
size +=1
The code below enables one to generate strings, that can be used to generate unique labels for example.
# define the generator handler
gen = iter_all_strings()
def label_gen():
for s in gen:
return s
# call it whenever needed
print label_gen()
print label_gen()
print label_gen()
I've ended up doing my own.
I think it can create any number of letters.
def AA(n, s):
r = n % 26
r = r if r > 0 else 26
n = (n - r) / 26
s = chr(64 + r) + s
if n > 26:
s = AA(n, s)
elif n > 0:
s = chr(64 + n) + s
return s
n = quantity | r = remaining (26 letters A-Z) | s = string
To print the list :
def uprint(nc):
for x in range(1, nc + 1):
print AA(x,'').lower()
Used VBA before convert to python :
Function AA(n, s)
r = n Mod 26
r = IIf(r > 0, r, 26)
n = (n - r) / 26
s = Chr(64 + r) & s
If n > 26 Then
s = AA(n, s)
ElseIf n > 0 Then
s = Chr(64 + n) & s
End If
AA = s
End Function
Using neo's insight on a while loop.
For a given iterable with chars in ascending order. 'abcd...'.
n is the Nth position of the representation starting with 1 as the first position.
def char_label(n, chars):
indexes = []
while n:
residual = n % len(chars)
if residual == 0:
residual = len(chars)
indexes.append(residual)
n = (n - residual)
n = n // len(chars)
indexes.reverse()
label = ''
for i in indexes:
label += chars[i-1]
return label
Later you can print a list of the range n of the 'labels' you need using a for loop:
my_chrs = 'abc'
n = 15
for i in range(1, n+1):
print(char_label(i, my_chrs))
or build a list comprehension etc...
Print the set of xl cell range of lowercase and uppercase charterers
Upper_case:
from string import ascii_uppercase
import itertools
def iter_range_strings(start_colu):
for size in itertools.count(1):
for string in itertools.product(ascii_uppercase, repeat=size):
yield "".join(string)
input_colume_range = ['A', 'B']
input_row_range= [1,2]
for row in iter_range_strings(input_colume_range[0]):
for colum in range(int(input_row_range[0]), int(input_row_range[1]+1)):
print(str(row)+ str(colum))
if row == input_colume_range[1]:
break
Result:
A1
A2
B1
B2
In two lines (plus an import):
from string import ascii_uppercase as ABC
count = 100
ABC+=' '
[(ABC[x[0]] + ABC[x[1]]).strip() for i in range(count) if (x:= divmod(i-26, 26))]
Wrap it in a function/lambda if you need to reuse.
code:
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in range(len(alphabet)):
for a in range(len(alphabet)):
print(alphabet[i] + alphabet[a])
result:
aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
...