print recursive pattern without quotes in python - python-3.x

my code for pattern:
def pattern(n):
if n==1:
return '1'
else:
return pattern(n-int(n/2))*2+str(n)
print(pattern(n))
i need:
>>> pattern(1)
1
>>> pattern(2)
112
>>> pattern(4)
1121124
>>> pattern(8)
112112411211248
but i get:
>>> pattern(1)
'1'
>>> pattern(2)
'112'
>>> pattern(4)
'1121124'
>>> pattern(8)
'112112411211248'
i have tried a lot but nothing is working to get rid of those pesky quotes.

The quotes are from the REPL printing the representation of the result of the function call, which is a string. If you do not want the representation then just print the result explicitly instead.

Related

Why i getting None In addition to the Output? [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 4 years ago.
I have defined a function as follows:
def lyrics():
print "The very first line"
print lyrics()
However why does the output return None:
The very first line
None
Because there are two print statements. First is inside function and second is outside function. When a function doesn't return anything, it implicitly returns None.
Use return statement at end of function to return value.
e.g.:
Return None.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
Because of double print function. I suggest you to use return instead of print inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()

Python Consecutive characters

If a string is given, substitute the character with number of times that character is repeated only if the character is repeated more than three times consecutively like below
Input: aaaaa Output: 5Za
Input: addeeeeuyyyyy OutPut: add4Zeu5Zy
Tried like below:
>>> from itertools import groupby
>>> strs="aaaaa"
>>> [[k, len(list(g))] for k, g in groupby(strs)]
[['a', 5]]
>>>
Along the same thought process you were using.
from itertools import groupby
def condense(strs):
new_str = ''
for k, g in groupby(strs):
length = len(list(g))
if length > 3:
new_str += f'{length}Z{k}'
else:
new_str += k*length
return new_str
print(condense('aaaaa '))
print(condense('addeeeeuyyyyy'))
You got a good part of it - you need to implement the restriction of only abbreviating consecutive letters that occure 4+ times and add the 'Z' to the output.
You could do it like so:
from itertools import groupby
def run_length_encode(data):
result = []
for letter,amount in ( (k, len(list(g))) for k, g in groupby(data)):
result.append(letter*amount if amount < 4 else f'{amount}Z{letter}')
return ''.join(result)
data = "someaaaaabbbcdccdd"
print(data, run_length_encode(data), sep = "=>" )
Output:
someaaaaabbbcdccdd => some5Zabbbcdccdd
You can find more solutions (regex f.e.) in this related post:
Run length encoding in Python
s=input()
ini=""
ans=""
for i in range(len(s)):
if ini=="":
ini=s[i]
c=0
if ini==s[i]:
c=c+1
if ini!=s[i]:
if c>=3:
ans=ans+str(c)+"Z"+ini
else:
ans=ans+c*ini
ini=s[i]
c=1
if c!=0 and c<3:
ans=ans+c*ini
elif c!=0 and c>=3:
ans=ans+str(c)+"Z"+ini
print(ans)

Performance Issue: Lookup sub-value of python dictionary if it is matching another value

I have a python dictionary as follows. Same way, dictionary might have 2 comma separate values for 'Var'(i.e. Dep1,Dep2) and then their respective SubValue (ABC1||A1B1||B1C1, ABC2||A2B2||B2C2).
I'm trying to extract value A1B1 (or A1B1 and B1C1 if there are two Var) with a match of mainValue 'ABC1' and prefix of SubVal 'ABC1'.
ld = { 'id' : 0
'Var': 'Dep1'
'SubVal': 'ABC1||A1B1,ABC2||A2B2,ABC3||A3B3',
'MainValue': 'ABC1'}
So far I tried splitting Subval into list (splitting by comma) and then convert each pair (|| separated) into another dictionary and then looking up the match.
Can anyone suggest a better approach in terms of performance to do this?
Let:
>>> ld = { 'id' : 0, 'Var': 'Dep1', 'SubVal': 'ABC1||A1B1,ABC2||A2B2,ABC3||A3B3', 'MainValue': 'ABC1'}
Your split + dict solution is roughly (note the maxsplit parameter to handle ABC1||A1B1||B1C1 cases):
>>> def parse(d):
... sub_val = dict(t.split('||', maxsplit=1) for t in ld['SubVal'].split(","))
... return sub_val[d['MainValue']]
>>> parse(ld)
'A1B1'
A benchmarck gives:
>>> import timeit
>>> timeit.timeit(lambda: parse(ld))
1.002971081999931
You build a dict for a one shot lookup: that's a bit overkill. You can perform a direct lookup for the MainValue:
>>> def parse_iter(d):
... mv = d['MainValue']
... g = (t.split('||', maxsplit=1) for t in d['SubVal'].split(","))
... return next(v for k, v in g if k == mv)
>>> parse_iter(ld)
'A1B1'
It is a little faster:
>>> timeit.timeit(lambda: parse_iter(ld))
0.8656512869993094
A faster approach is to look for the MainValue in the the ld[SubVal] string and extract the right SubVal. (I assume the MainValue can't be a SubVal or a substring of a SubVal).
With a regex:
>>> import re
>>> def parse_re(d):
... pattern = d['MainValue']+"\|\|([^,]+)"
... return re.search(pattern, d['SubVal']).group(1)
>>> parse_re(ld)
'A1B1'
This is around 25 % faster than the first version on the example:
>>> timeit.timeit(lambda: parse_re(ld))
0.7367669239997667
But why not perform the search manually?
>>> def parse_search(d):
... s = d['SubVal']
... mv = d['MainValue']
... i = s.index(mv) + len(mv) + 2 # after the ||
... j = s.index(",", i)
... return s[i:j]
>>> parse_search(ld)
'A1B1'
This version is around 60% faster than the first version (on the given example):
>>> timeit.timeit(lambda: parse_search(ld))
0.3840863969999191
(If the MainValue can be a SubVal, you can check if there is a comma before the MainValue or SubVal starts with MainValue.)

Difference between int(input()) and input(int()) in Python 3

when I type code as int(input()) and input(int()) for same input let say 12,output are 12 and 012 respectively . So why this,what is difference in syntax?
input() can take some text as parameter as description of the input-line.
From the manual:
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
int() is zero and therefore you pass zero to input if you do that:
# --> same as input(0):
input(int())
If you write int(input()) you first get the input which is a string and then cast it to an int:
>>> type(input())
5
<class 'str'>
>>> type(int(input()))
5
<class 'int'>
>>>
int() returns the integer 0. input() is using this as the prompt argument (which it prints out to stdout). Hence the extra 0 being printed in the front.

converting bytes to string gives b' prefix

I'm trying to convert an old python2 code to python3, and I'm facing a problem with strings vs bytes
In the old code, this line was executed:
'0x' + binascii.hexlify(bytes_reg1)
In python2 binascii.hexlify(bytes_reg1) was returning a string but in python3 it returns bytes, so it cannot be concatenated to "0x"
TypeError: can only concatenate str (not "bytes") to str
I tried converting it to string:
'0x' + str(binascii.hexlify(bytes_reg1))
But what I get as a result is:
"0xb'23'"
And it should be:
"0x23"
How can I convert the bytes to just 23 instead of b'23' so when concatenating '0x' I get the correct string?
can you try doing this and let me know whether it worked for you or not :
'0x' + str(binascii.hexlify(bytes_reg1)).decode("utf-8")
# or
'0x' + str(binascii.hexlify(bytes_reg1), encoding="utf-8")
note- Also if you can provide the sample of bytes_reg1, it will be easier to provide a solution.
Decode is the way forward, as #Satya says.
You can access the hex string in another way:
>>> import binascii
>>> import struct
>>>
>>> some_bytes = struct.pack(">H", 12345)
>>>
>>> h = binascii.hexlify(some_bytes)
>>> print(h)
b'3039'
>>>
>>> a = h.decode('ascii')
>>> print(a)
3039
>>>
>>> as_hex = hex(int(a, 16))
>>> print(as_hex)
0x3039
>>>

Resources