Skip to content

Instantly share code, notes, and snippets.

@quachngocxuan
Last active August 4, 2019 14:41
Show Gist options
  • Save quachngocxuan/c4c3b5cc73aeb40ef116511e322b8bba to your computer and use it in GitHub Desktop.
Save quachngocxuan/c4c3b5cc73aeb40ef116511e322b8bba to your computer and use it in GitHub Desktop.
Learn enough to be dangerous - Python

Learn enough to be dangerous - Python

Input

s = input()
n = int(input())
integer_list = map(int, input().split())
n = int(raw_input())
integer_list = map(int, raw_input().split())

Output

Format string with variable values

command_string += "{},".format(command[i+1])

Format float value (python3)

"{:.2f}".format(sum/3)

String manipulation

Loop char in a string

for c in s:

or

for i in range(0, len(s)):

Split & join

>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings. 
>>> a = "-".join(a)

Convert a string into a list for mutable

>>> string = "abracadabra"
>>> l = list(string)
>>> l[5] = 'k'
>>> string = ''.join(l)
>>> print string
abrackdabra

or slice the string and join it back.

>>> string = string[:5] + "k" + string[6:]
>>> print string
abrackdabra

Others:

num = ord(aChar)    # ascii value of a char
aChar = ord(num)    # char of an int value
print 'ab123'.isalnum()
print 'abcD'.isalpha()
print '1234'.isdigit()
print 'abcd123#'.islower()
print 'ABCD123#'.isupper()

Eval function

eval(LIST_NAME + "." + command_string)
for test in ('isalnum', 'isalpha', 'isdigit', 'islower', 'isupper'):
  any(eval("c." + test + "()") for c in s)

Loop in range

x = int ( raw_input())
y = int ( raw_input())
n = int ( raw_input())
ar = []
p = 0
for i in range ( x + 1 ) :
    for j in range( y + 1):
        if i+j != n:
            ar.append([])
            ar[p] = [ i , j ]
            p+=1
print ar
print ([[ i, j, k] for i in range( x + 1) for j in range( y + 1) for k in range(z+1) if ( ( i + j + k ) != n )])

Map & Reduce

Import this first

from functools import reduce
f = lambda x, y: x+y
sum = reduce(f, student_marks[query_name])
print("{:.2f}".format(sum/3))

Collection types

  • Lists are mutable (they can be changed), and tuples are immutable (they cannot be changed).
  • String is immutable

Loop a collection to check with 'any' condition

print(any(c.isalnum()  for c in s)) # True or False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment