combine multiple outputs in python - python

I am a noob and was wondering how to combine multiple outputs into one string that outputs
Here is my code
print ("password size (use numbers)")
passwordsize = int(input(""))
passwordsize = passwordsize -1
papers = ['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','?','!','1','2','3','4','5','6','7','8','9','0',]
q_list = [random.choice(papers) for i in range(passwordsize)]
' '.join(q_list)
poopers = q_list[0].replace("'", '')
print("/")
print(q_list)
for word in q_list:
result = word.replace("'", '')
print(result)
lets say that the random stuff picked was 3 a b c
it outputs...
3
a
b
c
I want it to output...
3abc
Any help is very much appreciated

Along the same lines as what #Chuck and #Ash proposed, but streamlining things a bit by taking fuller advantage of Python's standard library as well as the handy join string method:
import random
import string
passwordsize = 4 # int(input()) - 1
a = [*string.ascii_uppercase, *string.digits, "?", "!"]
print("".join(random.sample(a, passwordsize)))
Output:
W16H

import random
passwordsize = 4 # int(input("")) - 1
papers = ['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','?','!','1','2','3','4','5','6','7','8','9','0',]
q_list = [random.choice(papers) for i in range(passwordsize)]
result = ""
for word in q_list:
result += word
print(result)
String object in python can use add "+" operation to do concatenation.
For example, if you want to create s = "ABC", you can create it by s = 'A' + 'B' + 'C'.
The += operation can iteratively do the + operation.
Thus, you can create "ABC" by a for loop:
s = ""
for w in ['A', 'B', 'C']:
s += w

If you want every generated char is unique, use random.sample. But if you want every char can occur more than one, use random.choices instead:
from random import choices; from string import ascii_uppercase as caps, digits as nums
result = ''.join(choices(caps+'?!'+nums,k=int(input('password size (use numbers)\n'))))
print(result)
# password size (use numbers)
# 15
# DK6V1DZOFKA?3HG

Related

How to write a program that finds the similarities and differences in pairs of characters in a better way

I'm new to Python and trying to learn more by doing exercises, now, I need to write a program that finds the similarities and differences between two lines of characters:
user enters number of pairs
then she enters pairs of characters in each line
he can see each pair in the output with a new line below the pairs that shows the similarities and differences
For instance:
the number of pairs is 2
the input pairs of characters is like this
aaa
aaa
123
456
the desired result:
aaa
aaa
...
123
456
***
As you can see we show the similarities by a dot(.) and differences with (*). Below, you can see what I've written so far:
# Get the strings
number_of_pairs = int(input(""))
string_list = []
i = 0
while i < (number_of_pairs * 2):
string_list.append(input())
i += 1
first_item = ""
second_item = ""
result = []
j = 0
while j < len(string_list):
first_item = list(string_list[j]) # ['a', 'a', 'a']
second_item = list(string_list[j + 1]) # ['b', 'b', 'b']
for i in range(len(first_item)):
if first_item[i] == second_item[i]:
result.append(".")
else:
result.append("*")
print(string_list[j])
print(string_list[j + 1])
print(''.join(result))
result.clear()
j += 2
first_item = ""
second_item = ""
I was wondering if you could say whether there are better ways to write this piece of code. I want to be aware of other ways.
I wrote the code all by myself
since I'm new to Python programming, I need to know opinions of other experts.
There is a standard function zip() that takes lists and joins then together positionally. Recalling that strings are kind of lists of characters we can do:
for char_a, char_b in zip("hello", "world"):
print(char_a, char_b)
We get:
h w
e o
l r
l l
o d
This will help us compare these strings character by character:
for char_a, char_b in zip("hello", "world"):
print(char_a == char_b)
giving us:
False
False
False
True
False
for example.
As long as we compare strings of equal length zip() is great but it only pairs things up until the shorter of the lists is exhausted. If we might allow our user to enter strings of differing lengths we might want to use itertools.zip_longest(). I leave that to you.
Now that we have a way to compare two strings character by character, the rest falls out as:
import itertools
## How many pairs to ask for:
number_of_pairs = int(input("How many pairs will you enter: "))
## ------------------------
## save pairs at a time to a list
## ------------------------
pairs = []
for i in range(number_of_pairs):
print(f"Enter pair {i+1}")
pairs.append([
input("\tFirst Entery: "),
input("\tSecond Entery: ")
])
## ------------------------
## ------------------------
## ------------------------
for pair in pairs:
## ------------------------
## compare characters positionally within the two strings
## ------------------------
matches = "".join(
"." if x==y else "*"
for x,y
in itertools.zip_longest(*pair)
)
## ------------------------
print(pair[0])
print(pair[1])
print(matches)
print()
## ------------------------

I want to duplicate a random letter of a string 1 time. How can I do?

This is my string:
keyword = "qatarworldcup"
I mean my string should be qqatarworldcup, qatarworldcupp or qatarrworlddcup
This should be pretty easy to do if you break it up into parts.
Select a random letter from the word.
import random
letter_index = random.randint(0, len(keyword)-1)
Split the word into two parts at the letter you picked.
before, after = keyword[:letter_index], keyword[letter_index:]
Join the two parts, adding an extra instance of the selected letter
result = before + keyword[letter_index] + after
If your strings are big enough, or you're doing this multiple times, you could see a speedup from reducing the number of string concatenations, because that's an O(N) operation on account of the immutability of strings. Since the selected letter already exists in the word, you can split it such that the selected letter is the last character of before and the first character of after. Then, you only need a single concatenationThanks to #Mechanic Pig for your comment:
before, after = keyword[:letter_index+1], keyword[letter_index:]
result = before + after
from random import randint
keyword = "qatarwordcup"
idx = randint(0, len(keyword) - 1)
keyword = keyword[:idx] + keyword[idx] + keyword[idx:]
I'd do it like this
import random
#Find random position in string
r = random.randint(0, len(keyword) - 1)
#Create new string with added character at random position
newStr = keyword[:r] + keyword[r] + keyword[r:]
Iteration through index-character pairs, apply the condition on each "term" with the ternary operator and join everything together.
import random
# fix random number generator (for testing only!)
random.seed(190)
keyword = "qatarworldcup"
# random index
r = random.randint(0, len(keyword)-1)
out = ''.join(char * 2 if i == r else char for i, char in enumerate(keyword))
print(out)
#qaatarworldcup

multiplying letter of string by digits of number

I want to multiply letter of string by digits of number. For example for a word "number" and number "123"
output would be "nuummmbeerrr". How do I create a function that does this? My code is not usefull, because it doesn't work.
I have only this
def new_word(s):
b=""
for i in range(len(s)):
if i % 2 == 0:
b = b + s[i] * int(s[i+1])
return b
for new_word('a3n5z1') output is aaannnnnz .
Using list comprehension and without itertools:
number = 123
word = "number"
new_word = "".join([character*n for (n, character) in zip(([int(c) for c in str(number)]*len(str(number)))[0:len(word)], word)])
print(new_word)
# > 'nuummmbeerrr'
What it does (with more details) is the following:
number = 123
word = "number"
# the first trick is to link each character in the word to the number that we want
# for this, we multiply the number as a string and split it so that we get a list...
# ... with length equal to the length of the word
numbers_to_characters = ([int(c) for c in str(number)]*len(str(number)))[0:len(word)]
print(numbers_to_characters)
# > [1, 2, 3, 1, 2, 3]
# then, we initialize an empty list to contain the repeated characters of the new word
repeated_characters_as_list = []
# we loop over each number in numbers_to_letters and each character in the word
for (n, character) in zip(numbers_to_characters, word):
repeated_characters_as_list.append(character*n)
print(repeated_characters_as_list)
# > ['n', 'uu', 'mmm', 'b', 'ee', 'rrr']
new_word = "".join(repeated_characters_as_list)
print(new_word)
# > 'nuummmbeerrr'
This will solve your issue, feel free to modify it to fit your needs.
from itertools import cycle
numbers = cycle("123")
word = "number"
output = []
for letter in word:
output += [letter for _ in range(int(next(numbers)))]
string_output = ''.join(output)
EDIT:
Since you're a beginner This will be easier to understand for you, even though I suggest reading up on the itertools module since its the right tool for this kind of stuff.
number = "123"
word = "number"
output = []
i = 0
for letter in word:
if(i == len(number)):
i = 0
output += [letter for _ in range(int(number[i]))]
i += 1
string_output = ''.join(output)
print(string_output)
you can use zip to match each digit to its respective char in the word (using itertools.cycle for the case the word is longer), then just multiply the char by that digit, and finally join to a single string.
try this:
from itertools import cycle
word = "number"
number = 123
number_digits = [int(d) for d in str(number)]
result = "".join(letter*num for letter,num in zip(word,cycle(number_digits)))
print(result)
Output:
nuummmbeerrr

Splits a string by number

I have just written a very simple function which splits a string by a given number. It works, but got flaws. It sometimes breaks a word apart, for example:
string = "He could not meet her in conversation"
number_of_lines = 5
result = (textwrap.fill(string, count(string, number_of_lines)))
print result
He could
not meet
her in c
onversat
ion
Please note it breaks the word "conversation." I need suggestions how to overcome this problem, or there is an inbuilt function for this task already available.
Here is the actual function:
import textwrap
import re
def count (s, no_of_lines):
result = (textwrap.fill(s.upper(), 1))
count = 1
while (len(re.split('[\n]', result)) != no_of_lines):
count = count + 1
result = (textwrap.fill(s.upper(), count))
return count
You could use the break_long_words option of the TextWrapper constructor:
import textwrap
import re
# define a customised object with option set to not break long words
textwrap = textwrap.TextWrapper(break_long_words=False)
def count (s, no_of_lines):
# set the width option instead of using a count
textwrap.width = 1
result = textwrap.fill(s.upper())
while len(re.split('\n', result)) > no_of_lines:
textwrap.width += 1
result = textwrap.fill(s.upper())
return textwrap.width
string = "He could not meet her in conversation"
number_of_lines = 5
textwrap.width = count(string, number_of_lines)
result = textwrap.fill(string)
print (result)
Output:
He could
not meet
her in
conversation

regex is counting only one pattern, when two same patterns are kept consecutive.why?

The following is an input.
INPUT
2
businessman video demeanor demeanor dishonest acknowledge dvd honor sister opportunity
keen labour artistic favourite red definition impatient take behaviour warmth
1
demeanour
OUTPUT
2
Because here demeanour is converted to its US launguage equivalent 'demenor' and then the number of 'demeanour' and 'demeanor' have to be counted.
I wrote the following code but it outputs 1 instead of 2
import re
n = int(raw_input())
b = []
for i in range(n):
b.append(raw_input())
b = " ".join(b)
b = b + " "
t = int(raw_input())
c = []
for i in range(t):
c = raw_input()
d = c[:-2]+"r"
match = re.findall(r"\s"+re.escape(c)+"\s",b)
match2 = re.findall(r"\s"+re.escape(d)+"\s",b)
print len(match)+len(match2)
I may have not completely explained you the scenario to know more please visit,
https://www.hackerrank.com/challenges/uk-and-us-2
PS: This is my first question on stackoverflow. Please correct me, if the problem is presented incorrectly.
EDIT:
Correct Answer:
import re
n = int(raw_input())
b = []
for i in range(n):
b.append(raw_input())
b = " ".join(b)
b = b + " "
t = int(raw_input())
for i in range(t):
c = raw_input()
d = c.replace("ou","o")
k = re.compile(r'\b%s\b'%c,re.I)
l = re.compile(r'\b%s\b'%d,re.I)
match = k.findall(b)
match2 = l.findall(b)
print len(match)+len(match2)
Use Alternation in your regex:
import re
input='''\
businessman video demeanor demeanour dishonest acknowledge dvd honor sister opportunity keen labour artistic favourite red definition impatient take behaviour warmth'''
matches=re.findall(r'(demeanour|demeanor)', input)
print matches, len(matches)
# ['demeanor', 'demeanour'] 2
Or, use a optional quantifier:
matches=re.findall(r'(demeanou?r)', input)
print matches, len(matches)
To keep from matching xyzdemeanour use a word boundary:
matches=re.findall(r'(\bdemeanou?r\b)', 'demeanor demeanour xyzdemeanour demeanourxyz')
print matches, len(matches)
# ['demeanor', 'demeanour'] 2
If all you have to consider is words like odour -> odor (missing the u), you can make something like:
import re
n = int(raw_input()) # Read number of lines
b = ""
for i in range(n): # Read lines and concatenate them to a string
b += raw_input() + " "
t = int(raw_input()) # Read number of words
c = []
for i in range(t): # Read words
word = raw_input()
c.append(word) # Add each word to a list
c.append(word.replace("u","")) # Add also the word without the u to the list
totallen = 0
for i in c: # Search for all words
match = re.findall(r""+i+"\s",b) # find all occurrences of a word
totallen += len(match) # Add it to total count
print totallen # Print total
I tested it on the website you write and it passed all the tests, but I will recommend you to write names for a variable that explain better what the are suppose to have, like numberoflines, numberofwords, text,words, etc

Categories

Resources