blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
1d7b0eb474b258abc83f30e679910512fbe0f33f
sehammuqil/python-
/day 9.py
339
3.8125
4
age = 36 txt = "my name is john , and i am {}" print(txt.format(age)) quantity = 3 itemno = 567 price = 49.95 myorder= " i want {} pieces of item {} for {} dollars " print(myorder.format(quantity,itemno,price)) myorder= " i want {2} pieces of item {1} for {0} dollars " print(myorder.format(quantity,itemno,price))
a3cb102f415dfe67c53f3ff697b3d78369b5da11
sehammuqil/python-
/day18,19.py
481
4.1875
4
#list student =['sara','nora','hind'] print(student) #append student =['sara','nora','hind'] student.append("seham") print(student) #insert student =['sara','nora','hind'] student.insert(2,"seham") print(student) #pop student =['sara','nora','hind'] student.pop(2) print(student) #clear student =['sara','nora','hind'] student.clear() print(student) tuple = ("java","python","swift") if "python" in tuple: print("yes python in the tuple")
ae91ee6ae54b217b4db050fdb6312e1a1ba116b8
sehammuqil/python-
/day16.py
572
4.34375
4
thistuple = ("apple","banana","cherry") print(thistuple) thistuple=() print(thistuple) thistuple=(3,) print(thistuple) thistuple=(3,1.3,4.1,7) print(thistuple) thistuple=("ahmad",1.1,4,"python") print(thistuple) thistuple = ("apple","banana","cherry") print(thistuple[1]) thistuple = ("apple","banana","cherry") for x in thistuple: print(x) thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) thistuple = ("apple", "banana", "cherry","orange") print(thistuple [0:3])
5bac31f5d187ea3d676b865cce3a6134089a8017
sehammuqil/python-
/day24.py
790
3.890625
4
thisdict = { "brabd":"ford", "model":"mustang", "year":1964 } mydict= thisdict.copy() print(mydict) mydict=dict(thisdict) print(mydict) myfamily = { "child1": { "name":"emil", "year":2004 }, "child2": { "name":"tobias", "year":2007 }, "child3":{ "name":"linus", "year":2011 } } print(myfamily) child1: { "name": "emil", "year": 2004 } child2: { "name": "tobias", "year": 2007 } child3: { "name": "linus", "year": 2011 } #myfamily = { # "child1" : child1, # "child2": child2, # "child3":child3} print(myfamily) thisdict=dict(brand="ford",model="mustang",year=1964) print(thisdict)
a3c003e1a650a398285b3ef5f2383a264af7d4b9
acedb/toolbox
/toolbox/datetime.py
1,392
3.890625
4
'''Functions dealing with datetime types''' def round_six_hours(period): '''Round datetime to closest 6h unit. Period should be a df column which is already in datetime format. ''' if period.hour < 6: period = period.replace(hour = 0) elif period.hour < 12 : period = period.replace(hour = 6) elif period.hour < 18 : period = period.replace(hour = 12) else: period = period.replace(hour = 18) return period def to_date_format(dataframe): ''' Keep only complete years and create datetime column. Create new column 'period' out of columns 'date' and 'time'. Drop columns 'date' and 'time'. Filter dataframe to show only complaints dated >= 2007. N.B. NEEDS TO BE ADAPTED TO NEW USE! ''' df = dataframe.copy() # New period column out of concatenated 'date' and 'time' df['period'] = df['date'] + ' ' + df['time'] # Converts 'period' to datetime format df['period'] = df['period'].apply(lambda x: \ datetime.strptime(x, '%m/%d/%Y %H:%M:%S')) # Trims 'period' to hour df['period'] = df['period'].apply(lambda x: \ x.replace(minute = 0, second = 0)) # Filters dataframe to exclude crimes older than 2007 df = df[df['period'] > datetime(2006, 12, 31, 23, 59, 0)] # Drops columns 'date' and 'time' df.drop(columns = ['date', 'time'], inplace = True) return df
2ac79ffb3fee134375cae0469c39feece2fb1ca1
CristianCerutti/Sistemi-e-reti
/CreaPoligono.py
479
3.671875
4
#per aggiungere le librerie si schive import {nome libreria} import turtle #importa la libreria turtle e tutto ciò che contiene #from turtle import * #importa tutte le classi e si possono usare direttamente col loro nome nlati = int(input("inserire il numero dei lati: \n")) alice = turtle.Turtle() alice.begin_fill() cont = nlati while(cont > 0): alice.forward(40) alice.left(360/nlati) cont = cont-1 alice.end_fill() alice.done()
7b4f0817e681d4c375c9c6a55db67aa6b3480f29
CristianCerutti/Sistemi-e-reti
/es_pile_2.py
913
4.0625
4
def push_(pila, elemento): pila.append(elemento) def pop_(pila): return pila.pop() def main(): stringa = input("inserire una stringa di parentesi: ") pila = [] cont = 0 pos = 0 lunghezza = len(stringa) for _ in range(lunghezza): if(stringa[pos] == '(' ): push_(pila, '(') cont+=1 elif(stringa[pos] == '['): push_(pila, '[') cont+=1 elif(stringa[pos] == '{'): push_(pila, '{') cont+=1 elif(stringa[pos] == ')'): push_(pila, ')') cont+=1 elif(stringa[pos] == ']'): push_(pila, ']') cont+=1 elif(stringa[pos] == '}'): push_(pila, '}') cont+=1 pos += 1 for _ in range(cont): pop_(pila) if __name__ == "__main__": main()
1645420882248e7ffa84200b538f9294884da028
jmohit13/Algorithms-Data-Structures-Misc-Problems-Python
/data_structures/queue.py
1,719
4.25
4
# Queue Implementation import unittest class Queue: """ Queue maintain a FIFO ordering property. FIFO : first-in first-out """ def __init__(self): self.items = [] def enqueue(self,item): """ Adds a new item to the rear of the queue. It needs the item and returns nothing. """ # temp_list = []; temp_list.append(item) # self.items = temp_list + self.items self.items.insert(0,item) def dequeue(self): """ Removes the front item from the queue. It needs no parameters and returns the item. The queue is modified. """ return self.items.pop() def isEmpty(self): """ Tests to see whether the queue is empty. It needs no parameters and returns a boolean value. """ return self.items == [] def size(self): """ Returns the number of items in the queue. It needs no parameters and returns an integer. """ return len(self.items) class QueueTest(unittest.TestCase): def setUp(self): self.q = Queue() def testEnqueue(self): self.q.enqueue('ball') self.assertEqual(self.q.items[0],'ball') def testDequeue(self): self.q.enqueue('baseball') removedItem = self.q.dequeue() self.assertEqual(removedItem,'baseball') def testIsEmpty(self): self.assertTrue(self.q.isEmpty()) def testSize(self): self.q.enqueue('ball') self.q.enqueue('football') self.assertEqual(self.q.size(),2) if __name__ == "__main__": unittest.main()
a1572159f224683bf0ae26bfb969ac84a8411023
jmohit13/Algorithms-Data-Structures-Misc-Problems-Python
/data_structures/deque.py
1,909
4.03125
4
# Deque import unittest class Deque: """ A deque, also known as a double-ended queue, is an ordered collection of items similar to the queue. It has two ends, a front and a rear, and the items remain positioned in the collection. New items can be added/removed at either the front or the rear. This hybrid linear structure provides all the capabilities of stacks and queues in a single data structure. It does not require the LIFO and FIFO orderings that are enforced by stacks and queues data structures. """ def __init__(self): self.items = [] def addFront(self,item): self.items.insert(len(self.items),item) def addRear(self,item): self.items.insert(0,item) def removeFront(self): return self.items.pop() def removeRear(self): return self.items.pop(0) def isEmpty(self): return self.items == [] def size(self): return len(self.items) class DequeTest(unittest.TestCase): def setUp(self): self.dq = Deque() def testAddFront(self): self.dq.addFront(4) self.assertEqual(self.dq.items[len(self.dq.items)-1],4) def testAddRear(self): self.dq.addRear('shell') self.assertEqual(self.dq.items[0],'shell') def testRemoveFront(self): self.dq.addRear('dog') self.dq.addFront('cat') itemRemoved = self.dq.removeFront() self.assertEqual(itemRemoved,'cat') def testRemoveRear(self): self.dq.addRear('dog') self.dq.addFront('cat') itemRemoved = self.dq.removeRear() self.assertEqual(itemRemoved,'dog') def testIsEmpty(self): self.assertTrue(self.dq.isEmpty()) def testSize(self): self.assertEqual(self.dq.size(),0) if __name__ == "__main__": unittest.main()
984b68c51dc82fa0be17c840c5a68a8599ac1ae7
xposionn/NN-Perceptron-and-Adaline
/Algorithms/BackPropogation.py
1,904
4.0625
4
import numpy as np class BackPropogation(object): """ This class represents an Perceptron algorithm. """ def __init__(self,hiddenSize): #parameters self.inputSize = 33 self.outputSize = 2 self.hiddenSize = hiddenSize #weights self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # weight matrix from input to hidden layer self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # weight matrix from hidden to output layer def feedForward(self, X): #forward propogation through the network self.z = np.dot(X, self.W1) #dot product of X (input) and first set of weights self.z2 = self.sigmoid(self.z) #activation function self.z3 = np.dot(self.z2, self.W2) #dot product of hidden layer (z2) and second set of weights output = self.sigmoid(self.z3) return output def sigmoid(self, s, deriv=False): if (deriv == True): return 0.5*(1 + self.sigmoid(s))*(1 - self.sigmoid(s)) return (2/(1 + np.exp(-s))) - 1 def backward(self, X, y, output): #backward propogate through the network self.output_error = y - output # error in output self.output_delta = self.output_error * self.sigmoid(output, deriv=True) self.z2_error = self.output_delta.dot(self.W2.T) #z2 error: how much our hidden layer weights contribute to output error self.z2_delta = self.z2_error * self.sigmoid(self.z2, deriv=True) #applying derivative of sigmoid to z2 error self.W1 += X.T.dot(self.z2_delta) # adjusting first set (input -> hidden) weights self.W2 += self.z2.T.dot(self.output_delta) # adjusting second set (hidden -> output) weights def train(self, X, y): output = self.feedForward(X) self.backward(X, y, output)
55ceaf6dd6c2ef6583cdb6f3145cf9567af1c179
DivyanshiSingh/Python-programs
/phonebook.py
810
3.625
4
from tkinter import * root=Tk() root.geometry("300x300") root.title("PHONEBOOK") root.configure(bg="red") a=Entry(width="20",bg="white",fg="blue",font=("bold",30)) l1=Label(width="20",text="Enter name",font=("bold",30)) b1=Button(text="Find",width="20",bg="black",fg="blue",font=("bold",30)) l2=Label(width="20",text="Enter phone no",font=("bold",30)) b=Entry(width="20",bg="white",fg="blue",font=("bold",30)) b2=Button(text="Save",width="20",bg="black",fg="blue",font=("bold",30)) b3=Button(text="Delete",width="20",bg="black",fg="blue",font=("bold",30)) b4=Button(text="Update",width="20",bg="black",fg="blue",font=("bold",30)) l1.place(x=5,y=30) a.place(x=5,y=100) b1.place(x=400,y=100) l2.place(x=5,y=180) b.place(x=5,y=240) b2.place(x=5,y=340) b3.place(x=400,y=340) b4.place(x=100,y=420) root.mainloop()
a15af266be0ac2e87d756305f5627794ef2512f4
DivyanshiSingh/Python-programs
/runnerup.py
270
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 31 21:33:49 2019 @author: divyanshisingh """ l=[] ch=1 while ch!=0: m=int(input("enter the score")) l.append(m) ch=int(input("enter your choice<0/1>")) n=max(l) l.remove(n) print(max(l))
5fd9a4cc229e2eca7dd11ada601c3ba055fc7807
Flintstone-xu/crawler
/spider_practise_06_requests.py
1,113
3.640625
4
##任务:使用request来学习post和get的区别,并且查看cookie和session import requests import webbrowser #get请求 param={'wd':'科比'}#数据结构 request=requests.get('http://www.baidu.com/s',params=param)#传数据 print(request.url)#打印 #webbrowser.open(request.url)#浏览器打开url #post请求 data={'firstname':'flintstone','lastname':'xu'} request2=requests.post('http://pythonscraping.com/files/processing.php',data=data) print(request2.text) #webbrowser.open(request2.url)#浏览器打开url #cookies #数据结构 # payload={'username':'Morvan','password':'password'} # r=requests.post('http://pythonscraping.com/pages/cookies/welcome.php',data=payload) # print(r.cookies.get_dict()) # r=requests.get('http://pythonscraping.com/pages/cookies/profile.php',cookies=r.cookies) # print(r.text) #session session=requests.Session() payload={'username':'Morvan','password':'password'} r=session.post('http://pythonscraping.com/pages/cookies/welcome.php',data=payload) print(r.cookies.get_dict()) r=session.get('http://pythonscraping.com/pages/cookies/profile.php') print(r.text)
3c5f2ee72c7ebd047568d588d170c744c9cb1fd1
Breen-dev/jeu_rpg_repos
/Environnement.py
1,154
3.875
4
"""Classe qui établit les caractéristiques générales d'un environnement type. Ces caractéristiques seront reprises pour influencer les statistiques et les évênements qui apparaissent.""" class Environnement(): def __init__(self, weather, temperature, daytime, environnement): self.weather = weather self.temperature = temperature self.daytime = daytime self.environnement = environnement #setters def set_weather(self, weather): self.weather = weather def get_temperature(self, temperature): self.temperature = temperature def get_daytime(self, daytime): self.daytime = daytime def get_environnement(self, environnement): self.environnement = environnement #getters def get_weather(self): return self.weather def get_temperature(self): return self.temperature def get_daytime(self): return self.daytime def get_environnement(self): return self.environnement #Test du get env_1 = Environnement("pluie", 14, "jour", "forêt") print(env_1.get_weather())
c2584f5e013396b740dabb6144fb8dc27a4f2b67
anoopvenugopal/CA1Pg
/StudentRec.py
3,350
3.8125
4
''' Student record 1. Created a class for studentrec and declare init function 2. wrote the driver code for the program 3. Add display function for viewing the list 4. sorted the list using bubble sort 5. validated the input datas using regular expression 6. created a function for appending data to list 7. optimised the code 8. add retrive function''' #repository link:https://github.com/anoopvenugopal/CA1Pg.git import time import sys import re class StudentRec: def __init__(self,stId,stname,coursecode): self.stId=stId self.stname=stname self.coursecode=coursecode def showall(self): #to view all students print(self.stId,end='\t\t') print(self.stname,end='\t\t') print(self.coursecode) class StudentHandler: def add(self,student): #appending data to list st.append(student) def sort(self,s): #bubble sort for sorting for i in range(len(s)): for j in range(i+1,len(s)): if(int(s[i].stId)>int(s[j].stId)): s[i],s[j]=s[j],s[i] return st def retrieve(self): #remove the student having lowest IdNo fStd=st[0] st.pop(0) return fStd #Driver code st=list() stud=StudentHandler() while(True): choice=int(input(" 1: Press 1 to add students.\n 2: Press 2 to View all students.\n 3: Press 3 to pop the student with lowest ID.\n")) if choice==1: n=int(input('Enter no of students : ')) print('Students details entry....') for i in range(n): print('Student : ',i+1) stId=input('\tID:') check=re.match("[0-9]{8}$",stId) while(not check): print("\n Id must be 8 integers.") stId=input('\tID:') check=re.match("[0-9]{8}$",stId) stname=input('\tName:') coursecode=input('\tCourseCode:') while(not len(coursecode)==7): print("\n The course id must be 7 characters long.") coursecode=input('\tCourseCode:') std=(StudentRec(stId,stname,coursecode)) stud.add(std) print('Successfuly added students to Record') elif choice==2: # for showall data st=stud.sort(st) if (len(st)==0): print('****List empty****') else: print('Student Information') print('Student Id\t\tName\t\tCourse Code') for i in range(len(st)): st[i].showall() elif choice==3: st=stud.sort(st) if (len(st)==0): print('****List empty****') else: a=stud.retrieve() print(' Id :'+a.stId+'\tName :'+a.stname+'\tCoursecode :'+a.coursecode) print('\nNew updated list\n') print('Student Id\t\tName\t\tCourse Code') for i in range(len(st)): st[i].showall() userch=input("\n Enter Y to continue or Press anykey to exit.") if userch=='Y' or userch=='y': continue else: print('Bye') sys.exit()
f29d76b7e2da0d18937ebb9e495321d68665ed5b
akshatasawhney/Competitive-Coding-7
/kSmallestMatrix.py
752
3.578125
4
""" // Time Complexity : O(nlogk), // Space Complexity : O(k) // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no """ import heapq class Solution(object): def kthSmallest(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ heap=[] r=c=len(matrix) for i in range(r): for j in range(c): if len(heap)<k: heapq.heappush(heap,-matrix[i][j]) #maxheap elif -matrix[i][j] > heap[0]: #if size exceeds k heapq.heappop(heap) heapq.heappush(heap,-matrix[i][j]) return -heap[0]
9ddcebad74a904da1d3ae9e02714fc1a143ee7ac
A-Dmitriy/DZ_3
/3.5.py
1,257
4.0625
4
#5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится специальный символ, выполнение программы завершается. Если специальный символ введен после нескольких чисел, то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу. while 1: i = input("Введите цифру") i = i.split(" ") a = 0 while a < len(i): try: i[a] = int(i[a]) except ValueError: print("Value Error") break a = a + 1 z = 0 for c in i: z = z + c print(z)
38cb4ea6589b038526290390a3d45205f8021bb4
muondu/eduinox-e-degree
/Section1/Chapter3/3.2.py
526
3.828125
4
#try: # 3 / 0 #except Exception as e: # print("Error: %s" % e) #x = [1,2,3,4,5] #y = "Cactus" #try: # if 3 in x and "u" in y: # 3 / 0 # print("Yahoo") #except ZeroDivisionError as e: # print("Error: %s" % e) #except ArithmeticError as e: # print("Dance") try: 3 / 1 # print("Yahoo") except ZeroDivisionError as e: print("Error: %s" % e) except ArithmeticError as e: print("Error: %s" % e) except SyntaxError as e: print("Error %s" % e) finally: print("No error at all")
5f90242924a0f7710f1b63bd5d43513b0b1343cf
Nimsi123/MathProCore
/src/mathprocore/Question/helpers/imgh.py
6,858
3.65625
4
""" Contains a number of helper functions for dealing with Image objects. """ import re, sympy from .csympy.printing.latex import latex as clatex from .. import image from . import exprh latex_params = { "order": "none", "inv_trig_style": "power" } def to_sympy(img): """Mutates the image such that self.expressions is a list of sympy objects. img initially stores expression strings strings in self.expressions. A sympy string is any string that can be evaluated to produce a sympy object or objects. To store multiple expressions in a sympy string, delimit them with '{' and '}'. Note that this function will not throw an error if the image's expressions are already sympy objects. :param img: An image object whose expressions are expression strings. :type img: image.Image """ if img is image.Image.none: return img exprs = [] for e in img.expressions: if type(e) == str: e = exprh.to_sympy(e.replace("{", "").replace("}", "")) exprs.append(e) img.expressions = exprs img.update(exprh.to_sympy) def get_expr_strs_as_sympy(img): """Returns all expressions in an image storing expression strings as sympy objects. An expression is defined as either the entire expression string, or any substrings delimited by '{' and '}'. Note that this function does not mutate the img object. Ex. identifies a in y = {a} * x + b identifies the entire (y = a * x + b) :param img: An image object whose expressions are or include expression strings. :type img: image.Image :returns: A list of sympy objects representing the expression strings in the original image. :rtype: list """ if img is image.Image.none: return [] exprs = [] for expr in img.expressions: if "{" in expr and "}" in expr: exprs.extend(re.findall(r"{(.*?)}", expr)) else: exprs.append(expr) exprs = [ exprh.to_sympy(e) for e in exprs ] return exprs def to_latex(img, vars=[]): """Mutates the image such that self.expressions is a list of latex strings. img initially stores sympy objects in self.expressions. Some variables in the sympy object have not been replaced with values yet! For these variables, we delimit them by '@' symbols which can be easily replaced later on (by a call to subs_latex). :param img: An image object containing sympy expressions. :type img: image.Image :param vars: A list of variables in the sympy expression. :type vars: list, optional :returns: An image object whose expressions are latex strings. :rtype: image.Image """ if img is image.Image.none: return img substitutions = { var: sympy.symbols("@"+str(var)+"@") for var in vars } img.expressions = [ expr_as_latex(expr, substitutions) for expr in img.expressions ] def expr_as_latex(expr, substitutions): """Converts a sympy expression in an image object into a latex expression. Subsitutions are made into the sympy object based on the substitutions dict passed to the function. The latex expression that is returned is of the specific form required by the Desmos API. This function can handle piecewise functions, points, as well as regular sympy expressions. :param expr: A sympy object. :type expr: sympy :param substitutions: A dictionary that associates sympy symbols in the expression with values. Note that the keys must be sympy objects. :type substitutions: dict :returns: A latex string of the original expression including the given substitutions. :rtype: str """ # base case if type(expr) == str: return expr # equations if isinstance(expr, sympy.Rel): lhs, rhs = expr.args if isinstance(lhs, sympy.Piecewise): lhs = piecewise_as_latex(lhs, substitutions) if isinstance(rhs, sympy.Piecewise): rhs = piecewise_as_latex(rhs, substitutions) oper = "=" if expr.rel_op == "==" else expr.rel_op return expr_as_latex(lhs, substitutions) + " " + oper + " " + expr_as_latex(rhs, substitutions) # points if isinstance(expr, sympy.Point): return "\\left(" + ", ".join([expr_as_latex(arg, substitutions) for arg in expr.args]) + "\\right)" # generic sympy expressons sympy_expr = exprh.subs( expr, substitutions ) return exprh.replace(clatex(sympy_expr, **latex_params)) def piecewise_as_latex(expr, substitutions): """Converts a sympy.Piecewise object in an image into a latex expression. Subsitutions are made into the sympy object based on the substitutions dict passed to the function. The latex expression that is returned is of the specific form required by the Desmos API. :param expr: A sympy.Piecewise object. :type expr: sympy :param substitutions: A dictionary that associates sympy symbols in the expression with values. Note that the keys must be sympy objects. :type substitutions: dict :returns: A latex string of the original expression including the given substitutions. :rtype: str """ pieces = [] for ex, eq in expr.args: pieces.append(expr_as_latex(eq, substitutions) + ":" + expr_as_latex(ex, substitutions)) return "{" + ", ".join(pieces) + "}" def subs_latex(img, substitutions): """Substitutes values from a dictionary into the latex strings stored in an image. Assumes the variables in the image's expressions have been delimited with '@' symbols. Should be called on an image object after `as_latex()` has been called. :param img: An image storing latex expressions. :type img: image.Image :param substitutions: A dictionary that associates sympy symbols or strings in the expression with values. :type substitutions: dict :returns: A new image object with the given subsitutions applied to its expressions. :rtype: image.Image """ if img is image.Image.none: return img img = img.copy() image_subs = { "@"+str(key)+"@": value for key, value in substitutions.items() } img.expressions = [ exprh.replace(subs_latex_expr(expr, image_subs)) for expr in img.expressions ] img.update(exprh.subs, substitutions) return img def subs_latex_expr(expr, substitutions): """ Substitutes values from a dictionary into a latex string. :param expr: A latex string. :type expr: string :param substitutions: A dictionary that associates sympy symbols or strings in the expression with values. :type substitutions: dict :returns: A latex string of the original expression including the given substitutions. :rtype: str """ for key in substitutions: expr = expr.replace(key, "(" + clatex(substitutions[key]) + ")") return expr
932007159f1be668e0e285873555aa3ea95ef811
seankaczanowski/Code-Breaker
/main.py
3,483
3.625
4
''' Code Breaker 1.0 Developed by Sean Kaczanowski May 2020 No copyright Simple Code Guessing Game - 5 Colour Code - 8 Colours to Choose From - Gameboard showing current turn and past turns - Indicator for how many colours guessed are in the code but not necessarily in the correct order ''' import random # For word selection i = 0 while i == 0: # Main Game Loop # Title Screen / Menu Screen print('') print('+-----------------+') print('| C - - - |') print('| C - D - |') print('| C O D - |') print('| C O D E BREAKER |') print('+-----------------+') print('') # Simple graphic to show colour codes print('Colours') print('-------') print('(R)ed, (O)range, (Y)ellow, (G)reen,') print('(B)lue, Blac(K), (P)ink, (W)hite') print('') print('Main Menu') print('---------') print('1. Play') print('2. Quit') print('') j = 0 # Main Menu Selection Loop while j == 0: play = input('Press # and Enter: ') if play == '2' or play == '1': j = 1 else: # To deal with incorrect input print('') print('Error. Please Try Again') print('') if play == '2': # Exit Option quit() colours = ['R', 'O', 'Y', 'G', 'B', 'K', 'P', 'W'] # Colour options for code code = random.sample(colours, 5) # Code list sampled from colour options without replacement turns = 0 # Number of turns gameboard = [['CODEBOARD'],['=========']] # List of results to append to show game progress guess = [] # Empty list for guess win = 0 while win == 0: # Game loop until guess = code turns += 1 # Turns counter k = 1 while k == 1: # Loop to control incorrect input for guess guess = (input('Code Guess: ')) # Guess guess = guess.upper() # Convert to uppercase guess = list(guess) # Convert to list if len(guess) != 5: # Check for correct length - 5 print(' ') print('Error: Type in 5 Colours') print('Try Again.') print(' ') elif len(guess) > len(set(guess)): # Check for duplicates print(' ') print('Error: Same Colour Used More Than Once.') print('Try Again.') print(' ') elif len(set(guess) & set(colours)) < 5: # Check if the correct colours are used print(' ') print('Error: Incorrect Colour Used.') print('Try Again') print(' ') else: k = 0 result = [] # Result of turn to be added to gameboard for x, y in zip(code, guess): # Determine whether the guess is correct at each place in the code if x == y: result.append(x) else: result.append('-') common_colours = set(guess) & set(code) # Determines how many of the colours in the guess are in the code but not necessarily in the correct place guess.append(str(len(common_colours))) # Add how many correct colours guessed but not necessarily in code gameboard.append(guess) # Add guess turn plus common colours to gameboard print(' ') for i in range(len(gameboard)): # Gameboard printing of previous turns plus current turn print(' '.join(gameboard[i])) print(' '.join(result)) # Gameboard result showing the correct/incorrect colour guesses and the number of colours that were guessed that are in the code if guess == code: # Win scenario win = 1 print(' ') print('Correct! You Win!') print('Turns: ' + str(turns)) print(' ') else: print(' ')
b6aa06068380435c8254813087e9b0b0e6572461
Subhash3/CodeChef
/others/compare_two_num.py
313
4.09375
4
#!/usr/bin/env python3 result = list() for i in range(int(input())) : numbers = input().split() if int(numbers[0]) > int(numbers[1]) : result.append(">") elif int(numbers[0]) < int(numbers[1]) : result.append("<") else : result.append("=") for x in result : print(x)
42166bf4aaf652f80d82cc6d723156fa99254771
Subhash3/CodeChef
/others/n_primes.py
379
3.75
4
#!/usr/bin/env python3 import math primes = list() #pcount = 0 fcount = 0 num = 2 #N = 1000000 number = 10**6 #while pcount < N : while num <= number : for i in range(2, int(math.sqrt(num))) : if num % i == 0 : fcount += 1 break if fcount == 0 : primes.append(num) #pcount += 1 fcount = 0 num += 1 print(primes)
e141dbd66e1994dd7aa52017ca5ff587e5f7c8cb
Subhash3/CodeChef
/July_Lunch_Time/input.py
122
3.84375
4
#!/usr/bin/python3 import random N = int(input()) print(1) print(N) for i in range(N) : print(i+1, end=" ") print()
b847a76473e10b929f9df8abedfef63107b06038
Subhash3/CodeChef
/others/chef_and_wildcard_matching.py
504
3.859375
4
#!/usr/bin/python3 def compare_strings(first, second) : for i in range(len(first)) : matched = "No" if first[i] == '?' or second[i] == '?' or first[i] == second[i] : matched = "Yes" else : matched = "No" break return matched try : test_cases = int(input()) except : quit() for case in range(test_cases) : first_str = input() second_str = input() matched = compare_strings(first_str, second_str) print(matched)
ccabf2d44f90b7f08d731ca42549be109d1af51e
Subhash3/CodeChef
/others/number_tower.py
141
4.0625
4
#!/usr/bin/env python3 numbers = list() for i in range(int(input())) : numbers.append(int(input())) for num in numbers : print(num)
f8da99a0c14d1e046b293dcb8b590bfd39d44b7f
Subhash3/CodeChef
/OCT_LONG/chef_and_star_value_analysis.py
1,246
3.71875
4
#!/usr/bin/python3 try : T = int(input()) except : quit() for testCase in range(T) : N = int(input()) Arr = list() num_and_divisible = dict() even_numbers = list() length = 0 max_star = None max_value = None no_of_even = 0 for n in input().split() : star = 0 num = int(n) if num%2 == 0 : even_numbers.append(num) no_of_even += 1 if max_value == None or max_value < num : max_value = num Arr.append(num) length += 1 if num == 1 : star = length-1 elif num == 2 : star = no_of_even -1 elif num == max_value : pass # If it is the max element, then don't do anthing. else : if num%2 == 0 : #even : star = -1 array = even_numbers for k in even_numbers : if k%num == 0 : star += 1 else : star = 0 for i in range(length-2, -1, -1) : if Arr[i]%num == 0: star += 1 if max_star == None or max_star < star : max_star = star print(max_star)
b4bcf5b555dc3524054e1874efe9cada66cbad0d
Subhash3/CodeChef
/ATMOS/div1.py
489
3.75
4
#!/usr/bin/python3 from math import sqrt try : T = int(input()) except : quit() for testCase in range(T) : N = int(input()) xor = 0 for divisor in range(2, int(sqrt(N))+1) : if N % divisor == 0 : # print(divisor, end=', ') xor ^= divisor divisor_2 = int(N/divisor) if divisor_2 != divisor : # print(divisor_2, end=', ') xor ^= divisor_2 xor ^= N xor ^= 1 print(xor)
b1c3aa936391066534b7dabc58e97de5177ffe34
Subhash3/CodeChef
/July_Long_Challenge/parity_again.py.bkup
1,265
3.875
4
#!/usr/bin/python3 def count_bits(num, bit) : bit = str(bit) binary = bin(num)[2:] count = 0 for b in binary : if b == bit : count += 1 # print("No of " + str(bit) + "s in " + str(num) + " are: " + str(count)) return count try : T = int(input()) except : quit() for test_case in range(T) : even = 0 odd = 0 S = set() # print("Initially:", even, odd) Q = int(input()) for query in range(Q) : x = int(input()) elements_to_add = set() for y in S : if x != y : num = x^y if num != x and num not in elements_to_add and num not in S : # print(num, " is not in set ", elements_to_add) elements_to_add.add(num) if count_bits(num, 1) % 2 == 0 : even += 1 else : odd += 1 if x not in elements_to_add and x not in S: elements_to_add.add(x) if count_bits(x, 1) % 2 == 0 : even += 1 else : odd += 1 # S = S.union(set(elements_to_add)) S = S.union(elements_to_add) # print(S) print(even, odd)
f112756ee6510bf991a189a115fe25e5bd6c5b7a
Subhash3/CodeChef
/OCT_LONG/missing_number.py
3,170
3.515625
4
#!/usr/bin/python3 MAX_X = 1000000000000 def decimal_to_base(num, base) : if num == 0 : return '0' base_string = "" current_num = num while current_num : mod = current_num % base current_num = current_num // base if mod < 10 : base_string = str(mod) + base_string else : base_string = chr(mod+55) + base_string return base_string try : T = int(input()) except : quit() for testCase in range(T) : N = int(input()) known_decimal = None string_and_base_values = dict() strings = list() given_input = list() known_value_conflict = False common = set() for i in range(N) : values = input().split() given_input.append(values) B = int(values[0]) Y = values[1] strings.append(Y) if not known_value_conflict : if B != -1 : if known_decimal != None : new_known_decimal = int(Y, B) if known_decimal != new_known_decimal : known_value_conflict = True else : known_decimal = int(Y, B) # Now we have a known decimal value if known_decimal != None : if known_value_conflict : print(-1) else : known_value_in_all_bases = set() for base in range(2, 37) : base_string = decimal_to_base(known_decimal, base) known_value_in_all_bases.add(base_string) # print("Known value", known_decimal, "in all bases", known_value_in_all_bases) flag = True for s in strings : if s not in known_value_in_all_bases : flag = False break if not flag : print(-1) else : if known_decimal > MAX_X : print(-1) else : print(known_decimal) else : first = True for values in given_input : B = int(values[0]) Y = values[1] base_values = set() for base in range(2, 37) : # base_value = to_decimal(Y, base) # if base_value != None : # base_values.add(base_value) try : base_value = int(Y, base) base_values.add(base_value) except : pass string_and_base_values[Y] = base_values if first : common = base_values first = False else : common = common.intersection(base_values) # print(string_and_base_values) # print("Common:", common) # print() if common == set() : print(-1) else : smallest = None for num in common : if smallest == None or num < smallest : smallest = num if smallest > MAX_X : print(-1) else : print(smallest)
b2bfab527a62ad5cdf61e2eedba96b0e85df7056
Subhash3/CodeChef
/others/chef_and_strings.py
364
3.625
4
#!/usr/bin/env python3 for i in range(int(input())) : s1 = input() s2 = input() minimal = 0 maximal = 0 for l in range(len(s1)) : if s1[l] == '?' or s2[l] == '?': maximal += 1 continue if s1[l] != s2[l] : minimal += 1 maximal += 1 continue print(minimal, maximal)
a077a3a75987133d587df7c6c5a61066838b9c82
Subhash3/CodeChef
/others/nice.py
519
3.828125
4
#!/usr/bin/env python3 def mod(n) : if n > 0 : return n else : return -n for i in range(int(input())) : ints = input().split() a = int(ints[0]) b = int(ints[1]) n = int(ints[2]) if n % 2 == 0 : if mod(a) > mod(b) : print("1") elif mod(a) < mod(b) : print("2") else : print("0") else : if a > b : print("1") elif a < b : print("2") else : print("0")
21a00e4bfc27407aae5723f84c9b2e9de7591857
willreadscott/sockets
/receiver.py
3,841
3.78125
4
#!/usr/bin/env python3 """ The receivers listens on a channel for packets and forms them into a file, saving it in the specified location. Usage: ./receiver.py p_in p_out c_in filename p_in - the port that the receiver should listen on p_out - the port that the receiver should send from c_in - the port the channel is listening on filename - the file to which to write the received data Authors: Ben Frengley William Read Scott Date: 23 July 2015 """ import sys from socket import socket from packet import Packet from utils import get_port_number, LOCAL_ADDR, DEFAULT_MAGIC_NO, UDPEndpoint class Receiver(UDPEndpoint): """ A Receiver receives incoming packets to construct a sent file, sends acknowledgement packets upon successful transfer of packet. """ def __init__(self, r_in, r_out, c_in, filename): self.in_socket, self.out_socket = self.create_socket_pair(r_in, r_out, c_in) # remove timeout from the listening socket self.in_socket.settimeout(None) # open file we will write to try: self.file = open(filename, "xb") except FileExistsError: print("Invalid file - file already exists.") sys.exit(-1) # Expected sequence number, is either a 0 or 1. self.expected = 0 def create_packet(self): """ Create a new acknowledgement packet with the current expected number. """ return Packet(packet_type=Packet.TYPE_ACK, seqno=self.expected) def send_ack_packet(self): """ Sends an acknowledgement packet through the out socket. """ packet = self.create_packet() self.out_socket.send(packet.serialize()) def close_sockets(self): """ Closes all sockets. """ self.in_socket.close() self.out_socket.close() def handle_incoming_packets(self): """ Main loop for receiver, handles incoming packets and sends acknowledgement packet when received """ received_data_buffer = b'' while True: # Read in socket buffer received_data_buffer = self.in_socket.recv(1000) # Deserialize packet packet = Packet.deserialize(received_data_buffer) # validate the received packet if packet is None: continue if packet.magicno != DEFAULT_MAGIC_NO: continue self.send_ack_packet() if packet.seqno == self.expected: self.expected = 1 - self.expected # write any data from the packet to the file, or exit # if the data packet was empty if packet.dataLen > 0: print(packet.dataLen, "bytes written to file") self.file.write(packet.data) elif packet.dataLen == 0: self.close_sockets() self.file.close() sys.exit(0) def main(): # Make sure we received expected number of args if len(sys.argv) != 5: print("Invalid arguments -- expected arguments are p_in, p_out,", "c_in, and filename") sys.exit(-1) # Make sure all port numbers are valid p_in = get_port_number(sys.argv[1]) p_out = get_port_number(sys.argv[2]) c_in = get_port_number(sys.argv[3]) filename = sys.argv[4] # Initialize the receiver receiver = Receiver(p_in, p_out, c_in, filename) receiver.handle_incoming_packets() if __name__ == '__main__': main()
9b6eada29f71734486995cdd1d328d6c0465892c
timlyo/Year2_programming
/W2_8Queens.py
4,538
4
4
import random class Week2: def __init__(self): self.size = 0 def makeBoard(self, size): self.size = size board = [] for i in range(size): board.append([]) for j in range(size): board[-1].append(False) return board def displayBoard(self, b): divider = ("+---" * len(b)) + "+" for row in b: print(divider) line = "|" for piece in row: if piece is True: line += " X |" else: line += " |" print(line) def validatedSetAppend(self, set, newPos): if not 0 < newPos[0] < self.size: return if not 0 < newPos[1] < self.size: return self.setAppend(set, newPos) def setAppend(self, s, i): """ Add i to s unless i is already in s """ if not i in s: s.append(i) def inBoard(self, p, size): """ if point is valid for a board of given size, return True. Else return False """ if 0 <= p[0] < size and 0 <= p[1] < size: return True else: return False def pointShift(self, p, r, c): """ Return position of cell r,c away from given point p """ return (p[0] + r, p[1] + c) def appendIfInBounds(self, s, p, size): """ If point p is within the bounds of a board of given size, append to s unless it's already there """ if self.inBoard(p, size): self.setAppend(s, p) def queenSees(self, pos, size): """ Return a list of all squares "In view" of a queen in position pos on a board of size""" inView = [] # Row and column for i in range(size): # Column self.setAppend(inView, (i, pos[1])) # Row self.setAppend(inView, (pos[0], i)) # Diagonals for r in [-1, 1]: for c in [-1, 1]: self.appendIfInBounds(inView, self.pointShift(pos, r * i, c * i), size) # Take out position of queen so she doesn't see herself... if pos in inView: inView.remove(pos) else: raise Exception("This should never happen") return inView def rookSees(self, pos, size): """ Return a list of all squares "In view" of a rook in position pos on a board of size""" inView = [] # Row and column for i in range(size): # Column self.setAppend(inView, (i, pos[1])) # Row self.setAppend(inView, (pos[0], i)) #remove self if pos in inView: inView.remove(pos) else: raise Exception("This should never happen") return inView def knightSees(self, pos, size): """ Return a list of all squares "In view" of a rook in position pos on a board of size""" inView = [] self.setAppend(inView, pos) self.validatedSetAppend(inView, (pos[0] + 1, pos[1] + 2)) self.validatedSetAppend(inView, (pos[0] + 2, pos[1] + 1)) self.validatedSetAppend(inView, (pos[0] - 1, pos[1] + 2)) self.validatedSetAppend(inView, (pos[0] - 2, pos[1] + 1)) self.validatedSetAppend(inView, (pos[0] - 1, pos[1] - 1)) self.validatedSetAppend(inView, (pos[0] - 2, pos[1] - 2)) self.validatedSetAppend(inView, (pos[0] + 1, pos[1] - 2)) self.validatedSetAppend(inView, (pos[0] + 2, pos[1] - 1)) #remove self if pos in inView: inView.remove(pos) else: raise Exception("This should never happen") return inView def hasQueen(self, board, points): """ Returns True if any of the given points on the given board contain a queen """ for p in points: if board[p[0]][p[1]]: return True return False def cloneBoard(self, b, size): c = self.makeBoard(size) # clone for i in range(size): for j in range(size): c[i][j] = b[i][j] return c def fillBoardRecursion(self, board, row, size): """ Given a board completed to given row, try all possible positions for next row and continue """ if row == size: # Base case return board else: for col in range(size): if not self.hasQueen(board, self.knightSees((row, col), size)): b = self.cloneBoard(board, size) b[row][col] = True result = self.fillBoardRecursion(b, row + 1, size) if result != False: return result return False # Failed at this point, so return False def fillBoard(self, size): b = self.makeBoard(size) result = self.fillBoardRecursion(b, 0, size) return result def fillBoardRandomStart(self, size): b = self.makeBoard(size) p = random.randint(0, 7) b[0][p] = True result = fillBoardRecursion(b, 1, size) return result def fillBoardNaive(self, size): b = self.makeBoard(size) for r in range(size): for c in range(size): if not self.hasQueen(b, self.queenSees((r, c), size)): b[r][c] = True break else: break return b if __name__ == '__main__': week2 = Week2() board = week2.fillBoard(8) week2.displayBoard(board)
0b6dddb04db9fbc9b74d21bfb83992f36eae8d2d
nischal-sudo/Flask-repo
/Desktop/code/resources/user.py
920
3.578125
4
import sqlite3 from flask_restful import Resource,reqparse#Parser is a compiler that is used to break the data into smaller elements from models.user import UserModel class UserRegister(Resource):#new register(Sign upp) parser = reqparse.RequestParser() parser.add_argument("username", type = str, required = True, help = "This could not be empty") #request object in Flask. parser.add_argument("password", type = str, required = True, help = "This could not be empty") def post(self): data = UserRegister.parser.parse_args()#classname.paser.parse_args() if UserModel.find_by_username(data["username"]):#above connection return {"messege":"A user with that username already exists."},400 user = UserModel(data["username"],data["password"])#or (**data) user.save_to_db() return {"message":"User created successfully"},201
348906ac85caebe2bbe49afa0034b389adee8b3f
MiguelYanes/AI_Labs
/practica3IA/Practica3/alphabeta (2018_05_06 19_48_42 UTC).py
1,278
3.546875
4
# AlphaBeta Partial Search infinity = 1.0e400 def terminal_test(state, depth): return depth <= 0 or state.is_terminal def max_value(state, player, max_depth, alpha, beta, eval_function): """ Completar con el codigo correspondiente a la funcion <max_value> de la version del algoritmo minimax con poda alfa-beta """ return 0 def min_value(state, player, max_depth, alpha, beta, eval_function): """ Completar con el codigo correspondiente a la funcion <min_value> de la version del algoritmo minimax con poda alfa-beta """ return 0 def alphabeta_search(game, max_depth, eval_function): """ Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function. """ player = game.current_player # Searches for the action leading to the sucessor state with the highest min score successors = game.successors() best_score, best_action = -infinity, successors[0][0] for (action, state) in successors: score = min_value(state, player, max_depth, -infinity, infinity, eval_function) if score > best_score: best_score, best_action = score, action return best_action
da679d0f52076510c87670e8b3edcd79cdb86145
MiguelYanes/AI_Labs
/practica3IA/Practica3/minimax (2018_05_06 19_48_42 UTC).py
1,130
4
4
# Minimax Search infinity = 1.0e400 def terminal_test(state, depth): return depth <= 0 or state.is_terminal def max_value(state, player, max_depth): """ Completar con el codigo correspondiente a la funcion <max_value> del algoritmo minimax """ return 0 def min_value(state, player, max_depth): """ Completar con el codigo correspondiente a la funcion <min_value> del algoritmo minimax """ return 0 def minimax_search(game, max_depth=infinity): """ Given a state in a game, calculate the best move by searching forward all the way to the terminal states, or until max_depth levels are explored """ player = game.current_player # Searches for the action leading to the sucessor state with the highest min score successors = game.successors() best_score, best_action = -infinity, successors[0][0] for (action, state) in successors: score = min_value(state, player, max_depth) if score > best_score: best_score, best_action = score, action return best_action
583923231f4a5da0c8cf6e6928ac47aadc553623
hmdhszd/create-and-edit-xlsx-file-with-python-practicing-example
/my program.py
684
3.5625
4
import openpyxl workbook = openpyxl.load_workbook('example-XLSX-file.xlsx') print(workbook.get_sheet_names()) sheet = workbook.get_sheet_by_name('Sheet1') ########################### cell = sheet['B1'] print(cell.value) print(sheet['B1'].value) ########################### cell = sheet.cell(row = 2, column = 2) print(cell.value) print(sheet.cell(row = 2, column = 2).value) ########################### ########################### wb = openpyxl.Workbook() sheet = wb.get_sheet_by_name('Sheet') sheet['A1'].value = "hamid" wb.save('FileName.xlsx') ########################### sheet2 = wb.create_sheet() sheet2.title = "my new sheet" wb.save('FileName2.xlsx')
0255bf5031a423598d561a6ee9cb6a791af11b71
gino2010/pythontech
/algorithm/custom_sort.py
907
4
4
# # author gino # created on 2018/10/8 # 假设一组数字, 463175892 对其进行解密排序后 615947283 # 解密规则规则,移走第一个数字到末尾,取第二个数字,往复,直到全部取出。取出的数字序列则为结果 # 加密规则,与其逻辑相反 def decrypt(text: str) -> str: text_list = list(text) temp_str = '' while len(text_list) != 0: text_list.append(text_list.pop(0)) temp_str += text_list.pop(0) return temp_str def encrypt(text: str) -> str: text_list = list(text) temp_list = [] while len(text_list) != 0: temp_list.insert(0, text_list.pop()) temp_list.insert(0, temp_list.pop()) return ''.join(temp_list) if __name__ == '__main__': print("please input your text:") x = input() print("encrypt text: %s" % encrypt(x)) print("original text: %s" % decrypt(encrypt(x)))
22d0843e0bd2eb231713fb6f8fb5c714594b0ea8
haidragon/Python
/Python基础编程/Python-12/加强练习/开枪/开枪-6-拿枪.py
2,688
3.65625
4
class Person(object): def __init__(self,name): super(Person,self).__init__() self.name = name self.gun = None#保存枪的引用 self.hp = 100 def __str__(self): if self.gun: return "%s的血量为%d,他有枪"%(self.name,self.hp) else: return "%s的血量为%d,他没有枪"%(self.name,self.hp) def anzhuang_zidan(self,dan_jia_temp,zi_dan_temp): '''把子弹装到弹夹中''' #弹夹.保存子弹 dan_jia_temp.baocun_zidan(zi_dan_temp) def anzhuang_danjia(self,gun_temp,dan_jia_temp): '''把弹夹安装到枪中''' #枪.保存弹夹(弹夹) gun_temp.baocun_danjia(dan_jia_temp) def na_qiang(self,gun_temp): '''拿起一把枪''' self.gun = gun_temp class Gun(object): '''枪类''' def __init__(self,name): super(Gun,self).__init__() self.name = name #记录枪的类型 self.danjia = None#用来记录弹夹对象的引用 def __str__(self): if self.danjia: return "枪的类型:%s,弹夹:%s"%(self.name,self.danjia) else: return "枪的类型:%s,无弹夹" %(self.name) def baocun_danjia(self,dan_jia_temp): self.danjia = dan_jia_temp class Danjia(object): '''弹夹类''' def __init__(self,max_num): super(Danjia,self).__init__() self.max_num = max_num#记录弹夹的最大容量 self.zidan_list = []#记录所有子弹的引用 def __str__(self): return "子弹列表%d/%d"%(len(self.zidan_list),self.max_num) def baocun_zidan(self,zi_dan_temp): self.zidan_list.append(zi_dan_temp) class Zidan(object): def __init__(self,sha_shang_li): super(Zidan,self).__init__() self.sha_shang_li = sha_shang_li def main(): '''用来控制整个程序的流程''' #1、创建老王对象 laowang = Person("老王") #2、创建枪对象 ak47 = Gun("AK47") m14 = Gun("M14") #3、创建一个弹夹对象 dan_jia = Danjia(20) #4、创建一些子弹 for i in range(15): zi_dan = Zidan(10) #5、把子弹安装到弹夹中 laowang.anzhuang_zidan(dan_jia,zi_dan) #6、把弹夹安装到枪中 #laowang.安装到枪中(枪,弹夹) laowang.anzhuang_danjia(ak47,dan_jia) #test1:测试弹夹的信息 print(dan_jia) #test2:测试枪的信息 print(ak47) print(m14) #7、拿枪 laowang.na_qiang(ak47) # test3:测试老王的信息 print(laowang) #8、创建一个敌人 #9、开枪 if __name__ == 'main': main() else: main()
25b8bf15aa3fecdf8741ea9a7f437c50860c93c5
haidragon/Python
/Python核心编程/Python-04-系统编程-1/02-多线程/04-多线程使用全局变量.py
495
3.71875
4
from threading import Thread import time g_num = 100 def work1(): global g_num for i in range(3): g_num += 1 print("---in work1,g_num is %d---"%g_num) def work2(): global g_num print("---in work2,g_num is %d---"%g_num) print("---进程创建之前,g_num is %d---"%g_num) t1 = Thread(target=work1) t1.start() time.sleep(1) t2 = Thread(target=work2) t2.start() '''---进程创建之前,g_num is 100--- ---in work1,g_num is 103--- ---in work2,g_num is 103---'''
5d349c3af7051b75b96807b41102f7e54b083573
haidragon/Python
/Python基础编程/Python-08/文件/文件读写.py
278
3.515625
4
#1、打开文件 f = open("D:/Personal/Desktop/test.txt","w") #2、写入数据 f.write("hello world") #3、关闭文件 f.close() f = open('D:/Personal/Desktop/test.txt', 'r') content = f.read(5) print(content) print("-"*30) content = f.read() print(content) f.close()
dcb72ba1322aa085b0851b78b2d3e29f17b2ff99
haidragon/Python
/Python基础编程/Python-04/items/ItemDemo.py
813
4.28125
4
info = {"name": "laowang", "age": 18} # 遍历key for temp in info.keys(): print(temp) # 遍历value for temp in info.values(): print(temp) # 遍历items #Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。 info_Item = info.items() print(info_Item) #打印字典内的数据 #方法一:直接打印元组 for temp in info.items(): print(temp) '''结果: ('name', 'laowang') ('age', 18)''' print("="*50) #方法二:下标 for temp in info.items(): print("key=%s,value=%s"%(temp[0],temp[1])) '''结果: key = name, value = laowang key = age, value = 18''' print("="*50) #方法三:拆包 for temp1,temp2 in info.items(): print("key=%s,value=%s"%(temp1,temp2)) '''结果: key = name, value = laowang key = age, value = 18'''
6f6f3332c920fda4a3fc56b5184362f5e8bf13f9
haidragon/Python
/Python基础编程/Python-03/WhileDemo2.py
192
3.78125
4
i = 2 while i <= 3: j = 0 while j <= 3: j += 1 if j == 2: break #continue print("======") print("i=%dj=%d" % (i, j)) i += 1
9b4e92729e98d64c54dc2e77720ad805deecde1b
haidragon/Python
/Python基础编程/Python-09/对象/创建对象.py
778
4.15625
4
#创建一个类 class cat: #属性 #方法 def __init__(self,a,b): self.name = a self.age = b def __str__(self): return "--str--" def eat(self): print("猫在吃饭") def drink(self): print("猫在喝水") #若需要创建多个对象都调用这个方法,则形参需要都为self def introduce(self): print("%s的年龄为%d"%(self.name,self.age)) #创建一个对象 tom = cat("汤姆",40) #调用类中的方法 tom.drink() tom.eat() #添加属性 #tom.name = "汤姆" #tom.age = 40 #调用自我介绍方法 tom.introduce() #定义第二个类 lanmao = cat("蓝猫",20) #lanmao.name = "蓝猫" #lanmao.age = 20 lanmao.introduce() #定义第三个类 jumao = cat("橘猫",10) print(jumao)
fb24306d8a22f9bf18d3099d20197e6ce266a8dd
haidragon/Python
/Python基础编程/Python-11/异常/异常处理.py
468
3.5
4
try: print("可能产生异常的代码") except (KeyError,ErrorName-2,ErrorName-3....,ErrorName-n): print("捕获异常后的处理") except Exception: print("如果使用了Exception,name意味着只要上面的except没有捕获到异常,这个except一定会捕获到") else: print("没有异常才执行的功能,但凡有一个异常,这条代码永远不会被执行") finally: print("无论什么情况下总是会执行的代码")
4291b6684d405acf8adf2b9d1d4e4521a1a6c9fc
haidragon/Python
/Python核心编程/Python-02/02-装饰器/09-使用装饰器对有返回值的函数进行装饰.py
726
4
4
#装饰有返回值的函数 def func(functionName): print("--func--1--") def func_in(*args,**kwargs): print("--func_in--1--") ret = functionName(*args,**kwargs) print("--func_in--2--") #装饰有返回值的函数,需要接收返回值之后再将返回值返回即可 return ret print("--func--2--") return func_in @func def test(a , b , c): print("--test1--a=%d--b=%d--c=%d--"%(a,b,c)) return (a+b+c) @func def test2(a , b , c , d): print("--test1--a=%d--b=%d--c=%d--d=%d"%(a,b,c,d)) print(test(1,2,4)) ''' --func--1-- --func--2-- --func--1-- --func--2-- --func_in--1-- --test1--a=1--b=2--c=4-- --func_in--2-- 7 '''
0e4f852db6db82a00c24fed1a05e33530139401a
gjwang/testcpp
/find_perfect_hash.py
1,149
3.625
4
data = [ 10, 100, 32, 45, 58, 126, 3, 29, 200, 400, 0 ] def shift_right(value, shift_value): """Shift right that allows for negative values, which shift left (Python shift operator doesn't allow negative shift values)""" if shift_value == None: return 0 if shift_value < 0: return value << (-shift_value) else: return value >> shift_value def find_hash(): def hashf(val, i, j = None, k = None): return (shift_right(val, i) ^ shift_right(val, j) ^ shift_right(val, k)) & 0xF for i in xrange(-7, 8): for j in xrange(i, 8): #for k in xrange(j, 8): #j = None k = None outputs = set() for val in data: hash_val = hashf(val, i, j, k) if hash_val >= 13: pass #break if hash_val in outputs: break else: outputs.add(hash_val) else: print i, j, k, outputs if __name__ == '__main__': find_hash()
10c46acb72ab0e3edca820607cb35937dfd43995
rishabhusc/Python-leetcode
/deletenodehreatyerthenk.py
892
3.921875
4
class Node: def __init__(self,value): self.value=value self.next=None class LinkedList: def __init__(self): self.root=None def append(self,value): if self.root is None: self.root=Node(value) return cur=self.root while cur.next: cur=cur.next cur.next=Node(value) def removeelemGeeyteerThan(self,k): if self.root is None: return prev=None cur=self.root while cur: if cur.value>k: prev.next=cur.next cur=None prev=cur cur=prev.next def print(self): cur=self.root while cur: print(cur.value) cur=cur.next ll=LinkedList() ll.append(1) ll.append(2) ll.append(3) ll.append(4) ll.append(5) ll.removeelemGeeyteerThan(3) ll.print()
d9587a607ac4ca80f766c5353e0bae6c94704d9e
rishabhusc/Python-leetcode
/productexecptInd.py
197
3.734375
4
num=[1,2,3,4,5] output=[1]*len(num) prod=1 for i in range(len(num)): output[i]*=prod prod*=num[i] prod=1 for i in range(len(num)-1,-1,-1): output[i]*=prod prod*=num[i] print(output)
7a9e0673900f0d1b170f9e2b46d364c213444fb7
rishabhusc/Python-leetcode
/longestNonRepetingSubString.py
631
3.5625
4
s="abcddabc" def funct(s): ml=0 def helper(s,start): d=set() for i in range(start,len(s)): if s[i] not in d: d.add(s[i]) else: return i-start return len(s)-start for i in range(len(s)): ml=max(ml,helper(s,i)) return ml print(funct(s)) def longestsubstringWithNoRepeatingChar(s): seen={} start=0 ml=0 for i in range(len(s)): if s[i] in seen: start=max(start,seen[s[i]]+1) seen[s[i]]=i ml=max(ml,i-start+1) return ml print(longestsubstringWithNoRepeatingChar(s))
44db4d9817bfb89f549344d1cea3604aa0bfd0e9
rishabhusc/Python-leetcode
/picturePlacement.py
114
3.53125
4
arr=[0,1,2,3,4] placement=[0,1,2,1,2] ls=[] for i in range(len(arr)): ls.insert(placement[i],arr[i]) print(ls)
2f38aecc516f760db7184abbc5cafec2f5c2bae4
kirbocannon/aws_scripts
/archive/scrap2.py
4,328
3.90625
4
''' list = ['caw', 'baw', 'taw',' naw'] print(list[1:]) ''' # my_dict = {"caw": 1, "baw": 2, "law": 3} # # new_dict = {k: v * 2 for k,v in my_dict.items()} # # print(new_dict) # # for k,v in my_dict.items(): # print(k, v) # # import itertools # # list_1 = ["this", "is", "a", "list"] # list_2 = ["cat", "dog", "mouse"] # # # zipped = itertools.zip_longest(list_1, list_2) # # # # # # print(dict(zipped)) # # # # list_3 = [1, 2, 3, 4, 5, 6, 7, 8] # # # # print(list(filter(lambda x:x % 2 == 0, list_3))) import functools # my_list = range(1, 101) # # # sum = 0 # for i in my_list: # sum += i # # print(sum) # # num = 100 * (100 + 1) / 2 # print(num) # # def sum_of_all_evils(n): # return n * (1 + n) / 2 # # result = sum_of_all_evils(5) # # print(result) # # def first_funct(x): # z = 10 # def second_funct(y): # return x * y * z # return second_funct # # mult_by_three = first_funct(500) # # print(mult_by_three(4)) # def stepper_two(start=1, step=1, end=10000): # while start < end: # yield (start + 100 / 3 * 3 ** 2 * 400 + 3 / 8 - 52 * 57 * 88 * -1) # start += step # # caw = stepper_two(start=1, step=1) # # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # print(next(caw)) # # for num in range(1,30): # step = next(caw) # print(step) # def stepper(maximum): # i = 0 # while i < maximum: # val = (yield i) # # If value provided, change counter # if val is not None: # i = val # else: # i += 1 # # # # this = stepper(10) # print(next(this)) # print(next(this)) # from datetime import datetime # # # # my_nums = (x*x for x in range(1,20000000)) # my_list = [] # my_list_two = [] # my_list_three = [] # # before = datetime.now() # # for x in my_nums: # if x % 2 == 0: # my_list_two.append(x) # # after = datetime.now() # print(after - before) # # # # before = datetime.now() # # for x in range(1,20000000): # x = x * x # my_list.append(x) # # for num in my_list: # if num % 2 == 0: # my_list_three.append(num) # # after = datetime.now() # print(after - before) # from itertools import count # # counter = count(1,10) # print(next(counter)) # print(next(counter)) # print(next(counter)) # # ls = ['one', 'two', 'three'] # # ls[ls.index('one')] = 'hello' # # print(ls) from functools import reduce from itertools import groupby animal_kingdom = [ {'animal': 'fox', 'name': 'Charles'}, {'animal': 'rabbit', 'name': 'Yang'}, {'animal': 'whale', 'name': 'Chad'}, {'animal': 'dog', 'name': 'Mike'}, {'animal': 'wombat', 'name': 'Dave'}, {'animal': 'wombat', 'name': 'Mark'}, {'animal': 'wombat', 'name': 'Brad'}, {'animal': 'wombat', 'name': 'Tom'},] # mapped_dict = dict(map(lambda x: x.items(), animal_kingdom)) # mapped_list = list(map(lambda x: x.items(), animal_kingdom)) # reduced = reduce(lambda y, z: y + z, mapped_dict) # print(reduced) # sorted = mapped_list # print(sorted) # grouped_dict = list(groupby(animal_kingdom, key=lambda x: x['animal'])) # print(grouped_dict) # grouped = groupby(animal_kingdom, key=lambda x: x['animal']) # print({k:list(v) for k, v in grouped}) # for item in animal_kingdom: # for k, v in item.items(): # if k == 'name': # print(v) # # # print(reduce(lambda x, y: x + y, range(1,101))) dict_two = {'animal': 'fox', 'name': 'Charles'} admin = "default_name" # the following is an if statement checking all keys for 'name' then printing the value of the 'name' key if 'name' in dict_two.keys(): print(dict_two['name']) else: print(admin) # however as you can see here, you can do this with way less lines of code: found = dict_two.get('name', admin) print(found) my_list = ['caw', 'baw', 'taw'] mapped_list = map(lambda x: x, my_list) print(next(mapped_list)) reduced = reduce(lambda x, y: x + y[1], mapped_list) print(reduced) nums = range(1,101) num_iterator = filter(lambda x: x % 2 ==0, nums) for i in range(1, 26): next(num_iterator) print(list(num_iterator)) try: print("hey") except TypeError: print("error") finally: print("finally!")
492558471e0c076cee00aae3dfa3e3a75c4df57c
cwallace3/They_Fight_Crime_NLP
/10_Most_Common.py
1,048
3.71875
4
from collections import Counter from string import punctuation import nltk from nltk.corpus import stopwords def content_text(text): #Remove common stopwords including "he's" and "she's" stopwords = set(nltk.corpus.stopwords.words('english')) stopwords.update(("He's", "She's")) with_stp = Counter() without_stp = Counter() with open(text) as f: for line in f: spl = line.split() # update count off all words in the line that are in stopwrods with_stp.update(w.lower().rstrip(punctuation) for w in spl if w.lower() in stopwords) # update count off all words in the line that are not in stopwords without_stp.update(w.lower().rstrip(punctuation) for w in spl if w not in stopwords) # return a list with top ten most common words from each return [x for x in with_stp.most_common(10)],[y for y in without_stp.most_common(10)] wth_stop, wthout_stop = content_text("all_submissions2.txt") print (wthout_stop)
46f342b4ee2ee525541c5aeb403e7236e6b2f674
thalals/Algorithm_Study
/Taewoo/problem_solving/2021.05/2021.05.13/6416.py
1,251
3.71875
4
import sys input = sys.stdin.readline def is_tree(): is_root = False for i in range(1, len(tree)): if is_root and node_check[i] and len(tree[i]) == 0: return False if not is_root and node_check[i] and len(tree[i]) == 0: is_root = True if node_check[i] and len(tree[i]) > 1: return False if not is_root: return False return True # main k = 1 while True: nodes = [] is_end = False while True: numbers = list(map(int, input().split())) if len(numbers) != 0 and numbers[-1] == 0 and numbers[-2] == 0: nodes.extend(numbers) break if len(numbers) != 0 and numbers[-1] == -1 and numbers[-2] == -1: sys.exit(0) if len(numbers) == 0: continue nodes.extend(numbers) tree = [[] for _ in range(max(nodes) + 1)] node_check = [False for _ in range(max(nodes) + 1)] for i in range(0, len(nodes) - 1, 2): tree[nodes[i + 1]].append(nodes[i]) node_check[nodes[i]] = True node_check[nodes[i + 1]] = True if len(tree) == 1 or is_tree(): print(f'Case {k} is a tree.') else: print(f'Case {k} is not a tree.') k += 1
fbcfb80a8e5f05033dfa51ed591001334dad16ee
thalals/Algorithm_Study
/Geonil/Algorithms/String/BOJ16171.py
382
3.5
4
# 나는 친구가 적다 (Small) (BOJ 16171) import sys In = sys.stdin.readline def main(): string = In().rstrip() keyword = In().rstrip() new_string: str = '' for c in string: if c.isdigit(): continue new_string += c if keyword in new_string: print(1) else: print(0) if __name__ == "__main__": main()
7a76e5f031d792ef1e1b6e9dccec3c62ecffdf93
thalals/Algorithm_Study
/Geonil/problem_solving/week4/BOJ2231.py
393
3.5
4
import sys In = sys.stdin.readline def creater(num): answer = 0 length = len(str(num)) start_num = max(0, num - 9*length) for i in range(start_num, num): n = i for radix in str(i): n += int(radix) if n == num: answer = i break return answer def main(): num = int(In()) print(creater(num)) main()
cc76ad142defb01db64e3f78e749366d42edae28
thalals/Algorithm_Study
/SaeHyeon/트리2/4256.py
1,027
3.71875
4
# 이진 트리 순회 # 전위 순회와 중위 순회를 통해서 후위 순회를 구하는 문제 import sys input=sys.stdin.readline def Postorder(preorder,inorder): if len(preorder) == 0: return elif len(preorder) == 1: print(preorder[0],end=' ') return elif len(preorder) == 2: print(preorder[1],preorder[0], end= ' ') return #전위순회에서 이진트리의 루트노드는 맨 첫번쨰 pre_root=preorder[0] # 중위순회에서 루트의 위치를 찾는다 root_index=inorder.index(pre_root) in_left=inorder[0:root_index] pre_left=preorder[1:1+len(in_left)] Postorder(pre_left,in_left) in_right=inorder[root_index+1:] pre_right=preorder[len(pre_left)+1:] Postorder(pre_right,in_right) print(preorder[0], end= ' ') T=int(input()) for i in range(T): n=int(input()) preorder=list(map(int,input().split())) inorder=list(map(int,input().split())) Postorder(preorder,inorder) print()
28577a9f4431e1f958498037a6de1ac3ba8f0050
thalals/Algorithm_Study
/Geonil/Algorithms/Tree/BOJ3005.py
1,319
3.703125
4
import sys In = sys.stdin.readline class Node: def __init__(self, key): self.key = key self.child = {} class Trie: def __init__(self): self.root = Node(None) def insert(self, word): cur = self.root for c in word: if c not in cur.child: cur.child[c] = Node(c) cur = cur.child[c] cur.child['*'] = True def search_first(self): cur = self.root word = '' while True: if '*' in cur.child: break keys = list(cur.child.keys()) keys.sort() word += keys[0] cur = cur.child[keys[0]] return word def main(): trie = Trie() r, c = map(int, In().split()) # left to right l2r = [] for i in range(r): l2r.append(In().rstrip()) # top to bottom t2b = [] for j in range(c): string = '' for i in range(r): c = l2r[i][j] string += c t2b.append(string) # concat puzzle puzzle = l2r + t2b for p in puzzle: words = list(p.split('#')) for w in words: if len(w) < 2: continue trie.insert(w) print(trie.search_first()) if __name__ == "__main__": main()
992bafa01ffe7954203eab9b62b764d59362e0fd
thalals/Algorithm_Study
/SaeHyeon/2021년 상반기/week7/1920.py
530
3.625
4
import sys input=sys.stdin.readline n1=int(input()) li1=sorted(map(int,input().split())) # 찾아야 될 리스트 n2=int(input()) li2=map(int,input().split()) # 찾을 값 def binarySearch(j,li1,left,right): if left > right: return 0 mid = (left+right)//2 if j == li1[mid]: return 1 elif j > li1[mid]: return binarySearch(j,li1,left,mid-1) else: return binarySearch(j,li1,mid+1,right) for i in li2: left=0 right=len(li1)-1 print(binarySearch(i,li1,left,right))
fba9eef5fe2c2aac66194ec0392db6f38d1e8df9
thalals/Algorithm_Study
/SaeHyeon/2021년 상반기/week3/1427.py
123
3.640625
4
n=input() li=[] for x in n: li.append(int(x)) li.sort() li.reverse() for i in range(len(li)): print(li[i],end='')
b0fe7d3992e2fc0f2f7b2731f8ccf3909d849dec
thalals/Algorithm_Study
/Geonil/problem_solving/week14/BOJ11279.py
543
3.515625
4
# 최대 힙 import sys import heapq In = sys.stdin.readline class Heap(): def __init__(self): self.heap = [] def push(self, num): heapq.heappush(self.heap, (-num, num)) def pop(self): if self.heap: return heapq.heappop(self.heap)[1] else: return 0 def main(): n = int(In()) h = Heap() for _ in range(n): num = int(In()) if num == 0: print(h.pop()) else: h.push(num) if __name__ == "__main__": main()
e2f44d2a2bd378a31dad1fbf2cc24ef1e5b70b3d
thalals/Algorithm_Study
/Seunghwan/week4/BOJ7568.py
923
3.59375
4
# 입력 # 첫 줄에는 전체 사람의 수 N이 주어진다. # 그리고 이어지는 N개의 줄에는 각 사람의 몸무게와 키를 나타내는 양의 정수 x와 y가 하나의 공백을 두고 각각 나타난다. # 출력 # 여러분은 입력에 나열된 사람의 덩치 등수를 구해서 그 순서대로 첫 줄에 출력해야 한다. # 단, 각 덩치 등수는 공백문자로 분리되어야 한다. n = int(input()) # n 입력 data_list = [] # 키와 몸무게 for i in range(n): # 입력한 n만큼 x,y = map(int, input().split()) # x,y 값을 각각 받는다 data_list.append((x,y)) # 만들어놓은 리스트에 넣기 # print(data_list) for i in data_list: num = 1 for j in data_list: #각각 키와 몸무게를 하나씩 비교해서 카운트해준다 if i[0] < j[0] and i[1] < j[1]: num += 1 print(num, end = " ") # 띄어쓰기
f1f6cf64bde4602c167dfe214ccf0143609ff74e
itzadi22/Basic-python
/regex_metacharacters.py
267
3.703125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 22:51:54 2021 \d Digit \D Non Digit @author: ASUS """ import re string="#cricket,I love you cricket 10 times" s1=re.findall("\d+", string) print(s1) s2=re.findall("\D+", string) print(s2)
89f16c51799d07983adbe5d78a5cbd92839c3716
itzadi22/Basic-python
/regex_split.py
194
3.53125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 30 22:02:08 2021 @author: ASUS """ import re string="#movies,I love watching horror,movies" print(re.split(',', string))
fd98c217fe18dc168423ab6311fa1d21d23ad2f0
itzadi22/Basic-python
/square_of_no.py
159
3.78125
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 17 10:18:19 2021 @author: ASUS square of numbers """ a=int(input("enter any number : ")) print(a*a)
f26aa3f52b6ec268af850fa9c4723829fc3d827f
itzadi22/Basic-python
/string_formatting.py
229
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 17 18:44:50 2021 @author: ASUS string formatting """ a="name" b="is" c="my" d=c + " " + a + " " + b print(d) e="adarsh" f="my name is {}".format(e) print(f)
1027ce4eccdafefe9f87c849efbd4aa229ff88b5
itzadi22/Basic-python
/any_power_to_no.py
187
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Mar 17 10:50:31 2021 @author: ASUS any power to number """ import math r=int(input("Enter any number")) a=math.pow(r,10) print(a)
e65b012f7d51a6c7859b0338de5712b107601872
Sagar2366/SPOJ-Solutions-in-Python
/PALIN.py
1,073
3.8125
4
#!/usr/bin/python # created by Christian Blades (christian.blades@gmail.com) - Sat Oct 02, 2010 # Solution to http://www.spoj.pl/problems/PALIN/ def getInput(): a = raw_input('number: ') return int(a) def isPalindrome(num): numString = str(num) start = 0 end = len(numString) - 1 while(start < end): if numString[start] != numString[end]: return False start += 1 end -= 1 return True def nextPalindrome(num): if len(str(num)) < 2: if num < 9: return num + 1 else: return 11 num += 1 while(not isPalindrome(num)): num += 1 return num # main loop if __name__ == '__main__': while True: try: num = getInput() except ValueError: print "Please only type integers" except EOFError: print "Goodbye" break except KeyboardInterrupt: print "Goodbye" break else: palResult = nextPalindrome(num) print "Next palindrome: %d" % palResult
266615fe9516995bbeffdd10fc206dd847500ae3
modobit/Python
/condition.py
287
3.828125
4
temprature = 21 if temprature > 30: print(" Its hot today") elif temprature > 20: print(" Its nice today") else: print(" Its Cold") print("Done") # Inline messaging with conditional terniatary age = 22 message = "Eligible" if age >=18 else "Not Eligible" print(message)
5c9b96a421e3a49b17b6e64019a10971a1928553
nayeem56/python-learn
/sent/type conversion.py
68
3.609375
4
dollars=input('Dollars:$') rupees=int(dollars)*'RS'75 print(rupees)
6645a21b2d81032e3d1267d1678862d0d2641a2d
nivetha-ashokkumar/python-basics
/fibonacci.py
270
4.09375
4
number = int(input("Enter positive integer:")) number1 = 0 number2 = 1 number3 = 2 print(number1) print(number2) while number3 < number: number4 = number1 + number2 print(number4) number1 = number2 number2 = number4 number3 = number3 + 1
55413d521ceee10b6ae22acc3fae9e87e39f0673
nivetha-ashokkumar/python-basics
/dict_function.py
531
3.75
4
details = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} print(details) details = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} print(len(details)) details = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} print(details.keys()) details = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} print(details.values()) details = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} print(details.items()) details1 = {"name" : "nivetha", "age" : 21, "dept" : "CSE"} details2 = {"age" : 25} details1.update(details2) print(details1)
58c7422b78870cfe0971e50b37d34320ee748b5b
nivetha-ashokkumar/python-basics
/bubblesort.py
264
4.03125
4
list1 = [20, 10, 25, 15, 30] print("unsorted list:", list1) for j in range(len(list1) - 1): for i in range(len(list1) - 1): if list1[i] > list1[i + 1]: list1[i], list1[i + 1] = list1[i + 1],list1[i] print("sortd list:", list1)
1a6b2d6da21f7e87c107dd45b2ffeec143c2aef6
nivetha-ashokkumar/python-basics
/factorial.py
459
4.125
4
def factorial(number1, number2): temp = number1 number1 = number2 number2 = temp return number1, number2 number1 = int(input("enter first value:")) number2 = int(input("enter second vakue:")) result = factorial(nnumber1, number2) print("factorial is:", result) def check(result): if(result != int): try: print(" given input is not integer") except: print("error") return result
eff065312dc4b5f0e125bc5ad9d507c465429312
luhralive/python
/NeilLi1992/0000/main.py
813
3.71875
4
from PIL import Image from PIL import ImageFont from PIL import ImageDraw file_name = raw_input("Please input the image name, including file appendix: ") try: img = Image.open("test.jpg") s = raw_input("Please input the number to display: ") try: num = int(s) img_width = img.size[0] img_height = img.size[1] font_size = 60 * img_height / 480 font_height = 60 font_width = 40 text_x = img_width - font_width * len(str(num)) text_y = 0 font = ImageFont.truetype("Arial.ttf", font_size) draw = ImageDraw.Draw(img) draw.text((text_x, text_y), str(num), (255,0,0), font=font) img.save("new_image.jpg") except: print "The input is not a number!" except: print "Can't find specified file!"
50c5f524ba1f7305f7582bbddfaf0fb1aa521ae6
luhralive/python
/Lyndon1994/0006.py
1,217
3.578125
4
# -*- coding: utf-8 -*- """ **第 0006 题:** 你有一个目录,放了你一个月的日记,都是 txt, 为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。 """ import os import re def findWord(DirPath): if not os.path.isdir(DirPath): return fileList = os.listdir(DirPath) reObj = re.compile('\b?(\w+)\b?') for file in fileList: filePath = os.path.join(DirPath, file) if os.path.isfile(filePath) and os.path.splitext(filePath)[1] == '.txt': with open(filePath) as f: data = f.read() words = reObj.findall(data) wordDict = dict() for word in words: word = word.lower() if word in ['a', 'the', 'to']: continue if word in wordDict: wordDict[word] += 1 else: wordDict[word] = 1 ansList = sorted(wordDict.items(), key=lambda t: t[1], reverse=True) print('file: %s->the most word: %s' % (file, ansList[1])) if __name__ == '__main__': findWord('source/0006')
c443508ec82b797e3f700aed0ff548fdecf4271a
luhralive/python
/sarikasama/0006/0006.py
852
3.828125
4
#!/usr/bin/env python3 #get the most important word in the text import os, re from pprint import pprint def most_important_word(f): #get the count of words in the text res = {} content = f.read() tmp = re.split(r"[^a-zA-Z]",content) for w in tmp: if not w: continue w = w.lower() if w not in res: res[w] = 1 else: res[w] += 1 #get the word of most importance res['']=0 max = '' for i in res: if res[i] > res[max]: max = i return max def main(): res = {} os.chdir('test') for root,dirs,files in os.walk(os.getcwd()): for file in files: with open(file,'r') as f: res[f.name]=most_important_word(f) return res if __name__ == "__main__": res = main() pprint(res)
892f861fecd3bcc59244ebd317c6f16fa48642a2
luhralive/python
/will/0001/app_store.py
3,117
3.8125
4
# 第 0001 题: 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? ''' 想法思路: 1. 字符串方式 2. 时间戳方式 3. UUID全局标识符,使用uuid1或者uuid5算法 4. 加密算法 ''' import random, string, time, math, uuid chars = string.ascii_letters + string.digits def gen1(): ''' 根据26个大小写字母和数字随机选择10个 涉及模块: 1. random: random.random()函数是这个模块中最常用的方法了,它会生成一个随机的浮点数,范围是在0.0~1.0之间。 random.uniform()正好弥补了上面函数的不足,它可以设定浮点数的范围,一个是上限,一个是下限。 random.randint()随机生一个整数int类型,可以指定这个整数的范围,同样有上限和下限值。 random.choice()可以从任何序列,比如list列表中,选取一个随机的元素返回,可以用于字符串、列表、元组等。 random.shuffle()如果你想将一个序列中的元素,随机打乱的话可以用这个函数方法。 random.sample()可以从指定的序列中,随机的截取指定长度的片断,不作原地修改。 2. string string.digits: 0-9 string.printable:可打印字符集 string.ascii_letters: 大小字母集 ''' key = ''.join(random.sample(chars, 10)) #key2 = ''.join(random.choice(chars) for i in range(10)) return key def gen2(): ''' 当前时间戳生成 1. math.modf(x)返回一个list,包括小数部分及整数部分 2. https://gist.github.com/willhunger/85b119793f01211de50db0e0a257dbf0 3. http://www.wklken.me/posts/2015/03/03/python-base-datetime.html ''' key = math.modf(time.time())[0] return key def gen3(): ''' UUID:通用唯一识别码,由一组32位数的16进制数字所构成 uuid1()——基于时间戳 由MAC地址、当前时间戳、随机数生成。可以保证全球范围内的唯一性,但MAC的使用同时带来安全性问题,局域网中可以使用IP来代替MAC。 uuid2()——基于分布式计算环境DCE(Python中没有这个函数) 算法与uuid1相同,不同的是把时间戳的前4位置换为POSIX的UID,实际中很少用到该方法。 uuid3()——基于名字的MD5散列值 通过计算名字和命名空间的MD5散列值得到,保证了同一命名空间中不同名字的唯一性,和不同命名空间的唯一性,但同一命名空间的同一名字生成相同的uuid。 uuid4()——基于随机数 由伪随机数得到,有一定的重复概率,该概率可以计算出来。 uuid5()——基于名字的SHA-1散列值 算法与uuid3相同,不同的是使用 Secure Hash Algorithm 1 算法 ''' return uuid.uuid4() for i in range(200): print(gen2())
8a1e5c9a01cdf662d892e06dd1344f44be378593
luhralive/python
/AK-wang/0001/key_gen_deco.py
837
4.15625
4
#!/usr/bin/env python # -*-coding:utf-8-*- # 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), # 使用 Python 如何生成 200 个激活码(或者优惠券)? import string import random KEY_LEN = 20 KEY_ALL = 200 def base_str(): return (string.letters+string.digits) def key_gen(): keylist = [random.choice(base_str()) for i in range(KEY_LEN)] return ("".join(keylist)) def print_key(func): def _print_key(num): for i in func(num): print i return _print_key @print_key def key_num(num, result=None): if result is None: result = [] for i in range(num): result.append(key_gen()) return result if __name__ == "__main__": # print_key(KEY_ALL) key_num(KEY_ALL)
36d4bb1df1b94b7d8abcac43da7c482453cf0f4c
luhralive/python
/sarikasama/0011/0011.py
507
4.1875
4
#!/usr/bin/env python3 #filter sensitive words in user's input def filter_sensitive_words(input_word): s_words = [] with open('filtered_words','r') as f: line = f.readline() while line != '': s_words.append(line.strip()) line = f.readline() if input_word in s_words: print("Freedom") else: print("Human Rights") if __name__ == '__main__': while True: input_word = input('--> ') filter_sensitive_words(input_word)
94b4dad1e310adb29b8ef2199eae53a2b7b54164
luhralive/python
/LuHR_showcode/x0004.py
854
3.671875
4
#coding:utf-8 #任一个英文的纯文本文件,统计其中的单词出现的个数。 import re def readFile(file = 'input.txt'): try: with open(file,'r',encoding='UTF-8') as f: txts = f.read() except BaseException as e: print(e) return txts def getEwordsCount(txts): words = re.compile('([a-zA-Z]+)') dic = {} for x in words.findall(txts): if x not in dic: dic[x] = 1 else: dic[x] += 1 L = [] for k,v in dic.items(): #items以列表返回可遍历的(键, 值) 元组数组 L.append((k, v)) # return L.sort( key = lambda t:t[0]) L.sort( key = lambda t:t[0]) return L if __name__ == '__main__': txts = readFile() list1 = getEwordsCount(txts) print(list1)
7f77b4664e7707f2fc6dec3ba66e7e5db64c3b9f
luhralive/python
/Drake-Z/0011/0011.py
692
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- '第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。' __author__ = 'Drake-Z' import os import re def filter_word(a): f = open('filtered_words.txt', 'r', encoding = 'utf-8').read() if a == '': print('Human Rights !') elif len(re.findall(r'%s' % (a), f)) == 0: print('Human Rights !') #非敏感词时,则打印出 Human Rights ! else: print('Freedom !') #输入敏感词语打印出 Freedom ! z = input('请输入词语:') filter_word(z)
7212075838786e34bae819ce3d7294f9fc1903ef
luhralive/python
/endersodium/0001/0001.py
870
3.609375
4
# coding:utf-8 # Python Requirement:3 # Made by EnderSodium ender@enderself.co # 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)? import random # Generate alphabetical stuff def gene_let(code): randomnum = random.randint(65,90) temp = chr(randomnum) return code + temp # Generate numerical stuff def gene_num(code): temp = str(random.randint(0,9)) return code + temp def generate(): code = '' code = gene_let(code) code = gene_num(code) code = gene_num(code) code = gene_let(code) code = gene_num(code) code = gene_let(code) code = gene_num(code) code = gene_num(code) code = gene_let(code) code = gene_num(code) print code def main(): for i in range(199): generate() if __name__ == '__main__': main()
aa85a1a0bc0d41623d45fd2e1cd99f370153c6a4
luhralive/python
/pylyria/0004/0004.py
918
3.734375
4
#! /usr/bin/env python #第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Copyright By PyLyria # CreateTime: 2016-03-01 23:04:58 import re from string import punctuation from operator import itemgetter def remove_punctuation(text): text = re.sub(r'[{}]+'.format(punctuation), '', text) return text.strip().lower() def split(file_name): with open(file_name,'rt') as f: lines = (line.strip() for line in f) for line in lines: yield re.split(r'[;,\s]\s*', line) if __name__ == '__main__': word2count = {} for line in split('chapter1.txt'): words = (remove_punctuation(word) for word in line) for word in words: word2count[word] = word2count.get(word, 0) + 1 sorted_word2count = sorted(word2count.items(),key=itemgetter(0)) print(sorted_word2count)
2863bc17227450b7cec06bb9b5a1787b5ca5db5e
luhralive/python
/renzongxian/0002/0002.py
1,334
3.515625
4
# -*- coding:utf8 -*- # Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-12-06 # Python 2.7, MySQL-python does not currently support Python 3 """ 第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。 """ import uuid import MySQLdb def generate_key(): key_list = [] for i in range(200): uuid_key = uuid.uuid3(uuid.NAMESPACE_DNS, str(uuid.uuid1())) key_list.append(str(uuid_key).replace('-', '')) return key_list def write_to_mysql(key_list): # Connect to database db = MySQLdb.connect("localhost", "test", "test1234", "testDB") # Use function cursor() to open the cursor operation cursor = db.cursor() # If the table exists, delete it cursor.execute("drop table if exists ukey") # Create table sql = """create table ukey ( key_value char(40) not null )""" cursor.execute(sql) # Insert data try: for i in range(200): cursor.execute('insert into ukey values("%s")' % (key_list[i])) # Commit to database db.commit() except: # Rollback when errors occur db.rollback() # Close database db.close() if __name__ == '__main__': write_to_mysql(generate_key())
74fccaa5a23a7774a114525a834c26e155df6b54
luhralive/python
/robot527/0004/statistic_words.py
1,200
3.796875
4
#! usr/bin/python3 """ 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 """ print('Please input a text file name which in the current working directory.') print('Usage - example.txt') file_name = input("@> ") def deal_punctuation(the_string): from string import punctuation as punc punc_list = list(punc) punc_list.remove('-') ret_string = the_string for each_punc in punc_list: ret_string = ret_string.replace(each_punc, ' ') ret_string = ret_string.replace(' -', ' ').replace('- ', ' ') return ret_string def stat(the_file): try: with open(the_file) as textfile: word_list = [] for each_line in textfile: temp = deal_punctuation(each_line) word_list += temp.split() print('This file has ', word_list.__len__(), ' words.') word_set_list = sorted(set(word_list)) for each_word in word_set_list: print(each_word + ' : ', word_list.count(each_word)) except IOError as err: print('File error: ' + str(err)) if __name__ == '__main__': stat(file_name)
edd3c24bbdcf1af0d963ba26d958a72236a22fe2
luhralive/python
/AK-wang/A0000/sushu.py
593
3.546875
4
#!/bin/env python #-*-coding:utf-8-*- #寻找n以内的素数,看执行时间,例子100000内的素数 import sys def prime(n): flag = [1]*(n+2) flag[1] = 0 # 1 is not prime flag[n+1] = 1 p=2 while(p<=n): print p for i in xrange(2*p,n+1,p): flag[i] = 0 while 1: p += 1 if(flag[p]==1): break # test if __name__ == "__main__": n = int(sys.argv[1]) prime(n) # n = 100000,find 9592 primes #$ time ./sushu.py 100000 |wc -l #9592 #real 0m0.083s #user 0m0.078s #sys 0m0.009s
2c8697bc9d189648ee827974fa2051fc02ada2c5
luhralive/python
/AK-wang/0012/f_replace.py
985
4.28125
4
#!/usr/bin/env python # -*-coding:utf-8-*- # 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换, # 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 def f_words(f_file): filtered_list = [] with open(f_file, 'r') as f: for line in f: filtered_list.append(line.strip()) return filtered_list def filtered_or_not(f_word, input_str): return (f_word in input_str) def f_replace(f_word, input_str): return input_str.replace(f_word, "**") def main(f_file, input_str): f_words_list = f_words(f_file) for f_word in f_words_list: if filtered_or_not(f_word, input_str): input_str = f_replace(f_word, input_str) return input_str if __name__ == "__main__": input_str = raw_input("please input your string:") f_file = "filtered_words.txt" print main(f_file, input_str)
9f9b01ccd6c9eb277f99f33ad6cb5a7bc3e3111b
luhralive/python
/Matafight/0007/testDir/importantdiary.py
1,023
3.5625
4
#_*_ encoding: utf-8 _*_ import re class countWord: def __init__(self): self.dic={}; self.word=""; def count(self,filename): self.dic={}; fopen=file(filename,'r'); for lines in fopen.readlines(): words=re.findall(r"\w+",lines); for items in words: if items in self.dic.keys(): self.dic[items]+=1; else: self.dic[items]=1; #对字典value值排序 dict= sorted(self.dic.iteritems(), key=lambda d:d[1], reverse = True); self.word=dict[0][0]; def getWord(self): return self.word; if __name__=="__main__": diarycount=countWord(); order=1; importantlist=[]; for order in range(1,4): fname="diary"+str(order)+".txt"; diarycount.count(fname); importantlist.append(diarycount.getWord()); order+=1; for item in importantlist: print str(item)+"\t";
a31fcd621eacd25158fe063530c23c9caa0e8955
luhralive/python
/renzongxian/0012/0012.py
1,016
4.125
4
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-12-22 # Python 3.4 """ 第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换, 例如当用户输入「北京是个好城市」,则变成「**是个好城市」。 """ def filter_words(words): # Read filtered words from file named 'filtered_words.txt' file_object = open('filtered_words.txt', 'r') filtered_words = [] for line in file_object: filtered_words.append(line.strip('\n')) file_object.close() # Check if the input words include the filtered words and replace the filtered with '*' for filtered_word in filtered_words: if filtered_word in words: words = words.replace(filtered_word, '*'*len(filtered_word)) print(words) if __name__ == '__main__': while True: input_words = input('Input some words:') filter_words(input_words)
04c21f2a42de064d9cf1d6bddc0394d719a7cbea
luhralive/python
/problem 0004/solution for problem 0004.py
244
4
4
def count(): name = raw_input("Enter file:") if len(name) < 1 : name = "test.txt" handle = open(name) count_words=list() for line in handle: count_words+=line.split() return len(count_words) print count()
fa48c5a35d00ad72f000ee150fe8208e7aa6d7ae
luhralive/python
/jhgdike/0004/solution.py
292
3.9375
4
# coding: utf-8 import re from collections import Counter def word_count(txt): word_pattern = r'[a-zA-Z-]+' words = re.findall(word_pattern, txt) return Counter(words).items() if __name__ == '__main__': txt = open('test.txt', 'r').read().lower() print word_count(txt)
4e2a0fc8684813b56dc50d555307ff3af7b770c7
luhralive/python
/DIYgod/0004/count_word.py
244
3.640625
4
# -*- coding: utf-8 -*- import re def count(filepath): f = open(filepath, 'rb') s = f.read() words = re.findall(r'[a-zA-Z0-9]+', s) return len(words) if __name__ == '__main__': num = count('count_test.txt') print num
66e8c164dc795360af7f697ae93311c6971a4e1d
luhralive/python
/renzongxian/0004/0004.py
829
3.78125
4
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-12-07 # Python 3.4 """ 第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 """ import sys def word_count(file_path): file_object = open(file_path, 'r') word_num = 0 for line in file_object: line_list = line.split() word_num += len(line_list) file_object.close() return word_num if __name__ == "__main__": if len(sys.argv) <= 1: print("Need at least 1 parameter. Try to execute 'python 0004.py $image_path'") else: for infile in sys.argv[1:]: try: print("The total number of words is ", word_count(infile)) except IOError: print("Can't open file!") pass
4afa12e7a27291560d036119d0a885c5176f64f2
luhralive/python
/asahiSky/0011/test.py
287
3.8125
4
import os fileName = 'filtered_words.txt' nameList = open(fileName,'rt') nameList = nameList.readlines() print(nameList) while True: s = input('What do you want to say:') if (s+'\n') in nameList: print('Freedom') continue if (s=='exit'): break else: print('Human Rights')
4adcefec39176e2bbda3f1e751ccace491dbf441
luhralive/python
/lwh/2/active_code.py
666
3.875
4
""" 做为 Apple Store App 独立开发者,你要搞限时促销, 为你的应用生成激活码(或者优惠券), 使用 Python 如何生成 200 个激活码(或者优惠券)? 激活码格式: 19个字符组成,分成4组,中间用"-"连接起来 必须同时包含大小写字母数字 """ import random import string def generate_active_code(): active_code = [] ascii_ = string.ascii_letters + string.digits active_code = ["".join([random.choice(ascii_) for i in range(16)]) for i in range(200)] return active_code if __name__ == "__main__": active_code = generate_active_code() print(active_code)
1b5004f226e8d8a843a82f6edd21e52ba095f8c9
luhralive/python
/keysona/0004/0004.py
557
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: key # @Date: 2015-11-17 14:15:01 # @Last Modified by: key # @Last Modified time: 2015-11-17 17:26:46 #-------------------------------- #第 0004 题:任一个英文的纯文本文件,统计其中的单词出现的个数。 #-------------------------------- from collections import Counter def words(): c = Counter() with open('test.txt') as f: for line in f: c.update(line.split(' ')) return sum(c.values()) if __name__ == '__main__': print(words())
33e13977e564ba7901ca4bf859eb83ce9a5a5f6c
luhralive/python
/Mr.Lin/0006/0006.py
794
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: 30987 # @Date: 2015-01-13 11:11:49 # @Last Modified by: 30987 # @Last Modified time: 2015-01-13 17:10:27 import re def hot_words(file_path): file = open(file_path,'r') file_content = file.read() p = re.compile(r'[\W\d]*') word_list = p.split(file_content) word_dict = {} for word in word_list: if word not in word_dict: word_dict[word] = 1 else: word_dict[word] += 1 sort = sorted(word_dict.items(), key=lambda e: e[1], reverse=True) sort = sorted(word_dict.items(), key=lambda e: e[1], reverse=True) print("The most word in '%s' is '%s',it appears '%s' times" % (file_path,sort[1][0], sort[1][1])) file.close() if __name__ == '__main__': hot_words('test.txt')
2b900915b9b4dc855b14095e86b60b2be1fb40bf
luhralive/python
/yefan/004/004.py
613
3.65625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ python实现任一个英文的纯文本文件,统计其中的单词出现的个数、行数、字符数 """ file_name = "movie.txt" line_counts = 0 word_counts = 0 character_counts = 0 with open('C:\Python27\oneday_one\movie.txt', 'r') as f: for line in f: words = line.split() line_counts += 1 word_counts += len(words) character_counts += len(line) print "line_counts ", line_counts print "word_counts ", word_counts print "character_counts ", character_counts
e1c776c9e9b165faed2b3609965c2b6ec758e07f
luhralive/python
/yefan/007/007.py
1,194
3.578125
4
# -*- coding: utf-8 -*- #list all the files in your path(完整路径名path\**.py) import os def get_files(path): files=os.listdir(path) files_path=[] for fi in files: fi_path= path+'\\' + fi if os.path.isfile(fi_path): if fi.split('.')[-1]=='py': files_path.append(fi_path) elif(os.path.isdir(fi_path)): files_path+=get_files(fi_path) return files_path # Count lines and blank lines and note lines in designated files def count_lines(files): line, blank, note = 0, 0, 0 for filename in files: f = open(filename, 'rb') for l in f: l = l.strip() line += 1 if l == '': blank += 1 elif l[0] == '#' or l[0] == '/': note += 1 f.close() return (line, blank, note) if __name__ == '__main__': a=r'c:\python27' #files = get_files(r'c:\python27\oneday_one') files = get_files(r'F\v6:') print len(files),files lines = count_lines(files) print 'Line(s): %d, black line(s): %d, note line(s): %d' % (lines[0], lines[1], lines[2])