...
Code Block |
---|
def expand(x): return ''.join(x) * 3 |
Print string n times
Code Block |
---|
n = 2;
s ="Programming";
print(s * n); # ProgrammingProgramming |
Basic Operators
Python Arithmetic Operators
...
Code Block |
---|
import os if not os.path.exists('test.png'): # do something if 'test.png' does not exist pass |
Algorithms
...
Check all unique or not
Code Block |
---|
def isall_palindromeunique(wordlst): j =return len(wordlst) == len(set(lst)) x = [1,1,2,2,3,2,3,4,5,6] y = [1,2,3,4,5] all_unique(x) # False all_unique(y) # True |
Palindrome number - Determine whether an integer is a palindrome
Code Block |
---|
def is_palindrome(word): j = len(word)--1 i =0 while i<j and word[i].lower()==word[j].lower(): i+=1 j-=1 i =0 while i<j return (i>=j) and word[i].lower()==word[j].lower(): print(is_palindrome('i+=1 j-=1 return (i>=j) print(is_palindrome('Deleveled')) |
Two sum - return indices of the two numbers such that they add up to a specific target
...
Code Block | ||
---|---|---|
| ||
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# collect value serially
v=[]
p=head
while p!=None:
v.append(p.val)
p=p.next
# reorder based on the given logic
i=0
lcnt=len(v)
j=lcnt-1
p=head
while p!=None:
p.val = v[i]
i += 1
p=p.next
if p!=None:
p.val = v[j]
j-=1
p = p.next
|
Compact - Remove Falsy values (None, False, "")
Code Block |
---|
def compact(lst): return list(filter(None, lst)) compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] |
Python Simple Web Server
Code Block | ||||
---|---|---|---|---|
| ||||
import SimpleHTTPServer
import SocketServer
PORT = 8888
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever() |
You can run above as
Code Block |
---|
python -m simple_http_server.py |