1. Print a-n: a b c d e f g h i j k l m n
2. Every second in a-n: a c e g i k m
3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}: hello.com/a hej.com/b ... hallo.com/n
>>> import string
>>> string.ascii_lowercase[:14]
'abcdefghijklmn'
>>> string.ascii_lowercase[:14:2]
'acegikm'
To do the urls, you could use something like this
[i + j for i, j in zip(list_of_urls, string.ascii_lowercase[:14])]
Assuming this is a homework ;-) - no need to summon libraries etc - it probably expect you to use range() with chr/ord, like so:
for i in range(ord('a'), ord('n')+1):
print chr(i),
For the rest, just play a bit more with the range()
Hints:
import string
print string.ascii_lowercase
and
for i in xrange(0, 10, 2):
print i
and
"hello{0}, world!".format('z')
for one in range(97,110):
print chr(one)
Get a list with the desired values
small_letters = map(chr, range(ord('a'), ord('z')+1))
big_letters = map(chr, range(ord('A'), ord('Z')+1))
digits = map(chr, range(ord('0'), ord('9')+1))
or
import string
string.letters
string.uppercase
string.digits
This solution uses the ASCII table. ord gets the ascii value from a character and chr vice versa.
Apply what you know about lists
>>> small_letters = map(chr, range(ord('a'), ord('z')+1))
>>> an = small_letters[0:(ord('n')-ord('a')+1)]
>>> print(" ".join(an))
a b c d e f g h i j k l m n
>>> print(" ".join(small_letters[0::2]))
a c e g i k m o q s u w y
>>> s = small_letters[0:(ord('n')-ord('a')+1):2]
>>> print(" ".join(s))
a c e g i k m
>>> urls = ["hello.com/", "hej.com/", "hallo.com/"]
>>> print([x + y for x, y in zip(urls, an)])
['hello.com/a', 'hej.com/b', 'hallo.com/c']
import string
print list(string.ascii_lowercase)
# ['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']
import string
print list(string.ascii_lowercase)
# ['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']
and
for c in list(string.ascii_lowercase)[:5]:
...operation with the first 5 characters
myList = [chr(chNum) for chNum in list(range(ord('a'),ord('z')+1))]
print(myList)
Output
['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']
list(string.ascii_lowercase)
['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']
Try:
strng = ""
for i in range(97,123):
strng = strng + chr(i)
print(strng)
import string
string.printable[10:36]
# abcdefghijklmnopqrstuvwxyz
string.printable[10:62]
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
#1)
print " ".join(map(chr, range(ord('a'),ord('n')+1)))
#2)
print " ".join(map(chr, range(ord('a'),ord('n')+1,2)))
#3)
urls = ["hello.com/", "hej.com/", "hallo.com/"]
an = map(chr, range(ord('a'),ord('n')+1))
print [ x + y for x,y in zip(urls, an)]
The answer to this question is simple, just make a list called ABC like so:
ABC = ['abcdefghijklmnopqrstuvwxyz']
And whenever you need to refer to it, just do:
print ABC[0:9] #prints abcdefghij
print ABC #prints abcdefghijklmnopqrstuvwxyz
for x in range(0,25):
if x % 2 == 0:
print ABC[x] #prints acegikmoqsuwy (all odd numbered letters)
Also try this to break ur device :D
##Try this and call it AlphabetSoup.py:
ABC = ['abcdefghijklmnopqrstuvwxyz']
try:
while True:
for a in ABC:
for b in ABC:
for c in ABC:
for d in ABC:
for e in ABC:
for f in ABC:
print a, b, c, d, e, f, ' ',
except KeyboardInterrupt:
pass
This is your 2nd question: string.lowercase[ord('a')-97:ord('n')-97:2] because 97==ord('a') -- if you want to learn a bit you should figure out the rest yourself ;-)
I hope this helps:
import string
alphas = list(string.ascii_letters[:26])
for chr in alphas:
print(chr)
About gnibbler's answer.
Zip -function, full explanation, returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. [...] construct is called list comprehension, very cool feature!
# Assign the range of characters
first_char_start = 'a'
last_char = 'n'
# Generate a list of assigned characters (here from 'a' to 'n')
alpha_list = [chr(i) for i in range(ord(first_char), ord(last_char) + 1)]
# Print a-n with spaces: a b c d e f g h i j k l m n
print(" ".join(alpha_list))
# Every second in a-n: a c e g i k m
print(" ".join(alpha_list[::2]))
# Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}
# Ex.hello.com/a hej.com/b ... hallo.com/n
#urls: list of urls
results = [i+j for i, j in zip(urls, alpha_list)]
#print new url list 'results' (concatenated two lists element-wise)
print(results)
Another way to do it
import string
aalist = list(string.ascii_lowercase)
aaurls = ['alpha.com','bravo.com','chrly.com','delta.com',]
iilen = aaurls.__len__()
ans01 = "".join( (aalist[0:14]) )
ans02 = "".join( (aalist[0:14:2]) )
ans03 = "".join( "{vurl}/{vl}\n".format(vl=vlet,vurl=aaurls[vind % iilen]) for vind,vlet in enumerate(aalist[0:14]) )
print(ans01)
print(ans02)
print(ans03)
Result
abcdefghijklmn
acegikm
alpha.com/a
bravo.com/b
chrly.com/c
delta.com/d
alpha.com/e
bravo.com/f
chrly.com/g
delta.com/h
alpha.com/i
bravo.com/j
chrly.com/k
delta.com/l
alpha.com/m
bravo.com/n
How this differs from the other replies
iterate over an arbitrary number of base urls
cycle through the urls using modular arithmetic, and do not stop until we run out of letters
use enumerate in conjunction with list comprehension and str.format
Related
I am creating a function that returns a histogram with each letter of the alphabet and asterisks that map out how many times each character appears in a string. So far I have:
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']
def character_frequency_string(text):
#remove_extraneous function removes anything that is not a letter in the alphabet from the text string
new_text = remove_extraneous(text)
for char in new_text:
if char in new_text:
print(char +' ' + '*'*new_text.count(char))
if char not in new_text:
print(char)
My docstring is the following (with the outputs as they are right now, incorrect):
'''
Examples:
>>> character_frequency_string('hello world!')
h *
e *
l ***
l ***
o **
w *
o **
r *
l ***
d *
>>> character_frequency_string('testing!')
t **
e *
s *
t **
i *
n *
g *
'''
The correct output for 'hello world!' would be:
How could I change my code so that the histogram works as intended (with all of the alphabet in order, displaying an asterisk beside each letter for its character frequency, still displaying letters when they aren't in the text, just with no asterisk.)
Iterate over alphabet:
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']
def character_frequency_string(text):
new_text = text
for char in alphabet:
print(char + ' ' + '*' * new_text.count(char))
character_frequency_string('hello world!')
Output
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
The above solution has O(n^2) time complexity, a more performant alternative is to use collections.Counter.
You could do the following, using a collections.Counter and f-strings:
from collections import Counter
from string import ascii_lowercase as alphabet
def character_frequency_string(text):
c = Counter(text.lower())
for x in alphabet:
print(f"{x} {'*' * c[x]}")
>>> character_frequency_string("hello world!")
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
Some docs:
Counter
string.ascii_lowercase
A dictionary approach. Notice the text may contain characters which do not belongs to the alphabet such as punctuation and white spaces. In case, such excluded characters are implemented also as string.punctuation and string.whitespace.
import string
alphabet = string.ascii_lowercase
def character_frequency_string(text, sep='*'):
d = dict.fromkeys(alphabet, 0)
for c in tuple(text.lower()):
if c in d:
d[c] += 1
print(*(f'{k} {sep*v}' for k, v in d.items()), sep='\n')
t = 'hello world!'
character_frequency_string(t)
You could use set for getting the same result
import re
strString = input("Please give input value of the string :")
strString = re.sub(r"[^a-zA-Z]","",strString)
strString=strString.lower()
print(strString)
a = list(sorted(set(strString.lower())))
for i in range(len(a)):
count = 0
for k in range(len(strString)):
if a[i] == strString[k]:
count = count + 1
str(a[i])+"is"+str(count)
print(a[i] + " " + "*" *count)
So basically what I want to do is if the random string of characters generated is over 6 chars long it adds a space in a random place in that string and then the remaining ones are added on after the space so for example: raw output: "aoneicse", what I want : "aoneic se" or "aone icse".
Here is my code:
import random
alist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
blist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
clist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define the 3 words
a = ''.join(random.choices(alist, k = random.randint(2,8)))
b = ''.join(random.choices(blist, k = random.randint(2,8)))
c = ''.join(random.choices(clist, k = random.randint(2,8)))
# each letter is a certain word, if this word exceeds 6 characters add a space in a random place
if a length = > 6:
asp = [a + " "]
if b length = > 6:
bsp = [b + " "]
if c length = > 6:
csp = [c + " "]
# or something along the lines of this i guess
This code does not currently work, BTW.
You don't need to create a list of strings with every letter of the alphabet, there's already a string module that does that for you:
import string
print(' ' + string.ascii_lowercase)
# Outputs abcdefghijklmnopqrstuvwxyz
You also don't need to create three different variables, you can just use a single one and use that:
import string
base_str = ' ' + string.ascii_lowercase
Then, you can use a list to generate your words based on this string:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
Now, just apply your space requirement to each word:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
new_words = []
for word in words:
if len(word) < 6:
new_word = word
else:
pos = random.randrange(len(word))
new_word = word[:pos] + ' ' + word[pos:]
new_words.append(new_word)
Using random.seed(0), new_words is equal to ['j xazmxvz', 'oxmg', 'buzns pcb'].
Don't join the choices immediately. Generate the list, and if it is long enough, pick an index in the middle (sufficiently far from either end, depending on your needs), and perform a slice assignment to the empty list at that position. Then join the list into a single string.
import string
a = random.choices(string.ascii_lowercase, k=random.randint(2,8))
if len(a) > 6:
# Adjust the arguments to randint as desired
x = random.randint(2, len(a) - 2)
a[x:x] = ' '
a = ''.join(a)
import random
character = list(map(chr, range(ord('a'), ord('z') + 1)))
def get_char():
return character[random.randint(0, len(character) - 1)]
def gen_word(min_len, max_len):
word = [get_char() for _ in range(random.randint(min_len, max_len))]
if len(word) > 6:
word[random.randint(1, len(word) - 2)] = ' '
return ''.join(word)
for i in range(10):
print(gen_word(4, 10))
Iād use slices to return a space, sliced-in at the right spot; Something along the lines of:
def split(input_str):
if len(input_str) > 6:
space_at = rand(0,len(input_str))
return input_str[:space_at] + ā ā + input_str[space_at:]
else:
return input_str
import random
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']
iterations = 1
running = True
def random_picker():
random_choice = random.choice(alphabet)
iterations =+ 1
print(random_choice)
while running == True:
if iterations <=26:
random_picker()
else:
running == False
I'm trying to get a different random letter through each iteration, through all 26. Each letter picked needs to update the random_choice variable.
Your program will continue looping until 26 letters are returned. Since you want a different letter on each iteration, it's probably easier to shuffle the alphabet array and loop over it instead of trying to choose a random letter in each iteration:
random.shuffle(alphabet)
Paul M. EDIT - Here is an example of how you might use it to achieve the desired effect:
from string import ascii_lowercase
from random import shuffle
alphabet = list(ascii_lowercase)
shuffle(alphabet)
for char in alphabet:
print(char)
Output:
j
m
z
w
k
y
d
f
l
c
u
b
t
s
e
p
x
g
a
r
n
h
i
q
o
v
>>>
Python novice here. The goal of the following Code is, to print all possible combinations to pair n characters of the set.
The Problem is that the following code gives an output, that also has more then n characters.
In the Following Code example n=3, but in the Output there are combinations with more then 3.
Code:
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, "", n, k)
def printAllKLengthRec(set, prefix, n, k):
if (k == 0) :
print(prefix)
return
for i in range(n):
newPrefix = prefix + set[i]
printAllKLengthRec(set, newPrefix, n, k-1)
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S','T','V','W','Y']
k = 3
printAllKLength(set1, k)
Output:
WNT
WNV
WNW
WNY
WPQA
WPQC
WPQD
WPQE
WPQF
WPQG
WPQH
WPQI
WPQK
WPQL
WPQM
WPQN
WPQPQ
WPQR
WPQS
WPQT
WPQV
WPQW
WPQY
WRA
The aim would be to generate strictly strings of length 3, so if anyone could point me in the right direction, I would be more than grateful.
I rewrote you functions a bit and stripped them to the essentials:
def printAllKLength(set, k):
printAllKLengthRec(set, "", k)
def printAllKLengthRec(set, string, k):
if len(string) == k:
print(string)
return
for c in set:
printAllKLengthRec(set, string + c, k)
return
if __name__ == "__main__":
print("First Test")
set1 = ['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K',
'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y']
k = 3
printAllKLength(set1, k)
A little hint for next time, break you sample size down to for example len(set1) = 3. then it is far easier to debug and you don't get lost in your own code.
You can use Itertools' combinations function. It takes an iterable and the length of the combination as parameters.
import itertools
num_char = 3
my_set = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}
combinations = itertools.combinations(my_set, num_char)
for i in combinations:
print("".join(i))
I have this list which contains letters, and I need to check if a pre-determined word located in another list is horizontally inside this list of letters.
i.e.:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
I don't need to tell if a word was not found, but if it was I need to tell which one.
My problem is that so far I've tried to compare letter by letter, in a loop similar to this:
for i in range(n): # n = number of words
for j in range(len(word_to_search[i])): # size of the word I'm searching
for k in range(h): # h = height of crossword
for m in range(l): # l = lenght of crossword
But it's not working, inside the last loop I tried several if/else conditions to tell if the whole word was found. How can I solve this?
You can use str.join:
mat_input = [['v', 'e', 'd', 'j', 'n', 'a', 'e', 'o'], ['i', 'p', 'y', 't', 'h', 'o', 'n', 'u'], ['s', 'u', 'e', 'w', 'e', 't', 'a', 'e']]
words_to_search = ['python', 'fox']
joined_input = list(map(''.join, mat_input))
results = {i:any(i in b or i in b[::-1] for b in joined_input) for i in words_to_search}
Output:
{'python': True, 'fox': False}
I'd start by joining each sublist in mat_input into one string:
mat_input_joined = [''.join(x) for x in mat_input]
Then loop over your words to search and simply use the in operator to see if the word is contained in each string:
for word_to_search in words_to_search:
result = [word_to_search in x for x in mat_input_joined]
print('Word:',word_to_search,'found in indices:',[i for i, x in enumerate(result) if x])
Result:
Word: python found in indices: [1]
Word: fox found in indices: []