Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Code snippets on how to use different features in Python 3

License

NotificationsYou must be signed in to change notification settings

codophobia/python-code-snippets

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

List

# Create a list and iterate over itnumbers= []numbers.append(1)numbers.append(2)numbers.append(3)fornuminnumbers:print(num)'''123'''
# Create a list and iterate over itnumbers= [1,2,3]length=len(numbers)foriinrange(length):print(numbers[i])# Output'''123'''
# Modify values in a listnumbers= [1,2,3]foriinrange(len(numbers)):numbers[i]+=1print(numbers)'''[2, 3, 4]'''
# Sort a list in-place in ascending ordera= [2,4,1,9,8]a.sort()print(a)'''[1, 2, 4, 8, 9]'''
# Sort a list in-place in descending ordera= [2,4,1,9,8]a.sort(reverse=True)print(a)'''[9, 8, 4, 2, 1]'''

Strings

# Declare a string and iterate over the charactersstring='Hello'forcinstring:print(c)'''Hello'''
# Declare a string and iterate over the charactersstring='Hello'foriinrange(len(string)):print(string[i])'''Hello'''
# Modifying a stringstring='hello'string[0]='H''''TypeError: 'str' object does not support item assignment'''
# Sort a strings='shivam'sorted_s=''.join(sorted(s))print(sorted_s)'''ahimsv'''

Tuples

# Declare a tuple and iterate over itvowels= ('a','e','i','o','u')forvinvowels:print(v)'''aeiou'''
# Declare a tuple and print elementsvowels= ('a','e','i','o','u')print(vowels[0])print(vowels[2])print(vowels[-1])'''aiu'''
# Modify a tuplevowels= ('a','e','i','o','u')vowels[0]='b''''TypeError: 'tuple' object does not support item assignment'''

Dictionary

# Declare a dictionary and print key value pairsd= {'1':'Dhoni','2':'Sachin','3':'Dravid'}fork,vind.items():print(k,v)'''1 Dhoni2 Sachin3 Dravid'''
# Dynamically insert key values and print itd= {}# Store square of numbers from 1 to 5foriinrange(1,6):d[i]=i*i# Print the squarefork,vind.items():print(k,v)# Output'''1 12 43 94 165 25'''

Set

# Declare a set, insert values and print its=set()s.add(1)s.add(4)s.add(3)s.add(1)print(s)'''{1, 3, 4}'''

2D list/array

# Declare a 2D listN=5M=5matrix= [0]*Nforiinrange(N):col= [0]*Mmatrix[i]=colprint(matrix)'''[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]'''
# Declare a 2D listN=5M=5matrix= [[0forjinrange(M)]foriinrange(N)]print(matrix)'''[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]'''
# Declare a 2D listN=5M=5matrix= [[0]*Mforiinrange(N)]print(matrix)'''[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]'''
# Modify the values in a 2D listmatrix= [[0]*4foriinrange(3)]foriinrange(3):forjinrange(4):matrix[i][j]+=1print(matrix)'''[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]'''

Deque

# Operations on dequefromcollectionsimportdequedq=deque([])dq.append(1)dq.append(2)dq.appendleft(3)dq.appendleft(4)print(dq)print(dq.pop())print(dq.popleft())'''deque([4, 3, 1, 2])24'''

Queue

# Implement queue using dequefromcollectionsimportdequeq=deque([])q.append(1)q.append(2)q.append(3)print(q)print(q.popleft())print(q.popleft())'''deque([1, 2, 3])12'''
# Implement queue using QueuefromqueueimportQueueq=Queue()q.put(1)q.put(2)q.put(2)print(q.qsize())print(q.get())print(q.get())print(q.qsize())'''3121'''

Stack

# Implement stack using liststack= []stack.append(1)stack.append(2)stack.append(3)print(stack)print(stack.pop())print(stack.pop())print(stack)'''[1, 2, 3]32[1]'''
# Implement stack using dequefromcollectionsimportdequestack=deque([])stack.append(1)stack.append(2)stack.append(3)print(stack)print(stack.pop())print(stack.pop())print(stack)'''deque([1, 2, 3])32deque([1])'''

Ordered dictionary

# Operations on ordereddictfromcollectionsimportOrderedDictd=OrderedDict()d[1]=2d[2]=3d[3]=4# If we print the dictionary now, the keys will be printed in order of insertion.fork,vind.items():print(k,v)print(d.popitem(last=False))print(d.popitem())'''1 22 33 4(1, 2)(3, 4)'''

Defaultdict

# Operations on defaultdictfromcollectionsimportdefaultdictnumbers= [1,1,2,5,2,8]d=defaultdict(int)fornuminnumbers:d[num]+=1fork,vind.items():print(k,v)'''1 22 25 18 1'''

Counters

fromcollectionsimportCounternumbers= [1,1,2,5,2,8]cntr=Counter(numbers)fork,vincntr.items():print(k,v)'''1 22 25 18 1'''

Namedtuples

fromcollectionsimportnamedtuplePoint=namedtuple('Point', ['x','y'])p1=Point(1,2)print(p1.x,p1.y)'''1 2'''

Heaps

# Min heap usageimportheapqL= []heapq.heapify(L)# Min heapheapq.heappush(L,3)# Pushing 3 into heapheapq.heappush(L,2)# Pushing 2 into heapprint(L)print(heapq.heappop(L))# Popping the minimum elementprint(L)'''[2, 3]2[3]'''

Binary search

# Check if an elements is present or not and return the index if element is presentfrombisectimportbisect_lefta= [1,2,4,4,5]x=4idx=bisect_left(a,x)ifidx!=len(a)anda[idx]==x:print(f'{x} is present at index{idx}')else:print('Element not found')'''4 is present at index 2'''
# Find index of first element greater than or equal to target(x)frombisectimportbisect_lefta= [1,2,4,4,5]x=6idx=bisect_left(a,x)ifidx==len(a):print('All elements are smaller than the target element')else:print(idx)'''All elements are smaller than the target element'''
# Find index of first element greater than target(x)frombisectimportbisect_righta= [1,2,4,4,5]x=4idx=bisect_right(a,x)ifidx==len(a):print('All elements are smaller than the target element')else:print(idx)'''4'''

Linked list

# Create a singly linked list and traverse itclassNode:def__init__(self,data):self.data=dataself.next=NoneclassLinkedList:def__init__(self):self.head=Nonedefinsert_at_end(self,data):new_node=Node(data)ifself.headisNone:self.head=new_nodeelse:temp=self.headwhile(temp.next):temp=temp.nexttemp.next=new_nodedeftraverse(self):temp=self.headwhile(temp):print(temp.data)temp=temp.nextll=LinkedList()ll.insert_at_end(1)ll.insert_at_end(2)ll.insert_at_end(3)ll.traverse()'''123'''

Binary Tree

# Create a binary tree and traverse itclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=Noneroot=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.right.left=Node(5)# Binary tree created from the above code'''              1             /\            2   3           /\          4       5'''definorder(root):ifnotroot:returnprint(root.data)inorder(root.left)inorder(root.right)inorder(root)'''12435'''

Graph

# Create a graph and traverse itfromcollectionsimportdefaultdictgraph=defaultdict(list)graph[1].append(2)# 1 -> 2graph[2].append(3)# 1 -> 2 -> 3graph[4].append(1)# 4 -> 1 -> 2 -> 3visited=set()defdfs(node,graph,visited):ifnodenotinvisited:print(node)visited.add(node)forvingraph[node]:dfs(v,graph,visited)dfs(4,graph,visited)'''4123'''

About

Code snippets on how to use different features in Python 3

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp