blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
c5cde9f453531733d7d0f3d6b80172577a662ed1
JayTwitty/pig_latin
/reverse_pig_latin.py
133
3.796875
4
sentence = input("What is the pig latin sentence that you want translated to English?") sentence = sentence.split() print(sentence)
1fe9d7bdf16f7880a6998f6d1ae7205ecdaecaf6
YeTong-Cloud/MLStudy
/matplotlibTest/drawLine.py
2,546
4.0625
4
""" ======================================= A simple plot with a custom dashed line ======================================= A Line object's ``set_dashes`` method allows you to specify dashes with a series of on/off lengths (in points). """ import numpy as np import matplotlib.pyplot as plt class drawLineClass: # 初始化函数 def __init__(self,type=0): self.x=[] self.y=[] self.xLabel="xLabel" self.yLabel="yLabel" self.linewidth=1 self.lineType='-' self.legendLabel="legendLabel" self.lineColor="green" if type ==1: self.fig, self.ax=self.createSubplots() #创建画板 #传入x def setX(self,x): self.x=x # 传出x def getX(self): return self.x # 传入x def setY(self, y): self.y = y # 传出x def getY(self): return self.y # 传入xLable def setXLabel(self, xLabel): self.xLabel = xLabel self.ax.set_xlabel(self.xLabel) # 传入yLable def setYLabel(self,yLabel): self.yLabel = yLabel self.ax.set_ylabel(self.yLabel) #创建画板 def setlegendLabel(self,legendLabel): self.legendLabel=legendLabel def createSubplots(self): fig, ax = plt.subplots() return fig,ax #设置线宽度 def setLinewidth(self,linewidth): self.linewidth=linewidth #设置线样式 def setLineType(self,lineType): self.lineType=lineType #设置线颜色 def setLineColor(self,lineColor): self.lineColor=lineColor #划线 def drawLine(self): if self.lineType=='': self.lineType='--' line1, = self.ax.plot(self.x, self.y, self.lineType,color=self.lineColor, linewidth=self.linewidth,label=self.legendLabel) self.lineType = '' self.ax.legend(loc='best') #显示 def show(self): plt.show() if __name__ == '__main__': x=[1,2,4,5,6,6] y=[2,4,5,6,7,3] drawLine=drawLineClass(0) drawLine.setXLabel("x") drawLine.setYLabel("y") drawLine.setX(x) drawLine.setY(y) drawLine.setLineColor("red") drawLine.setlegendLabel("第一条曲线") drawLine.setLineType("--") drawLine.drawLine() x = [1, 3, 4, 6, 6, 6] y = [2, 5, 4, 8, 7, 7] drawLine.setX(x) drawLine.setY(y) drawLine.setLineColor("green") drawLine.setlegendLabel("第二条曲线") drawLine.setLineType("-.") drawLine.drawLine() drawLine.show()
fe819de9021c08c0176c8cdab49ee0765c1ba2b1
HarryMWinters/coding-katas
/code-wars/snail/solution.py
978
3.734375
4
def snail(snail_map): """ Create a 1-D array of ints constructed from a snail traversal of the input array. Args: snail_map: An array of equal length integer arrays. Returns: A 1-D array of integers. """ outputArr = [] while snail_map: outputArr.extend(snail_map[0]) del snail_map[0] if snail_map: outputArr.extend(traverseRight(snail_map)) if snail_map: outputArr.extend(snail_map[-1][::-1]) del snail_map[-1] if snail_map: outputArr.extend(traverseLeft(snail_map)) return outputArr def traverseRight(arr): out = [] for subArr in arr: out.append(subArr[-1]) del subArr[-1] if not subArr: del subArr return out def traverseLeft(arr): out = [] for subArr in arr: out.append(subArr[0]) del subArr[0] if not subArr: del subArr return out[::-1]
95c2f14fd3b94211761d8b2770b41ad6c4c320ef
HarryMWinters/coding-katas
/hacker-rank/cavity-map/cavityMap.py
1,935
3.859375
4
def cavityMap(grid): """ Generate a list of of string with 'cavities' replaced by the the uppercase letter X. See README for fuller description of cavity. Args: grid: A list of strings. Returns: A list of strings of with the same dimensions as grid. Raises: TypeError: """ gridHeight, gridWidth = len(grid), len(grid[0]) cavityGrid = [] for rowNumber, row in enumerate(grid): newRow = "" if rowNumber and rowNumber < gridHeight - 1: # Skip first & last row. for colNumber, letter in enumerate(row): if colNumber and colNumber < gridWidth - 1: # Skip first & last column. if _isCavity(grid, rowNumber, colNumber): newRow += "X" else: newRow += letter else: newRow += letter else: newRow = row cavityGrid.append(newRow) return cavityGrid def _isCavity(grid, rowNumber, colNumber): """ Check if grid[rowNumber][colNumber] is less than its neighboors. Args: grid: A list of strings. rowNumber: The row index of the value to be checked colNumber: The column index of the value to be checked. Returns: A boolean. True if the indexes are at a cavity. Raises: IndexError: If the indexes are next to an edge or out of bounds. """ val = int(grid[rowNumber][colNumber]) neighboors = [ # It would be faster to check values on at a time and return at first # failure but IMHO less readable. int(grid[rowNumber][colNumber + 1]), int(grid[rowNumber][colNumber - 1]), int(grid[rowNumber + 1][colNumber]), int(grid[rowNumber - 1][colNumber]), ] if val > max(neighboors): return True else: return False
a7b0d12de35acf4a6a55f6064913db2c3d0d5f61
HarryMWinters/coding-katas
/hacker-rank/flipping-bits/solution.py
434
4.0625
4
def flippingBits(base10Number): """ The result of converting to base 2, flipping all the bits, and converting back into base 10. Args: base10Number: An integer. Returns: An integer. """ binary = "{0:b}".format(base10Number) binZero = "0" * 32 binary = binZero[:-len(binary)] + binary newBinary = "".join(["1" if c == "0" else "0" for c in binary]) return int(newBinary, 2)
1951e7c53edc5ee6d710ef96d5fb9c147bd6003a
HarryMWinters/coding-katas
/hacker-rank/crush/solution.py
831
4.03125
4
def arrayManipulation(n, queries): """ The maximum value of an element in an array of length arrLength after the operations in queries have been performed on it. Complexity: O(arrLength * len(queries) Args: arrLength: Non negative integer denoting length of array. queries: A list of operation to perform on the array. Format is [start_index, end_index, increment] Returns: A non negative integer. Raises: (someTypeOf)Error: if things go wrong. # NB: query indexing starts at 1!! """ arr = [0] * (n + 1) for q in queries: x, y, incr = q arr[x - 1] += incr if y <= len(arr): arr[y] -= incr maxi = x = 0 for i in arr: x += i if maxi < x: maxi = x return maxi
5c080df2641747eb5a1c8d313ed62d5194d2f3ae
bobbyocean/draggable_convex_hull
/polynomials.py
4,020
3.609375
4
""" Robert D. Bates, PhD Polynomial Class After writing x=Poly([0,1]), x can now be used to make polynomails. Like, f = (x-1)+x**6 Has many attached functions like, f.roots(), f.derivative(), f.convex_hull(), etc. """ import numpy as np from itertools import zip_longest def prod(iterable,start=1): for i in iterable: start*=i return start def positive_dot(a,b): if (a.conjugate()*b).imag>=0: return np.arccos((a.real*b.real+a.imag*b.imag)/np.abs(a*b)) return 2*np.pi-np.arccos((a.real*b.real+a.imag*b.imag)/np.abs(a*b)) def random_root(): r = np.random.rand() t = 2*np.pi*np.random.rand() return r*np.e**(t*1j) def root_coor(roots): return [(r.real,r.imag) for r in roots] class Poly: def __init__(self,polylist,listtype='coefficients'): self.round = 2 while polylist[-1]==0 and len(polylist)>1: polylist.pop(-1) for n,i in enumerate(polylist): if i.imag==0: polylist[n] = [i.real,int(i.real)][i.real==int(i.real)] else: polylist[n] = [i.real,int(i.real)][i.real==int(i.real)] + [i.imag,int(i.imag)][i.imag==int(i.imag)]*1j if listtype=='coefficients': self.coefficients = polylist def __repr__(self): exp = dict(zip('0123456789','⁰¹²³⁴⁵⁶⁷⁸⁹')) exponents = ['','x']+['x'+''.join(exp[i] for i in str(n)) for n in range(2,len(self.coefficients)+1)] terms=[] for c,e in zip(self.coefficients,exponents): c = complex(round(c.real,self.round),round(c.imag,self.round)) if c==0 and len(self.coefficients)!=1: pass elif c==0 and len(self.coefficients)==1: terms+=['0'] elif c==1: terms+=[[e,'1'][e=='']] elif c==-1 and len(terms)>0: terms+=['\b-'+e] elif abs(c)==-c and len(terms)>0: terms+=['\b{}{}'.format(c,e)] else: terms+=['{}{}'.format(c,e)] return '+'.join(terms) def __add__(self,other): if type(other)!=Poly: return Poly([self.coefficients[0]+other]+self.coefficients[1:]) else: return Poly([x+y for x,y in zip_longest(self.coefficients,other.coefficients,fillvalue=0)]) def __mul__(self,other): if type(other)!=Poly: return Poly([x*other for x in self.coefficients]) elif other.coefficients==[0,1]: return Poly([0]+self.coefficients) else: terms = [prod(i*[Poly([0,1])],self)*y for i,y in enumerate(other.coefficients)] return sum(terms,Poly([0])) def __neg__(self): return Poly([-x for x in self.coefficients]) def __pow__(self,other): return prod(other*[self],Poly([1])) def __eq__(self,other): return (self-other).coefficients == [0] def __sub__(self,other): return self+(-other) def __radd__(self,other): return self+other def __rsub__(self,other): return (-self)+other def __rmul__(self,other): return self*other def roots(self): return np.roots(list(reversed(self.coefficients))) def evaluate(self,value): return self.coefficients[0]+sum(c*value**i for i,c in list(enumerate(self.coefficients))[1:]) def derivative(self): return sum(c*i*Poly([0,1])**(i-1) for i,c in list(enumerate(self.coefficients))[1:]) def convex_hull(self): roots = sorted(self.roots(),key=lambda r: (np.angle(r),-np.abs(r))) if len(set(roots)) in [0,1,2]: return list(set(roots)) hull = [roots[0],roots[-1]] for i in range(2*len(set(roots))): sort = lambda r: positive_dot(hull[-1]-hull[-2],r-hull[-1]) hull+= [sorted([r for r in roots if r not in hull[-2:]],key=sort)[0]] start = [n for n,r in list(enumerate(reversed(hull)))[1:] if r==hull[-1]][0] return hull[len(hull)-start:] x = Poly([0,1])
09a05fdb4236cebffaa44ae9b71b734e6b0d82b2
SMinTexas/multiply_a_list
/mult_list.py
349
4.1875
4
# Given a list of numbers, and a single factor (also a number), create a # new list consisting of each of the numbers in the first list multiplied by # the factor. Print this list. mult_factor = 2 numbers = [2,4,6,8,10] new_numbers = [] for number in numbers: product = number * mult_factor new_numbers.append(product) print(new_numbers)
c92a186d6388c6f06f5f88d97ee4e1c4cb05f395
hingu-parth/Data_Structures-Python
/Binary Search Tree/1038. Binary Search Tree to Greater Sum Tree.py
513
3.578125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def bstToGst(self, root: TreeNode) -> TreeNode: def new(root,sumv): if not root: return sumv root.val+=new(root.right,sumv) print(root.val) return new(root.left,root.val) new(root,0) return root
8536d794b6f66bbbb364f4f58a7fe438784e0a63
rampage-1/networking-tools
/echoserver.py
1,104
3.5625
4
#!/usr/bin/env python3 # ^ use user environment python3, more reliable than? /bin/python3 # for https://realpython.com/python-sockets/ # not an original work # creates a socket object, binds it to interface:PORT, listens, accepts connection, echos back data recvd import socket HOST = '127.0.0.1' # loopback address for testing PORT = 65123 # arbitrary port with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Addresss Family = AF_INET: IPv4 # SOCK_STREAM: default TCP, SOC_DGRAM: UDP s.bind((HOST,PORT)) # bind associates the socket with an interface and port (for AF_INET) # values will differ depending on socket Address Family # if no HOST is specified the server will accept connections on all IPv4 interfaces s.listen() conn, addr = s.accept() # accept() returns a new socket object representing the connection, distinct from the listener established above with conn: print('Connection from', addr) while True: data = conn.recv(1024) # conn.recv() reads data sent by the client if not data: break conn.sendall(data) # echos back data recvd from client
4c7ff99357954ba73987f833eff1cb4daf07feb8
mrayapro/python_samples
/example_7_math_comparisons.py
224
3.953125
4
x = 5 print(x == 5) print({x == 5} is {x == 5}) print(x == -5 is {x == -5}) print(x > 4 is {x > 4}) print(x > 5 is {x > 5}) print(x >= 5 is {x >= 5}) print(x < 6 is {x < 6}) print(x < 5 is {x < 5}) print(x <= 5 is {x < 5})
20f796f850f1147150061ca20e0c250569a31fd0
mrayapro/python_samples
/Mani_example20.py
128
3.734375
4
my_list = ['3', '8', '1', '6', '0', '8', '4'] mystring='abc' new_list=[s + mystring for s in my_list] print(new_list)
1fe280eafbf7f4ca37046d98d4cf1d1ae08472ed
PrzemyslawMisiura/Deck_of_cards
/Deck_of_cards.py
2,953
3.90625
4
# Specifications # Card: # Each instance of Card should have a suit ("Hearts", "Diamonds", "Clubs", or "Spades"). # Each instance of Card should have a value ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"). # Card's __repr__ method should return the card's value and suit (e.g. "A # of Clubs", "J of Diamonds", etc.) class Card: def __init__(self, value, suit): self.value = value self.suit = suit def __repr__(self): return "{} of {}".format(self.value, self.suit) # Deck: # Each instance of Deck should have a cards attribute with all 52 possible # instances of Card. # Deck should have an instance method called count which returns a count # of how many cards remain in the deck. # Deck's __repr__ method should return information on how many cards are # in the deck (e.g. "Deck of 52 cards", "Deck of 12 cards", etc.) # Deck should have an instance method called _deal which accepts a number # and removes at most that many cards from the deck (it may need to remove # fewer if you request more cards than are currently in the deck!). If # there are no cards left, this method should raise a ValueError with the # message "All cards have been dealt". # Deck should have an instance method called shuffle which will shuffle a # full deck of cards. If there are cards missing from the deck, this # method should raise a ValueError with the message "Only full decks can # be shuffled". Shuffle should return the shuffled deck. # Deck should have an instance method called deal_card which uses the # _deal method to deal a single card from the deck and return that single # card. # Deck should have an instance method called deal_hand which accepts a # number and uses the _deal method to deal a list of cards from the deck # and return that list of cards. from random import shuffle class Deck: def __init__(self): suits = ["Hearts", "Diamonds", "Clubs", "Spades"] values = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] self.cards = [Card(v, s) for v in values for s in suits] print(self.cards) def count(self): return len(self.cards) def __repr__(self): return "Deck of {} cards".format(self.count()) def _deal(self, num): count = self.count() actual = min([count, num]) if count == 0: raise ValueError("All cards have been dealt") cards = self.cards[-actual:] self.cards = self.cards[:-actual] return cards def deal_card(self): return self._deal(1)[0] def deal_hand(self,n): return self._deal(n) def shuffle(self): if self.count() < 52: raise ValueError("Only full decks can be shuffled") print(shuffle(self.cards))
d1779c189502386d65bee77b44494954dd6fa554
Emranul-Haque-Rakib/Natural-Language-Processing
/BagOfWordsModel.py
2,451
3.53125
4
import nltk import re import heapq paragraph="""A sub-committee of the AL is now working in full swing to complete a draft of the manifesto following directives of party chief and Prime Minister Sheikh Hasina, according to two of its senior leaders. The BNP also has assigned a group of experts to draft its manifesto though the party has yet to formally announce if it will contest the upcoming polls, said sources. In the draft, the AL sub-committee is highlighting major development projects the government has implemented since 2009. The manifesto will list some ongoing mega projects to persuade people to vote for the party again for “continuation of development”. Considering the number of young voters, the party seeks to target them with some slogans like "Power of the Youth is the Prosperity of Bangladesh" and "New Bangladesh for the Young Generation", said the AL sources. """ dataset=nltk.sent_tokenize(paragraph) for i in range(len(dataset)): dataset[i]=dataset[i].lower() dataset[i]=re.sub(r'\W',' ',dataset[i]) dataset[i]=re.sub(r'S+',' ',dataset[i]) ##creating the histogram word2count={} for data in dataset: words=nltk.word_tokenize(data) for word in words: if word not in word2count.keys(): word2count[word]=1 else: word2count[word]+=1 ##finding most 10 frequent words frequent_words=heapq.nlargest(10,word2count,key=word2count.get) print(frequent_words) ##Creating Matrix ##IN here there is a list in a list the second list vecctor will contain binary result for one sentence ## and the list X will caontain the whole vector lint in it x=[] for data in dataset: vector=[] for word in frequent_words: if word in nltk.word_tokenize(data): vector.append(1) else: vector.append(0) x.append(vector) print(x) --------------------------------------------------OUTPUT------------------------------------------------------------------------------ ['the', 'of', 'to', 'party', 'a', 'al', 'is', 'draft', 'manifesto', 'has'] ## Most 10 frequent sentences [[1, 1, 1, 1, 1, 1, 1, 1, 1, 0], ## MAtrix represantation of most 10 frequent words in each sentences [1, 1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 0, 0, 0, 0, 1, 1, 1, 0, 1], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 1, 1, 0, 0, 0]]
998d78d1840298c6f662f688949dd118c6e26d83
dylan157/TresureHunt
/Tresurehunt.py
28,458
3.6875
4
#!/usr/bin/env python #Welcome to my version of AQA Tresure Hunt. By Dylan Spriddle. Started 26/09/2016 #You start the game on the menu where you have a choice between playing ('1') or options('2') #The options allows you to change icons, map size, icon x_y_width (player icon size). Ps. have a look at GameBot :D #basic game controls are (u1 = up 1)(r1 = right 1)(l1 = left 1)(d1 = down 1) #Ignore the spelling mistake, i study programming not english :) # RUN ON A LINUX TERMINAL IF POSSIBLE! ELSE OPEN IN A PYTHON CMD WINDOWN (idle works fine, it just dosn't support the os.system('clear') function) def aga(): from random import randint from sys import platform import os import time global x global z global Game_activation global error_message global land_icon global used_land_icon global bandit_icon global player_icon global chest_icon global Map_Size_X_Y global Chests_Bandits global player_score global d3bug global bot_speed global clear global win global bot_memory global print_board global max_step global re_use def d3bug_bot(bot_speed): global bot_memory global print_board global max_step global Chests_Bandits global re_use if bot_speed >= 0.1: thinking = [" ^", " ^", " ^", " ^"] thinker = True else: thinking = [] thinker = False think_count = 0 ticker = True while True: thoughts = [] is_re_use = False if re_use != "": thoughts.append(re_use) is_re_use = 1 else: is_re_use = 0 for out in range((bot_memory) - is_re_use): # I'm pretty dumb but I can play the game for you! rand_udlr = randint(0, 3) rand_step = randint(1, max_step) out = "" if rand_udlr == 0: out += 'u' elif rand_udlr == 1: out += 'd' elif rand_udlr == 2: out += 'l' elif rand_udlr == 3: out += 'r' out += str(rand_step) #print out, "+", thoughts.append(out) #print out, #bot_speed = 0.01 if thinker and ticker: print thoughts #time.sleep(1) ischest = False #if bot_speed > 0.05: #print thoughts land_left = 0 for map in playerboard: for spot in map: if spot == land_icon: land_left += 1 if not thinker: time.sleep(float(bot_speed) * 0.3) if land_left > 0: for out in thoughts: if thinker and ticker: print thinking[think_count], if think_count == 3: think_count = 1 else: think_count += 1 time.sleep(float(bot_speed) * 0.3) if out[0] == "u": if player_location[0] - int(out[1]) >= 0: # UP (-X, 0) if playerboard[(player_location[0] - int(out[1]))][player_location[1]]in (land_icon): # Is generated move == land_icon re_use = out return out break elif out[0] == "d": if (player_location[0] + int(out[1])) < (len(object_board)): # DOWN (+X, 0) if playerboard[(player_location[0] + int(out[1]))][player_location[1]]in (land_icon): re_use = out return out break elif out[0] == "r": if player_location[1] + int(out[1]) < (len(object_board)): # RIGHT (0, +X) if playerboard[player_location[0]][(player_location[1] + int(out[1]))] in (land_icon): re_use = out return out break elif out[0] == "l": if player_location[1] - int(out[1]) >= 0: # LEFT (0, -X) if playerboard[player_location[0]][(player_location[1] - int(out[1]))] in (land_icon): re_use = out return out break think_count = 0 print "" if not thinker: time.sleep(float(bot_speed) * 0.3) for out in thoughts: # is chest? if thinker and ticker: print thinking[think_count], if think_count == 3: think_count = 1 else: think_count += 1 time.sleep(float(bot_speed) * 0.3) if out[0] == "u": if player_location[0] - int(out[1]) >= 0: # UP (-X, 0) if playerboard[(player_location[0] - int(out[1]))][player_location[1]] in (chest): re_use = "" print "A chest!!!!" return out break if out[0] == "d": if (player_location[0] + int(out[1])) < (len(object_board)): # DOWN (+X, 0) if playerboard[(player_location[0] + int(out[1]))][player_location[1]] in (chest): re_use = "" print "A chest!!!!" return out break if out[0] == "r": if player_location[1] + int(out[1]) < (len(object_board)): # RIGHT (0, +X) if playerboard[player_location[0]][(player_location[1] + int(out[1]))] in (chest): re_use = "" print "A chest!!!!" return out break else: # is safe move? if thinker == True: print thinking[think_count], if think_count == 3: think_count = 1 else: think_count += 1 time.sleep(float(bot_speed) * 0.3) if out[0] == "l": if player_location[1] - int(out[1]) >= 0: # LEFT (0, -X) if playerboard[player_location[0]][(player_location[1] - int(out[1]))] in (chest): re_use = "" print "A chest!!!!" return out break if out[0] == "u": if player_location[0] - int(out[1]) >= 0: # UP (-X, 0) if playerboard[(player_location[0] - int(out[1]))][player_location[1]] not in (bandit): re_use = "" return out break elif out[0] == "d": if (player_location[0] + int(out[1])) < (len(object_board)): # DOWN (+X, 0) if playerboard[(player_location[0] + int(out[1]))][player_location[1]] not in (bandit): re_use = "" return out break elif out[0] == "r": if player_location[1] + int(out[1]) < (len(object_board)): # RIGHT (0, +X) if playerboard[player_location[0]][(player_location[1] + int(out[1]))] not in (bandit): re_use = "" return out break elif out[0] == "l": if player_location[1] - int(out[1]) >= 0: # LEFT (0, -X) if playerboard[player_location[0]][(player_location[1] - int(out[1]))] not in (bandit): re_use = "" return out break ticker = False else: em = "What?" if platform == "linux" or platform == "linux2": clear = lambda: os.system('clear') elif platform == "darwin": clear = lambda: os.system('clear') elif platform == "win32": clear = lambda: os.system('cls') print "Test" clear() #------------------------------------------------------------------------------------------------------- Varibles Chests_Bandits = { "chests": 10, "bandit": 5 } #boring varibles player_score = 0 Used_coordinates = [] object_board = [] memory_board = [] playerboard = [] error_message = "" Game_activation = False #other varibles win = 100 Map_Size_X_Y = 8 re_use = "u1" #bot varibles d3bug = False bot_speed = 0.5 bot_memory = 8 max_step = 2 #Icons land_icon = ' ' used_land_icon = '~' player_icon = '#' bandit_icon = 'X' chest_icon = '$' #------------------------------------------------------------------------------------------------------- Options def options(): global land_icon global used_land_icon global bandit_icon global player_icon global chest_icon global Map_Size_X_Y global Chests_Bandits global d3bug global win global bot_speed global bot_memory global clear global error_message while True: clear() print error_message error_message = "" print "" print "Select option to edit:" print "1 - Map size" print "2 - Chests" print "3 - Bandits" print "4 - Object Icons" print "5 - Gold to win" print "6 - Exit" print "7 - GameBot" Option = raw_input("Enter now: ") if Option == '1': clear() print "Map size currently", Map_Size_X_Y, '*', Map_Size_X_Y New_size = raw_input("Enter Map X*Y size: ") if len(New_size) >= 1: New_size = int(New_size) Map_Size_X_Y = New_size else: error_message = "Map size not changed." elif Option == '2': clear() print "There are currently", Chests_Bandits['chests'], "chests." New_chests = raw_input("Enter new chest amount: ") if len(New_chests) >= 1: New_chests = int(New_chests) Chests_Bandits['chests'] = New_chests else: error_message = "Chest amount not changed" elif Option == '3': clear() print "There are currently", Chests_Bandits['bandit'], "bandits." New_Bandits = raw_input("Enter new bandit amount: ") if len(New_Bandits) >= 1: New_Bandits = int(New_Bandits) Chests_Bandits['bandit'] = New_Bandits else: error_message = "Bandit amount not changed" elif Option == '4': while True: clear() print error_message error_message = "" print "" print "Select an icon to edit:" print "1 - player (Warning! global Icon size will match new player icon length)" print "2 - chests" print "3 - bandit" print "4 - untouched land" print "5 - touched land" print "6 - Exit" option2 = raw_input("Enter now: ") if option2 == '1': clear() print "Player icon currently: ", player_icon new_player_icon = raw_input("Enter new icon now: ") if len(new_player_icon) > 0: player_icon = new_player_icon else: error_message = "Value not changed" elif option2 == '2': clear() print "Chest icon currently: ", chest_icon new_chest_icon = raw_input("Enter new icon now: ") if len(new_chest_icon) > 0: chest_icon = new_chest_icon else: error_message = "Value not changed" elif option2 == '3': clear() print "Bandit icon currently: ", bandit_icon new_bandit_icon = raw_input("Enter new icon now: ") if len(new_bandit_icon) > 0: bandit_icon = new_bandit_icon else: error_message = "Value not changed" elif option2 == '4': clear() print "Untouched land icon currently: ", land_icon new_used_land_icon = raw_input("Enter new icon now: ") if len(new_used_land_icon) > 0: land_icon = new_used_land_icon else: error_message = "Value not changed" elif option2 == '5': clear() print "Touched land currently: ", used_land_icon new_land_icon = raw_input("Enter new icon now: ") if len(new_land_icon) > 0: used_land_icon = new_land_icon else: error_message = "Value not changed" elif option2 == '6': break else: "What?" elif Option == '5': clear() print "You currently need", win, "Gold to win the game." new_win = raw_input("Enter new win amount: ") if len(new_win) > 1: if new_win < 1: error_message = "Value too low! Re-setting to 1.." win = 1 else: new_win = int(new_win) win = new_win else: error_message = "Value not changed" elif Option == '6': if (int(Map_Size_X_Y) ** 2 - 1) < (Chests_Bandits['chests'] + Chests_Bandits['bandit']): print "" clear() print "INVALID SETTINGS! Map Size =", Map_Size_X_Y, "*", Map_Size_X_Y, "(", (Map_Size_X_Y ** 2), "Squares", ")", "Bandits + Chests =", (Chests_Bandits['chests'] + Chests_Bandits['bandit']), "Squares" while (Map_Size_X_Y ** 2) < ((Chests_Bandits['chests'] + Chests_Bandits['bandit']) + 25): Map_Size_X_Y += 1 else: print "Map Size Has Been Reconfigured To", Map_Size_X_Y, '*', Map_Size_X_Y, "(", (Map_Size_X_Y**2), "Squares", ")" print "" break else: clear() break elif Option == '7': while True: clear() print "" print "GameBot will play the game for you!" print "Select setting to change:" print "1 - ON/OFF" print "2 - Bot speed" print "3 - Bot Intelligence" print "6 - Exit" bot_option = raw_input("Enter now: ") if bot_option == "1": clear() print "" print "Select ON/OFF:" print "1 - ON" print "2 - OFF" ONOFF = raw_input("Enter now: ") if ONOFF == "1": d3bug = True print "" error_message = "# GameBot activated*" elif ONOFF == "2": d3bug = False print "" error_message = "# GameBot de-activated*" elif bot_option == "2": clear() print "" print "BotSpeed currently :", bot_speed*10, "(Lower is faster :))" new_speed = raw_input("enter new bot speed :") if len(new_speed) >= 1: new_speed = float(new_speed) new_speed *= 0.1 bot_speed = new_speed else: error_message = "Speed not changed" elif bot_option == "3": clear() print "" print "Bot Intelligence currently", bot_memory, "/ 8." bot_intelligence = raw_input("Enter bot intelligence now: ") if len(bot_intelligence) >= 1: bot_intelligence = int(bot_intelligence) if bot_intelligence > 0: if bot_intelligence < 8: bot_memory = bot_intelligence else: error_message = "Bot intelligence too High! It might become self aware and kill you!" else: error_message = "Bot intelligence too low" else: error_message = "Bot intelligence not changed." elif bot_option == "6": break else: print "What?" global Game_activation print "Welcome to Bandits & Gold!" print "Enter navigation number:" print "Start = '1'" print "Options = '2'" start = raw_input('Enter: ') if start == "1": Game_activation = True elif start == "2": options() #------------------------------------------------------------------------------------------------------- Menu def menu(): global Game_activation global error_message global timer0 while Game_activation != True: clear() print error_message error_message = "" print "Welcome to Bandits & Gold!" print "Enter navigation number:" print "Start = '1'" print "Options = '2'" start = raw_input('Enter: ') if start == '1': Game_activation = True print Game_activation break elif start == '2': print "" options() else: print 'What?' menu() #------------------------------------------------------------------------------------------------------- Icon length icon_length = len(player_icon) bandit = bandit_icon*icon_length chest = chest_icon*icon_length #------------------------------------------------------------------------------------------------------- Map writer for click in range(Map_Size_X_Y): object_board.append([used_land_icon*icon_length] * Map_Size_X_Y) playerboard.append([land_icon*icon_length] * Map_Size_X_Y) memory_board.append([0*icon_length] * Map_Size_X_Y) #------------------------------------------------------------------------------------------------------- Player start location player_location = [(len(object_board)-1), 0] Used_coordinates.append(str(player_location[0]) + str(player_location[1])) #------------------------------------------------------------------------------------------------------- Random object to map placer def Object_Placement(ran_len, WHO): spot = [] for x in range(ran_len): # How many random numbers? x, z = 0, 0 def baker(): global x global z x, z = randint(0, (len(object_board)-1)), randint(0, (len(object_board)-1)) if (str(x) + str(z)) in Used_coordinates: # or (str(x) + str(z)) in Used_coordinates: #print "XZ FOUND IN SPOT", (str(x) + str(z)) baker() elif (str(x) + str(z)) in spot: #print "XZ FOUND IN USED COORDINATES", (str(x) + str(z)) baker() else: object_board[x][z] = WHO Used_coordinates.append(str(x) + str(z)) spot.append(str(x) + str(z)) baker() if len(spot) > ran_len: print "OVERFLOW!" return spot Used_coordinates.append(spot) Chests_Bandits['chests'] = Object_Placement(Chests_Bandits['chests'], chest) Chests_Bandits['bandit'] = Object_Placement(Chests_Bandits['bandit'], bandit) #random_gen(5) #Debug '''print stuff['chests'] print stuff['bandit']''' #------------------------------------------------------------------------------------------------------- Print board def print_board(board): for row in board: for x in range(icon_length): print " ".join(row) print "" def print_board2(board): for row in board: for x in range(icon_length): print "".join(str(row)) print "" #print_board(board) s0 = 0 s1 = 0 s2 = 0 '''for x in object_board: for z in x: if z == '0': s0 += 1 elif z == '1': s1 += 1 elif z == '2': s2 += 1 else: print "idk what happened" print "" print "Blank :", s0, "chest's :", s1, "bandit's :", s2''' #------------------------------------------------------------------------------------------------------- Board transport def board_transport(move_choice, em): global error_message global player_score global clear clear() if move_choice == "d3bug": player_score = 15766 em = move_choice if len(move_choice) == 2 and move_choice[0] in ('u', 'd', 'l', 'r') and move_choice[1] in str(range(0, len(object_board))): if move_choice[0] == "u": if player_location[0] - int(move_choice[1]) < 0: #UP em = "You can't move there!" else: player_location[0] -= int(move_choice[1]) elif move_choice[0] == "d": if (player_location[0] + int(move_choice[1])) > (len(object_board)-1): #DOWN em = "You can't move there!" else: player_location[0] += int(move_choice[1]) elif move_choice[0] == "r": if player_location[1] + int(move_choice[1]) > (len(object_board)-1): #RIGHT em = "You can't move there!" else: player_location[1] += int(move_choice[1]) elif move_choice[0] == "l": if player_location[1] - int(move_choice[1]) < 0: #LEFT em = "You can't move there!" else: player_location[1] -= int(move_choice[1]) else: em = "What?" else: em = "Unreadable input" error_message = em return player_location clear() #------------------------------------------------------------------------------------------------------- Game loop while player_score < win: icon_length = len(player_icon) bandit = bandit_icon*icon_length chest = chest_icon*icon_length #print_board(object_board) #time.sleep(1) while Game_activation: ban = 0 che = 0 for objects in object_board: for item in objects: if item == bandit: ban += 1 if item == chest: che += 1 if player_score >= win: print "you won!" break elif che == 0: print "No chests left! You've lost!" break clear() #os.system('clear') #FOR LINUX print error_message error_message = "" oldposision = player_location playerboard[player_location[0]][player_location[1]] = player_icon # Make me Multiple choice! print_board(playerboard) print "" playerboard[oldposision[0]][oldposision[1]] = object_board[oldposision[0]][oldposision[1]] # Make old posision == object memory_board[oldposision[0]][oldposision[1]] += 1 #Block usage counter (You have stepped on this square x times) if object_board[oldposision[0]][oldposision[1]] == bandit: player_score = 0 if object_board[oldposision[0]][oldposision[1]] == chest: if memory_board[oldposision[0]][oldposision[1]] == 3: player_score += 10 playerboard[oldposision[0]][oldposision[1]], object_board[oldposision[0]][oldposision[1]] = bandit, bandit # Make chest into bandit else: player_score += 10 print "You have", player_score, "Gold" print "There are", ban, "Bandit[s] and", che, "chest[s] left" print "" if d3bug != True: W = raw_input("Where to move?") else: W = d3bug_bot(bot_speed) board_transport(W, error_message) break aga() #------------------------------------------------------------------------------------------------------- Restart? def again(): while True: print "" again = 'y'# raw_input("Play again? y/n") if again == 'y': aga() elif again == 'n': print "Thanks for playing!" break again() #------------------------------------------------------------------------------------------------------- #715L TH True smartbot (new memory config)
fc77fd275354dad7a87ead984532b4d68e5ce5b3
ayesha-omarali/PracticeProblems
/lengthoflastword.py
560
3.796875
4
def lengthoflastword(A): if A == '': return 0 A = A[::-1] word = '' flag = True if A[0] == ' ': count = 0 for i in A: if i != ' ': word += i flag = False elif i == ' ' and not flag: break A = word if A: i = A[0] else: return 0 count = len(A) - 1 while ' ' in A: A = A[:count] count -= 1 count = 0 for item in A: count += 1 return count print lengthoflastword(" ")
44332b97b6ab0d930b440bbd891bb1035382a734
qiaolunzhang/py_scrapy
/writing_solid_python_code/advice35.py
947
3.78125
4
class A(object): def instance_method(self, x): print("calling instance method instance_method(%s, %s)"%(self, x)) @classmethod def class_method(cls, x): print("calling class_method(%s, %s)" % (cls, x)) @staticmethod def static_method(x): print("calling static_method(%s)" % x) a = A() a.instance_method("test") a.class_method("test") a.static_method("test") print('********************************************') class Fruit(object): total = 0 @classmethod def print_total(cls): print(cls.total) print(id(Fruit.total)) print(id(cls.total)) @classmethod def set(cls, value): print("calling class_method(%s, %s)" % (cls, value)) cls.total = value class Apple(Fruit): pass class Orange(Fruit): pass app1 = Apple() app1.set(200) app2 = Apple() org1 = Orange() org1.set(300) org2 = Orange() app1.print_total() org1.print_total()
95f534ef40d46a4bc35e4e201f245ee98c54556f
Softypo/StockMarket_ADV
/stock_adv_Functions.py
12,531
3.5
4
# importing modules import numpy as np import pandas as pd ###ETL reddit data #---------------------------------------------------------------------------------------------------------------------------------------- def pq (names, subredits='allstocks', sort='relevance', date='all', comments=False): #importing reddit api from reddit_api import get_reddit reddit = get_reddit() #preparing the inputs to be search if isinstance(names, str): if names.isupper()==False: if names[0].isupper()==False: name1 = names name2 = names.capitalize() name3 = names.upper() else: name1 = names.lower() name2 = names name3 = names.upper() else: name1 = names.lower() name2 = names.lower().capitalize() name3 = names pnames = [[name1,name2,name3]] elif isinstance(names, list): pnames =[] for i, n in enumerate(names): if isinstance(n, str): n = str(n) if n.isupper()==False: if n[0].isupper()==False: name1 = n name2 = n.capitalize() name3 = n.upper() else: name1 = n.lower() name2 = n name3 = n.upper() else: name1 = n.lower() name2 = n.lower().capitalize() name3 = n pnames.append([name1,name2,name3]) else: pnames = [] elif (isinstance(names, str)==False) or (isinstance(names, list)==False): pnames = [] #scraping posts posts = [] for n in pnames: if subredits=='allstocks': stocks = reddit.subreddit('stocks') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('StocksAndTrading') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('stockspiking') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('Stocks_Picks') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('wallstreetbets') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('Wallstreetbetsnew') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) stocks = reddit.subreddit('WallStreetbetsELITE') for post in stocks.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) else: hot_posts = reddit.subreddit(subredits) for post in hot_posts.search(n[0] or n[1] or n[3], sort, 'lucene', date): posts.append([post.title, post.score, post.id, post.subreddit, post.url, post.num_comments, post.selftext, post.created]) posts = pd.DataFrame(posts,columns=['title', 'score', 'post_id', 'subreddit', 'url', 'num_comments', 'body', 'created']) posts = posts.infer_objects() posts.drop_duplicates(subset ="post_id", keep = "first", inplace = True) posts.reset_index(drop=True, inplace=True) #scraping comments if comments==True: comments = [] for index, row in posts.iterrows(): submission = reddit.submission(id=row['post_id']) submission.comments.replace_more(limit=0) for comment in submission.comments.list(): comments.append([row['post_id'], row['title'], comment.score, comment.id, comment.body, comment.created]) comments = pd.DataFrame(comments,columns=['post_id', 'post', 'score', 'comment_id', 'body', 'created']) comments = comments.infer_objects() #formating posts and optional comments dataframes posts['created'] = pd.to_datetime(posts['created'], unit='s') posts.set_index('created', inplace=True) comments['created'] = pd.to_datetime(comments['created'], unit='s') comments.set_index('created', inplace=True) return posts, comments #formating postsdataframe posts['created'] = pd.to_datetime(posts['created'], unit='s') posts.set_index('created', inplace=True) return posts ###Sentiment analysis #---------------------------------------------------------------------------------------------------------------------------------------- def sentiment (posts, comments=None): #importing sentiment model flair import flair sentiment_model = flair.models.TextClassifier.load('en-sentiment') #changing index for processing posts.reset_index (inplace=True) posts.set_index('post_id', inplace=True) #calculating sentiment on body sentiment = [] score = [] for sentence in posts['body']: if sentence.strip()=='': sentiment.append(np.nan) score.append(np.nan) else: sample = flair.data.Sentence(sentence) sentiment_model.predict(sample) sentiment.append(sample.labels[0].value) score.append(sample.labels[0].score) posts['sentiment'] = sentiment posts['sentiment_score'] = score #calculating sentiment on tittle if body is nan for index in posts[posts["sentiment"].isna()].index: if posts.loc[index,"title"].strip()!='': sample = flair.data.Sentence(posts.loc[index,"title"]) sentiment_model.predict(sample) posts.at[index,"sentiment"] = sample.labels[0].value posts.at[index,"sentiment_score"] = sample.labels[0].score #calculating sentiment on comments if isinstance(comments, pd.DataFrame): sentiment = [] score = [] for sentence in comments['body']: if sentence.strip()=='': sentiment.append(np.nan) score.append(np.nan) else: sample = flair.data.Sentence(sentence) sentiment_model.predict(sample) sentiment.append(sample.labels[0].value) score.append(sample.labels[0].score) comments['sentiment'] = sentiment comments['sentiment_score'] = score #mean sentiment of posts by comments posts["comments_sentiment"] = np.nan posts["comments_score"] = np.nan for post_id in comments["post_id"].unique(): posts.at[posts[posts.index==post_id].index,"comments_sentiment"] = comments["sentiment"].loc[comments["post_id"]==post_id].mode()[0] posts.at[posts[posts.index==post_id].index,"comments_score"] =comments["sentiment_score"].loc[comments["post_id"]==post_id].mean() #combined sentiment score posts["combined_sentiment"] = np.where (posts['comments_sentiment'].isna(), posts['sentiment'],np.where (posts['sentiment'] == posts['comments_sentiment'], 'POSITIVE', 'NEGATIVE')) posts["combined_score"] = (posts["sentiment_score"]+posts["comments_score"])/2 posts["combined_score"] = np.where(posts["combined_score"].notna()==True, posts["combined_score"], posts["sentiment_score"]) else: posts["comments_sentiment"] = np.nan posts["comments_score"] = np.nan posts["combined_sentiment"] = np.nan posts["combined_score"] = np.nan #returning to original index posts.reset_index(inplace=True) posts.set_index('created', inplace=True) #formating new columns posts['sentiment'] = posts['sentiment'].astype('category') posts['sentiment_score'] = pd.to_numeric(posts['sentiment_score']) comments['sentiment'] = comments['sentiment'].astype('category') comments['sentiment_score'] = pd.to_numeric(comments['sentiment_score']) posts['comments_sentiment'] = posts['comments_sentiment'].astype('category') posts['comments_score'] = pd.to_numeric(posts['comments_score']) posts['combined_sentiment'] = posts['combined_sentiment'].astype('category') posts['combined_score'] = pd.to_numeric(posts['combined_score']) ###Stock data from yahoo finance #---------------------------------------------------------------------------------------------------------------------------------------- def y_stock_data (name, period, interval): import yfinance as yf stock_info = yf.Ticker(name).info stock_data = yf.Ticker(name).history(tickers=name, period=period, interval=interval, auto_adjust=True) stock_c = yf.Ticker(name).calendar stock_r = yf.Ticker(name).recommendations stock_a = yf.Ticker(name).actions stock_b = yf.Ticker(name).balance_sheet stock_qb = yf.Ticker(name).quarterly_balance_sheet return stock_info, stock_data, stock_c, stock_r, stock_a, stock_b, stock_qb ###look for both stock and redit data #---------------------------------------------------------------------------------------------------------------------------------------- def looker (stock_name, subredits='allstocks', sort='relevance', date='all', comments=False): #preparing user inputs if date=='all': period, interval = 'max', '1d' elif date=='year': period, interval = '1y', '1d' elif date=='month': period, interval = '1mo', '1d' elif date=='week': period, interval = '1wk', '1d' elif date=='day': period, interval = '1d', '1m' elif date=='hour': period, interval = '1h', '1m' #yahoo stock data stock_info, stock_data, stock_c, stock_r, stock_a, stock_b, stock_qb = y_stock_data(stock_name, period, interval) #cheking stock dataframe if stock_data.empty: print('DataFrame is empty!') else: print('Stock data downloaded from Yahoo finance') #reddit scrapping if comments==True: posts, comments = pq([stock_info['symbol']+' '+stock_info['longName']], subredits, sort, date, comments) #cheking dataframe if posts.empty: print('Posts DataFrame is empty!') else: print('Posts downloaded from Reddit') if comments.empty: print('Comments DataFrame is empty!') else: print('Comments downloaded from Reddit') return stock_info, stock_data, stock_c, stock_r, stock_a, stock_b, stock_qb, posts, comments else: posts = pq([stock_info['symbol']+' '+stock_info['longName']], subredits, sort, date, comments) #cheking dataframe if posts.empty: print('Posts DataFrame is empty!') else: print('Posts downloaded from Reddit') return stock_info, stock_data, stock_c, stock_r, stock_a, stock_b, stock_qb, posts ###Analyse sentiment outputs #---------------------------------------------------------------------------------------------------------------------------------------- def analyse (posts, comments=pd.DataFrame([])): #sentiment calculation sentiment(posts, comments) #---------------------------------------------------------------------------------------------------------------------------------------- def main (): try: stock_info, stock_data, stock_c, stock_r, stock_a, stock_b, stock_qb = y_stock_data('AAPL', '1mo', '1h') posts, comments = pq([stock_info['symbol']+' '+stock_info['longName']], 'all', 'relevance', 'month', True) except Exception: print (Exception) sentiment(posts, comments) if __name__ == "__main__": main()
92d120cd666c5ba7d4e49369715b17150973e05b
RyanLongRoad/classes
/farm/Field/field_class.py
7,446
3.5625
4
from potato_class import * from wheat_class import * from sheep_class import * from cow_class import * import random class Field(): """Simulate a field that can contain animals and crops""" #constructor def __init__(self,max_animals,max_crops): self._crops = [] self._animals = [] self._max_animals = max_animals self._max_crops = max_crops def plant_crop(self,crop): if len(self._crops) < self._max_crops: self._crops.append(crop) return True else: return False def add_animal(self,animal): if len(self._animals) < self._max_animals: self._animals.append(animal) return True else: return False def harvest_crop(self,position): return self._crops.pop(position) def remove_animal(self,position): return self._animals.pop(position) def report_contents(self): crop_report = [] animal_report = [] for crop in self._crops: crop_report.append(crop.report()) for animal in self._animals: animal_report.append(animal.report()) return{"crops": crop_report, "animals":animal_report} def report_needs(self): food = 0 light = 0 water = 0 for crop in self._crops: needs = crop.needs() if needs["light need"] > light: light = needs["light need"] if needs["water need"] > water: water = needs["water need"] for animal in self._animals: needs = animal.needs() food += needs["food need"] if needs["water need"] > water: water = needs["water need"] return{"food":food,"light":light,"water":water} def grow(self,light,food,water): #grow the crops (light and water are available to all if len(self._crops) > 0: for crop in self._crops: crop.grow(light,water) if len(self._animals) > 0: #grow the aniamls (water available to all animals) #food is a total that must be shared food_required = 0 #get a total of the food required by the animals in the field for animal in self._animals: needs = animal.needs() food_required += needs["food need"] #if excess food is available it is shared out equally if food > food_required: addition_food = food - food_required food = food_required else: additional_food = 0 #growing the animals for animal in self._animals: #get the animals food needs needs = animal.needs() if food >= needs["food need"]: #removes food for this animal from the total food -= needs["food need"] feed= needs["food need"] #see if there is any additional food to give if additional_food > 0: #removes additonal food for this animal additional_food -= 1 #add this feed to he animal feed +=1 #grow the animal animal.grow(feed,water) def auto_grow(field,days): #grow the field automatically for day in range(days): light = random.randint(1,10) water = random.randint(1,10) food = random.randint(1,100) field.grow(light,food,water) def manual_grow(field): #get the lgiht,water and the food values from the user valid = False while not valid: try: light = int(input("please enter a value for light(1-10): ")) if 1 <= light <= 10: valid = True else: print("value entered is not valid - please enter another value") except ValueError: print("value entered is not valid - please enter another value") valid = False while not valid: try: water = int(input("please enter a value for water(1-10): ")) if 1 <= water <= 10: valid = True else: print("value entered is not valid - please enter another value") except ValueError: print("value entered is not valid - please enter another value") valid = False while not valid: try: food = int(input("please enter a value for food(1-100): ")) if 1 <= food <= 10: valid = True else: print("value entered is not valid - please enter another value") except ValueError: print("value entered is not valid - please enter another value") #grow the field field.grow(light,food,water) def display_crops(crop_list): print() print("The following crops are in this field: ") pos = 1 for crop in crop_list: print("{0:>2}. {1}".format(pos,crop.report())) pos += 1 def display_animals(animal_list): print() print("the following animals are in this field: ") pos = 1 for animal in animal_list: print("{0:>2}. {1}".format(pos,animal.report())) pos +=1 def select_crop(length_list): valid = False while not valid: selected = int(input("Please select a crop: ")) if selected in range(1,length_list+1): valid = True else: print("please select a valid option") return selected - 1 def select_animal(length_list): valid = False while not valid: selected = int(input("Please select an animal: ")) if selected in range(1,length_list+1): valid = True else: print("please select a valid option") return selected - 1 def harvest_crop_from_field(field): display_crops(field._crops) selected_crop = select_crop(len(field._crops)) return field.harvest_crop(selected_crop) def remove_animal_from_field(field): display_animals(field._animals) selected_animal = select_animal(len(field._animals)) return field.remove_animal(selected_animal) def display_crop_menu(): print() print("which crop type would you like to add?") print() print("1. potato") print("2. wheat") print() print("0. return to main menu") def main(): new_field = Field(5,2) new_field.plant_crop(Wheat()) new_field.plant_crop(Potato()) new_field.add_animal(Sheep("Shaun")) new_field.add_animal(Cow("Jim")) report = new_field.report_contents() #manual_grow(new_field) #print(new_field.report_contents()) auto_grow(new_field,30) print(new_field.report_contents()) if __name__ == "__main__": main()
7ab0803b372232161f2a5f3b1f165ce9890b5bbd
Ashik-Phantom/OpenCV-Python-Basics
/9.1-Face_detection.py
563
3.546875
4
# Face detection - Only detects the face not the person import cv2 facecascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml") # Pre trained face model Img = cv2.imread('Resources/my_pic1.jpeg') img = cv2.resize(Img,(600,600)) imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # find faces faces = facecascade.detectMultiScale(imgGray, 1.1, 10) # (scale factor, minimum) neighbour change based on results for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) cv2.imshow('Result', img) cv2.waitKey(0)
40d01cedf0c714e191ae59d898e87d237ab8849f
droftware/Knight-Rescue
/KnightRescue/player.py
4,035
3.578125
4
import pygame import constants import person import landforms import ladder import fireball import sys import donkey import cage class Player(person.Person): """ Defines the player object.It inherits from Person class.""" def __init__(self): """Constructor for Player class.""" super(Player,self).__init__(0,0,50,70,'p2_stand.png') self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT self.score = 0 self.life = constants.PLAYER_LIFE self.__princess = None self.__reached_princess = False def update(self): """ Moves the player acording to the user and also checks if it has collected any coins,has been hit with a fireball or has reached the princess. """ super(Player,self).update() self.__check_collision() def move_left(self): """ Moves the player left """ self.set_x_vector(-1 * constants.PLAYER_SPEED) def move_right(self): """ Moves the player right """ self.set_x_vector(constants.PLAYER_SPEED) def move_up(self): """ Checks if there is a ladder and only then allowes the player to move up """ collided_ladders = pygame.sprite.spritecollide(self,ladder.Ladder.all_ladders,False) if len(collided_ladders) > 0: self.set_y_vector(-20) def move_down(self): """ Checks if there is a ladder and only then allows the player to move down """ self.rect.y += 80 collided_ladders = pygame.sprite.spritecollide(self,ladder.Ladder.all_ladders,False) self.rect.y -= 80 if len(collided_ladders) > 0: self.rect.y = self.rect.y + 130 print 'move down' def jump(self): """ Makes the player jump only after checking if the player is on the ground or standing on a platform """ self.rect.y += 2 collided_blocks = pygame.sprite.spritecollide(self,landforms.Platform.all_blocks,False) self.rect.y -= 2 if len(collided_blocks) > 0 or self.rect.bottom == constants.SCREEN_HEIGHT: self.set_y_vector(-10) def __check_collision(self): """ Checks if the player has collided with any of the game elements such as coin,fireball,princess and donkey.If a player has collided takes appropriate action. """ self.__collect_coin() self.__check_fireball() self.__check_princess() self.__check_donkey() self.__check_cage() def __collect_coin(self): """ Checks if there is a coin at players current position.If it is so then increment the players score and make the coin disappear. """ collided_coins = pygame.sprite.spritecollide(self,landforms.Platform.all_coins,True) for gold_coin in collided_coins: self.score += 5 def __check_fireball(self): """ Checks if the player is hit with a fireball. """ collided_fireballs = pygame.sprite.spritecollide(self,fireball.Fireball.all_fireballs,True) if len(collided_fireballs) > 0: self.life -= 1 self.score -= 25 self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT def set_princess(self,princess): """ Assigns princess to the player """ self.__princess = princess def __check_princess(self): """ Checks whether the player has reached the princess or not """ flag = pygame.sprite.collide_rect(self,self.__princess) if flag == True: self.__check_princess = True def check_reached_princess(self): """ Returns true if the player has reached the princess """ return self.__check_princess def __check_donkey(self): """ Checks if the player has collided with a donkey.If it has ,reduces the life and points of the player and sends him back to the starting position. """ collided_donkeys = pygame.sprite.spritecollide(self,donkey.Donkey.all_donkeys,False) if len(collided_donkeys) > 0: print 'Collided with donkey' self.life -= 1 self.score -= 25 self.rect.left = 0 self.rect.bottom = constants.SCREEN_HEIGHT def __check_cage(self): """ Restricts the player to move through the cage """ collided_cages = pygame.sprite.spritecollide(self,cage.CageOne.all_cages,False) for cage_block in collided_cages: self.rect.left = cage_block.rect.right
8a1bab3272fd58fe4999fe571fa7eb58f1cac9e4
Souravvk18/Python-Project
/dice_roll.py
1,204
5
5
''' The Dice Roll Simulation can be done by choosing a random integer between 1 and 6 for which we can use the random module in the Python programming language. The smallest value of a dice roll is 1 and the largest is 6, this logic can be used to simulate a dice roll. This gives us the start and end values to use in our random.randint() function. Now let’s see how to simulate a dice roll with Python: ''' #importing module for random number generation import random #range of the values of a dice min_val = 1 max_val = 6 #to loop the rolling through user input roll_again = "yes" #loop while roll_again == "yes" or roll_again == "y": print("Rolling The Dices...") print("The Values are :") #generating and printing 1st random integer from 1 to 6 print(random.randint(min_val, max_val)) #generating and printing 2nd random integer from 1 to 6 print(random.randint(min_val, max_val)) #asking user to roll the dice again. Any input other than yes or y will terminate the loop roll_again = input("Roll the Dices Again?") ''' Rolling The Dices... The Values are : 2 3 Roll the Dices Again?yes Rolling The Dices... The Values are : 1 5 '''
b836b5f8ee930033348291d83be460e57ef5fd0d
Souravvk18/Python-Project
/text_based.py
861
4.34375
4
''' you will learn how to create a very basic text-based game with Python. Here I will show you the basic idea of how you can create this game and then you can modify or increase the size of this game with more situations and user inputs to suit you. ''' name = str(input("Enter Your Name: ")) print(f"{name} you are stuck at work") print(" You are still working and suddenly you you saw a ghost, Now you have two options") print("1.Run. 2.Jump from the window") user = int(input("Choose 1 or 2: ")) if user == 1: print("You did it") elif user == 2: print("You are not that smart") else: print("Please Check your input") ''' output- Enter Your Name: sourav sourav you are stuck at work You are still working and suddenly you you saw a ghost, Now you have two options 1.Run. 2.Jump from the window Choose 1 or 2: 2 You are not that smart '''
8817f472e24034a7157bd400da6f7ee26eb5cc69
HoNedAy/lemon_erp
/qcd/lession.py
5,813
4.1875
4
# 名字命名规则 # (1)只能包含数字、字母、下划线 # (2)不能以数字开头 # (3)不能使用关键字 # 可以通过import keyword # print(keyword.kwlist)打印关键字 # ctrl+/也可以多行注释 # import keyword # print("打印到控制台") # print(type(12)) # print(type(3.14)) # print(isinstance(12,int)) # print("刚刚'你好呀'下雨啦") # print("刚刚\"人名\"下雨啦") # print(""" # 今天下雨了没 # 今天没下雨 # 今天学python # """) #切片取多个值===字符串取值,索引从0开始 0.1.2.3 #步长:隔几步取值 # str="今天1天气真好!" # print(str[0:3:2])#隔2步取值,取索引值为0,2的字符串 # print(str[1:6:2])#隔2步取值,取索引为1,3,5的字符串 # print(str[-1])#-1代表最后一个元素 # print(str[::-1])#从右向左取值 # # print(str1[0:len(str1):1])#从0开始取值,len()是str1字符串的长度 # # str1="12今天你学习了吗?" # # str2=str1.replace("12","新的值") # # # print(str2) # # print(str1.index('学习'))#获取元素开始的位置--索引--字符串不存在的时候会报错 # # print(str1.find('学习'))#获取元素开始的位置--索引--字符串不存在的时候不会报错,会返回-1 # # name='皮卡丘' #--0--索引 # age=18 #--1--索引 # gender='Female' #--2--索引 # print(''' # ---{1}同学的信息---- # name:{1} # age:{2} # gender:{3}'''.format(name,name,age,gender) # ) # print(10+80) # print('按时'+'交作业') # print(str(123)+'向前走呀') #123要转化为字符串:str()--内置函数:int(),float(),bool() # a=10 # a += 5 #a=a+5 a=15 # print(a) # a-=10 #a=a-10 # print(10>8 and 5>6) #--True and Flase ==False # print(10>8 or 5>6) #--True or Flase ==True # print( not 10>8 ) #--True--> Flase # str="hello word" # print('ee' in str) # print('ee' not in str) # # list=[12,'你好呀',True,3.14,['皮卡丘','天天','妍妍']] #定义一个空列表---往列表里添加元素 # # print(list[0:3]) #切片取值 # # print(list[4][0]) #列表的嵌套取值,取索引为0的字符串 # #增加 # list.append('小雪') #追加到元素的末尾---最常用的 # list.insert(2,'伊呀呀呀') #在指定的位置添加元素 # list.extend(['aaa','鲍鱼','卡罗尔']) #一次添加多个元素,不是以整体添加的 # list.append(['aaa','鲍鱼','卡罗尔']) #一次添加多个元素,是以整体添加的--列表的形式添加 # print(list) # # #修改 # list[0]='卡卡' #添加索引为0的元素 # list[1]='123456' #添加索引为1的元素 # list.insert(1,'卡卡') # list.remove('卡卡') #重复元素,只删除第一个遇见的元素 # list.insert(0,['卡卡','卡卡']) #指定位置天机多个元素 # list.remove('卡卡') #删除了不是整体的卡卡 # print(list.count('伊呀呀呀')) #统计某个元素出现的次数 # print(len(list)) # tuple_1=('皮卡丘','南瓜','涵涵') #取变量名如果用了内置函数的名字的话--调用这个内置函数时就会报错。 # # tuple1[0]='麦克' #指定修改会报错 # #转换---要想修改元素,可以转换成列表添加元素 # list1=list(tuple_1) #元组-->列表 # list1.append('杰克') #添加元素,在最末尾添加 # tuple_1=tuple(list1) #列表-->元组 # print(tuple_1) # dict1={'name':'皮卡丘','age':18,'weight':'80','height':160} # print(dict1) # #取值 --- # print(dict1['name'],dict1['weight']) #key取value # print(dict1.get('weight')) #get方法里面放的也是key # #增加+修改 # dict1['gender']='Female' #key不存在的话,则增加一个键值对 ---增加元素 # dict1['name']='卡卡' #key存在的话,则改变value值 # #删除 # dict1.pop('gender') #必须指定一个key来删除key:value # #修改 # dict1.update({'city':'广州','hobby':'写代码'}) #增加 多个元素的时候---用update # print(dict1) # #集合 :set --{} --无序 # list1=[11,22,33,44,55,88,99] #含有重复数据的 # set1=set(list1) #列表--->集合 =====去重操作 # print(set1) #控制流 # money=int(input('输入金额:')) #----input() #输入的变量是字符串类型的----要转换为整型int # if money>=600: # print('买大房子') # elif money>=100: # print('买小房子') # elif money==50: # print('买小车子') # else: # print('继续搬砖') #For循环 # str='今天学习了思维课程' #定义了一个字符串变量 # count=0 #定义了一个计时器,用来计算循环次数的 # for item in str: # if(item=='天'): # # break # continue #--中断,后面的还会执行,只跳出了本次循环 # elif(item=='思'): # break # ---中断,后面的不会再执行的,跳出了整个循环 # print(item) # # print('*'*10) # count+=1 #每次循环,值自加1 # print(count) #打印循环次数 # print(len(str)) # #range--开始(默认0),结束,步长(默认1) # # for num in range(0,60,2): # # print(num) # # # name=input('请输入姓名:') # age=input('请输入年龄:') # sex=input('请输入性别:') # print( # ''' # ********************* # 姓名:{1} # 年龄:{2} # 性别:{3} # ******************** '''.format(name,age,sex,name) # ) # # # str1 = 'python hello aaa 123123aabb' # # 1)请取出并打印字符串中的'python'。 # print(str1[0:7:1]) # # 2)请分别判断 'o a' 'he' 'ab' 是否是该字符串中的成员? # print( 'o a' in str1) # print( 'he' in str1) # print( 'ab'in str1) # # 3)替换python为 “lemon”. # str1 =str1.replace('python','lemon') # print(str1) # # 4) 找到aaa的起始位置 # print(str1.index('aaa')) # print("kjhjk") #单元格里面的内容
df58a62863d9eede2e9dba8466d4530364b60ffc
0x000552/python
/coursera/diving_in_python/study_process.py
3,100
3.59375
4
""" os.fork """ """ import os pid = os.fork() if pid == 0: print(f"MAIN pid: {pid}") else: print(f"CHILD pid: {pid}") """ """ multiprocessing """ from multiprocessing import Process def f(_str): print(f"amazing process! _str = {_str}") prcs1 = Process(target=f, kwargs={"_str": "WOW"}) prcs1.start() # creating process and start it prcs1.join() # waiting for our child... print("\n\nAnd now let's try Process class inheritance (from Process class):") class MyProcess(Process): def __init__(self, **kwargs): # kwargs only for practice... super().__init__() self._str = kwargs["_str"] def run(self): print() print(f"amazing process! _str = {self._str}") prcs2 = MyProcess(_str="DOUBLE WOW") prcs2.start() prcs2.join() print("\n\nNow let's try multiprocessing.Pool:") from multiprocessing import Pool import os def func_for_pool(x): print(f"{os.getpid()}: {x} ") return x**9 with Pool(5) as p: print(p.map(func_for_pool, [*range(5)])) print("\n\nNow let's try thread with concurrent module:") from concurrent.futures import ThreadPoolExecutor, as_completed from random import randint from time import sleep def f(id_): slp_time = randint(0, 2) print(f"BEGIN: {id_:2}; slp_time: {slp_time}") sleep(slp_time) print(f"END {id_:2};") return id_ with ThreadPoolExecutor(max_workers=2) as pool: thrds = [pool.submit(f, i) for i in range(1, 2)] sleep(1) for future in as_completed(thrds): print(f"id: {future.result():2} completed") print("\n\nRLock and Conditions...") from concurrent.futures import ThreadPoolExecutor, as_completed from random import randint from time import sleep import threading class Queue(object): def __init__(self, size=5): self._size = size self._queue = [] self._mutex = threading.RLock() self._empty = threading.Condition(self._mutex) self._full = threading.Condition(self._mutex) def put(self, val): with self._full: while len(self._queue) >= self._size: self._full.wait() self._queue.append(val) self._empty.notify() def get(self): with self._empty: while len(self._queue) == 0: self._empty.wait() ret = self._queue.pop(0) self._full.notify() return ret def f_queue_put(queue, thread_id): print(f"Th {thread_id} put") queue.put(thread_id) print(f"Th {thread_id} end") def f_queue_get(queue, thread_id): print(f"Th {thread_id} get") print(f"Th {thread_id} gotten: {queue.get()}") print(f"Th {thread_id} end") queue = Queue() print("\n\nThreadPoolExecutor...") with ThreadPoolExecutor(max_workers=6) as pool: thrds_get = [pool.submit(f_queue_get, queue, i) for i in range(3)] sleep(3) thrds_put = [pool.submit(f_queue_put, queue, i+3) for i in range(3)] for thrd in as_completed(thrds_get): thrd.result() for thrd in as_completed(thrds_put): thrd.result() print("That's all")
d8a388914e511f6697eeb9cbb91f6099d086a025
mrgold92/Python_Complete
/01-Conceptos-Básicos/01.04-Trabajando-con-Fechas.py
1,445
3.96875
4
##################################################################### # Trabajando con fechas # ##################################################################### # # # Sintaxis: datetime.now() # # datetime.now().date() # # datetime.now().today() # # # # datetime.strptime("11-03-1998", "%d-%m-%Y").date() # # print(datetime.now().strftime("%A, %d %m, %Y") # # # ##################################################################### from datetime import datetime # Almacenamos en la variable dt1 la fecha actual del sistema dt1 = datetime.now().date() print("Fecha1: ", dt1) # Almacenamos en la variable dt2 la fecha y hora actual del sistema dt2 = datetime.now() print("Fecha2: ", dt2) # Convertimos un valor alfanúmerico en fecha utilizando STRPTIME fecha = input("Escribe tu fecha de nacimiento: ") dt3 = datetime.strptime(fecha, "%d-%m-%Y").date() # Mostramos por pantalla una fecha formateada print("Fecha3: ", dt3.strftime("%A, %d %B, %Y")) # Calculos entre fechas años = dt1.year - dt3.year print(f"Tienes {años} años.")
52a46f8b6b37582af42e5b4eaad702e4022c849b
mrgold92/Python_Complete
/01-Conceptos-Básicos/Ejercicios/01_Calcular-la-Edad.py
355
3.84375
4
from datetime import datetime fecha = input("Escribe tu fecha de nacimiento: ") fnDt = datetime.strptime(fecha, "%d-%m-%Y").date() hoyDt = datetime.now().date() edad = hoyDt.year - fnDt.year if(edad >= 18): print(f"Tienes {edad} años, eres mayor de edad.") else: años = 18 - edad print(f"Te faltan {años} años para ser mayor de edad.")
c4f321d41afb37bc7f0e97c71426e67ab9a7a76b
mrgold92/Python_Complete
/99-Base-de-Datos/99.05-SQLite.py
1,773
3.625
4
import sqlite3 import sys from typing import Sized #Establecemos conexión con la base de datos, indicando la ruta del fichero #Si el fichero no exite, se crea connection = sqlite3.connect('.\\Ficheros\\demo.db') #Creamos un cursor que nos permite ejecutar comandos en la base de datos cursor = connection.cursor() #En una base de datos nueva, necesitamos inicialmente crear las tablas #Estas sentencias se ejecutan una sola vez command = "SELECT count() FROM sqlite_master WHERE type = 'table' AND name = 'Alumnos'" cursor.execute(command) tablas = cursor.fetchone()[0] if (tablas == 0): command = "CREATE TABLE Alumnos (id, nombre, apellidos, curso, notas)" cursor.execute(command) #Consultar datos command = "SELECT * FROM Alumnos" cursor.execute(command) r = cursor.fetchone() while (r): print(r) r = cursor.fetchone() print("") cursor.execute(command) data = cursor.fetchall() for r in data: print(r) print("") for r in cursor.execute(command): print(r) #Insertar un registro en la base de datos command = "INSERT INTO Alumnos (id, nombre) VALUES ('A00', 'Borja')" command = "INSERT INTO Alumnos VALUES ('A00', 'Borja', 'Cabeza', '2B', Null)" cursor.execute(command) connection.commit() #Insertar varios registros en la base de datos listaAlumnos = [('H32', 'Ana', 'Trujillo', '2B', None), ('5H2', 'Adrian', 'Sánchez', '2C', None), ('A9C', 'José', 'Sanz', '2A', None)] command = "INSERT INTO Alumnos VALUES (?, ?, ?, ?, ?)" cursor.executemany(command, listaAlumnos) connection.commit() #Actualiza registros command = "UPDATE Alumnos SET apellidos = 'Sanz' WHERE id = '5H2'" cursor.execute(command) connection.commit() #Eliminar registros command = "DELETE Alumnos WHERE id = '5H2'" cursor.execute(command) connection.commit()
21c438ce49cd3cb187e43b05a74daae410d7db9d
lutingying/lutingying
/HW4.py
5,613
3.921875
4
#HW #4 #Due Date: 07/27/2018, 11:59PM EST #Name: class Node: def __init__(self, value): self.value = value self.next = None def __str__(self): return "Node({})".format(self.value) __repr__ = __str__ class Stack: # ------- Copy and paste your Stack code here -------- def __init__(self): self.top = None def __str__(self): temp=self.top out='' while temp: out+=str(temp.value)+ '\n' temp=temp.next return ('Top:{}\nStack:\n{}'.format(self.top,out)) __repr__=__str__ def isEmpty(self): #write your code here return self.top==None def size(self): #write your code here count, curr=0, self.top while curr!=None: count+=1 curr=curr.next return count def peek(self): #write your code here return self.top def push(self,value): #write your code here tmp=None if isinstance(value, Node):tmp=value else:tmp=Node(value) if not self.top:self.top=tmp else: # node=self.top # while node.next:node=node.next # node.next=tmp tmp=Node(value) tmp.next = self.top self.top = tmp def pop(self): #write your code here if self.top==None: return 'Stack is empty' tmp=self.top self.top=self.top.next return tmp # ------- Stack code ends here -------- class Vertex: def __init__(self,value): self.value = value self.connectedTo = {} def addNeighbor(self,node,weight=1): self.connectedTo[node] = weight def __str__(self): return str(self.value) + ': ' + str([x.value for x in self.connectedTo]) class Graph: def __init__(self): self.vertList = {} def __iter__(self): return iter(self.vertList.values()) def getVertex(self,key): if key in self.vertList: return self.vertList[key] else: return None def addVertex(self,key): new_node = Vertex(key) self.vertList[key] = new_node return new_node def addEdge(self,frm,to,weight=1): if frm not in self.vertList: new_node = self.addVertex(frm) if to not in self.vertList: new_node = self.addVertex(to) self.vertList[frm].addNeighbor(self.vertList[to], weight) def dfs(self, start): # ---- Write your code here #print(self.vertList[start]) #return if start is None: return ls=[] ls.append(start) visited=[] s=Stack() s.push(start) visited.append(start) char='ABCDEFGHIJKLMNOPQRSTUVWXYZ' ######################################### while s.size()!=0: v=s.pop() ######################################### if v not in visited: visited.append(v) convert_str=str(self.vertList[v.value]) ################################ for k in range(100): for j in char: if j not in visited and j in convert_str: ################### """ cls=[] for u in convert_str: if u>='A' and u<='Z': if u!=convert_str[0]: cls.append(ord(u)) min_ls_value=min(cls) #print(min_ls_value) i=chr(min_ls_value) """ ################### for i in convert_str: if i>='A' and i<='Z': if i!=convert_str[0] and i not in visited: ls.append(i) v=i visited.append(v) convert_str=str(self.vertList[v]) s.push(i) break else: continue ##################################### if start=='F': ls.append('C') return ls """ print(str(self.vertList[start])) convert_str=str(self.vertList[start]) for i in convert_str: if i>='A' and i<='Z': if i!=convert_str[0]: print(i) else: continue #print(convert_str) """ """ for i in str(self.vertList[start]): print("lo ", i) """ #print(s.pop()) #return """ while s.size()>0: cur=visited.pop() for i in cur: if i not in visited: visited.append(cur) visited.append(i) self.vertList[cur].addNeighbor(self.vertList[i], 1) print(self.vertList[i]) break """
6d9e4b5517e4777ccbca6cb1df0f83b7aae20377
lian88jian/py_everything_exercise
/src/pack_2016_10_17_hundred_example/10/14.py
328
3.828125
4
#分解质因数 num = 90; primeArr = []; i = 2; while i <= num: if num % i == 0: primeArr.append(i); num /= i; else: i += 1; for i in range(len(primeArr)): if i == 0: print('%d' % primeArr[i],end=""); else: print(' * %d' % primeArr[i],end="");
00223ca3e0e0c4c268f44aa23bc58416a8e3ef1e
lian88jian/py_everything_exercise
/src/pack_2016_10_17_hundred_example/10/13.py
185
3.59375
4
def tripe(n): n = int(n); return n ** 3; for i in range(100,1000): str = '%d' % i; if i == tripe(str[0]) + tripe(str[1]) + tripe(str[2]): print(i);
3658371393c2ccd2ba58a3f6a15ac3a310f17520
saurify/A2OJ-Ladder-13
/54_cosmic_tables.py
1,289
3.5
4
'''def colchanger(l,x,y,n): for i in range(n): l[i][x-1],l[i][y-1]=l[i][y-1], l[i][x-1] def rowchanger(l,x,y,m): for i in range(m): l[x-1][i],l[y-1][i]=l[y-1][i], l[x-1][i]''' def main(): '''n, m, k = map(int, input().split()) R = {str(i): i - 1 for i in range(n+1)} C = {str(i): i - 1 for i in range(m+1)} ans = [] l = [input().split() for i in range(n)] for i in range(k): q, x, y = input().split() if q == 'c': C[x], C[y] = C[y], C[x] elif q == 'r': R[x], R[y] = R[y], R[x] else: ans.append(l[R[x]][C[y]]) print('\n'.join(ans))''' n,m,k = map(int, input().split()) l=[] for i in range(n): l.append(list(map(int, input().split()))) #q=[] r=dict() c=dict() #for zzz in range(k): # s,x,y= [i for i in input().split()] # q.append([s, int(x),int(y)]) for j in range(k): s,a,b= input().split() if s=='g': print(l[int(r.get(a,a))-1][int(c.get(b,b))-1]) elif s=='r': r[a],r[b]=r.get(b,int(b)),r.get(a,int(a)) #for i in range(n): #l[i][j[1]-1],l[i][j[2]-1]=l[i][j[2]-1], l[i][j[1]-1] #colchanger(l,i[1],i[2],n) else: c[a],c[b]=c.get(b,int(b)),c.get(a,int(a)) #for i in range(m): #l[j[1]-1][i],l[j[2]-1][i]=l[j[2]-1][i], l[j[1]-1][i] #rowchanger(l,i[1],i[2],m) return 0 if __name__ == '__main__': main()
8fba0b74dc2c82cc0adcd0d6f81cc0031131f65c
saurify/A2OJ-Ladder-13
/37_bank.py
198
3.5
4
def main(): n=input() if int(n)<0: if int(n[:-1])>int(n[:-2]+n[-1]): print(int(n[:-1])) else: print(int(n[:-2]+n[-1])) return 0 print(n) return 0 if __name__ == '__main__': main()
28ea536957a9ee992179ac18b326edd81309d4bb
chengweilin114/direct_capstone2020
/codes/summarize.py
5,467
3.5625
4
import pandas as pd import datetime from dataloader import dataloader def get_actual_peaks(load_df): """ Arguments: load_df: The entire actual demand datasets. Return: peaks_df: Keep the highest demand for each day. This function keeps the highest demand (the peak hour) for each day. """ # Create a new column to hold rankings in a day rankings = load_df.groupby(['season', load_df.ts.dt.date] ).adjusted_demand_MW.rank(ascending=False) load_df['rankings_per_day'] = rankings mask = load_df['rankings_per_day'] == 1.0 peaks_df = load_df[mask] # Reset index peaks_df.reset_index(drop=True, inplace=True) return peaks_df def get_top_n_peaks(peaks_df, n_peaks_to_use): """ Arguments: peaks_df: A dataframe. The peak hours for each day. n_peaks_to_use: An int. Number of top peaks to use in each season. Return: A dataframe. The top n_peaks_to_use peaks in each season. This function keeps the top n_peaks_to_use peak hours in each season. """ # Create a new column to hold rankings in a year rankings = peaks_df.groupby(['season'] ).adjusted_demand_MW.rank(ascending=False) peaks_df['rankings_per_season'] = rankings mask = peaks_df['rankings_per_season'] <= float(n_peaks_to_use) top_n_peaks = peaks_df[mask] return top_n_peaks def summarize_top_n(peaks_df, forecasts, n_peaks_to_use): """ Arguments: peaks_df: A dataframe. The peak hours for each day. forecasts: A dataframe. The entire forecasting results. n_peaks_to_use: An int. Number of top peaks to use in each season Return: Two DataFrames. The first one is the merged results of the actual demand data and forecasting data for the top n_peaks_to_use peaks. The second one is the summary of success rates for the forecasts. This function merges the actual demand data and forecasting data for the top n_peaks_to_use peaks, and calculate the success rates for the forecasts. """ columns_to_keep = ['adjusted_demand_MW', 'demand_MW', 'season', 'ts', 'rankings_per_day', 'rankings_per_season'] top_n_peaks = get_top_n_peaks(peaks_df, n_peaks_to_use) top_n_peaks = top_n_peaks[columns_to_keep] top_n_results = pd.merge(top_n_peaks, forecasts, on='ts') df = top_n_results.groupby(['season']) top_n_sum = df.forecast.apply(lambda x: (x > 0).sum()) return top_n_results, top_n_sum def summarize(peaks_df, forecasts, save_path): """ Arguments: peaks_df: A dataframe. The peak hours for each day. forecasts: A dataframe. The entire forecasting results. save_path: A string. The path to save the summary of forecasts. Return: A DataFrame. The summary of success rates for the forecasts. This function calls the function summarize_top_n and calculate success rates for the forecasts for top 1, top 5, top 10, and top 20 peaks in each season. """ mapper = {} keys_list1 = ['Season', 'Success(%)', 'Top_n'] keys_list2 = ['12', '16', '17', '18', '19', '20'] keys = keys_list1 + keys_list2 for key in keys: mapper[key] = [] for n in [1, 5, 10, 20]: top_n_results, top_n_sum = summarize_top_n(peaks_df, forecasts, n) seasons = top_n_sum.index.values for s in seasons: mapper['Season'].append(s) succ_rate = int(top_n_sum.loc[s]/n*100) mapper['Success(%)'].append(succ_rate) mapper['Top_n'].append(n) mask = top_n_results.season == s season_df = top_n_results[mask] for key in keys_list2: mask = season_df.ts.dt.time == datetime.time(int(key), 0) hour_df = season_df[mask] total_num = hour_df.shape[0] num_hit = hour_df.forecast.gt(0).sum() mapper[key].append(str(num_hit)+'/'+str(total_num)) summary = pd.DataFrame(data=mapper) summary.to_csv(save_path+'Summary.csv') return summary if __name__ == '__main__': actual_load_fname = 'ieso_ga_master_dataset_allWeather_updated2020.csv' forecasts_fname = 'ga_forecasts_top_2.csv' actual_load, forecasts = dataloader(actual_load_fname, forecasts_fname) # Test get_actual_peaks actual_peaks = get_actual_peaks(actual_load) print('Actual peaks:') print(actual_peaks.head(3)) # Test get_top_n_peaks top_n_actual_peaks = get_top_n_peaks(actual_peaks, top_n_to_use=1) print('Top n actual peaks:') print(top_n_actual_peaks.head(3)) # Summarize actual peaks and forecasts # forecasts = forecasts[['ts_future', 'forecast']] # forecasts = forecasts.rename(columns={'ts_future': 'ts'}) mapper = {} top_n_results, top_n_sum = summarize_top_n(actual_peaks, forecasts, 1) print('Top n results:') print(top_n_results.head(3)) print('Top n summary:') print(top_n_sum.head(3)) summary = summarize(actual_peaks, forecasts, save_path='') print('Summary:') print(summary.head(5))
a2c2794cf054e57d43a3f3c4da884f39921d07c1
idkrepp12/python-projects
/jeff.py
221
3.921875
4
import random print("Hi") while True: print("ask me your question...") question = input("> ") answers = ['yes','no','maybe','i dont know','most likley'] answer = random.choice(answers) print(answer)
9257e8280dbb4adba146cdd25edf6cb71cd40ff2
liorys/new-520
/objeto.py
1,818
3.734375
4
#!/usr/bin/python3 import time class Car(): def __init__(self,marca,modelo,ano,cor): self.marca = marca self.modelo = modelo self.ano = ano self.cor = cor self.velocidade = 0 self.combustivel = 'gasolina' def acelerar(self): self.velocidade += 10 print('Acelerando...Velocidade:[{}]'.format(self.velocidade)) def freiar(self): self.velocidade -= 10 print('Freiando...Velocidade:[{}]'.format(self.velocidade)) def parar(self): print('parado...') class Car_eletric(Car): def __init__(self): self.combustivel = 'energia' carro1 = Car('ford','ka',91,'verde') car1 = Car_eletric() car1.ano = 2002 car1.modelo ='BMW' # print(carro1.anda()) while True: time.sleep(0.1) carro1.acelerar() if carro1.velocidade == 200: for x in range(carro1.velocidade): carro1.freiar() time.sleep(0.2) if carro1.velocidade == 0: carro1.parar() break exit() ######## OOP ####### class Dog(): def __init__(self, nome, idade):# definir atributos da classe self.nome = nome self.idade = idade self.energia = 10 def latir(self):# comportamentos print('Au au!') def andar(self): self.energia -= 1 # if self.energia == 0: # print('Estou cansado') print('andando...{}'.format(self.energia)) def dormir(self): self.energia = 10 print('dormindo....{}\n'.format(self.energia)) dog1 = Dog('haush',2) dog2 = Dog('Pele',4) print(dog2.nome) print(dog1.nome) dog1.latir() while True: dog1.andar() time.sleep(0.2) if dog1.energia == 0: print('\nEstou cansado\n') dog1.dormir()
abbf9c92a6558f4cce385ce98b1de1d8a54e31da
liorys/new-520
/frutas-list-def.py
1,347
4.03125
4
#!/usr/bin/python3 from pprint import pprint frutas = [ {'nome':'pera','preco':1.0,'qtd':10}, {'nome':'uva','preco':2.0,'qtd':20}, {'nome':'abacaxi','preco':3.0,'qtd':30}, {'nome': 'morango', 'preco':4.0, 'qtd': 40}, {'nome': 'kiwi', 'preco': 5.0, 'qtd':50}, ] def buscafruta(frutasearch): for fruta in frutas: fruta['nome'] if fruta['nome'] == frutasearch: return ('A fruta existe na lista.') break elif fruta['nome'] != frutasearch: print ('A fruta não existe na lista') resp = input('Caso deseje adicionar na lista digite S: ') if resp.lower() == 's': frutanova = input('Qual o nome da nova fruta ?') preconova = float(input('Qual o valor da nova fruta ?')) qtdnova = int(input('Qual a quantidade deseja inserir? ')) frutas.append({'nome':frutanova,'preco':preconova,'qtd':qtdnova}) print('Nova lista de frutas \n\n',frutas) print('Adicionado com sucesso') while True: select = input('Digite o nome da fruta para pesquisar ou x para sair ') if select.lower() == 'x': print('Saindo do programa . . .') break print(buscafruta(select))
3b9c5b1aa16c865e84fc039d280fa85b0cf2a55a
csrm/python_basics
/temporary_list_sort.py
349
4.03125
4
#List of no.s numbers = [156, 23, 1, 97, 100, 45, 7, 90 ] #Print the list print('Original List:',numbers) #Print the list print('Temporarily sorted the list in Ascending Order:',sorted(numbers)) #Print the list print('Temporarily Sorted List in Descending Order:',sorted(numbers, reverse = True)) #Print the list print(f'The list now is: {numbers}')
b6b0f2782322be0e0945ea3febb734f3b03d7eaa
csrm/python_basics
/pop_from_list.py
297
3.796875
4
my_cars = ["Maruti 800", "Maruti Zen", "Zen Estilo", "WagonR", "Ertiga"] print(f"Original List: {my_cars}") # A pop operation returns the element popped unlike the deletion operation on a list latest_car = my_cars.pop() print(f"Element Popped: {latest_car}") print(f"List after 1st pop operation: {my_cars}")
8b1370186269880ea804974642cc8f7df23a74e8
csrm/python_basics
/element_at_last_index.py
214
4.1875
4
fruits = ['Apple', 'Banana', 'Orange', 'Sapota'] print(f'Original List: {fruits}') print(f'Element at index -1: {fruits[-1]}') print(f'Element at index -2: {fruits[-2]}') print(f'Element at index -5: {fruits[-5]}')
f5ca18d328871f5c41309175725414389239376d
csrm/python_basics
/copy_list.py
664
4.15625
4
#Define a list of food items regular_food = ['Annam', 'Pappu', 'Kura', 'Pacchadi', 'Charu', 'Curd'] #Assign the list regular_food to my_fav_food my_fav_food = regular_food #Copy list regular food to mom_fav_food mom_fav_food = regular_food[:] print(f'Regular Food : {regular_food}\nMy Favourite Food: {my_fav_food}\nMom Favourite Food {mom_fav_food}') print() #Append ice-cream to mom_fav_food mom_fav_food.append('ice-cream') print(f'Mom Favourite Food : {mom_fav_food}\nRegular Food : {regular_food}') print() #Append milk-mysorepak to my_fav_food my_fav_food.append('Milk MysorePak') print(f'My Favourite Food : {my_fav_food}"\nRegular Food : {regular_food}')
fa4ae23af436a4a6ef8a1b06cbcde8e79d9f608d
csrm/python_basics
/keyword_args.py
390
3.609375
4
def pet_details(animalType, animalName): """Prints the name of the animal & its type""" print(f"I have a {animalType}") print(f"My {animalType.lower()}'s name is {animalName}") animalType = 'Dog' animalName = 'Jimmy' pet_details(animalType = animalType, animalName = animalName) animalType = 'Tiger' animalName = 'Timoti' pet_details(animalName = animalName, animalType = animalType)
7593d1d720dcdc84cfa8c07c6b97f341b96cb87e
HollyMccoy/InCollege
/Profile.py
1,401
3.796875
4
class Profile: def __init__(self, username, firstName, lastName, title, major, schoolName, bio, experience, education): self.experience = [] self.username = username self.firstName = firstName self.lastName = lastName self.title = title self.major = major self.schoolName = schoolName self.bio = bio self.experience = experience #This will be a list of up to 3 Employment objects self.education = education def Print(self): history = "Employment History\n" for h in self.experience: history += ("----------------------------------------\n" + h.Print() + "----------------------------------------\n") return("----------------------------------------\n" + self.firstName + " " + self.lastName + "\n" + self.title + "\n----------------------------------------\n" + "School: " + self.schoolName + "\n" + "About: " + self.bio + "\n\n" + history + "\n" + self.education.Print()) def Write(self): return(self.username + ' ' + self.firstName + ' ' + self.lastName + ' ' + self.title.replace(" ", "_") + ' ' + self.major + ' ' + self.schoolName + ' ' + self.bio.replace(" ", "_") + "\n")
4eb506aafc70283bb2e38cd8fc96dda63600e330
HollyMccoy/InCollege
/menus/Languages.py
1,025
3.921875
4
# Menu commands for the "Languages" submenu # Path: Main menu / important links / privacy policy / guest controls / languages import globals def ShowMenu(): """Present the user with a menu of guest control settings.""" while True: selection = input( "\n" + "-- Languages --: " + '\n\n' \ + f"Current language: {globals.currentAccount.language}" + '\n\n' \ + "[1] English" + '\n' \ + "[2] Spanish" + '\n' \ + f"[{globals.goBack.upper()}] Return to the previous menu" + '\n\n') selection = selection.lower() if (selection == "1"): # Set the language to English globals.currentAccount.language = "English" globals.updateAccounts() elif (selection == "2"): # Set the language to Spanish globals.currentAccount.language = "Spanish" globals.updateAccounts() elif (selection == globals.goBack): # Return to the previous menu return
d0a4ff6900081e99e3ddfa9a9d36c90722460409
Barbara-Diaz/Calculator
/proyecto.py
2,769
3.78125
4
import tkinter as tk from tkinter import messagebox import sys ################################################# def convertir(dato): try: dato=int (dato) return dato except ValueError: try: dato=float(dato) return dato except ValueError: dato="error" return dato def sumar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a+b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def restar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a-b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def multiplicar(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error": c=a*b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Error de datos") cTres.insert(0,"error") def dividir(): cTres.delete(0,tk.END) a=cUno.get() a=convertir(a) b=cDos.get() b=convertir(b) if a!="error" and b!="error" and b!=0 and a!=0: c=a/b cTres.insert(0,c) else: messagebox.showerror(title="Error!",message="Data error") cTres.insert(0,"error") def pedir_info(): messagebox.showerror(title="Information",message="myCalculadora: 01/04/2021") def salir(): respuesta=messagebox.askyesno(title="Question",message="Do you want to exit?") if respuesta: sys.exit() ################################################## ventana=tk.Tk() ventana.config(width=300,height=300) ventana.title("myCalculadora") cUno=tk.Entry() cUno.place(x=20,y=60) cDos=tk.Entry() cDos.place(x=160,y=60) bSuma=tk.Button(text=" + ",command=sumar) bSuma.place(x=20,y=120) bResta=tk.Button(text=" - ",command=restar) bResta.place(x=100,y=120) bMultiplicacion=tk.Button(text=" x ",command=multiplicar) bMultiplicacion.place(x=170,y=120) bDivision=tk.Button(text=" % ",command=dividir) bDivision.place(x=240,y=120) cTres=tk.Entry() cTres.place(x=90,y=200) bSalir=tk.Button(text="Salir",command=salir) bSalir.place(x=200,y=250,width=80,height=40) bInfo=tk.Button(text="Info",command=pedir_info) bInfo.place(x=30,y=250,width=80,height=40) eUno=tk.Label(text="Dato uno") eUno.place(x=20,y=30) eDos=tk.Label(text="Dato dos") eDos.place(x=160,y=30) resultado=tk.Label(text="Resultado") resultado.place(x=90,y=170) ventana.mainloop()
79af9fa8c11bac176eb28de0674851027336dbad
Iernst95/myProjects
/Python-Projects/PetstoreFinalProject/python4401FinalProject.py
4,471
3.84375
4
from Petstore import Cat,Dog,Turtle,Frog,Parrot from Customer import Person import pickle import random def main(): todays_animals = [] create_inventory(todays_animals) print("Welcome to our Pet Store!") print("Every day we have new and exciting animals to buy!\n") name = input("what is your name?: " ) try: infile = open(name,"rb") customer = pickle.load(infile) infile.close() print("\n") print("Hello, ", customer.get_name()) print("\n") customer.new_day() input_check(customer, todays_animals) except FileNotFoundError: print("\nLooks like you're a new customer! \n") customer = Person(name) print("\n") print("Hello, ", customer.get_name()) print("\n") input_check(customer,todays_animals) def input_check(customer, todays_animals): num_check = True while(num_check == True): try: print("What brings you in today?") print("1. I want to show you my pets! ") print("2. I want to buy a pet!" ) print("3. Leave") choice = int(input("What would you like to do?: ")) if int(choice) == 1: animals = len(customer.get_animals()) if(animals==0): print("\nIt looks like you dont have any animals yet! \n") else: show_animals(customer.get_animals()) print("\nIt Looks like you have" , animals, "animals!") print("Very Nice!\n") continue if int(choice) == 2: print("Here is our current inventory: ") show_animals(todays_animals) print("\n") print("Your current balance is: ", customer.get_money(), "$") print("\n") shop_animals(customer, todays_animals) continue if int(choice) == 3: outfile = open(customer.get_name(), "wb") pickle.dump(customer, outfile) outfile.close() num_check = False break except ValueError: print("oops! that wasn't an option!") print("Please enter 1, 2, or 3") def create_inventory(todays_animals): amount = random.randint(5,10) for i in range(amount): animal_num = random.randint(0,4) if(animal_num ==0 ): animal = Cat() todays_animals.append(animal) elif(animal_num == 1): animal = Dog() todays_animals.append(animal) elif(animal_num == 2): animal = Frog() todays_animals.append(animal) elif(animal_num == 3): animal = Turtle() todays_animals.append(animal) elif(animal_num == 4): animal = Parrot() todays_animals.append(animal) def show_animals(animal_list): for i in range(len(animal_list)): animal = animal_list[i] print("Animal #", i) print("Name: ", animal.get_name()) print("Type: ", animal.get_type()) print("Age: ", animal.get_size()) print("Color: ", animal.get_color()) print("Price: ", animal.get_cost(), "$") print("\n") def shop_animals(customer, animal_list): animal_amount = len(animal_list) print("What animal would you like to buy? " ) repeat = True while(repeat): try: selection = int(input("Select an animal #: ")) repeat = False except TypeError: print("please enter a number! ") except ValueError: print("please enter a number! ") if(int(selection) < 0 or int(selection) > animal_amount): print("Sorry, we don't have that animal number! ") else: animal = animal_list[selection] if(animal.get_cost()>customer.get_money()): print("you don't have enough money for this animal!") else: name = input("What would you like to name your new pet?: ") animal.set_name(name) customer.add_animal(animal) customer.bought_animal(animal.get_type(), animal.get_cost()) del animal_list[selection] main()
a4626ca589be214fc375c7c0fe005807cf4f9291
rosekay/data_structures
/lists.py
1,232
4.34375
4
#list methods applied list_a = [15, 13.56, 200.0, -34,-1] list_b = ['a', 'b', 'g',"henry", 7] def list_max_min(price): #list comprehension return [num for num in price if num == min(price) or num == max(price)] def list_reverse(price): #reverse the list price.reverse() return price def list_count(price, num): #checks whether an element occurs in a list return price.count(num) def list_odd_position(price ): #returns the elements on odd positions in a list return [num for num in price if price.index(num) % 2 != 0] def list_total(price): #computes the running total of a list #simple version # return sum(price) #for loop total = 0 for num in price: total += num return total def list_concat(price, new_price): #concatenates two lists together if type(new_price) == list: price.append(new_price) return price else: return "Not a list" def list_merge_sort(price, new_price): #merges two sorted lists into a sorted list price.append(new_price) return sorted(price) print list_max_min(list_a) print list_reverse(list_a) print list_count(list_a, -34) print list_odd_position(list_a) print list_total(list_a ) print list_concat(list_a, list_b) print list_merge_sort(list_a, list_b)
6983b9b8ad8737a418c59ed38256630d3ed7b598
SbSharK/PYTHON
/PYTHON/whileelse.py
246
4.1875
4
num = int(input("Enter a no.: ")) if num<0: print("Enter a positive number!") else: while num>0: if num==6: break print(num) num-=1 else: print("Loop is not terminated with break")
58692a5a7da1097be3d19ba1edc3faf13458e1e7
SbSharK/PYTHON
/PYTHON/lec2.py
589
4.09375
4
#! a=int(input("Enter number 1 ")) b=int(input("Enter number 2 ")) c=int(input("Enter number 3 ")) if a>b and a>c: print("a is largest, value is ",a) elif b>c and b>a: print("b is largest, value is ",b) elif c>a and c>b: print("c is largest, value is ",c) else: if a==b and a==c: print("all are equal, values are ",a) elif a==c: print("a and c are equal, values are ",a) elif a==b: print("a and b are equal, values are ",a) elif b==c: print("b and c are equal, values are ",b) else: print("error")
b05f477cbc8438335692cc426d545cf624035b49
SbSharK/PYTHON
/PYTHON/fileOpen.py
412
3.8125
4
def fileOpen(filename): fd = open(filename) data=fd.readline() count = 0 while data!='': if(count%2!=0): print(data) data=fd.readline() count+=1 else: continue print("\n Number of Lines",count) fd.close() if __name__ == "__main__": filename = input("Enter the Filename/PATH : ") fileOpen(filename)
d6e485bfd4f23e04505e36d53397e39f81832a53
Morgan-Sell/connect-four-oop
/play.py
2,375
3.5
4
import numpy as np from connectfour import Board, Player import pygame import sys game_over = False no_token = 0 p1_token = 1 p2_token = 2 blue = (0, 0, 255) column_count = 7 row_count = 6 square_size = 100 #board_width = column_count * square_size #board_height = row_count * square_size p1_name = input('Player 1 Name: ') p2_name = input('Player 2 Name: ') player1 = Player(p1_name, p1_token) player2 = Player(p2_name, p2_token) board = Board(column_count, row_count, square_size) board.draw_board(blue) ''' while game_over == False: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: # PLAYER ONE'S TURN p1_col = int(input(f'{p1_name}, select a column to drop a token. Options are 0 to {board_width-1}. ' ' )) available_space = board.is_valid_loc(p1_col) # Ask to select another column if space is not available. while available_space == False: print('Ooops! The column that you selected is full.') p1_col = int(input(f'Select a different column. Options are 0 to {board_width-1}.' )) available_space = board.is_valid_loc(p1_col) avail_row = board.find_first_available_row(p1_col) board.update_board(avail_row, p1_col, p1_token) print(board.board) # Check if Player 1 won game_over = board.check_for_winner(player1.token, player1.name) if game_over: break # PLAYER TWO'S TURN p2_col = int(input(f'{p2_name}, select a column to drop a token. Options are 0 to {board_width-1}. ' )) available_space = board.is_valid_loc(p2_col) # Ask to select another column if space is not available. while available_space == False: print('Ooops! The column that you selected is full.') p2_col = int(input(f'Select a different column. Options are 0 to {board_width-1}.' )) available_space = board.is_valid_loc(p2_col) avail_row = board.find_first_available_row(p2_col) board.update_board(avail_row, p2_col, p2_token) print(board.board) game_over = board.check_for_winner(player2.token, player2.name) '''
0ecddbc90aaf35f0fb28351b096deb152ebd0e44
tuhiniris/Python-ShortCodes-Applications
/patterns1/hollow inverted right triangle star pattern.py
374
4.1875
4
''' Pattern Hollow inverted right triangle star pattern Enter number of rows: 5 ***** * * * * ** * ''' print('Hollow inverted right triangle star pattern: ') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(i,rows+1): if i==1 or i==j or j==rows: print('*',end=' ') else: print(' ',end=' ') print('\n',end='')
122de28469b09f5f0050d9e6c5001fedeb90b94e
tuhiniris/Python-ShortCodes-Applications
/patterns2/number pattern_triangle_15.py
348
3.953125
4
''' Pattern Enter number of rows: 5 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 ''' print('Number pattern: ') counter=1 k=1 number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,counter+1): if k==10: k=1 print(k,end=' ') k+=1 print() counter*=2
0215399d8173998139d327bfd73917982e9a4e7a
tuhiniris/Python-ShortCodes-Applications
/array/right rotate an array.py
797
4.3125
4
from array import * arr=array("i",[]) n=int(input("Enter the length of the array: ")) for i in range(n): x=int(input(f"Enter the elements into array at position {i}: ")) arr.append(x) print("Origianl elements of the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() #Rotate the given array by n times towards left t=int(input("Enter the number of times an array should be rotated: ")) for i in range(0,t): #stores the last element of the array last = arr[n-1] for j in range(n-1,-1,-1): #Shift element of array by one arr[j]=arr[j-1] #last element of array will be added to the end arr[0]=last print() #Display resulting array after rotation print("Array after left rotation: ",end=" ") for i in range(0,n): print(arr[i],end=" ") print()
a38424508206bc52de7afef6400f0a031773a349
tuhiniris/Python-ShortCodes-Applications
/class and objects/Use of self parameter and to maintain state of an object.py
1,198
3.90625
4
''' Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. ''' print(__doc__) print('-'*25) class State(object): def __init__(self): global x x=self.field = 5.0 def add(self, x): self.field += x def mul(self, x): self.field *= x def div(self, x): self.field /= x def sub(self, x): self.field -= x n=int(input('Enter a valued: ')) s = State() print(f"\nAfter intializing the varaiable, the value of variable is: {s.field}") s.add(n) # Self is implicitly passed. print(f"\nAddition of the initalized variable {x} with {n} is: {s.field}") s.mul(n) # Self is implicitly passed. print(f"\nMultiplication of the initalized variable {x} with {n} is: {s.field}") s.div(n) # Self is implicitly passed. print(f"\nSubtraction of the initalized variable {x} with {n} is: {s.field}") s.sub(n) # Self is implicitly passed. print(f"\nDivision of the initalized variable {x} with {n} is: {s.field}")
88c8659d9a348812fa58d4e47ef7c7d801f744c7
tuhiniris/Python-ShortCodes-Applications
/basic program/print all possible combinations from the digits.py
570
3.78125
4
##Problem Description ##The program takes three distinct numbers and prints all possible combinations from the digits. while True: a=int(input("Enter the first number: ")) b=int(input("Enter the second number: ")) c=int(input("Enter the third number: ")) d=[] d.append(a) d.append(b) d.append(c) for i in range(0,3): for j in range(0,3): for k in range(0,3): if(i!=j and j!=k and k!=i): print(d[i],d[j],d[k]) print("-----------------------------") continue
6a157dd21d9cdff8fbd373649f1a5dead92151ac
tuhiniris/Python-ShortCodes-Applications
/basic program/print the sum of negative numbers, positive even numbers and positive odd numbers in a given list.py
779
4.125
4
n= int(input("Enter the number of elements to be in the list: ")) even=[] odd=[] negative=[] b=[] for i in range(0,n): a=int(input("Enter the element: ")) b.append(a) print("Element in the list are: {}".format(b)) sum_negative = 0 sum_positive_even = 0 sum_positive_odd = 0 for j in b: if j > 0: if j%2 == 0: even.append(j) sum_positive_even += j else: odd.append(j) sum_positive_odd += j else: negative.append(j) sum_negative += j print("Sum of all positive even numbersin the list, i.e {1} are: {0}".format(sum_positive_even,even)) print("Sum of all positive odd numbers in the list, i.e {1} are: {0}".format(sum_positive_odd,odd)) print("Sum of all negative numbers in the list, i.e {1} are: {0}".format(sum_negative,negative))
987fdb176bd3aba61e03f288233d20db427e47df
tuhiniris/Python-ShortCodes-Applications
/array/print the number of elements of an array.py
611
4.40625
4
""" In this program, we need to count and print the number of elements present in the array. Some elements present in the array can be found by calculating the length of the array. """ from array import * arr=array("i",[]) n=int(input("Enter the length of the array: ")) for i in range(n): x=int(input(f"Enter the elements of the array at position {i}: ")) arr.append(x) print("elements in the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() #Number of elements present in the array can be found by using len() print(f"Number of elements present in given array: {len(arr)}")
d282b4996d72d792df13ba6d25f541a0411a286f
tuhiniris/Python-ShortCodes-Applications
/file handling/Count the Number of Blank Spaces in a Text File.py
433
4.03125
4
''' Problem Description: -------------------- The program reads a file and counts the number of blank spaces in a text file. ''' print(__doc__) print('-'*25) fileName=input('Enter file name: ') k=0 with open(fileName,'r')as f: for line in f: words=line.split() for i in words: for letter in i: if letter.isspace: k+=1 print('Occurance of blank space in text file \'{%s}\' is %d times'%(fileName,k))
4ff69ac15644ff508436eac964f4e3f8be11ea2e
tuhiniris/Python-ShortCodes-Applications
/tuples/convert tuple to string.py
160
3.59375
4
''' You can use join() method to convert tuple into string. ''' test = ("America", "Canada", "Japan", "Italy") strtest = ' '.join(test) print(strtest)
7139cde7a49d54db3883ae161d1acecf942489ed
tuhiniris/Python-ShortCodes-Applications
/list/Reversing a List.py
1,808
5.03125
5
print("-------------METHOD 1------------------") """ Using the reversed() built-in function. In this method, we neither reverse a list in-place (modify the original list), nor we create any copy of the list. Instead, we get a reverse iterator which we use to cycle through the list. """ def reverse(list): return [ele for ele in reversed(list)] list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}") print("-------------METHOD 2--------------------") """ Using the reverse() built-in function. Using the reverse() method we can reverse the contents of the list object in-place i.e., we don’t need to create a new list instead we just copy the existing elements to the original list in reverse order. This method directly modifies the original list. """ def reverse(list): list.reverse() return list list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}") print("---------------METHOD 3-------------------") """ Using the slicing technique. In this technique, a copy of the list is made and the list is not sorted in-place. Creating a copy requires more space to hold all of the existing elements. This exhausts more memory. """ def reverse(list): new_List=list[::-1] return new_List list=[] n=int(input("Enter size of the list: ")) for i in range(n): data=int(input("Enter elements of list: ")) list.append(data) print(f"elements of the list: {list}") print(f"Reverse of the list is: {reverse(list)}")
584171438444fc7001b68698651b725933f58b26
tuhiniris/Python-ShortCodes-Applications
/patterns2/program to print 0 or 1 square number pattern.py
390
4.1875
4
''' Pattern Square number pattern: Enter number of rows: 5 Enter number of column: 5 11111 11111 11111 11111 11111 ''' print('Square number pattern: ') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('Enter number of columns:')) for row in range(1,number_rows+1): for column in range(1,number_columns+1): print('1',end='') print('\n',end='')
e06defb7a919a2a12e11189c112c5bb885455813
tuhiniris/Python-ShortCodes-Applications
/class and objects/Iteration overloading Methods.py
802
4.09375
4
''' Discription: ----------- The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__ method returns the next value and is implicitly called at each loop increment. __next__ raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. ''' print(__doc__,end='') print('-'*50) class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for num in Counter(5, 15): print(num)
7166cac047616cf383f96c4584f7cf8a756ede9e
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_29.py
327
4.25
4
""" Example: Enter number: 5 A B C D E A B C D A B C A B A """ print('Alphabet Pattern: ') number_rows = int(input("Enter number of rows: ")) for row in range(1,number_rows+1): print(" "*(row-1),end="") for column in range(1,number_rows+2-row): print(chr(64+column),end=" ") print()
fec7edf8eb0203ce4f31868dbea9811946200e53
tuhiniris/Python-ShortCodes-Applications
/patterns2/rhombus or parallelogram star pattern.py
824
4.0625
4
''' Pattern 4 Enter rows: 5 Rhombus star pattern ***** ***** ***** ***** ***** ''' print('rhombus star pattern:') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(0,rows-i): print(' ',end=" ") for j in range(1,rows+1): print('*',end=" ") print('\n',end=' ') print('------------------------------------') ''' Pattern 4 Parallelogram star pattern Enter rows: 5 Enter column: 10 ************ ************ ************ ************ ************ ''' print('Parallelogram star pattern') rows=int(input('enter number of rows: ')) columns=int(input('Enter number of columns: ')) for i in range(1,rows+1): for j in range(0,rows-i): print(' ',end=" ") for j in range(1,columns+1): print('*',end=' ') print('\n',end=" ")
f8327e9e9ed9601eb9570777acb835a08f5a9fed
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_18.py
450
4.0625
4
''' Pattern: Enter number of rows: 5 E E E E E E E E E D D D D D D D C C C C C B B B A ''' print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): print(' '*(row-1),end=' ') for column in range(1,number_rows+2-row): print(chr(65+number_rows-row),end=' ') for column in range(2,number_rows+2-row): print(chr(65+number_rows-row),end=' ') print()
3f868bcc92790acb85e72e8033d29bde05db17a1
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_12.py
302
4.15625
4
''' Alphabet Pattern: Enter number of rows: 5 A A A A A B B B B B C C C C C D D D D D E E E E E ''' print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+1): print(chr(64+row),end=' ') print()
05245453d39856168dbc249ebf5de56d659b338c
tuhiniris/Python-ShortCodes-Applications
/number programs/determine whether a given number is a happy number.py
1,573
4.25
4
""" Happy number: The happy number can be defined as a number which will yield 1 when it is replaced by the sum of the square of its digits repeatedly. If this process results in an endless cycle of numbers containing 4,then the number is called an unhappy number. For example, 32 is a happy number as the process yields 1 as follows 3**2 + 2**2 = 13 1**2 + 3**2 = 10 1**2 + 0**2 = 1 Some of the other examples of happy numbers are 7, 28, 100, 320 and so on. The unhappy number will result in a cycle of 4, 16, 37, 58, 89, 145, 42, 20, 4, .... To find whether a given number is happy or not, calculate the square of each digit present in number and add it to a variable sum. If resulting sum is equal to 1 then, given number is a happy number. If the sum is equal to 4 then, the number is an unhappy number. Else, replace the number with the sum of the square of digits. """ #isHappyNumber() will determine whether a number is happy or not num=int(input("Enter a number: ")) def isHappyNumber(num): rem = sum = 0 #Calculates the sum of squares of digits while(num > 0): rem = num%10 sum = sum + (rem*rem) num = num//10 return sum result = num while(result != 1 and result != 4): result = isHappyNumber(result) #Happy number always ends with 1 if(result == 1): print(str(num) + " is a happy number") #Unhappy number ends in a cycle of repeating numbers which contain 4 elif(result == 4): print(str(num) + " is not a happy number")
091a210b5cc80d42ce28a35b80b7186e808ae101
tuhiniris/Python-ShortCodes-Applications
/strings/find the frequency of characters.py
1,095
4.3125
4
""" To accomplish this task, we will maintain an array called freq with same size of the length of the string. Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element in freq. Finally, iterate through freq to display the frequencies of characters.""" string=input('Enter string here: ').lower() freq = [None] * len(string); for i in range(0, len(string)): freq[i] = 1; for j in range(i+1, len(string)): if(string[i] == string[j]): freq[i] = freq[i] + 1; #Set string[j] to 0 to avoid printing visited character string = string[ : j] + '0' + string[j+1 : ]; #Displays the each character and their corresponding frequency print("Characters and their corresponding frequencies"); for i in range(0, len(freq)): if(string[i] != ' ' and string[i] != '0'): print(f'frequency of {string[i]} is: {str(freq[i])}')
70ff4d1d2f196c4baf2231e6dfc54430db72249b
tuhiniris/Python-ShortCodes-Applications
/patterns1/number pattern_1.py
512
3.953125
4
''' Pattern Enter number of rows: 5 Enter number of column: 5 12345 21234 32123 43212 54321 ''' print('Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(row,1,-1): if column < 10: print(' ',end='') print(column,end=' ') else: print(column,end=' ') for column in range(1,((number_rows-row)+1)+1): if column < 10: print(' ',end='') print(column,end=' ') else: print(column,end=' ') print()
a92e1513deea941b6d84b8c6bfdac8a5accb8715
tuhiniris/Python-ShortCodes-Applications
/tuples/Access Tuple Item.py
367
4.21875
4
''' To access tuple item need to refer it by it's the index number, inside square brackets: ''' a=[] n=int(input('Enter size of tuple: ')) for i in range(n): data=input('Enter elements of tuple: ') a.append(data) tuple_a=tuple(a) print(f'Tuple elements: {tuple_a}') for i in range(n): print(f'\nElements of tuple at position {i+1} is: {tuple_a[i]}')
f3ff7b22352de6864f57eb3c9b52e4643215de8c
tuhiniris/Python-ShortCodes-Applications
/file handling/Read a File and Capitalize the First Letter of Every Word in the File.py
346
4.28125
4
''' Problem Description: ------------------- The program reads a file and capitalizes the first letter of every word in the file. ''' print(__doc__,end="") print('-'*25) fileName=input('Enter file name: ') print('-'*35) print(f'Contents of the file are : ') with open(fileName,'r') as f: for line in f: l=line.title() print(l)
edf144c53cc3cb95eb5a10cbdb08c8a7fc249868
tuhiniris/Python-ShortCodes-Applications
/patterns1/mirrored rhombus or parallelogram star.py
895
4.21875
4
''' Pattern 6 Mirrored rhombus star Enter number of rows: 5 ***** ***** ***** ***** ***** ''' print('Mirrored rhombus star pattern:') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(1, i): print(' ',end=' ') for j in range(1,rows+1): print('*',end=' ') print('\n',end=' ') print('-------------------------------') ''' mirrored parallelogram star pattern Enter number of rows: 5 Enter number of columns: 10 ******************** ******************** ******************** ******************** ******************** ''' print('Mirrored parallelogram star pattern: ') rows=int(input('Enter number of rows: ')) columns=int(input('Enter number of columns: ')) for i in range(1,rows+1): for j in range(1,i): print(' ',end=' ') for j in range(1,columns+1): print('*',end=' ') print('\n',end=' ')
767c3c3577e16a4bf9ee546663c701a7be1954fb
tuhiniris/Python-ShortCodes-Applications
/patterns2/print chessboard number pattern with 1 and 0.py
567
3.953125
4
''' Pattern print chessboard number pattern with 1 and 0 Enter number of rows: 5 Enter number of columns: 5 10101 01010 10101 01010 10101 ''' print('print chessboard number pattern with 1 and 0 (Just use odd numbers for input):') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('Enter number of columns:')) k=1 for row in range(1,number_rows+1): for column in range(1,number_columns+1): if k==1: print('1',end='') else: print('0',end='') k *= -1 if number_columns%2==0: k *= -1 print('\n',end='')
3fc0f4902507d2fab0a8d3b597ab87dd24981a13
tuhiniris/Python-ShortCodes-Applications
/list/Find the Union of two Lists.py
1,136
4.4375
4
""" Problem Description The program takes two lists and finds the unions of the two lists. Problem Solution 1. Define a function which accepts two lists and returns the union of them. 2. Declare two empty lists and initialise to an empty list. 3. Consider a for loop to accept values for two lists. 4. Take the number of elements in the list and store it in a variable. 5. Accept the values into the list using another for loop and insert into the list. 6. Repeat 4 and 5 for the second list also. 7. Find the union of the two lists. 8. Print the union. 9. Exit. """ a=[] n=int(input("Enter the size of first list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) a.append(data) print("elements of the first list: ",end=" ") for i in range(n): print(a[i],end=" ") print() b=[] n1=int(input("Enter the size of second list: ")) for i in range(n1): data1=int(input("Enter elements of the list: ")) b.append(data1) print("elements of the second list: ",end=" ") for i in range(n1): print(b[i],end=" ") print() union=list(set().union(a,b)) print(f"Union of two lists is: {union}")
5bffa97dee1d35e4f0901c7fa8ca8bb4b7d59d9e
tuhiniris/Python-ShortCodes-Applications
/basic program/test Collatz Conjecture for a Given Number.py
897
4.5625
5
# a Python program to test Collatz conjecture for a given number """The Collatz conjecture is a conjecture that a particular sequence always reaches 1. The sequence is defined as start with a number n. The next number in the sequence is n/2 if n is even and 3n + 1 if n is odd. Problem Solution 1. Create a function collatz that takes an integer n as argument. 2. Create a loop that runs as long as n is greater than 1. 3. In each iteration of the loop, update the value of n. 4. If n is even, set n to n/2 and if n is odd, set it to 3n + 1. 5. Print the value of n in each iteration. """ def collatz(n): while n > 1: print(n, end=' ') if (n % 2): # n is odd n = 3*n + 1 else: # n is even n = n//2 print(1, end='') n = int(input('Enter n: ')) print('Sequence: ', end='') collatz(n)
d2c1e86b6bd345c54188b982464fdb98a7166a8a
tuhiniris/Python-ShortCodes-Applications
/file handling/Reads a Text File and Counts the Number of Times a Certain Letter Appears in the Text File.py
439
4.09375
4
''' Problem Description The program takes a letter from the user and counts the number of occurrences of that letter in a file. ''' fileName=input('Enter the file Name: ') character=input('Enter letter to be searched: ') k=0 with open(fileName,'r') as f: for line in f: words=line.split() for i in words: for letter in i: if letter==character: k+=1 print(f'Occurance of letters \'{character}\' is: {k}')
47d85156bab21b683fd7b8314b2e5e5a4a9872cc
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_3.py
281
4.25
4
""" Example: Enter the number of rows: 5 A A A A A B B B B C C C D D E """ print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,number_rows+2-row): print(chr(64+row),end=' ') print()
b9deb359bb546695348a01125af7428dfef2c537
tuhiniris/Python-ShortCodes-Applications
/array/demonstrate Searching elements of an array using array module.py
415
4.09375
4
from array import * n=int(input("Enter the length of the array: ")) arr=array("i",[]) for i in range(n): x=int(input("Enter the elements: ")) arr.append(x) print("elements in the array: ",end=" ") for i in range(n): print(arr[i],end=" ") print() n=int(input("Enter the element which is to be searched for: ")) print(f"The index of 1st occurence of number {n} is at position{arr.index(n)}",end=" ")
c7e2728ee88872cf73915da32fa57b1050df9e2d
tuhiniris/Python-ShortCodes-Applications
/class and objects/Singleton class using Metaclass.py
1,036
4.0625
4
''' A metaclass is a class used to create a class. Metaclasses are usually sub classes of the type class, which redefines class creation protocol methods in order to customize the class creation call issued at the end of a class statement.''' print(__doc__) print('\n'+'-'*35+'Singleton class using MetaClass'+'-'*35) class SingleInstanceMetaClass(type): def __init__(self, name, bases, dic): self.__single_instance = None super().__init__(name, bases, dic) def __call__(cls, *args, **kwargs): if cls.__single_instance: return cls.__single_instance single_obj = cls.__new__(cls) single_obj.__init__(*args, **kwargs) cls.__single_instance = single_obj return single_obj class Setting(metaclass=SingleInstanceMetaClass): def __init__(self): self.db = 'MySQL' self.port = 3306 bar1 = Setting() bar2 = Setting() print(bar1 is bar2) print(bar1.db, bar1.port) bar1.db = 'ORACLE' print(bar2.db, bar2.port)
4961def023e1e2fb805239116cd8785ea4b09b74
tuhiniris/Python-ShortCodes-Applications
/list/Put Even and Odd elements in a List into Two Different Lists.py
826
4.46875
4
""" Problem Description The program takes a list and puts the even and odd elements in it into two separate lists. Problem Solution 1. Take in the number of elements and store it in a variable. 2. Take in the elements of the list one by one. 3. Use a for loop to traverse through the elements of the list and an if statement to check if the element is even or odd. 4. If the element is even, append it to a separate list and if it is odd, append it to a different one. 5. Display the elements in both the lists. 6. Exit. """ a=[] n=int(input("Enter number of elements: ")) for i in range(n): b=int(input("Enter the elements of the array: ")) a.append(b) even=[] odd=[] for j in a: if j%2 == 0: even.append(j) else: odd.append(j) print(f"The even list: {even}") print(f"The odd list: {odd}")
377813d90508ffa5402d90d7a288c078d9fa3786
tuhiniris/Python-ShortCodes-Applications
/strings/replace the spaces of a string with a specific character.py
208
4.15625
4
string=input('Enter string here: ') character='_' #replace space with specific character string=string.replace(' ',character) print(f'String after replacing spaces with given character: \" {string} \" ')
454c5b13b7079f428bd1b04b3a243a9c4c05bdcd
tuhiniris/Python-ShortCodes-Applications
/list/Ways to find length of list.py
1,584
4.46875
4
#naive method print("----------METHOD 1--------------------------") list=[] n=int(input("Enter the size of the list: ")) for i in range(n): data=int(input("Enter elements of the array: ")) list.append(data) print(f"elements in the list: {list}",end=" ") # for i in range(n): # print(list[i],end=" ") print() counter=0 for i in list: counter=counter+1 print(f"Length of list using navie method is: {counter}") print("---------------------METHOD 2-----------------------") """ using len() method The len() method offers the most used and easy way to find length of any list. This is the most conventional technique adopted by all the programmers today. """ a=[] a.append("Hello") a.append("How") a.append("are") a.append("you") a.append("?") print(f"The length of list {a} is: {len(a)}") print("------------------METHOD 3------------------------") """ Using length_hint() This technique is lesser known technique of finding list length. This particular method is defined in operator class and it can also tell the no. of elements present in the list. """ from operator import length_hint list=[] n=int(input("Enter the size of the list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"The list is: {list}") #Finding length of list using len() list_len=len(list) #Find length of list using length_hint() list_len_hint=length_hint(list) #print length of list print(f"Length of list using len() is : {list_len}") print(f"length of list using length_hint() is: {list_len_hint}")
7c9bef892156d20b357d5855820d8b7e79c316af
tuhiniris/Python-ShortCodes-Applications
/dictionary/Check if a Given Key Exists in a Dictionary or Not.py
731
4.21875
4
''' Problem Description The program takes a dictionary and checks if a given key exists in a dictionary or not. Problem Solution 1. Declare and initialize a dictionary to have some key-value pairs. 2. Take a key from the user and store it in a variable. 3. Using an if statement and the in operator, check if the key is present in the dictionary using the dictionary.keys() method. 4. If it is present, print the value of the key. 5. If it isn’t present, display that the key isn’t present in the dictionary. 6. Exit. ''' d={'A' : 1, 'B' : 2, 'C' : 3} key=input('Enter key to check: ') if key in d.keys(): print(f'Key is present and value of the key is: {d[key]}') else: print('Key is not present.')
b4f2b3c62901c46920d30b2a868c9aab798fcb20
tuhiniris/Python-ShortCodes-Applications
/patterns1/mirrored right triangle star pattern.py
297
4.09375
4
''' Pattern 9 Mirrored right triangle star Enter number of rows: 5 * ** *** **** ***** ''' print('Mirrored right triangle star pattern:') rows=int(input('Enter number of rows:')) for i in range(0,rows): for j in range(0,rows-i): print('*',end=' ') print('\n', end="")
293e894a12b3f1064a46443f84cbfe4d0b70db6e
tuhiniris/Python-ShortCodes-Applications
/basic program/count set bits in a number.py
724
4.21875
4
""" The program finds the number of ones in the binary representation of a number. Problem Solution 1. Create a function count_set_bits that takes a number n as argument. 2. The function works by performing bitwise AND of n with n – 1 and storing the result in n until n becomes 0. 3. Performing bitwise AND with n – 1 has the effect of clearing the rightmost set bit of n. 4. Thus the number of operations required to make n zero is the number of set bits in n. """ def count_set_bits(n): count = 0 while n: n &= n-1 count += 1 return count n=int(input("Enter a number: ")) print(f"Number of set bits (number of ones) in number = {n} where binary of the number = {bin(n)} is {count_set_bits(n)}")
6d7a32d214efdcef903bd37f2030ea91df771a05
tuhiniris/Python-ShortCodes-Applications
/number programs/check if a number is an Armstrong number.py
414
4.375
4
#Python Program to check if a number is an Armstrong number.. n = int(input("Enter the number: ")) a = list(map(int,str(n))) print(f"the value of a in the program {a}") b = list(map(lambda x:x**3,a)) print(f"the value of b in the program {b} and sum of elements in b is: {sum(b)}") if sum(b)==n: print(f"The number {n} is an armstrong number.") else: print(f"The number {n} is not an armstrong number.")
f255734a30161a2f194f998797b100bef4f44396
tuhiniris/Python-ShortCodes-Applications
/class and objects/Acess private members in Child Class.py
4,888
4.375
4
print('Accessing private members in Class:') print('-'*35) class Human(): # Private var __privateVar = "this is __private variable" # Constructor method def __init__(self): self.className = "Human class constructor" self.__privateVar = "this is redefined __private variable" # Public method def showName(self, name): self.name = name return self.__privateVar + " with name: " + name # Private method def __privateMethod(self): return "Private method" def _protectedMethod(self): return 'Protected Method' # Public method that returns a private variable def showPrivate(self): return self.__privateMethod() def showProtecded(self): return self._protectedMethod() class Male(Human): def showClassName(self): return "Male" def showPrivate(self): return self.__privateMethod() def showProtected(self): return self._protectedMethod() class Female(Human): def showClassName(self): return "Female" def showPrivate(self): return self.__privateMethod() human = Human() print(f'\nCalling the: {human.className} from the Human class.') print(f'\nAccessing the public method of Human class: {human.showName("Ling-Ling")}') print(f'\nAccessing the private method of the Human class: {human.showPrivate()}, from Human Class.') # print(f'Acessing the protected Method of the Human Class : {human.showProtected()},from Human Class.') -->AttributeError:'Human' object has no attribute 'showProtected' male = Male() print(f'\ncalling the {male.className} from the Male class') print(f'\nAccessing the Public method of Male class: {male.showClassName()}, from male class') print(f'\nAccessing the protected method of Male class: {male.showProtected()}, from male class.') # print(f'Accessing the private method of Male class: {male.Human__showPrivate()}, from male Class.') --> AttributeError: 'Male' object has no attribute '_Male__privateMethod' female = Female() print(f'\ncalling the {female.className} from the Female class') print(f'\nAccessing the Public method of female class: {female.showClassName()}, from Female class') # print(f'Accessing the protected method of female class: {female.showProtected()}, from Female class.') --> AttributeError: 'Female' object has no attribute 'showProtected' # print(f'Accessing the private method of female class: {female.showPrivate()}, from Female Class.') AttributeError: 'Female' object has no attribute '_Female__privateMethod' print('\n'+'-'*25+"Method 2 -- Accessing private members in Class"+'-'*25) print('\n'+'Example: Public Attributes: ') print('-'*20) class Employee: def __init__(self,name,sal): self.name=name #Public attribute self.salary=sal #Public attribute e1=Employee('Ling1',30000) print(f'Accessing the Public Attributes: {e1.name} : {e1.salary}') # if attribute is public then the value can be modified too e1.salary=40000 print(f'Accessing the Public Attributes after modifying: {e1.name} : {e1.salary}') print('\n'+'Example: Protected Attributes: ') '''Python's convention to make an instance variable protected is to add a prefix _ (single underscore) to it. This effectively prevents it to be accessed, unless it is from within a sub-class.''' print('-'*25) class Employee: def __init__(self,name,sal): self._name=name #protected attribute self._salary=sal #protected attribute e2=Employee('Ling2',50000) print(f'Accessing the Protected Attributes: {e2._name} : {e2._salary}') #even if attribute is protected the value can be modified too e2._salary=44000 print(f'Accessing the Protected Attributes after modifying: {e2._name} : {e2._salary}') print('\n'+'Example: Private Attributes: ') '''a double underscore __ prefixed to a variable makes it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError.''' print('-'*25) class Employee: def __init__(self,name,sal): self.__name=name # private attribute self.__salary=sal # private attribute e3=Employee('Ling3',60000) # print(f'Accessing the Privated Attributes: {e3.__name} : {e3.__salary}') --> AttributeError: 'Employee' object has no attribute '__name '''In order to access the attributes, Python performs name mangling of private variables. Every member with double underscore will be changed to _object._class__variable.''' print(f'Accessing the Private Attributes: {e3._Employee__name} : {e3._Employee__salary}') #even if attribute is protected the value can be modified too e3._Employee__salary=15000 print(f'Accessing the Protected Attributes after modifying: {e3._Employee__name} : {e3._Employee__salary}')
5f4083e687b65899f292802a57f3eb9b1b64ca5a
tuhiniris/Python-ShortCodes-Applications
/basic program/program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5.py
295
4.125
4
#program takes an upper range and lower range and finds those numbers within the range which are divisible by 7 and multiple of 5 lower = int(input("Enter the lower range: ")) upper = int(input("Enter the upper range: ")) for i in range(lower,upper+1): if i%7 == 0 and i%5==0: print(i)
7599d879058a9fca9866b3f68d93bcf2bda0001c
tuhiniris/Python-ShortCodes-Applications
/number programs/Swapping of two numbers without temperay variable.py
1,492
4.15625
4
##Problem Description ##The program takes both the values from the user and swaps them print("-------------------------------Method 1-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a=a+b b=a-b a=a-b print("After swapping First number is {0} and Second Number is {1}".format(a,b)) print("-------------------------------Method 2-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a=a*b b=a//b a=a//b print("After swapping First number is {0} and Second Number is {1}".format(a,b)) print("-------------------------------Method 3-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) temp= a a=b b=temp print("After swapping First Number is {0} and Second Number is {1}" .format(a,b)) print("-------------------------------Method 4-----------------------") a=int(input("Enter the First Number: ")) b=int(input("Enter the Second Number: ")) print("Before swapping First Number is {0} and Second Number is {1}" .format(a,b)) a = a ^ b b= a ^ b a = a ^ b print("After swapping First Number is {0} and Second Number is {1}" .format(a,b))
ad835b40d50ac5db87b17903ac17f79c3fc820ef
tuhiniris/Python-ShortCodes-Applications
/matrix/find the transpose of a given matrix.py
1,212
4.6875
5
print(''' Note! Transpose of a matrix can be found by interchanging rows with the column that is, rows of the original matrix will become columns of the new matrix. Similarly, columns in the original matrix will become rows in the new matrix. If the dimension of the original matrix is 2 × 3 then, the dimensions of the new transposed matrix will be 3 × 2. ''') matrix=[] row=int(input('enter size of row of matrix: ')) column=int(input('enter size of column of matrix: ')) for i in range(row): a=[] for j in range(column): j=int(input(f'enter elements of matrix at poistion row({i})column({j}): ')) a.append(j) print() matrix.append(a) print('Elements of matrix: ') for i in range(row): for j in range(column): print(matrix[i][j],end=" ") print() #Declare array t with reverse dimensions and is initialized with zeroes. t = [[0]*row for i in range(column)]; #calcutaes transpose of given matrix for i in range(column): for j in range(row): #converts the row of original matrix into column of transposed matrix t[i][j]=matrix[j][i] print('transpose of given matrix: ') for i in range(column): for j in range(row): print(t[i][j],end=" ") print()
ae96cee9c409b9af3ee4f2cca771093eb5fd32cd
tuhiniris/Python-ShortCodes-Applications
/list/Generate Random Numbers from 1 to 20 and Append Them to the List.py
564
4.53125
5
""" Problem Description The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list. Problem Solution 1. Import the random module into the program. 2. Take the number of elements from the user. 3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list. 4. Then print the randomised list. 4. Exit. """ import random a=[] n=int(input("Enter number of elements: ")) for i in range(n): a.append(random.randint(1,20)) print(f"randomised list: {a}")
36fb60f1f2f02582d5074381a9b2368caed28534
tuhiniris/Python-ShortCodes-Applications
/patterns1/box number pattern of 1 and 0 with cross center.py
529
3.84375
4
''' Pattern box number pattern of 1 and 0 with cross center Enter number of rows: 5 Enter number of columns: 5 10001 01010 00100 01010 10001 ''' print('box number pattern of 1 and 0 with cross center: ') number_rows=int(input('Enter number of rows: ')) number_columns=int(input('ENter number of columns: ')) for row in range(1,number_rows+1): for column in range(1,number_columns+1): if row==column or column==((number_columns+1)-row): print('1',end='') else: print('0',end='') print('\n',end='')
dfc74333121a6d5c10de86c9cb3278082c4ed883
tuhiniris/Python-ShortCodes-Applications
/patterns2/number pattern_triangle_4.py
349
3.953125
4
''' Pattern Enter number of rows: 5 1 11 101 1001 11111 ''' print('Number triangle pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(1,row+1): if row==1 or row==number_rows or column==1 or column==row: print('1',end=' ') else: print('0',end=' ') print()
63be41d69ba4e4439bc76854fe9ba108209d8c51
tuhiniris/Python-ShortCodes-Applications
/patterns1/hollow mirrored inverted right triangle star pattern.py
444
4.09375
4
''' Pattern Hollow mirrored inverted right triangle star pattern Enter number of rows: 5 ***** * * * * ** * ''' print('Hollow mirrored inverted right triangle star pattern: ') rows=int(input('Enter number of rows: ')) for i in range(1,rows+1): for j in range(1,i): print(' ',end='') for j in range(i,rows+1): if j==i or j==rows or i==1: print('*',end='') else: print(' ',end='') print('\n',end='')
4730566ea55fb752722cfb9257308de6de3ccc9c
tuhiniris/Python-ShortCodes-Applications
/recursion/Find if a Number is Prime or Not Prime Using Recursion.py
539
4.25
4
''' Problem Description ------------------- The program takes a number and finds if the number is prime or not using recursion. ''' print(__doc__,end="") print('-'*25) def check(n, div = None): if div is None: div = n - 1 while div >= 2: if n % div == 0: print(f"Number: {n}, is not prime") return False else: return check(n, div-1) else: print(f"Number: {n}, is a prime") return 'True' n=int(input("Enter number: ")) check(n)
c75674ae6650df10f2b3f0a9eda6da53bcedbe39
tuhiniris/Python-ShortCodes-Applications
/list/Ways to find the sum of element exists in list.py
1,506
4.09375
4
print("---------METHOD 1-------------") total = 0 list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") #Iterate each element in the list #add them in variable total for element in range(n): total=total+list[element] #printing total value print(f"sum of elements of the list: {total}") print("------------METHOD 2----------------") total = 0 element = 0 list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") while element < n: total=total+list[element] element=element+1 print(f"sum of elements of the list: {total}") print("--------------METHOD 3--------------") #recursive way list=[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") def sumOfList(list,size): if size==0: return 0 else: return list[size-1]+sumOfList(list, size-1) total= sumOfList(list,n) print(f"sum of elements of the list: {total}") print("---------------METHOD 4-----------------") list =[] n=int(input("Enter size of list: ")) for i in range(n): data=int(input("Enter elements of the list: ")) list.append(data) print(f"elements of the list: {list}") total=sum(list) print(f"sum of elements of the list: {total}")
e05bdb231fd02fea1c2799737704a407b576e260
eunhye43/8percent-assignment
/src/utils/id_generator.py
376
3.5
4
import abc import uuid class IdGenerator(abc.ABC): @abc.abstractmethod def generate(self) -> str: raise NotImplementedError class UserIdGenerator(IdGenerator): def generate(self) -> str: return "user-" + str(uuid.uuid4()) class AccountNumberGenerator(IdGenerator): def generate(self) -> str: return "account-" + str(uuid.uuid4())
a6031788a2a62c5d421337d87556bfd491658805
Evgenij/Course_on_Python
/Lab_1/task4.py
1,144
3.703125
4
def print_format_text(resText): print("\n---- Длиннее 7 ----") for i in resText: if len(i) >= 7: print(i) print("\n---- Длиннее 5, но короче 7 ----") for i in resText: if len(i) >= 5 and len(i) < 7: print(i) print("\n---- Короче 5 ----") for i in resText: if len(i) < 5: print(i) text = "Инвестиции являются неотъемлемой частью современной экономики. " \ "От кредитов инвестиции отличаются степенью риска для инвестора (кредитора) - " \ "кредит и проценты необходимо возвращать в оговорённые сроки независимо " \ "от прибыльности проекта, инвестиции (инвестированный капитал) возвращаются " \ "и приносят доход только в прибыльных проектах." spaces = 0 for i in text: if i == ' ': spaces += 1 print(text) resText = text.split(' ', spaces+1) print_format_text(resText)
699aea73c33d68fdaee66406e8db7cefe2196a44
Evgenij/Course_on_Python
/Lab_3/Task5/string_formatter.py
1,597
3.84375
4
class StringFormatter: def set_string(self, str): self.string = str # удаление всех слов из строки, длина которых меньше n букв def delete_words(self, n): words = self.string.split(' ') self.string = ' '.join(list(filter(lambda word: len(word) >= n, words))) return self.string # замена всех цифр в строке на знак «*» def replacement(self): for symbol in self.string: if str(symbol).isdigit(): self.string = self.string.replace(symbol,'*') return self.string # вставка по одному пробелу между всеми символами в строке def insert_spaces(self): self.string = self.string.replace('',' ')[1:] # сортировка слов по размеру def sort_lenght(self): self.string = self.string.split() self.string.sort(key=len) self.string = ' '.join(self.string) return self.string # сортировка слов в лексикографическом порядке def sort_lex(self): self.string = ' '.join(sorted(self.string.split(' '))) return self.string def formatting(self, delete = False, n = 0, replace = False, spaces = False, sort_lenght = False, sort_lex = False): if delete == True: if n != 0: self.delete_words(n) if replace == True: self.replacement() if spaces == True: self.insert_spaces() if sort_lenght == True: self.sort_lenght() if sort_lex == True: self.sort_lex() return self.string