blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2818b43c8741fa7e68c8e51f59b42952f116e965
manishhedau/Python-Projects
/Tkinter/simple_form.py
1,634
3.71875
4
from tkinter import * from tkinter import messagebox root = Tk() root.title("Button object") first_name = Label(root,text='First Name :') first_name.grid(row=0,column=0) first_name_entry = Entry(root,justify=CENTER) first_name_entry.grid(row=0,column=1) last_name = Label(root,text='Last Name :') last_name.grid(row=1,column=0) last_name_entry = Entry(root,justify=CENTER) last_name_entry.grid(row=1,column=1) father_name = Label(root,text='Father Name :') father_name.grid(row=2,column=0) father_name_entry = Entry(root,justify=CENTER) father_name_entry.grid(row=2,column=1) mother_name = Label(root,text='Mother Name :') mother_name.grid(row=3,column=0) mother_name_entry = Entry(root,justify=CENTER) mother_name_entry.grid(row=3,column=1) phone_number = Label(root,text='Phone Number :') phone_number.grid(row=4,column=0) phone_number_entry = Entry(root,justify=CENTER) phone_number_entry.grid(row=4,column=1) email_id = Label(root,text='Email Id :') email_id.grid(row=5,column=0) email_id_entry = Entry(root,justify=CENTER) email_id_entry.grid(row=5,column=1) password = Label(root,text='Password :') password.grid(row=6,column=0) password_entry = Entry(root,justify=CENTER,show="*") password_entry.grid(row=6,column=1) def Submitinfo(): msg = messagebox.showinfo( "User Details", "Your Information has successfully submited") lst=[first_name_entry,last_name_entry,father_name_entry,mother_name_entry,phone_number_entry,email_id_entry,password_entry] for i in lst: i.delete(0,END) submit = Button(root,text='Submit',command=Submitinfo,height=1,font=5) submit.grid(row=7,column=1) root.mainloop()
3f3353508b485f99d7fc385a5472ef2c2fb0f5a2
utshav2008/python_training
/random/csv.py
406
3.6875
4
import csv dic = {"John": "[email protected]", "Mary": "[email protected]"} #dictionary download_dir = "numbers.csv" #where you want the file to be downloaded to csv = open(download_dir, "w") #"w" indicates that you're writing strings to the file columnTitleRow = "minute,number_of_messages\n" csv.write(columnTitleRow) for key in dic.keys(): name = key email = dic[key] row = name + "," + email + "\n" csv.write(row)
96327a873468c716021dbdfde22e9e3e3f6cbc72
Malixlocate/Single-Etudes
/Etude11/arithmatic.py
1,799
3.703125
4
import itertools import shlex import os from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-file', metavar='FILE', help='input a file using -file <filename>') args = parser.parse_args() targetFound = False with open(args.file) as file: inputs = [] count = 0 for line in file: count += 1 nextline = file.next() inputs.append(shlex.split(line + nextline)) def leftToRight(current, equation, depth): global targetFound #print(equation) if(targetFound): return elif(current != target and depth >= len(values) -1): return elif(current == target and depth >= len(values) -1): finished = True print("L" + str(target) + " "+ str(equation)) else: depth = depth + 1 nextVal = values[depth] leftToRight(values[depth] + current, equation + "+" + str(nextVal), depth) leftToRight(values[depth] * current, equation + "*" + str(nextVal), depth) for i in range(len(inputs)): values = [] targetFound = False for j in range(len(inputs[i]) -2): values.append(inputs[i][j]) values = list(map(int,values)) target = inputs[i][len(inputs[i]) -2] target = int(target) sign = inputs[i][len(inputs[i]) -1] depth = 0 equation = "" if(sign is 'L'): leftToRight(values[depth], str(values[depth]), depth) elif(sign is 'N'): print("Normal order not implemented") else: print("Incorrect input, please use 'L' or 'N' for the operation sign") """ Normal order is much more difficults to implement because we would have to consider BEDMAS order, effectily pushing the sign onto the equation, evaluating that equation and then poping that sign off if it was not the deired sign
7fbdcad8857a9615ce807ab15fce77c80e17f6d2
conwayjj/AdventOfCode2020
/day10/day10_2_bonus.py
1,597
3.609375
4
import time def calculatePaths(array): #Hack here because there are no two jumps in input size = len(array) if size == 1 or size == 2: return 1 if size == 3: return 2 if size == 4: return 4 if size == 5: return 7 print("LEN NOT SUPPORTED: ", size) return 1 start = time.perf_counter() with open("input2.txt") as file: source = file.readlines() adapters = [0] for line in source: adapters.append(int(line)) #print(int(line)) adapters.sort() adapters.append(adapters[-1]+3) #print (adapters, len(adapters)) differences = {0:0, 1:0, 2:0, 3:0} threeJumps = [0] for i in range(1,len(adapters)): jump = adapters[i]-adapters[i-1] differences[jump] += 1 if jump == 3: threeJumps.append(i) ##solution = 1 ##for i in range(1,len(threeJumps)): ## solution *= calculatePaths(adapters[threeJumps[i-1]:threeJumps[i]]) adapterPaths = {0:1} for i in range(1,len(adapters)): adapter = adapters[i] # print (adapter, type(adapter)) paths = 0 for j in range(1,4): #print (adapter-j) if adapter-j in adapterPaths: newPaths = adapterPaths[adapter-j] paths += adapterPaths[adapter-j] #print("PATH: ", adapter, adapter-j, paths, newPaths) adapterPaths[adapter] = paths #print (adapterPaths) print (differences) print ("1: ", differences[1], "3: ", differences[3]) print ("ANSWER: ", differences[1] * differences[3]) #print ("WAYS TO ARRANGE: ", solution) print("WAYS TO ARRANGE (NO_HACK): ", adapterPaths[adapters[-1]]) stop = time.perf_counter() print("TIME: ", stop-start)
068efaf28dfecdb4fbfea4a2df1b53c3c2c39f52
jasongros619/Settlers-of-Catan
/roadclass.py
2,497
3.625
4
from basic_functions import abxy class Road(object): def __init__(self,data): self.id=data[0] self.c1=(data[1],data[2]) #(a,b) of 1st corner self.c2=(data[3],data[4]) #(a,b) of 2nd corner self.p1=abxy( self.c1 ) #(x,y) of 1st corner self.p2=abxy( self.c2 ) #(x,y) of 2nd corner self.ci1=data[5] #corner 1 id self.ci2=data[6] #corner 2 id self.x=(self.p1[0]+self.p2[0])/2 #x coordinate of midpoint self.y=(self.p1[1]+self.p2[1])/2 #y coordinate of midpoint #ids of nearby roads self.roads=[] for r in data[7:13]: if r==-1: break self.roads.append(r) #ids of nearby hexes self.hexes=[] for h in data[13:19]: if h==-1: break self.hexes.append(h) self.owner=None def drawRoad(self,turtle,color="white"): p1=abxy( self.c1 ) p2=abxy( self.c2 ) turtle.up() turtle.goto( p1[0],p1[1] ) turtle.down() turtle.color("black") turtle.pensize( 9 ) turtle.goto( p2[0], p2[1] ) turtle.pensize(5) turtle.color(color) turtle.goto( p1[0], p1[1] ) turtle.pensize( 1 ) def canRoad(self,player,corner_id=None): #check if a road is already there if self.owner!=None: print("There is already a road built here.") return False #regular turn if corner_id == None: corners = [corn.id for corn in player.corners] if not(self.ci1.id in corners or self.ci2.id in corners): print("You do not have a road connected to this point.") return False #setup round else: if not(self.ci1.id == corner_id or self.ci2.id == corner_id): print("You must place a road connected to your newest settlement.") return False return True def buildRoad(self,player,turtle): # set board's road's owner to player self.owner = player #add corners to player corners = [corn.id for corn in self.owner.corners] if self.ci1.id not in corners: self.owner.corners.append(self.ci1) if self.ci2.id not in corners: self.owner.corners.append(self.ci2) # draw it self.drawRoad(turtle,player.color)
ff00ef2649206f827765554aabb779eb555c4b6c
akhilram/wisebite
/backend python/getItems.py
4,208
3.953125
4
import csv import sys import string import re complete_food_string = "" transtable = {ord(c): " " for c in string.punctuation} # if c!= ',' stopwords = [] def buildStopWords(stopfile): """This function builds a stopword list from a stopwords file given as input. stopwords list is kept global. stopwords file format: one stopword per line Usage: buildStopWords(filepath) Args: stopfile : full path of stopwords file Returns: NA """ global stopwords stopwords = [word.strip() for word in open(stopfile).readlines()] def preprocess(input_string, doStopWords, doPunctuation): """This function preprocess the input_string to remove punctuation and/or remove stopwords Usage: preprocess('this is a string', True, False) Args: input_string : absolute path of csv file containing data doStopWords : boolean to represent whether to remove stopwords doPunctuation : boolean to represent whether to remove punctuations Returns: preprocessed string """ new_str = input_string.lower() if doPunctuation: new_str = new_str.translate(transtable) if doStopWords: try: new_str = " ".join([word for word in new_str.split() if word not in stopwords]) except ValueError as e: new_str = "" return new_str def createFoodStringFile(data_file, output_file): """This function creates a giant string of all food items listed in data_file. The food string is then written to output_file Usage: createFoodStringFile(data file name, output file name) Args: data_file : full path of csv file containing data output_file : name of output_file into which the food string is to be written Returns: NA Note: Please verify the csv format. """ food_list = [] with open(data_file) as csvfile: reader = csv.DictReader(csvfile) for row in reader: preprocessed_foodname = preprocess(row['name'], True, True) food_list.append(preprocessed_foodname) food_str = ",".join(food_list) with open(output_file, 'w') as fout: fout.write(food_str) def isValidFood(input_string): """This function verifies whether the input string is a food item Usage: isfood = isValidFood('cereal', food_dict) Args: input_string : string to be validated to be a food item food_dict : dictionary containing all food items for validation Returns: Boolean representing if the string is valid food or not """ if re.search(input_string, complete_food_string) != None: return True else: return False def extractFoodItems(input_list): """This function return a list of valid food items from a word list. One food item may be a sequence of multiple words. Usage: food_list = extractFoodItems(['peanut', 'butter', 'jelly'], ['peanut', 'peanut butter', 'jelly']) Args: food_dict : dictionary containing all food items for validation input_list : the input word list - construct this by calling split() on raw input string. Returns: List of valid food items. Note: If a food list cannot be constructed incorporating all the words in the list, this function returns None. """ word_count = len(input_list) if word_count == 0: return [] for i in range(word_count,-1,-1): if isValidFood(" ".join(input_list[:i+1])): rest = extractFoodItems(input_list[i+1:]) if rest == None: continue else: return [" ".join(input_list[:i+1])] + rest def main(): global complete_food_string data_file = "..\\backend python\\nutrition_data_clean_jm.csv" food_str_file = "..\\backend python\\all_food.txt" stop_file = "..\\backend python\\stopwords.txt" buildStopWords(stop_file) try: complete_food_string = open(food_str_file, 'r').read() if complete_food_string.strip() == "": raise ValueError('food string empty') except (FileNotFoundError, ValueError) as e: createFoodStringFile(data_file, food_str_file) complete_food_string = open(food_str_file, 'r').read() input_string = sys.argv[1] #'peanut butter jelly mixed' processed_input = preprocess(input_string, True, True) response = extractFoodItems(processed_input.split()) food_items = " " if response == None else ",".join(response) print(food_items) sys.stdout.flush() if __name__ == '__main__': main()
98f0bc25a75dd83f0fa03576fc6259abd97dd88b
pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate
/samples/conceptual_samples/class/class_and_object_variables.py
1,424
4.3125
4
# this is a sample python script program which is created to demonstrate the nature of class and object variables class robot: """represents the robot with a name.""" # this is a class variable which is created to count the number of robots. population=0 def __init__(self,name): """initializes the data""" self.name=name print"\nInitializing {} robots\n".format(self.name) # when the person is created, the robot. # adds to the population robot.population+=1 def die(self): """Iam terminating.""" print" {} is being destroyed !".format(self.name) robot.population-=1 if robot.population==0: print' {} was a last one.'.format(self.name) else: print'There are still {:d} robots working.'.format(robot.population) def say_hi(self): """ greetings given by the robot yes you can definitely do that""" print'greetings, my master call me {}.'.format(self.name) @classmethod def how_many(cls): """prints the current population""" print"we have {:d} robots".format(cls.population) droid1=robot("A-class") droid1.say_hi() robot.how_many() droid2=robot("B-class") droid2.say_hi() robot.how_many() print'\n The robots can do some work over here' print'Now the robots have finished their job , so lets destroy them.' droid1.die() droid2.die() robot.how_many() # this is the end of the file . happy coding..!!
8d48eb05e3ba95ea9a2818f1b4ac5729c39aa3e8
AshTiwari/Python-Guide
/Basic Python/user_defined_functions.py
1,157
4.09375
4
#User Defined Functions in python # Functions #Syntax ''' def funct_name (parameters): statements return (expression) x = funct_name(parameter_value) #x takes the value returned by function. #If the function dosen't return any value the x will take value 'None'. ''' def increment(val): val=val+1 print(val) return val x= increment(4) print('The value returned by "increment function" is\n:') print(x) ''' Note: 1."def" stands for definition. 2.Parameters dosen't have types. => It has both advantage and disadvantage. 1. Coding becomes easy. 2. Debugging becomes difficult. ****************************************************** Excercise ******************************************************* 1. >> def increment(val) >> val=val+1 >> print(val) >> x= increment(4) >> print(x) Predict O/P: Ans:4 None The function returns 'None'. So x takes 'None'. Thus, not secifying types may give results which we didn't expect at begining. '''
450bdab51ac97a1108e3d353a6073a83398eac64
cain19811028/python-codility
/python_count_semiprimes.py
2,384
4.28125
4
import json from math import sqrt """ Task:CountSemiprimes Count the semiprime numbers in the given range [a..b] ------------------------------ A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. You are given two non-empty zero-indexed arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges. Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N. For example, consider an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 The number of semiprimes within each of these ranges is as follows: (1, 26) is 10, (4, 10) is 4, (16, 20) is 0. Write a function: def solution(N, P, Q) that, given an integer N and two non-empty zero-indexed arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries. For example, given an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 the function should return the values [10, 4, 0], as explained above. Assume that: N is an integer within the range [1..50,000]; M is an integer within the range [1..30,000]; each element of arrays P, Q is an integer within the range [1..N]; P[i] ≤ Q[i]. """ N = 26 P = [1, 4, 16] Q = [26, 10, 20] """ 用半質數相乘取出結果 Correctness:100%、Performance:40% """ def solution(N, P, Q): S = [0] * (N+1) # 先取得半質數列表 prime = [ p for p in range(2, int(N / 2) + 1) if 0 not in [ p % d for d in range(2, int(sqrt(p))+1)] ] # 標註所有相乘結果 for i in prime: for j in prime: k = i * j if k <= N: S[k] = 1 # 取得範圍內有多少註記 result = [] for i in range(0, len(P)): result.append(len(list(filter(lambda x: x == 1, S[P[i]:Q[i]+1])))) return result print(solution(N, P, Q))
c5382550016a36833e93fa5add87b2e0f685dece
ArunkumarRamanan/CLRS-1
/ProgrammingInterviewQuestions/4_Print2DArrayInSpiralOrder.py
1,097
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Aug 20 10:10:30 2016 @author: Rahul Patni """ # Print 2 D array in spiral order def printSpiral(A, length, breadth): currLength = length - 1 currBreadth = breadth - 1 row = 0 col = 0 offset = 0 for i in range(length * breadth): track = i track -= offset if (track + 1) == 2 * (currLength + currBreadth): offset = 2 * (currLength + currBreadth) currLength -= 2 currBreadth -= 2 track = 0 print A[row][col], if currLength == 0 or track / currLength == 0: col += 1 elif (track - currLength) / currBreadth == 0: row += 1 elif (track - currLength - currBreadth) / currLength == 0: col -= 1 elif (track - currLength * 2 - currBreadth) / currBreadth == 0: row -= 1 return def main(): A = [[2,4,6,8, -2],[5,9,12,16, -4],[2,11,5,9, -6],[3,2,1,8, -8], [41, 42, 43, 44, 56]] for i in A: print i printSpiral(A, len(A[0]), len(A)) return main()
5e579db5383be32e820e762895822e3ba5c30b64
Winni8/python-project
/py_workspace/test_case/继承/继承2.py
615
3.515625
4
# _*_ coding:utf-8 _*_ # @Author :cjj # @time :2018/7/10 11:37 # @File :继承2.py # @Software :PyCharm class X(object): def f(self): print( 'x') class A(X): def f(self): super(A, self).f() print( 'a') class B(X): def f(self): super(B, self).f() print( 'b') class C(A, B, X): def f(self): super(C, self).f() print( 'c') class F(X): def f(self): super().f() print("f") class D(C,F): def f(self): super(D, self).f() print("d") d = D() print(D.mro()) d.f() # c = C() # c.f() #c.extral()
9822e46b9a7c1193f221fcb33dade1e5bc75466a
sonwonrak92/dataStructure_algorithm
/python_03.py
1,605
3.734375
4
''' ### Python Algorithm Study ### # author : laziness # date : 2019/08/06 세 번째 과제 ::이진탐색 구현하기:: 최초의 값이 중간 값과 같으면 중간 값의 인덱스를 리턴한다 최초의 값이 중간인덱스 값 보다 작으면 처음값과 중간값의 사이값과 비교한다 여기서 중간인덱스를 다시 마지막 인덱스로 설정한다 최초의 값이 중간 값 보다 크면 중간값과 마지막값의 사이값과 비교한다 여기서 중간값은 다시 처음 인덱스가 된다 따라서 최초의 인덱스, 중간 인덱스 , 마지막 인덱스, 결과인덱스 변수가 필요하다 ''' # Test Case test01 = [1,2,3,4,5] test02 = [55] test03 = [1,2,3,4,5,6,7,8,22,44,66,321] def solution(L, x): if x in L : stdIdx = 0 endIdx = len(L) - 1 while stdIdx <= endIdx : middleIdx = (stdIdx + endIdx) // 2 print('start : {}'.format(stdIdx)) print('middle : {}'.format(middleIdx)) print('endIdx : {}'.format(endIdx)) print(L[middleIdx]) print(x) if L[middleIdx] == x : return middleIdx elif L[middleIdx] > x : endIdx = middleIdx - 1 print('end : {}'.format(endIdx)) elif L[middleIdx] < x : stdIdx = middleIdx + 1 print('std : {}'.format(stdIdx)) else : answer = -1 return answer test = [2, 3, 5, 6, 9, 11, 15] print(solution(test03,2))
7f4ee3fd3ce06fb83f540ee60ba4245a2dca90f2
louisbemberg/python_notes
/py4e/921-python_objects.py
297
3.796875
4
class Dog: def __init__(self, breed, gender, age): self.age = age self.breed = breed self.gender = gender dog1 = Dog("border collie", 'female', 14) print('A', dog1.age, 'year-old', dog1.gender, dog1.breed, '.') # IMPORTANT # in dog.age, the "." is the OBJECT LOOKUP OPERATOR :)
62089574045cca63d799d2b3103536bc2cdb5518
ivan-samardzic/python-basics
/getting_input_from_users.py
257
4.28125
4
#input from user stored into variable name = input("Enter your name: ") print("Hello " + name + "!") #getting name and age name = input("Enter your name: ") age = input("Enter your age: ") print("Hello " + name + "! You are " + age + " year old!")
5dc6a0222a909d27eaa8ac2d661a5a64c8868485
KeithLacey/Python_assignments
/StringsandList.py
387
3.890625
4
words = "It's thanksgiving day. It's my birthday,too!" print words.find("day") print words.replace("day","month") x = [2,54,-2,7,12,98] print min(x) print max(x) x = ["hello",2,54,-2,7,12,98,"world"] print x[0],x[len(x)-1] x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() print x first = x[:len(x)/2] print first second = x[len(x)/2:] print second second.insert(0,first) print second
92804a3d253460d13e39a7a8559247ea958dca24
akjadon/HH
/Python/MachineLearning/Regression/02 - Multiple Linear Regression/MLR.py
1,119
3.703125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 18 23:20:36 2018 @author: abdul """ # Multi Linear Regression import numpy as np #for mathematical calculation import matplotlib.pyplot as plt #for ploting nice chat and graph import pandas as pd dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:,4].values # handling categorical data from sklearn.preprocessing import OneHotEncoder, LabelEncoder labelencoder_X = LabelEncoder() X[:, 3] = labelencoder_X.fit_transform(X[:,3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # avoiding dummy varibale trap X = X[:, 1:] # splitting data to train and test from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state = 0) # Fitting multiple linear regression to the tranning set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the test set result y_pred = regressor.predict(X_test)
d6fe41bfe52fe7837609b3fe52b78ff0e2f9510d
b1ck0/python_coding_problems
/Search_Sort/merge_sort.py
1,038
4.28125
4
def merge_sort(array): if len(array) > 1: i = len(array) // 2 left = array[:i] right = array[i:] merge_sort(left) # sort left half merge_sort(right) # sort right half i, j, k = 0, 0, 0 # if both lists have the same length this will be the only while block executed while i < len(left) and j < len(right): if left[i] < right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 # this will be executed of len(left) > len(right) while i < len(left): array[k] = left[i] i += 1 k += 1 # this will be executed of len(right) > len(left) while j < len(right): array[k] = right[j] j += 1 k += 1 return array if __name__ == "__main__": print(merge_sort([1, 33, 4, 6, 2, 3, 56, 67, 7, 43, 2, 2, 1, 23, 5, 6, 7, 4, 3, 2, 2, 3, 5, 6, 123]))
3f568df42291ce15c2ac3324f9c866185ad8eb5e
Pirci/leetcode
/problems/90. Subsets II/90.py
1,067
3.75
4
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: """Returns all possible subsets Args: nums (List[int]): integer array Returns: List[List[int]]: possible subsets output Time Complexity: nlogn(sort)+2^n(for) """ # Given nums=[1,2,2] # We will have to start with [] and then append the each item in nums with the previously added items # [] # [],[1] # [],[1],[2],[1,2] Here 2 is added first and then append with the previous 1. # [],[1],[2],[1,2],[2],[1,2],[2,2],[1,2,2] Last 2 is appended with the previous items. # We have to use set to get rid off duplicates. nums.sort() # Order matters for duplicates ans = [[]] for n in nums: tmp=[] for l in ans: tmp.append(l+[n]) ans.extend(tmp) return [list(l) for l in set([tuple(l) for l in ans])]
4abc18571d4e2914a8b2729b5f0811af1de34b10
HawkinYap/Leetcode
/leetcode9.py
601
3.71875
4
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return (False) len = 1 while int(x / len) >= 10: len = int(len * 10) while x > 0: l = int(x / len) r = int(x % 10) if l != r: return (False) else: x = int((x % len) / 10) len = int(len / 100) return (True) if __name__ == '__main__': x = 12321 solution = Solution() print(solution.isPalindrome(x))
fb87caa57fbcdac4a8e95c05f71f2824c0c82f20
grcninja/Small_Tasks
/LookUpDomainByIP.py
2,317
4.1875
4
''' Language & Version: Python 3.4 This script allow the user to identify the path and file that holds a list of IP addresses that they would like to look up the domain name for. The user can also indicate where to save the file and what to name it. ''' import csv import datetime import fileinput import os import socket import sys def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 print("THIS SCRIPT IS DESIGNED TO INGEST A LIST OF IP ADDRESSES ONLY.\n THE ONLY FORMATTING IT WILL DO FOR YOU IS REMOVE BLANK LINES OR WHITESPACE.\n**IF YOUR FILE HAS OTHER CRAP IN IT, THIS WON'T WORK.**\n\n") input_path = str(input("Enter the *PATH ONLY* to the list of IPs is at that you want to look up: ")) input_name = str(input("Enter the name of the file containing the IPs (include the extension): ")) output_path = str(input("Enter the *PATH ONLY* to where you want to save your file: ")) output_name = str(input("What do you want to name YOUR file? (A date will be added automatically and it will get a .txt extension) ")) dt = datetime.date.today() output_name = (output_name+"_"+str(dt)+".txt") output_file_name = os.path.join(output_path, output_name) input_file_name = os.path.join(input_path, input_name) process_file_name = os.path.join(input_path, "cleaned_input.txt") #stripout blank lines from the source file with open(input_file_name,'r') as f, open(process_file_name,"w")as f2: for line in f: line.rstrip() f2.write(line) lines = file_len(process_file_name) with open(process_file_name,"r") as fin, open(output_file_name,"w") as fout: reader = csv.reader(fin)#pulling the domain name out of this to look up the IP d = list(reader) print(d) print("lines = "+str(lines)) for i in range(lines): print("Loop number "+str(i)) ip = d[i][0] print("looking up "+str(ip)) try: domain = socket.gethostbyaddr(ip) print(str(domain)) fout.write(str(domain)+","+str(ip)+"\n") except socket.herror as e: fout.write(str(e)+"'"+str(ip)+"\n") except socket.gaierror as e: fout.write(str(e)+"'"+str(ip)+"\n") except socket.timeout as e: fout.write(str(e)+"'"+str(ip)+"\n")
6988799c868dd544f4fc24ff3380f5f7d9482425
DQder/WHN-Codefest-2020
/code/Problem 10.py
164
3.9375
4
i = 0 Sum = 0 while i < 5: i += 1 x = int(input("Enter a number:")) Sum += x ortalama = Sum / i print("Girdiğiniz sayıların ortalaması: ", ortalama)
074af21935d398f464fbb7b7a8f8be9800011271
JoshsHiddenTrove/ChessAI
/ReactApp/python/Board.py
848
3.796875
4
from typing import List import Pieces.Pieces as Pieces class Board: BackLine = ["R","K","B","Q","K","B","K","R"] def __init__(self): self.ChessBoard = [[None] * 8] * 8 self.GeneratePieces() def getBoard(self): return self.ChessBoard def GeneratePieces(self): for place in range(8): self.ChessBoard[1][place] = Pieces.Piece("White", "P", (1, place)) self.ChessBoard[7][place] = Pieces.Piece("Black", "P", (1, place)) self.ChessBoard[0][place] = Pieces.Piece("White", self.BackLine[place], (1, place)) self.ChessBoard[8][place] = Pieces.Piece("Black", self.BackLine[place], (1, place)) def printBoard(self): for x in range(0,8): for y in range(0, 8): print(self.ChessBoard[x][y].piece)
ccd652427fbc4bbf97ee89ec2711fe34015941be
agbarker/Cracking-the-Coding-Interview-Python
/ArraysAndStrings/URLify.py
746
4.3125
4
"""Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.""" """Replacement in place is not possible in python as strings are immutable. Much of the input is unecessary in python due to this constraint. I have eliminated the length variable input.""" def urlify(string): """Converts string with spaces to valid url. >>> urlify('taco cat') 'taco%20cat' >>> urlify('cat') 'cat'""" tokens = string.split(" ") i = 1 result = tokens[0] while i in range(len(tokens)): result = result + '%20' + tokens[i] i += 1 return result
a06a2a8ecb4f485a11819ced8b9dec1e21677131
MoutyWong/Python3-learning-Notes
/day01/day01_second.py
264
3.796875
4
# !/usr/bin/env python3 i = 100 while i > 0: if i > 50: print('This number greater than 50') if i < 50: print('This number less-than 50') i -= 1 str = 'I\'m OK' print (str) print (r'\\\n\\') print('''* ** ***''') print(r'''r rr rrr''')
ea85ac3b7a019fdb6eaa7cfe77466e72ed6f8928
jrmullen/cse233
/problem7/problem7.py
446
3.75
4
__author__ = 'Jeremy' import random def main(): random_numbers = open('random_numbers.txt', 'w') num_of_rands = int(input('How many random numbers should be written to the file?: ')) print('Numbers written: ') for count in range (num_of_rands): number = random.randint(1,500) print(number) random_numbers.write(str(number)+ '\n') random_numbers.close() print('numbers printed to file') main()
7cc8a68fea4bb57fab7550731b1ab183a408cb27
Sugandha05/learn-python
/while_loop_list.py
280
3.609375
4
book = ['ram', 'shyam', 'su', 'mo'] page = 0 # while book is not finished (till 6) # read(print) and update page number # while condition is true do following while page != 4: # print(page!=4) print(book[page]) page = page + 1 #print(book[page]) print(page!=4)
28546060b6b51e99c7e68f1bd01883f254e5ab84
tockata/HackBulgaria
/exam/loss_or_profit.py
513
3.53125
4
def loss_or_profit(income, outcome): total_income = 0 total_outcome = 0 for x in range(0, len(income)): total_income += income[x] for x in range(0, len(outcome)): total_outcome += outcome[x] result = total_income - total_outcome if result > 0: return ("+" + str(result)) elif result == 0: return ("=0") else: return str(result) print(loss_or_profit([1, 2, 3], [3])) print(loss_or_profit([10], [20, 30])) print(loss_or_profit([10], [10]))
734083d2e8bfe0160cc3c28eb80d19bc2c251b6d
Dyr-El/advent_of_code_2017
/FredrikB-Python/day2/day2.py
217
3.515625
4
#!/usr/bin/env python import re def solver(data): result = 0 f = open(data, 'r') for line in f: data = [int(x) for x in line.split()] result += max(data) - min(data) return result print solver('input.txt')
8257096c035180b699af17be48506b52b44eda21
erpost/python-beginnings
/etc/shirt_order_basic.py
647
4.03125
4
sm_price = 6 med_price = 7 lg_price = 8 shirt_order = 0 size = input("What size shirt would you like: ") quantity = input("How many shirts total: ") if size.lower() == "s" or size.lower() == "small": shirt_order = int(sm_price) * int(quantity) print("Your total will be $", shirt_order) elif size.lower() == "m" or size.lower() == "medium": shirt_order = int(med_price) * int(quantity) print("Your total will be $", shirt_order) elif size.lower() == "l" or size.lower() == "large": shirt_order = int(lg_price) * int(quantity) print("Your total will be $", shirt_order) else: print("Sorry, the size is not available ")
ff56084078ad7cc8a270b41bf433ac49e62eb9aa
mgbvox/davide_b
/proj3.py
3,963
3.90625
4
from person import Person class DynasticDescent: def __init__(self): self.tree = dict() self.ids = [] self.next_id = 1 def add(self): name = str(input('What is the name of the human?')) self.add_person(Person(name)) def add_person(self, person): ''' Adds a person to the family tree. :param person: a Person() object :return: None ''' # Gives person an ID if they don't have one. if not person.id: latest_id = self.next_id person.id = latest_id self.ids.append(latest_id) self.next_id += 1 #Adds them to the tree if they're not already in the tree: tree_key = person.get_key() if not tree_key in self.tree: self.tree[tree_key] = person print(f'Added {person.name.upper()} to the family tree!') else: print(f'{person.name} is already in the tree! Key: {tree_key}') def ensure_in_tree(self, person): if person.get_key() not in self.tree: print(f'{person.name} not in tree; adding!') self.add_person(person) else: print(f'{person.name} in tree! Good job!') def lookup(self, name): matches = [] for name_key in self.tree.keys(): if name.upper() in name_key.upper(): matches.append(name_key) if len(matches) == 0: print(f'{name} not in tree yet; making a new person (Happy Birthday Person!)') new_person = Person(name) self.add_person(new_person) return new_person elif len(matches) == 1: #Just return the matching person obj. return self.tree[matches[0]] elif len(matches) > 1: #User needs to pick a person! print("Found more than one match, here's the list:") print(matches) choice = str(input('Which ID do you choose?')) chosen_key = f'{name.title()}_{choice}' return self.tree[chosen_key] def relate(self, parent_name = None, child_name = None, parent = None, child = None): ''' Adds a child to a parent Person object. :param parent: a Person object. :param child: a Person object. :return: None ''' if not parent_name and not parent: parent_name = str(input("What is the name of the parent human? ")) if not child_name and not child: child_name = str(input("What is the name of the child human? ")) if not parent: parent = self.lookup(parent_name) if not child: child = self.lookup(child_name) ''' What happens if two people in the tree have the same name? ''' if (parent and child): #Make sure parent and child are both in tree self.ensure_in_tree(parent) self.ensure_in_tree(child) #add parent to child's parent list, and child to parent's child list. # parents = {'parent_id' : [parent_1, parent_2, ....]} # Matt -> 'Matt_1' child.parents.append(parent.get_key()) parent.children.append(child.get_key()) def get_ancestors(self, person, degree, depth = 0): if depth == degree: return [person.name] else: ancestors = [] parents = person.parents for parent_key in parents: parent = self.lookup(parent_key) ancestors += self.get_ancestors(parent,degree,depth=depth+1) return ancestors if __name__ == "__main__": tree = DynasticDescent() user_input = '' while user_input != 'quit': user_input = str(input('What would you like to do next? ')) if user_input == 'add': tree.add() elif user_input == 'relate': tree.relate()
f8c8f59b94d81cc981bf589613fc350151a16abf
786662216/backup-for-python2
/练习/filter().py
236
3.625
4
#判断素数 def not_prime_num(n):# if n == 1 : return False else: for i in range(2,n): if n % i == 0: return True return False l = range(1,101) print filter(not_prime_num,l)
33f761e75ad838ec23f2451085d345a476bbad79
tmtrinesh/PythonBasics
/search.py
283
3.59375
4
pos = -1 def search(list,n): i= 0 while i< len(list): if list[i] == n: globals()['pos'] = i return True i = i+1 return False list = [5,8,4,9,7,1] n = 7 if search(list,n): print("Found at",pos) else: print("Not found")
ab72c074d1213cfe55b0c914fb75a01e2d0ee28e
frasertweedale/drill
/py/treespan.py
531
3.546875
4
class Tree: def __init__(self, l, r): self.l = l self.r = r def treespan(tree): """Return max span of tree assuming all links have weight of 1.""" if tree is None: return (0, 0, 0) lspan = 0 ldepth = 0 rspan = 0 rdepth = 0 if tree.l: lspan, lldepth, lrdepth = treespan(tree.l) ldepth = lldepth + 1 if tree.r: rspan, rldepth, rrdepth = treespan(tree.r) rdepth = rrdepth + 1 return max((lspan, rspan, ldepth + rdepth)), ldepth, rdepth
81df55c66c7bcc6f400d6a7d66a79f0e65591935
JoshuaShin/A01056181_1510_assignments
/A5/q09.py
2,297
3.84375
4
""" q09.py A base conversion module. """ # Joshua Shin # A01056181 # April 15th 2019 import doctest import math def base_conversion(original_base: int, original_number: int, destination_base: int) -> int: """ Convert original number in original base to destination base. PRECONDITION original base must be between 2 and 10 PRECONDITION destination base must be between 2 and 10 RETURN Correctly converted number with destination base >>> base_conversion(2, 10101, 8) 25 """ if original_number == 0: return 0 elif original_number < 0: return -1 * to_destination_base(to_decimal(abs(original_number), original_base), destination_base) else: return to_destination_base(to_decimal(abs(original_number), original_base), destination_base) def to_decimal(number: int, original_base: int) -> int: """ Convert the number with original base to decimal. PRE-CONDITION original base must be an integer between 2 and 10 RETURN the number with given base converted to decimal >>> to_decimal(10101, 2) 21 """ if 2 <= original_base <= 10: sep_numbers, dec_number = [int(index) for index in str(abs(number))], 0 num_length = len(sep_numbers) for i in range(0, num_length): dec_number += sep_numbers[i] * (original_base ** (num_length - 1 - i)) return dec_number else: raise ValueError("Base must be an integer between 2 and 10.") def to_destination_base(number: int, destination_base: int) -> int: """ Convert decimal number to destination base. PRE-CONDITION destination_base must be an integer between 2 and 10 RETURN the number in decimal converted to destination base >>> to_destination_base(21, 8) 25 """ if 2 <= destination_base <= 10: destination_number = "" for i in range(math.trunc(math.log(number, destination_base)) + 1): destination_number += str(number % destination_base) number = math.trunc(number / destination_base) return int(destination_number[::-1]) else: raise ValueError("Base must be an integer between 2 and 10.") def main(): doctest.testmod() print(base_conversion(10, -21, 2)) if __name__ == '__main__': main()
180a4959170d5d19711d385047b49299a95b619b
andrekorol/logica-programacao
/Python/particle.py
4,602
3.984375
4
from __future__ import annotations from typing import List class Vec: """Vetor com componentes x e y.""" def __init__(self, x: float, y: float): self.x = x self.y = y def plus(self, other: Vec): """Soma um vetor com o outro.""" return Vec(self.x + other.x, self.y + other.y) def times(self, factor: float): """Multiplica o vetor por um valor escalar.""" return Vec(self.x * factor, self.y * factor) class Particle: """Particula com posicao (x, y) e velocidade (Vx, Vy).""" def __init__(self, pos: Vec, speed: Vec): self.pos = pos self.speed = speed self.acceleration = Vec(0, 0) class Obstacle: """Obstaculo com comprimento, largura e posicao (x, y).""" def __init__(self, length: float, width: float, x: float, y: float): self.length = length self.width = width self.pos = Vec(x, y) @staticmethod def create(index: int): """Cria um obstaculo a partir de valores dados como input.""" length = float(input(f"Entre o comprimento do {index + 1}° obstaculo: ")) width = float(input(f"Entre a largura do {index + 1}° obstaculo: ")) x_pos = float(input(f"Entre a posicao em x do {index + 1}° obstaculo: ")) y_pos = float(input(f"Entre a posicao em y do {index + 1}° obstaculo: ")) return Obstacle(length, width, x_pos, y_pos) class Force: """Forca com magnitude e direcao (x, y).""" def __init__(self, magnitude: float, x: float, y: float): self.magnitude = magnitude self.direction = Vec(x, y) class State: """Estado da simulacao.""" def __init__(self, particle: Particle, obstacles: List[Obstacle]): self.particle = particle self.obstacles = obstacles def main(): """Funcao principal que executa o programa.""" x_pos = float(input("Entre a posicao inicial em x da particula: ")) y_pos = float(input("Entre a posicao inicial em y da particula: ")) x_speed = float(input("Entre a componente Vx da velocidade inicial da particula: ")) y_speed = float(input("Entre a componente Vy da velocidade inicial da particula: ")) initial_pos = Vec(x_pos, y_pos) initial_speed = Vec(x_speed, y_speed) particle = Particle(initial_pos, initial_speed) num_obstacles = int(input("Entre o numero de obstaculos: ")) # No minimo 3 obstaculos num_obstacles = num_obstacles if num_obstacles >= 3 else 3 obstacles = [] for i in range(num_obstacles): obstacles.append(Obstacle.create(i)) state = State(particle, obstacles) while True: answer = input("Deseja inserir uma forca que atuara na particula? [Y/n] ") particle = state.particle new_accel = particle.acceleration if answer.lower() != "n": magnitude = float(input("Entre o modulo da forca: ")) force_x = float(input("Entre a componente x da forca: ")) force_y = float(input("Entre a componente y da forca: ")) force = Force(magnitude, force_x, force_y) new_accel = particle.acceleration.plus( force.direction.times(force.magnitude) ) new_speed_x = particle.speed.x + new_accel.x new_speed_y = particle.speed.y + new_accel.y new_pos_x = particle.pos.x + new_speed_x # * 1 segundo new_pos_y = particle.pos.y + new_speed_y # * 1 segundo # Check collisions for obstacle in state.obstacles: if new_pos_x >= obstacle.pos.x + obstacle.width: new_speed_x *= -1 new_pos_x = obstacle.pos.x print( f"Particula colidiu com obstaculo em ({obstacle.pos.x}, {obstacle.pos.y})" ) if new_pos_y >= obstacle.pos.y + obstacle.length: new_speed_y *= -1 new_pos_y = obstacle.pos.y print( f"Particula colidiu com obstaculo em ({obstacle.pos.x}, {obstacle.pos.y})" ) particle = Particle(Vec(new_pos_x, new_pos_y), Vec(new_speed_x, new_speed_y)) state = State(particle, obstacles) print(f"Posicao da particula: x = {particle.pos.x}, y = {particle.pos.y}") answer = input("Deseja continuar a simulacao? [Y/n]") if answer.lower() == "n": break print(f"Posicao da particula: x = {particle.pos.x}, y = {particle.pos.y}") print(f"Velocidade da particula: Vx = {particle.speed.x}, Vy = {particle.speed.y}") if __name__ == "__main__": main()
09437bd4d05ecdbc03d4659e36ceeec9cb3de9f1
gvsharshavardhan/python_go4guru
/string_case.py
777
3.84375
4
currntamt = 500 flag = True trail = 0 while flag: trail += 1 username = input("please enter your user name:") password = input("please enter your password:") if(username.lower() == "harsha" and password == "password123"): withdrawamt = int(input("please enter some amt to withdraw:")) if withdrawamt > currntamt: print("your withdraw amt is more than current balance, you cannot withdraw!!") else: currntamt = currntamt-withdrawamt print("amt wothdrawn succesfully!") print("your current balance is : ", currntamt) break else: print("please check your credentiuals!!") print("you have {} more trails".format(3-trail)) if(trail == 3): break
6ccd1c0951b093b8f03c4d7a12d86a5467e2ed89
sujivennapusa/python-program
/w3day13task/myfile.py
285
3.765625
4
myfile=open('demo.txt','a+') """ myfile.write("hello world") """ i=input("enter the name:") myfile.write(i+"\n") print(myfile.tell()) myfile.seek(0) """ myfile.write("karnataka is a state in india") """ """ myfile=open('demo.txt','r') """ x=myfile.read() print(str(x)) myfile.close()
546feec896e27325096c592ab06cb55495b50685
olekmali/eTCP_Python
/20_intro_to_python/205_more_on_lists.py
975
4.4375
4
# More on lists # pointer/alias to existing list demonstrated days_of_the_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] print( days_of_the_week ) work_days = days_of_the_week work_days.remove('Saturday') work_days.remove('Sunday') print( work_days ) print( days_of_the_week ) print("Something went wrong?\nLet's try again!") # list copied to a new list demonstrated days_of_the_week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] print( days_of_the_week ) work_days = days_of_the_week[:] work_days.remove('Saturday') work_days.remove('Sunday') #work_days.remove('Sunday') # removing non-existing element causes a runtime error print( work_days ) print( days_of_the_week ) # accessing by index works the same as accessing characters in a string print( days_of_the_week[1:6] ) print( days_of_the_week[:1] ) print( days_of_the_week[6:] ) print( days_of_the_week[-2:] )
a16f13ee1dce613701a044f8ed5684ad997dc2af
Lempi-sudo/ParserDocument
/emailParser(3).py
1,002
3.75
4
#Создать текстовый документ содержащий список адресов электронных почт, # их можно придумать самому. Количество не менее 50. #Записать в выходной файл список доменов электронных почт из входного файла. import re def ReadFile(filename): with open(filename,"r", encoding="utf8") as myfile: text = myfile.read() return text def WriteFile(listemail , filename ): with open(filename,'w', encoding="utf8") as file: file.write('домены электронной почты : \n') for email in listemail: file.write(email+'\n') def ParseEmail(text): textlookfor = r"[@][\w-]+\.+[\w.]+" allresulr = re.findall(textlookfor, text) return allresulr if __name__ == '__main__': text=ReadFile('text.txt') listemail=ParseEmail(text) WriteFile(listemail,'emailparse.txt')
92ff27214b5985b003d8f2d3d5bd8dc5fb7357cd
gitStanden/2DAlienInvasion
/alienInvasion/ship.py
1,550
3.90625
4
import pygame from pygame.sprite import Sprite class Ship(Sprite): """A class to manage the ship.""" def __init__(self, aiGame): """Initilise the ship and set its starting position.""" super().__init__() self.screen = aiGame.screen self.screenRect = aiGame.screen.get_rect() self.settings = aiGame.settings # Load the ship image and get its rect. self.image = pygame.image.load("Images/playership.bmp") self.rect = self.image.get_rect() # Start each new ship at the bottom center of the screen. self.rect.midbottom = self.screenRect.midbottom # Store a devimal vlaue for the ship's horizontal position. self.x = float(self.rect.x) # Movement Flag self.movingRight = False self.movingLeft = False def update(self): """Update the ship's position based on the movement flag.""" # Update the ship's x value, not the rect. if self.movingRight and self.rect.right < self.screenRect.right: self.x += self.settings.shipSpeed if self.movingLeft and self.rect.left > 0: self.x -= self.settings.shipSpeed # Update rect object from self.x self.rect.x = self.x def centerShip(self): """Center the ship on the screen""" self.rect.midbottom = self.screenRect.midbottom self.x = float(self.rect.x) def blitme(self): """Draw the ship at its current location.""" self.screen.blit(self.image, self.rect)
700d89e364197deaeff90928068b39090743f912
BioroboticsLab/bb_behavior
/bb_behavior/plot/background.py
7,005
3.515625
4
import cv2 import numba import numpy as np def generate_median_images(gen, N=10): """ Takes an image generator and yields a median image of the last N images every N images. Arguments: gen: generator A generator that yields greyscale images. N: int A median image is generated every N images. Yields: smooth_image: np.array(dtype=np.float32) Image of same shape as original images. """ idx = 1 try: im = next(gen) except StopIteration: return buffer = np.zeros(shape=(N, im.shape[0], im.shape[1]), dtype=np.float32) buffer[0] = im for i, im in enumerate(gen): buffer[idx] = im idx = (idx + 1) % N if idx == 0: # Output every N images smooth_image = np.nanmedian(buffer, axis=0) yield smooth_image @numba.njit def increase_histogram(hist, image, is_float=False): """Takes a histogram and an image. Increases histogram counters for this image in-place. Arguments: hist: np.array(shape=(255, H, W), dtype=np.float32) Histogram that will be changed in-place. image: np.array(shape=(H, W)) Counts for color values from this image will be increased in the histogram. Datatype can either be int or float, see is_float. is_float: bool If True, values from image should be in range (0, 1). Otherwise, values should be in range(0, 255). """ for y in numba.prange(image.shape[0]): for x in numba.prange(image.shape[1]): value = image[y, x] if is_float: int_value = int(255.0 * value) else: int_value = int(value) hist[int_value, y, x] += 1.0 def generate_mode_images(gen, only_return_one=False, smoothing=0.95): """Takes an image generator and yields new images with pixel values being the mode of the original images' values. Arguments: gen: generator Generator yielding greyscale images. Either integer-based data type and range (0, 255). Or float data type and range (0, 1). only_return_one: bool If true, one modal image will be generated for the whole generator. Otherwise, each image will yield the current state of the mode. smoothing: float Value between [0, 1] to control how fast the histogram adjusts to changes. Will be set to 1 if only_return_one is set. 1 = slowest adjustment. 0 = instant. Yields: modal_image: np.array(dtype=np.uint8) Images of the same shape as the original image. """ import itertools bins=256 try: first_image = next(gen) except StopIteration: first_image = None if first_image is None: return None is_float = not (first_image.dtype is np.integer) if is_float and first_image.max() > 1.0: raise ValueError("Image appears to be floating data type but max value is above 1.0.") histogram = np.zeros(shape=(bins, first_image.shape[0], first_image.shape[1]), dtype=np.float32) last_background_image = None for i, im in enumerate(itertools.chain((first_image,), gen)): diff = 0.0 increase_histogram(histogram, im, is_float=is_float) if (not only_return_one) and i > 3: last_background_image = np.argmax(histogram, axis=0) yield last_background_image.astype(np.uint8) if not only_return_one: histogram *= smoothing if only_return_one: yield np.argmax(histogram, axis=0).astype(np.uint8) def make_background_video(image_generator, output_filename, mode_smoothing=0.95, median_steps=10, codec="XVID", fps=10.0): """Takes an image generator and creates and saves a background-subtracted video. Arguments: image_generator: generator Generator yielding grescale images as np.array with shape (H, W). output_filename: string Filename of the resulting video. Recommended file type: mp4. mode_smoothing: float Value in range (0, 1). Controls how fast the modal image adjusts to background changes. 1 = slowest adjustment. 0 = instant. median_steps: int One median image will be generated for every median_steps images. codec: string Fourcc codec to be passed to OpenCV. fps: float Replay speed of the output video. """ from prefetch_generator import BackgroundGenerator background_writer = None for image in BackgroundGenerator( generate_mode_images(generate_median_images( image_generator, N=median_steps), smoothing=mode_smoothing), 4): if image is None: return if background_writer is None: fourcc = cv2.VideoWriter_fourcc(*codec) background_writer = cv2.VideoWriter(output_filename, fourcc, fps, (image.shape[1],image.shape[0]), False) background_writer.write(image) def make_background_image(image_generator, output_filename=None, mode_smoothing=0.95, median_steps=10, use_threading=True): """Takes an image generator and creates and returns and optionally saves a background-subtracted image. Arguments: image_generator: generator Generator yielding grescale images as np.array with shape (H, W). The images should be dtype=float32 and the values should be between 0.0 and 1.0. output_filename: string Optional. Filename of the resulting image. mode_smoothing: float Value in range (0, 1). Controls how fast the modal image adjusts to background changes. 1 = slowest adjustment. 0 = instant. median_steps: int One median image will be generated for every median_steps images. use_threading: bool Default true. Whether to load the images and generate the median in a different thread. Returns: image: np.array(shape=(H, W), dtype=np.uint8) Greyscale background image. """ import imageio median_image_generator = generate_median_images(image_generator, N=median_steps) if use_threading: from prefetch_generator import BackgroundGenerator median_image_generator = BackgroundGenerator(median_image_generator, 6) image = list(generate_mode_images(median_image_generator, only_return_one=True, smoothing=mode_smoothing)) if image is None or len(image) == 0: return None image = image[0] # List should contain only one element. if output_filename is not None: imageio.imwrite(output_filename, image) return image
1d549c2f3ae68c869cf8b23bcbbba3244b360bfb
arijort/prep
/ctci/isunique.py
729
4.28125
4
#!/usr/bin/env python import unittest def isunique(s): """ Function to determine whether a given string has unique values. """ # 1 use a set to keep track, iterate st = set() for c in s: if c in st: return False else: st.add(c) return True class UniqueTest(unittest.TestCase): """ Test whether a given string contains unique values. No assumptions about sortedness of the string. https://github.com/careercup/CtCI-6th-Edition-Python/tree/master/Chapter1 """ def test_unique(self): s1 = 'asdfg' self.assertTrue(isunique(s1)) s2 = 'asdfiouasdfjkasdfg' self.assertFalse(isunique(s2)) s3 = '' self.assertTrue(isunique(s3)) if __name__ == '__main__': unittest.main()
afd8c6f155739c12ad00518c0d2c454dddfdd097
shukyp/Python-Lang
/oo_derived_class.py
5,790
3.5625
4
#=========================================================================== # BaseClass Module #=========================================================================== """ #BaseClass - Shows How a calss looks loke # # Author: Shuky Persky # """ from oo_base_class import * #=========================================================================== class DerivedClass_Triangle(BaseClass): _figure_index = 1 #class attribute @classmethod def _get_next_index(cls): idx = cls._figure_index; #use (local/derived) class attribute cls._figure_index += 1 return idx @staticmethod # inhrited by derived class and overrides the base class same method def _something (val): # and overrides the base class same mehod return (val * 44) #initializer (not a constructor) def __init__(self, base, height): self._cache = {} self._shape = "Triangle" self._width = base #length of triangle base self._length = height #triangle height self._local_index = DerivedClass_Triangle._get_next_index() # use (local/derived) class method self._glbl_index = self._get_next_shape_index() # The classmethod of the Base class is inherited # so it uses the BaseClass attribute def __call__ (self): '''Callable instance ''' if (self._local_index not in self._cache): id = self._local_index shape = self._shape self._cache[id] = shape return (id, shape) return None def __repr__ (self): return ('{obj.__class__.__name__}({obj._width}, {obj._length})'.format(obj=self)) def __str__(self): return ('{obj.__class__.__name__}: type:{obj._shape}, width={obj._width}, height={obj._length}'.format(obj=self)) def area(self): return (self._width * self._length / 2) #=========================================================================== class DerivedClass_Rectangular(BaseClass): _figure_index = 1 @classmethod #inhrited by derived class and overrides the base class same method def _get_next_index(cls): #may also be used as constrtors idx = cls._figure_index #use (local/derived) class attribute cls._figure_index += 1 return idx @staticmethod # inhrited by derived class def _something (val): # and overrides the base class same mehod return (val * 33) #initializer (not a constructor) def __init__(self, shape, width, length): self._cache = {} self._shape = shape self._width = width self._length = length self._local_index = DerivedClass_Rectangular._get_next_index() #use (local/derived) class method self._glbl_index = self._get_next_shape_index() # The classmethod of the Base class is inherited # so it uses the BaseClass attribute def __call__(self): '''Callable instance ''' if (self._local_index not in self._cache): id = self._local_index shape = self._shape self._cache[id] = shape return (id, shape) return None def clear(self): self._cache.clear() def __repr__(self): return '{obj.__class__.__name__}({obj._shape}, {obj._width}, {obj._length})'.format(obj=self) def __str__(self): return '{obj.__class__.__name__}: type:{obj._shape}, width={obj._width}, length={obj._length}'.format(obj=self) def area(self): return (self._width * self._length) #=========================================================================== def derived_class_mdl(): '''module entry point function :Args: None :return description ''' print ('\n\n ======== derived_class Module is Running ') #create triangle object & show info tri = DerivedClass_Triangle(10, 10) x = tri() # invokes __call__ if (x != None): print('\nid={obj[0]}, shape={obj[1]}'.format(obj=x)) tri.show_info() print(tri) # invokes __str__ #tri # from REPL invokes __repr__ print(f'{tri!s}') #invokes __str__ print(f'{tri!r}') #invokes __repr__ #create triangle object & show info rec_rec = DerivedClass_Rectangular('Rectangle', 12, 12) x = rec_rec() # invokes __call__ if (x != None): print('\nid={obj[0]}, shape={obj[1]}'.format(obj=x)) rec_rec.show_info() print(rec_rec) # invokes __str__ #rec_rec # from REPL invokes __repr__ print (f'{rec_rec!s}') # invokes __str__ print (f'{rec_rec!r}') # invokes __repr__ #create triangle object & show info rec_sq = DerivedClass_Rectangular('Square', 9, 9) x = rec_sq() # invokes __call__ if (x != None): print('\nid={obj[0]}, shape={obj[1]}'.format(obj=x)) rec_sq.show_info() print(rec_sq) # invokes __str__ #rec_sq # from REPL invokes __repr__ print (f'{rec_sq!s}') # invokes __str__ print (f'{rec_sq!r}') # invokes __repr__ print ('\n ----------- derived_class Module is Done >>>> ')
5288c0a123723effa90b80b32d9d1b53b08d8879
huffmp2/python
/ticketprompt.py
523
4.125
4
prompt= input("How old are you?") prompt = int(prompt) if prompt <= 3: print ("Your ticket is free!") elif prompt <= 12: print ("Your ticket is $10!") else: print ("Your ticket is $15!") while prompt < 12: prompt= input ("Children must be accompanied by an adult. Please enter your age.") prompt = int(prompt) if prompt <= 3: print ("Your ticket is free!") elif prompt <= 12: print ("Your ticket is $10!") else: print ("Your ticket is $15!")
25cf02674109d8553fa243d7e57af5ca7b6e6a4c
gustavoddainezi/Exercicios-URI-Online-Judge
/Python/1133.py
190
3.96875
4
# -*- coding: utf-8 -*- x = int(input()) y = int(input()) aux = x if x > y: x = y y = aux while(x < y): x += 1 if(x % 5 == 2 or x % 5 == 3 and x != y): print(x)
10eee9175b724f1666808915cbd3ae7035869ede
diceitoga/regularW3PythonExercise
/data_analytics_sentdex1.py
648
3.765625
4
#sentdex data analytics. import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt ''' simple line plot....you will be using pyplot all of the time. import matplotlib.pyplot as plt is always the convention ''' #plt.plot(x,y) when you plot, you plot [x,y] where both x =[] and y=[] with list of elements in each x and y to plot as coordinates. plt.plot([1,2,3],[5,7,4]) plt.show() ##the plot funciton will allow for plotting but will be running in the background. so you have to plt.show() to put it to display ######################## ''' when you are plotting you should have label, Legends and titles for graph
6b917e485dc27ed71ce91600675c1c2bb61dc13d
p-lots/codewars
/7-kyu/rearrange-number-to-get-its-maximum/python/solution.py
177
3.53125
4
def max_redigit(num): if not 99 < num < 1000: return None result = int(''.join(sorted(str(num), reverse=True))) return result if result >= num else None
096b96d557ccbdadb99c367e1553fcad66ff4fdd
deemcher/homework2
/date_and_time.py
1,234
4.53125
5
""" Домашнее задание №2 Дата и время * Напечатайте в консоль даты: вчера, сегодня, месяц назад * Превратите строку "01/01/17 12:10:03.234567" в объект datetime """ from datetime import date, datetime, timedelta def print_days(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ date_today = date.today() date_yesterday = date.today() - timedelta(days=1) date_month = date.today() - timedelta(days=30) print(date_today) print(date_yesterday) print(date_month) #return date_today, date_yesterday, date_month def str_2_datetime(): """ Эта функция вызывается автоматически при запуске скрипта в консоли В ней надо заменить pass на ваш код """ date_string = "01/01/17 12:10:03.234567" date_dt = datetime.strptime(date_string, "%d/%m/%y %H:%M:%S.%f") print(date_dt) if __name__ == "__main__": print_days() str_2_datetime()
5920eb6aa694fde56eb4a5cc1655547f624a451d
julianalvarezcaro/holbertonschool-higher_level_programming
/0x0A-python-inheritance/1-my_list.py
249
4.03125
4
#!/usr/bin/python3 """MyList class module""" class MyList(list): """ MyList class which inherits from list """ def print_sorted(self): """Prints a list in ascending order without altering it""" print(sorted(self))
c192177295a380d324e4822d27d4b2907f044900
joshcabral/FlexTracker
/database/row.py
2,696
3.875
4
class row: """A base row class for holding the information of a row before it is inserted, updated or deleted from a table. Each of these classes can be treated as a builder. A good way to create a row would be like this: r = users_row().set_user_id("_____").set_password("___") and so on. Each setting function will return self. Columns are stored in a dictionary keys by the column name. """ def __init__(self): """Initializes shared values between each row class.""" self.table = "" self.cols = {} self.id_name = "" def get_table(self): return self.table def get_columns(self): return self.cols def get_id_name(self): return self.id_name class users_row(row): """class for a users row.""" def __init__(self): row.__init__(self) self.table = "users" self.id_name = "user_id" def set_user_id(self, user_id): self.cols['user_id'] = user_id return self def set_password(self, password): self.cols['password'] = password return self def set_access_key(self, key): self.cols['key'] = key return self def set_email(self, email): self.cols['email'] = email return self def set_phone_number(self, phone_number): self.cols['phone_number'] = phone_number return self def set_preferences(self, preferences): self.cols['preferences'] = preferences return self class flex_info_row(row): """A class for a flex_info row.""" def __init__(self): row.__init__(self) self.table = "flex_info" self.id_name = "user_id" def set_user_id(self, user_id): self.cols['user_id'] = user_id return self def set_meal_plan(self, meal_plan): self.cols['meal_plan'] = meal_plan return self def set_current_flex(self, current_flex): self.cols['current_flex'] = current_flex return self class product_info_row(row): """class for a product_info row.""" def __init__(self): row.__init__(self) self.table = "product_info" self.id_name = "product_id" def set_product_id(self, product_id): self.cols['product_id'] = product_id return self def set_barcode(self, barcode): self.cols['barcode'] = barcode return self def set_name(self, name): self.cols['name'] = name return self def set_price(self, price): self.cols['price'] = price return self def set_location(self, location): self.cols['location'] = location return self
a8b3d60080604ec5c04e16e37138eb2ef10fa9ab
th3c0d3br34ker/File-Splitter
/fileSplitCore.py
2,192
3.8125
4
from traceback import print_exc from os import getcwd, remove, chdir, listdir, mkdir from os.path import basename def fileJoiner(folder): """ This function joins all the files in the input folder and outputs a single file. Args: folder: path of the folder which contains the splitted files. """ try: chdir(folder) print("Current directory : ", getcwd()) print("{} is selected.".format(folder)) files = [x for x in listdir()] print("\nFile to be joned : ") for i in files: print(i) fn = files[0] filename = fn.replace(fn[fn.index('_partfile_'):], '') with open(filename, 'wb') as main_file: for f in files: with open(f, 'rb') as part_file: file_obj = part_file.read() main_file.write(file_obj) remove(f) chdir("..") print("\nFiles joined to {} file.".format(filename)) except Exception: print("\nFailed!") print_exc() def fileSplitter(filename, size): """ This functions splits the input file into equal sizes of size size and outputs the files in a folder with '_partfile'. Args: filename: name of the file. size: size of each chunk. """ print("{} will be splitted.".format(basename(filename))) try: with open(filename, 'rb') as file: f = file.read(size) count = 0 foldername = basename(filename) foldername = foldername+"_partfile" mkdir(foldername) chdir(foldername) while(len(f) > 0): if(count < 10): fpart = '0'+str(count) else: fpart = str(count) with open(foldername+"_"+fpart, 'wb') as part: part.write(f) part.close() count += 1 f = file.read(size) file.close() print("\nFile Splitted to", foldername) except Exception: print("\nFailed!") print_exc()
08776a9a7d1a3edaade60ef2989758495c20cc02
Moly-malibu/cs-module-project-algorithms
/single_number/single_number.py
683
3.890625
4
''' Input: a List of integers where every int except one shows up twice Returns: an integer ''' def single_number(arr): no_dups = [] for x in arr: if x not in no_dups: no_dups.append(x) #add else: no_dups.remove(x) return no_dups[0] def single_number_best(nums): count = {} for num in nums: if num not in counts: count[num] = 1 else: counts[num] += 1 for key in count: if count[key] == 1: return key arr = [] if __name__ == '__main__': # Use the main function to test your implementation arr = [2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2] print(f"The odd-number-out is {single_number(arr)}")
e533f12a91a6bcbeac43c136174d419f6389ad43
neilshah101/daily-practise
/weekly_journal/week_1/day5/live class practise/bubble-sort.py
674
3.921875
4
numbers = [2,1,45,67,89,4,5,7,9,100] def bubble_sort_ascending(alist): for i in range(len(alist)-1 , 0 , -1): for j in range(i): if alist[j] >alist[j+1]: temp = alist[j] alist[j] = alist[j+1] alist[j+1] = temp return alist print (bubble_sort_ascending(numbers)) def bubble_sort_descending(alist): for i in range(len(alist)-1 , 0 , -1): for j in range(i): if alist[j] <alist[j+1]: temp = alist[j] alist[j] = alist[j+1] alist[j+1] = temp return alist print (bubble_sort_descending(numbers))
69ce3f8d06145c416737a163e7947bdc93c19a99
rheaganguli/stratagem
/level1.py
4,555
3.859375
4
import turtle import math import random import os import sys from game_constants import const wn = turtle.Screen() wn.bgcolor(const.COLOR_WHITE) wn.addshape("investigation.gif") wn.update() wn.setup(const.DIM_1000,const.DIM_1000) wn.tracer(0) questions = [] CURR_NUMB = 0 Y_OFFSET = 0 SPACE = 24 instructionsShown = False def filled_rectangle(t, l, w): t.begin_fill() for i in range(2): t.right(90) t.forward(l) t.right(90) t.forward(w) t.end_fill() #covers previous question in order to paste new one over it class cleanCoverup(turtle.Turtle): def __init__(self, x, y): turtle.Turtle.__init__(self) self.shape(const.SHAPE_SQUARE) self.color(const.COLOR_WHITE) self.penup() self.goto(x, y) def destroy(self): self.goto(const.DIM_2000, const.DIM_2000) self.hideturtle() class picTurt(turtle.Turtle): def __init__(self, x, y): turtle.Turtle.__init__(self) self.y = y self.x = x self.shape("investigation.gif") self.penup() self.goto(self.x, self.y) self.speed(0) #Function which draws on the text that is displayed during the program class textTurt(turtle.Turtle): def __init__(self, text, x, y): turtle.Turtle.__init__(self) self.y = y self.x = x self.text = text self.penup() self.goto(self.x, self.y) self.color(const.COLOR_BLACK) self.speed(0) for i in range(len(const.LEVEL1_QUESTIONS)): quest = const.LEVEL1_QUESTIONS[i] question = textTurt(quest, const.POS_MIN_150, const.POS_MIN_320) questions.append(question) def printToPlayer(textTurtle): print("printToPlayer") cover = cleanCoverup(const.POS_500, const.POS_MIN_210) filled_rectangle(cover, const.DIM_1000, const.DIM_1000) textTurtle.write(textTurtle.text, move=False, align=const.LEFT, font=(const.FONT, 16, const.TEXT_TYPE)) def showInstructions(): print("moveToNext") textTurtle = textTurt(const.LEVEL1_INSTRUCTIONS, const.POS_MIN_350, const.POS_MIN_150) printToPlayer(textTurtle) instructionsShown = True def LoadQuestions(): cover = cleanCoverup(const.POS_500, const.POS_500) filled_rectangle(cover, const.DIM_1000,const.DIM_1000) pic = picTurt(const.POS_0, const.POS_0) wn.update() askQuestion(CURR_NUMB) def showPubInfo(): textTurtle = textTurt(const.PUB_INFO, const.POS_MIN_490, const.POS_350) printToPlayer(textTurtle) showPubInfo() def checkForAnswer(questionNumber): answer = turtle.textinput("Enter Your Answer Here: ", "Answer Question Number " + str(CURR_NUMB+1) + " Here") if answer == None: return False userInput = answer.lower() if questionNumber == 0: if userInput == "c": print(userInput) return True else: return False elif questionNumber == 1: if userInput == "b": print(userInput) return True else: return False elif questionNumber == 2: if userInput == "b": print(userInput) return True else: return False elif questionNumber == 3: if userInput == "a": print(userInput) return True else: return False elif questionNumber == 4: if userInput == "c": print(userInput) return True else: return False elif questionNumber == 5: if userInput == "c": print(userInput) return True else: return False elif questionNumber == 6: if userInput == "b": print(userInput) return True else: return False def askQuestion(numb): global CURR_NUMB printToPlayer(questions[numb]) correct = checkForAnswer(numb) if numb > 5: const.CURRENT_LEVEL = const.CURRENT_LEVEL + 1 if correct: textTurtle = textTurt("Excellent Work", const.POS_MIN_150, const.POS_MIN_350) printToPlayer(textTurtle) numb = numb + 1 CURR_NUMB = CURR_NUMB + 1 askQuestion(numb) else: textTurtle = textTurt("You're definitely going to jail", const.POS_MIN_150, const.POS_MIN_350) printToPlayer(textTurtle) sys.exit("Player Lost") showInstructions() turtle.listen() turtle.onkey(LoadQuestions, const.KEY_RIGHT) turtle.mainloop()
814eac6f47fe61928c585589f7de698b5aa8159a
MacHu-GWU/rolex-project
/tests/test_std_datetime_flaw.py
1,347
3.5625
4
# -*- coding: utf-8 -*- """ Limitation of standard datetime library. **中文文档** - 在Python27中, datetime类没有实现 ``datetime.timestamp()`` 方法 - 在Python3中, 对于1970年之前的时间无法获得timestamp - 在Python3中, datetime.fromtimestamp(timestamp) 不支持负值 """ from __future__ import print_function from datetime import datetime, date def datetime_timestamp_method_not_implemented_in_python2(): try: dt = datetime(2014, 1, 1) print(dt.timestamp()) except Exception as e: print("datetime.timestamp() is not implemented in Python2; %s" % e) def datetime_timestamp_not_support_datetime_before_1970_01_01_in_python3(): try: dt = datetime(1900, 1, 1) print(dt.timestamp()) except Exception as e: print( "datetime.timestamp() doesn't support datetime before 1970-01-01; %s" % e) def datetime_fromtimestamp_not_support_negative_value(): try: dt = datetime.fromtimestamp(-1) print(dt) except Exception as e: print("datetime.fromtimestamp() doesn't support negative value; %s" % e) if __name__ == "__main__": datetime_timestamp_method_not_implemented_in_python2() datetime_timestamp_not_support_datetime_before_1970_01_01_in_python3() datetime_fromtimestamp_not_support_negative_value()
0a4313082e817159e85e477efa2ac2556a5f8984
calebl37/tic-tac-toe-python
/tic-tac-toe-simulator.py
2,190
4
4
board=[] import math import random def print_board(sidelength): row = '' for i in range(0,(sidelength*sidelength)): row += "| " + board[i] + " " if (i+1) % sidelength == 0: print("+---"*sidelength + "+") print(row + "|") row = '' print("+---"*sidelength + "+") def check_win(player,sidelength): for j in range(0,sidelength): #0,1,2...sidelength - 1 win_vert = True win_horiz = True win_diag1 = True win_diag2 = True for i in range(0,len(board)): if i % sidelength == j: #vertical check column j if board[i] == player and win_vert: win_vert = True else: win_vert = False if i >= sidelength*j and i < sidelength*(j+1): #horizontal check row j if board[i] == player and win_horiz: win_horiz = True else: win_horiz = False if i % (sidelength+1) == 0: #diagonal 1 check #print(i) if board[i] == player and win_diag1: win_diag1= True else: win_diag1 = False if i % (sidelength - 1) == 0 and i > 0 and i < (len(board)-sidelength+1): #diagonal 2 check #print(i) if board[i] == player and win_diag2: win_diag2 = True else: win_diag2 = False return (win_vert or win_horiz or win_diag1 or win_diag2) def initialize_sim(): global board size = int(input("What is the side length of the tic tac toe board?")) board = [""]*size*size half = (size*size)/2 num_x = 0 num_o = 0 for i in range(0,len(board)): player = random.randint(1,2) if player == 1: if num_x < math.ceil(half): board[i] = "x" num_x +=1 else: board[i] = "o" num_o +=1 else: if num_o < math.floor(half): board[i] = "o" num_o +=1 else: board[i] = "x" num_x +=1 print_board(size) print("x winner: " + str(check_win("x",size))) print("o winner: " + str(check_win("o",size))) again = input("Sim again? (y/n)") if again == "y": initialize_sim() initialize_sim()
0cdcceb766d3f864bf89fe5cac2e4c76e91e655c
bksahu/dsa
/dsa/patterns/binary_search/rotation_count.py
1,026
3.8125
4
""" Given an array of numbers which is sorted in ascending order and is rotated ‘k’ times around a pivot, find ‘k’. You can assume that the array does not have any duplicates. Input: [10, 15, 1, 3, 8] Output: 2 Explanation: The array has been rotated 2 times. Input: [4, 5, 7, 9, 10, -1, 2] Output: 5 Explanation: The array has been rotated 5 times. Input: [1, 3, 8, 10] Output: 0 Explanation: The array has been not been rotated. """ def rotation_count(nums): left, right = 0, len(nums)-1 while left <= right: mid = left + (right - left)//2 if mid < right and nums[mid] > nums[mid+1]: return mid+1 if mid > left and nums[mid-1] > nums[mid]: return mid if nums[left] < nums[mid]: left = mid + 1 else: right = mid - 1 return 0 # not rotated if __name__ == "__main__": print(rotation_count([10, 15, 1, 3, 8])) print(rotation_count([4, 5, 7, 9, 10, -1, 2])) print(rotation_count([1, 3, 8, 10]))
f44b41800b324da9cfb47544a2d84f5634ba739c
Jose0Cicero1Ribeiro0Junior/Curso_em_Videos
/Python_3/Modulo 2/3_Repetições em Python (while)/Exercício_064_Tratando_vários_valores_v1.0_v1.py
568
4
4
#Exercício Python 64: Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag). núm = cont = soma = 0 núm = int(input('Digite um número [999 para parar': )) while núm != 999: soma += núm cont += 1 núm = int(input('Digite um número [999 para parar': )) print('Você digitou {} números e a soma entre eles foi {}.'.format(cont, soma))
f27a459b02f64f1dce5157dbefe219ff5dc0cc3a
Vivekagent47/HackerRank
/Problem Solving/40.py
586
3.5
4
#!/bin/python3 import math import os import random import re import sys # Complete the kaprekarNumbers function below. def kaprekarNumbers(p, q): result = [] for i in range(p, q + 1): x = str(int(pow(i, 2))) l = x[0:int(len(x) / 2)] if x[0:int(len(x) / 2)] else 0 r = x[int(len(x) / 2):len(x)] if x[int(len(x) / 2):len(x)] else 0 if(int(l) + int(r) == i): result.append(str(i)) print(' '.join(result) if len(result) > 0 else 'INVALID RANGE') if __name__ == '__main__': p = int(input()) q = int(input()) kaprekarNumbers(p, q)
6ad5172e4f82e192d75b5921c1901fd7b0d66990
KurinchiMalar/DataStructures
/Sorting/BubbleSortOrig.py
1,113
3.6875
4
def swap(Ar,x,y): temp = Ar[x] Ar[x] = Ar[y] Ar[y] = temp return Ar def do_bubblesort(Ar): #O(n*n) count = 0; for i in range(0,len(Ar)): for k in range(len(Ar)-1,i,-1): #if k == 0: #when k = 0 ; Ar[0] and Ar[-1] will be compared # break if Ar[k] < Ar[k-1]: count = count+1 print(str(count)+":"+"swap("+str(k)+","+str(k-1)+")") Ar = swap(Ar,k,k-1) return Ar # swapped is never made to zero. Buggy here!! Don't see this. O(n) def do_bubblesort_improved(Ar): swapped = 222222 count = 0 for i in range(0,len(Ar)): if swapped == 0: break for k in range(len(Ar)-1,i,-1): if k == 0: break elif Ar[k] < Ar[k-1]: count += 1 print(str(count)+":"+"swap("+str(k)+","+str(k-1)+")") Ar = swap(Ar,k,k-1) swapped = 1 return Ar A = [2,1,3,4,5] print(do_bubblesort(A)) A = [2,1,3,4,5] print("========================") print(do_bubblesort_improved(A))
92ce4da5ccfd4bb5492ec4115538abb13a504992
GINK03/yukicoder-solvers
/0841.py
183
3.84375
4
s1, s2 = input().split() if len([x for x in [s1, s2] if x in {'Sat', 'Sun'}]) == 2: print('8/33') elif len({s1} & {'Sat', 'Sun'}) == 1: print('8/32') else: print('8/31')
2a7fb47c3ff3894d743789692304be8413e0ff62
slabykonrad/basis-of-writing-scripts
/task8_v2.py
551
3.734375
4
#!/usr/bin/python3 def chooseElementsByCriterium(stud_list,kryterium): listOfStudents=[] for item in stud_list: if float(item["grade"]) == float(kryterium) : listOfStudents.append(item) return listOfStudents def readFromFile(name): studentList=[] with open(name) as fin: for line in fin: line=line.split() student = {'student': {'name':line[0],'surname':line[1]} ,'grade':line[2]} studentList.append(student) return studentList list = chooseElementsByCriterium(readFromFile("task8_file.txt"),3.5) for tmp in list: print(tmp)
25c3ca3c1c65e30c86974644efb173dcbe3338a8
JoshMez/Python_Intro
/Functions/Default_Values.py
777
3.75
4
#When you write a function you can assign a default value to a parameter. # # #Dont think of think of the default value of being set in stone. #It will only be used when you have not see anything else. ############################################################ # def Charecter(charecters, studio='Marvel' ): """Seeing my fav charecter.""" print(f"Studio type: {studio}") print(f"Charecter: {charecters}") #Changing the default agurment #Notice how the default variable has not been used. Charecter(studio='DC', charecters='Batman') ############################################################### # #Avoiding errors. #Sometimes you may have errors on in your functions. # #Soemtimes you can provide more or less arugments than the functions needs. #But you ne
871ae0fafa18d35475676f2ea2e25cbdae4c3dac
jasonphx1/python_courses
/ProgramWiz_Tutorials/calendar_display/display_calendar.py
166
3.75
4
#!/usr/bin/env python3 #URL: https://www.programiz.com/python-programming/examples/display-calendar import calendar yy = 2014 mm = 11 print(calendar.month(yy, mm))
c94fc4c14e2c387cbe74a68a2930275d5746747e
Haker3310/domashka
/2020/December/12.12.2020/_1.py
717
3.734375
4
import random class Stack: def __init__(self): self._stack = [] def push(self, x): self._stack.append(x) def pop(self): try: return self._stack.pop(0) except IndexError: return "Очередь пуста." def peek(self): try: return self._stack[self.count() - 1] except IndexError: return "Очередь пуста." def count(self): return len(self._stack) someStack = Stack() for i in range(random.randint(5, 20)): someStack.push(random.randint(0, 100)) for i in range(someStack.count()): print(someStack.pop(), end='\nЭтот человек сейчас первый : ')
2ffd1e40ca982e6247860af85e7363fbc6d1d8d7
sujasriman/guvi
/code/prog4.py
107
3.875
4
a=input() b=ord(a) if((b>=97 and b<=122) or (b>=65 and b<=90)): print("Alphabet") else: print("No")
33ee772b20cd5c7491d1f45c2cc0f797de006cb3
stevalang/Data-Science-Lessons
/Pandas/pandas_group_challenge.py
1,358
4.1875
4
import pandas as pd import numpy as np grocery = pd.DataFrame({'category':['produce', 'produce', 'meat', 'meat', 'meat', 'cheese', 'cheese'], 'item':['celery', 'apple', 'ham', 'turkey', 'lamb', 'cheddar', 'brie'], 'price':[.99, .49, 1.89, 4.34, 9.50, 6.25, 8.0]}) grouped_grocery = grocery.groupby('category') # for name, category in grouped_grocery: # print(name) # print(category) # grouped_grocery.filter(lambda x: x < 3) a = grouped_grocery.filter(lambda x: x.mean() < 3) one_mean = a.drop(a, axis=1) two_max = grouped_grocery.max() # grouped_grocery['new_price'].transform(lambda x: x * .9 if grouped_grocery['category'].max() > 3) three_round = grocery['price'].transform(lambda x: x*.9 if x > 3 else x) ''' Perform the following operations using split-apply-combine. Remove all items in categories where the mean price in that category is less than $3.00. Find the maximum values in each category for all features. (What does Pandas take to be the maximum value of the 'item' column?) If the maximum price in a category is more than $3.00, reduce all prices in that category by 10%. Return a Series of the new price column. ''' print('\n') print(one_mean) print('\n') print(two_max) print('\n') print(three_round)
6fb6689d4a03122d6013f244fe7647d307042091
amberno1111/Data_Structure_and_Algorithm
/LeetCode/Python/Add_Strings.py
897
3.890625
4
# Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. # Note: # 1. The length of both num1 and num2 is < 5100 # 2. Both num1 and num2 contains only digits 0-9 # 3. Both num1 and num2 does not contain any leading zero # 4. You must not use any built-in Biginteger library or convert the inputs to integer directly. class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ result, carry, val = '', 0, 0 for i in range(max(len(num1), len(num2))): if i < len(num1): val += int(num1[-i - 1]) if i < len(num2): val += int(num2[-i - 1]) result += str(val % 10) val //= 10 if val != 0: result += str(val) return result[::-1]
53e85eb6f62e975ecc8d16df928439b4c3d1701b
Vincent105/python
/04_The_Path_of_Python/11_function/0113_filter.py
265
3.734375
4
def oddfn(x): return x if (x % 2 == 1) else None mylist = [5, 10, 15, 20, 25, 30] ''' filter_object = filter(oddfn, mylist) oddlist = [item for item in filter_object] print(oddlist) ''' oddlist = list(filter(lambda x: ( x % 2 == 1), mylist)) print(oddlist)
7a0907e119535fea487f0fffbf6283a9826e5ed5
nickest14/Leetcode-python
/python/medium/Solution_19.py
795
3.953125
4
# 19. Remove Nth Node From End of List from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(0, head) left = dummy right = head while n > 0: right = right.next n -= 1 while right: left = left.next right = right.next # delete node left.next = left.next.next return dummy.next root = ListNode(1) root.next = ListNode(2) root.next.next = ListNode(3) root.next.next.next = ListNode(4) ans = Solution().removeNthFromEnd(root, 2) print(ans)
aca83edb832a20f2c62db41f2c0bcc47b0f79cea
Roberto1987/ml_for_trading
/test/test_scipy_optimizer.py
685
3.515625
4
import scipy.optimize as opt import numpy as np import matplotlib.pyplot as plt import pandas as p def f(X): Y = (X - 1.5)**2 + 0.5 print('X = {}, Y = {}'.format(X, Y)) return Y def test_run(): Xguess = 0.0 min_result = opt.minimize(f, Xguess, method='SLSQP', options={'disp': True}) print("Minima found at:") print('X = {}, Y = {}'.format(min_result.x, min_result.fun)) # Plot function values, mark minima Xplot = np.linspace(0.5, 2.5, 21) Yplot = f(Xplot) plt.plot(Xplot,Yplot) plt.plot(min_result.x, min_result.fun, 'ro') plt.title('Minima of an objective function') plt.show() test_run()
5b882487a563eed6ad631dd117bc721aa595fd94
Djusk8/CodeWars
/8 kyu/Convert a Boolean to a String.py
633
4.28125
4
# ------------ KATA DESCRIPTION ------------ """ https://www.codewars.com/kata/551b4501ac0447318f0009cd 8 kyu - Convert a Boolean to a String Implement a function which convert the given boolean value into its string representation. """ # --------------- SOLUTION --------------- import codewars_test as test boolean_to_string = lambda x: str(x) # --------------- TEST CASES --------------- @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(boolean_to_string(True), "True") test.assert_equals(boolean_to_string(False), "False")
c3ef38fcbe37d3c8512f2d510d26ec6b1b4a0779
nsshayan/Python
/Learning/Network_process_WA/Day1/july24/requests/weather_report.py
1,308
3.9375
4
""" A simple program to fetch weather report for a city (defaults to 'Bengaluru') using OpenWeatherMap API """ API_KEY = "932c152d6ff8d185bfdd9d2a5f8e33e4" BASE_URL = "http://api.openweathermap.org/data/2.5/weather" Output = """ Location: {} Description: {} Current temperature: {}\u00B0 Celsius Minimum temperature: {}\u00B0 Celsius Maximum temperature: {}\u00B0 Celsius Sunrise at: {} Sunset at: {} """ def get_weather_report(location): import requests QUERY_STRING = f"?q={location}&units=metric&APPID={API_KEY}" URL = BASE_URL + QUERY_STRING response = requests.get(URL) if response.ok: result = response.json() return Output.format( location, result["weather"][0]["description"].capitalize(), result["main"]["temp"], result["main"]["temp_min"], result["main"]["temp_max"], result["sys"]["sunrise"], result["sys"]["sunset"] ) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument( "location", nargs='?', const="Bengaluru", help="get weather report for a location") args = parser.parse_args() results = get_weather_report(args.location)
16ac6e5969d58e267ffc2815b787e12a86d10f74
VinuthnaGummadi/Python
/PhytonProject/Assignment1/Source/Lab1/Assignment1/RectanglePerimeter.py
1,007
4.53125
5
# This program displays the perimeter of a rectangle #Take input from user length = input("Enter Length:") breadth = input("Enter Breadth:") perimeter = 0 # Check if entered values are not null if(length!="" and breadth!=""): # Exception if entered value if not int. # This block is executed when the entered number is Integer try: length=int(length) breadth=int(breadth) perimeter = 2*(length + breadth) print("Perimeter of Rectangle is:"+str(perimeter)) except ValueError: pass # Exception if entered value if not float # This block is executed if the entered number is not an Integer and is Float value try: length=float(length) breadth = float(breadth) perimeter = round(2*(length + breadth),2) print("Perimeter of Rectangle is:" + str(perimeter)) except ValueError: print("Enter Integer or Float value.") else: print("Enter Integer or Float value.")
0e9ce365b22995f54b0ed4656e38d7f1dd5d8f99
michaelwayman/python-genetic
/genetic/evolvable.py
2,248
4.3125
4
from abc import ABCMeta, abstractmethod class Evolvable(object): """Abstract Base Class to create "evolvable" objects An `Evolvable` represents an object that has a specific set of "genes" and "alleles". A "gene" represents a broader idea, like "hair color", whereas an "allele" is a particular mutation of the hair color gene, giving us: blondes, brunettes, etc. An `Evolvable`s value to us, is that in its complete state, represents a solution to a particular problem. The idea of the Evolvable class is that multiple instances can be combined to create new Evolvables. """ __metaclass__ = ABCMeta def __init__(self, genes): """ Args: genes: list of the genes that each `Evolvable` must have Note: - Subclasses of this ABC should call super on this method. - `_cache` and `cache_attrs` are for performance optimizations. """ self.genes = {gene: None for gene in genes} # Once an instance of `Evolvable` is complete and not going to change, the `Evolve` class # will set `cache_attrs` to True. We can make use of this for better performance. self.cache_attrs = False self._cache = {} @abstractmethod def can_survive(self): """ Returns: A boolean whether or not this `Evolvable` can survive in the wild. """ raise NotImplemented @abstractmethod def fitness_level(self): """ Returns: some sort of number that summarizes how desirable this `Evolvable` genes are. (The bigger the better) """ raise NotImplemented def unique(self): """ Note: Depending on what your genes look like you might want override this method for something more efficient Returns: some hashable that can uniquely identify the particular sequence of genes (to avoid creating duplicates) """ if self.cache_attrs: if 'unique' not in self._cache: self._cache['unique'] = str(sorted(self.genes.items())) return self._cache['unique'] return str(sorted(self.genes.items()))
81927bb8b58c77813454e32aa6cc7d02de90e9ff
jamesljeffrey1995/DevOpsPython
/Challengeoftheday/countVowels.py
183
3.640625
4
def countVowelsCalc(word): vowels = "aeiou" count = 0 for i in range(len(word)): for e in range(len(vowels)): if vowels[e] == word[i].lower(): count += 1 return count
0f6eb066777d946bfc24c9ad49a1550f82ab0ade
taras193/pythonhomework
/homework_06_05_2019_task_2.py
442
3.71875
4
#1 multiplying # a="7271" # first_digit=int(a[:1]) # second_digit=int(a[1:-2]) # third_digit=int(a[2:-1]) # four_digit=int(a[3:]) # multiplying=first_digit*second_digit*third_digit*four_digit # print (multiplying) # #2 reverse # a_reversed=a[::-1] # print (a_reversed) #3 sorting # list=[first_digit,second_digit,third_digit,four_digit] # newList = sorted(list) # newList.sort() # print (newList) txt = "Hello my FRIENDS" x = txt.lower() print(x)
cd50e5778232127dbe8dc47e36f2b3ea66002c48
raadxrahman/CSE423-COMPUTER-GRAPHICS
/Theory/MidpointLineAlgorithm.py
735
4.1875
4
#Midpoint Line Algorithm def midpointline(x0,y0,x1,y1): dx = x1 - x0 dy = y1 - y0 d_init = (2*dy) - dx d = d_init while x0!=x1 and y0!= y1: print(x0,y0) if d > 0: x0 += 1 y0 += 1 d += 2*(dy - dx) else: x0 += 1 d += 2*dy print(x0,y0) def slope(x0,y0,x1,y1): slope_m = (y1-y0)/(x1-x0) print("Slope = " + str(slope_m)) if 0 < slope_m < 1: midpointline(x0,y0,x1,y1) else: print("Slope not within 0 and 1") if __name__ == '__main__': x0 = int(input("Enter x0: ")) y0 = int(input("Enter y0: ")) x1 = int(input("Enter x1: ")) y1 = int(input("Enter y1: ")) slope(x0,y0,x1,y1)
2452f2ac0ccceb1cdb02880202bb70918eba9f03
dumalang/python-cheatsheet
/1.5.classes.py
622
3.921875
4
class myClass(): def method1(self): print("myClass method 1") def method2(self, someString): print("myClass method 2 " + someString) def method3(self, someString=""): print("myClass method 3 " + someString) class childClass(myClass): def method1(self): myClass.method1(self) print("myClass method 1") def method2(self, someString): print("myClass method 2 ") def main(): c = myClass() c.method1() c.method2("wkwk") c.method3() print("=" * 10) d = childClass() d.method1() d.method2("wkwk") d.method3() main()
e129f04af242760693543ecb5aae02755e03afe4
SteveChristian70/Projects
/MortgageCalc.py
1,374
4.3125
4
#Mortgage calculator with additional payments # ask for loan amount amount = int(input("Please enter the loan amount you are seeking without a comma: " )) # annual percent interest percInterest = float(input("What percent interest rate will the loan be at? " )) # calculating monthly interest rate monthlyInterest = percInterest/(100 * 12) # give length of mortgage length = float(input("How many years will the mortgage be for? " )) # calculate total number of payments paymentNum = length * 12 monthlyPayment = amount * ( monthlyInterest / (1 - (1 + monthlyInterest) ** (- paymentNum))) print "Total loan = $%0.2f" % amount print "Interest = %0.2f%s" % (percInterest, "%") print "Years = %0.f" % length print "Number of payments = %0.f" % paymentNum print "Payment amount = $%0.2f" % monthlyPayment print "-"*50 print "Total cost = $%0.2f" % (paymentNum * monthlyPayment) print "Total interest = $%0.2f" % (paymentNum * monthlyPayment - amount) #print "-"*50 # payments made so far #payments = int(input("How many payments have you made so far? " )) #remainingAmount = amount * (1 - ((1 + monthlyInterest) ** payments - 1) / ((1 + monthlyInterest) ** paymentNum - 1)) #print "The outstanding principal after %d payments is $%0.2f" % (payments, remainingAmount) #print "At this point you have paid a total of $%0.2f" % (monthlyPayment * payments)
3b2ad85b9bd9cf1a37948c8b939756924a7f1085
sashank-kasinadhuni/CodeEvalSolutions
/Easy_Lowest_Unique.py
748
3.578125
4
import argparse def Lowest_Unique(): parser = argparse.ArgumentParser() parser.add_argument("filename") args = parser.parse_args() with open(args.filename) as f: for line in f: line = line.rstrip('\n') line = [int(i) for i in line.split()] counts = dict() for i in line: if i in counts: counts[i] += 1 else : counts[i] = 1 print(counts) min_Idx = -1 for idx in range(0,len(line)): if (counts[line[idx]] == 1): if(min_Idx == -1): min_Idx = idx else: min_Idx = min_Idx if line[min_Idx]<line[idx] else idx print(min_Idx+1) Lowest_Unique()
e2df98b9183f8cd028a563fdcee6ead253e6f67e
orel1108/hackerrank
/practice/algorithms/implementation/the_grid_search/the_grid_search.py
959
3.65625
4
#!/bin/python def contains(grid, pattern, row, col): for ROW in range(len(pattern)): for COL in range(len(pattern[0])): x = ROW + row y = COL + col if (x >= len(grid)) or (y >= len(grid[0])): return False if grid[x][y] != pattern[ROW][COL]: return False return True t = int(raw_input().strip()) for _ in range(t): R, C = map(int, raw_input().strip().split()) grid = [] for __ in range(R): grid.append(str(raw_input().strip())) r, c = map(int, raw_input().strip().split()) pattern = [] for __ in range(r): pattern.append(str(raw_input().strip())) ans = False for ROW in range(R): for COL in range(C): if contains(grid, pattern, ROW, COL): ans = True break if ans: break if ans: print "YES" else: print "NO"
d62ecfc1e4168f6f706cf8bd26d998314e3a48e1
Tmk10/exercism.io
/secret-handshake/secret_handshake.py
1,115
3.5
4
def handshake(code): result = [] secret = {0: "wink", 1: "double blink", 2: "close your eyes", 3: "jump"} # mapping gestures to positions in string position = list(enumerate(bin(code)[-1:1:-1])) # cutting "0b" and enumerate bin numbers with place in string for flag in position: if flag[0] == 4 and flag[1] == "1": # checking if list reverse is needed result.reverse() break else: # adding gesture to list if current flag is set to 1 result.append(secret[flag[0]]) if flag[1] == "1" else None return result def secret_code(actions): result = ["0", "0", "0", "0"] secret = {"wink": 0, "double blink": 1, "close your eyes": 2, "jump": 3, } # mapping gestures to positions in string for item in actions: result[secret[item]] = "1" result.reverse() # checking order of flags, if bigger flag value appear before smaller, the list is reversed if len(actioons) > 1 and secret[actions[0]] > secret[actions[1]]: result.insert(0, "1") return int("".join(result), 2)
32c905b111ced7765fa029a09b62dc51e0a2c24c
v1v3k/DecisionTree
/tree_r.py
7,803
3.59375
4
import pandas as pd import math import sys import numpy as np # <codecell> import sys data_file_loc, = sys.argv[1:] # This piece of code reads the csv file as a table data_set = pd.DataFrame.from_csv(data_file_loc, sep='\t') data_set.reset_index(inplace=True) # <codecell> # Create three sets of columns, integer, float and categorical integer_columns = ['age', 'duration', 'campaign', 'pdays', 'previous', 'nr_employed'] float_columns = ['emp_var_rate', 'cons_price_idx', 'cons_conf_idf', 'euribor3m'] data_set[integer_columns] = data_set[integer_columns].astype(int) data_set[float_columns] = data_set[float_columns].astype(float) all_columns = set(data_set.columns) integer_columns_set = set(integer_columns) float_columns_set = set(float_columns) categorical_columns_set = all_columns.difference(integer_columns_set).difference(float_columns_set) categorical_columns_set.remove('target') # <codecell> # Find the distinct values of all categorical features categorical_column_distinct_values_map = {} for column in categorical_columns_set: distinct_values = data_set[column].unique() categorical_column_distinct_values_map[column] = distinct_values # <codecell> # The following piece of code calculates entropy given a set of data over a given feature and feature value def entropy(data_set, feature, feature_value, greater=True): if feature in categorical_columns_set: reduced_data_set = data_set[data_set[feature] == feature_value] else: if greater: reduced_data_set = data_set[data_set[feature] > feature_value] else: reduced_data_set = data_set[data_set[feature] <= feature_value] if len(reduced_data_set) == 0: return sys.maxint total_count = len(reduced_data_set) yes_data = reduced_data_set[reduced_data_set['target'] == 'yes'] yes_count = len(yes_data) no_count = total_count - yes_count yes_pi = yes_count * 1.0 /total_count no_pi = no_count * 1.0/total_count yes_entropy = 0.0 no_entropy = 0.0 if yes_count != 0: yes_entropy = -yes_pi * math.log(yes_pi, 2) if no_count != 0: no_entropy = - no_pi * math.log(no_pi, 2) entropy = yes_entropy + no_entropy return entropy # <codecell> # This peice of code selects a feature that minimizes entropy on the given data set def select_feature(data_set, features_not_allowed_set): if len(data_set) == 0: print "ERROR: The length of dataset passed to select_feature was zero" # First try out the categorical features min_entropy_thus_far = sys.maxint # Now select from numerical features. We shall use the median to split for feature in integer_columns_set.union(float_columns_set): if feature not in features_not_allowed_set: feature_entropy = 0.0 split_value = data_set[feature].median() feature_entropy += entropy(data_set, feature, split_value, greater=False) feature_entropy += entropy(data_set, feature, split_value, greater=True) if feature_entropy < min_entropy_thus_far: min_entropy_thus_far = feature_entropy selected_feature = feature return selected_feature # <codecell> class DecisionTreeNode: def __init__(self, data_set= None, selected_feature= None, split_value=None): self.data_set = data_set self.selected_feature = selected_feature # Split value field is only for numerical features self.split_value = split_value self.children = {} def major_label(data_set): yes_count = len(data_set[data_set['target'] == 'yes']) no_count = len(data_set) - yes_count if yes_count > no_count: return "yes" return "no" def classify(root_node, data_row): if root_node is None: return None if len(root_node.children) == 0: # If this node has no children then we shall compute the label # by counting the majority label at this node's data return major_label(root_node.data_set) else: # Check which node to go to based on current node's selected feature selected_feature_this_node = root_node.selected_feature if selected_feature_this_node in categorical_columns_set: data_row_value_on_selected_feature = data_row[selected_feature_this_node] if not root_node.children.has_key(data_row_value_on_selected_feature): return major_label(root_node.data_set) next_node = root_node.children[data_row_value_on_selected_feature] return classify(next_node, data_row) else: if data_row[selected_feature_this_node] <= root_node.split_value: if not root_node.children.has_key("<="): return major_label(root_node.data_set) next_node = root_node.children["<="] return classify(next_node, data_row) else: if not root_node.children.has_key("<="): return major_label(root_node.data_set) next_node = root_node.children[">"] return classify(next_node, data_row) # Should never reach here print "Error: Reached impossible case in classify" return None # <codecell> # This piece of code builds a decision tree def build_tree(tree, previously_selected_features): #print "Length of dataset", len(tree.data_set) # If the length of the data becomes too small stop if len(tree.data_set) < 1000: #print "Returning since dataset length has become less than 10" return tree # If all the labels are the same in the dataset stop yes_count = len(tree.data_set[tree.data_set['target'] == 'yes']) if len(tree.data_set) == yes_count or yes_count == 0: #print "Returnign since all are yeses or no's" return tree # If none of the base conditions batch we shall further split the tree # Select the best feature to split the tree on best_feature = select_feature(tree.data_set, previously_selected_features) if best_feature is None: return tree #print "Selected best feature ", best_feature tree.selected_feature = best_feature # Add children nodes to this tree for all non zero branches of the best feature # Case 1 : Best feature is categorical (categorically good I tell you) if best_feature in categorical_columns_set: distinct_values = categorical_column_distinct_values_map[best_feature] for value in distinct_values: #print "Creating subtree for value", value data_subset = tree.data_set[tree.data_set[best_feature] == value] if len(data_subset) != 0: child_node = DecisionTreeNode(data_set = data_subset) tree.children[value] = build_tree(child_node, previously_selected_features + [best_feature]) # Case 2: Best feature if numerical (If it wasnt categorically good, atleast its numerically good) else: tree.split_value = tree.data_set[best_feature].median() #print "Split value is ", split_value data_subset_lesser = tree.data_set[tree.data_set[best_feature] <= tree.split_value] data_subset_greater = tree.data_set[tree.data_set[best_feature] > tree.split_value] child_node_lesser = DecisionTreeNode(data_set = data_subset_lesser) child_node_greater = DecisionTreeNode(data_set = data_subset_greater) tree.children["<="] = build_tree(child_node_lesser, previously_selected_features + [best_feature]) tree.children[">"] = build_tree(child_node_greater, previously_selected_features + [best_feature]) return tree # <codecell> decision_tree = None def get_prediction(df_row): return classify(decision_tree, df_row) # <codecell>
461fe2de6f91d53a02bf642e3a3d23847551a051
el-mat/ectools
/algorithm.py
1,205
3.984375
4
import sys def binarySearch(inlist, cmp_func, first=0, last=None): '''Returns index of first item that cmp_func returns 0. None if can't be found cmp_func is < 0 if the value you are looking for is less than what is passed to cmp_func by this function. > 0 if it is more, 0 if equal. ''' last = len(inlist)-1 if not last else last if last < first: return None mid = (last + first) / 2 d = cmp_func(inlist[mid]) if d < 0: last = mid - 1 elif d > 0: first = mid + 1 else: return mid return binarySearch(inlist, cmp_func, first, last) def expandRegion(inlist, cmp_func, start=0): '''Expands a region in a list based on cmp_func While cmp_func returns true keep adding to region returns a tuple (first,last) for boundaries of the region ''' if not cmp_func(inlist[start]): return None first = start last = start while first > 0: if not cmp_func(inlist[first-1]): break first -= 1 ll = len(inlist) while last < (ll-1): if not cmp_func(inlist[last+1]): break last += 1 return (first,last)
2aefec1431dfbfd2f8be2646ce6c415da9139001
nberger62/python-udemy-bootcamp
/Built_In_Functions/filter.py
462
3.90625
4
#filter : Returns filter objects which can be converted into other iterables #The object contains only the values that return true to the lambda #evens = list(filter(lambda x: x % 2 == , 1)) #evens # 2, 4 #using filters and maps [user for user in users if not user["tweets"]] usernames = list(map(lambda user: user["username"].upper(), filter(lambda u: not u['tweets'], users)) def remove_negatives(nums): return list(filter(lambda l: l >= 0, nums))
3bd13e62b56fb06c8b710b33e5c85b6e31c40d2a
zxpgo/Python
/069test.py
404
3.5625
4
from tkinter import * root = Tk() text= Text(root, width=30, height=30) text.pack() text.insert(INSERT,"I Love\n") text.insert(END, 'Fish.com!') #插入按钮 #插入图片 photo = PhotoImage(file="bg.gif") def show(): text.image_create(END,image=photo) b1 = Button(text, text='点我点我', command=show) text.window_create(INSERT, window=b1) mainloop()
92d3852c59b4d161c7373507bdc64d5f028f8d99
elsandkls/SNHU_IT140_itty_bitties
/dynamic.py
592
3.5625
4
# Get our arguments from the command line import sys A= int(sys.argv[1]) B= int(sys.argv[2]) # Write your code below myList = [] myString = "" # We pass in 2 numbers, A and B. # You should create a list with A rows and B columns. # You should then populate each cell like this # R0C0, R0C1, R0C2 etc. for i in range(0,A,1): myList.append([]) for x in range(0,B,1): myList[i].append("") i = 0 x = 0 for i in range(0,A,1): print(i) for x in range(0,B,1): myList[i][x] = "R" + str(i) + "C" + str(x) print(i,x,myList[i][x]) print(myList)
49381ec0ae62ca673bcb977b7cde9e8ee421afa4
ramalho/propython
/fundamentos/execucao.py
1,103
3.578125
4
import sys import atexit print '-> 1 inicio' def funcaoA(): print '-> 6 funcao A' return 'resultado A' def funcaoB(): print '-> 8 funcao B' def funcaoC(): print '-> 11 funcao C' return funcaoC funcaoD = lambda:sys.stdout.write('-> 12 funcao D\n') def funcaoE(): print '-> 13 funcao E' print 'FIM' class Classe(object): print '-> 2 bloco de declaracoes da Classe' def __init__(self): print '-> 9 inicializacao da instancia da Classe' def metodo(self): print '-> 10 metodo da instancia da Classe' return 'resultado metodo' if True: print '-> 3 condicional True' if False: assert False, 'Isso nunca devia acontecer' atexit.register(funcaoE) print '-> 4 logo antes do if __main__' if __name__=='__main__': print '-> 5 __main__' print funcaoA print funcaoA() print '-> 7 __main__ (cont.)' print funcaoB resultadoB = funcaoB() print resultadoB objeto = Classe() objeto.metodo() resultadoB() print funcaoD funcaoD()
8023eeb5fdc2cefdd2a9c75cffe5a95c8a3a62fc
Kirktopode/Python-Homework
/LearnProgram3.0.py
203
3.53125
4
def birthday(child): print "Happy birthday to you, happy birthday to you, happy birthday, dear", child + ", happy birthday to you!" person = raw_input("Who is the birthday child? ") birthday(person)
1c088281b1968db3b11d3d68a23597282bdb0a9a
roberg11/is-206-2013
/Assignment 2/ex14.py
1,053
4.03125
4
from sys import argv script, user_name, country = argv prompt = 'Ummm... ' print "Hi %s, I'm the %s script, and I will take you to %s." % (user_name, script, country) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) print "Where do you live %s" % user_name lives = raw_input(prompt) print "So %s is in %s" % (lives, country) print "What kind of computer do you have?" computer = raw_input(prompt) print """ Allright, so you said %r about liking me. You live in %r. Not sure where that is, but I'm sure it's in %r. And you have a %r computer. Nice. """ % (likes, lives, country, computer) #### Study drills # Find out what Zork and Adventure were. Try to find a copy and play it. # Change the prompt variable to something else entirely. # Answer: Changed to 'Umm...' # Add another argument and use it in your script. # Answer: added country to the argument # Make sure you understand how I combined a """ style # multiline string with the % format activator as the last print.
d982313da041492dff6375549996a795cc910d32
alexander-colaneri/python
/studies/curso_em_video/ex009-tabuada.py
1,497
4.28125
4
# Nº 9 - Tabuada # Descrição: Faça um programa que leia um número Inteiro qualquer e mostre na tela a # sua tabuada. class CalculadoraDeTabuada(): '''Calcula um número indicado pelo usuário multiplicado de 1 a 10.''' def __init__(self): self.numero = 0 self.resultados = [] def iniciar(self): '''Função inicial do programa.''' print(f'{" CALCULADORA DE TABUADA ":*^40}') self.receber_numero() self.calcular_tabuada() self.mostrar_resultados() print('\nTenha um bom dia!') def receber_numero(self): '''Recebe número indicado pelo usuário para cálculo de tabuada.''' print('Indique o número que deseja calcular a tabuada:') while True: try: self.numero = int(input()) break except ValueError: print('Digite um número inteiro, sem espaços ou letras.') def calcular_tabuada(self): '''Calcula a tabuada de um número indicado pelo usuário.''' for i in range(1, 11): self.resultados.append(self.numero * i) # Resultados armazenados em uma lista. return None def mostrar_resultados(self): '''Exibe os cálculos e resultados.''' print('-' * 20) for i in range(1, 11): print(f'{self.numero} X {i : >2} = {self.resultados[i - 1]}') print('-' * 20) return None tabuada = CalculadoraDeTabuada() tabuada.iniciar()
b80ad2a23f283f13c94e85d16c363748dbf173d3
kenwoov/PlayLeetCode
/Algorithms/Medium/1574. Shortest Subarray to be Removed to Make Array Sorted/answer.py
622
3.5
4
from typing import List class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: N = len(arr) j = N - 1 while j > 0 and arr[j-1] <= arr[j]: j -= 1 if j == 0: return 0 res = j for i in range(N): if i > 0 and arr[i-1] > arr[i]: break while j < N and arr[i] > arr[j]: j += 1 res = min(res, j - i - 1) return res if __name__ == "__main__": s = Solution() result = s.findLengthOfShortestSubarray([1, 2, 3, 10, 4, 2, 3, 5]) print(result)
5526347bc49ea232d34d2dffbdcb8596479f891f
stevalang/Coding-Lessons
/SoftUni/Python Developmen/Python-Fundamentals/06_OOP/demo.py
686
3.71875
4
class Animal: def __init__(self, command, name, food_limit, location): self.name = name self.food_limit = food_limit self.location = location self.command = command def feed(self): pass animals = [] # Add:Bonie:3490:RiverArea print(animal.name) print(animal.location) print(animal.food_limit) while True: line = input() if line == "Last Info": break animals = [] command, name, daily_limit, location = input().split(':') if command == 'Add': animals.append(name) Animal(name).food_limit += daily_limit else: pass animal = Animal(command, name, food_limit, location)
a30eea690236389d1f7f9d3f531c395e7af6f005
happyssun96/baekjoon
/배열/4344_평균은넘겠지.py
277
3.78125
4
N = int(input()) for _ in range(N): scores = list(map(int, input().split())) avg = sum(scores[1:]) / scores[0] count = 0 for i in scores[1:]: if i > avg: count += 1 percent = (count / scores[0]) * 100 print('%.3f' %percent + '%')
2ed3be2792812023d6a59ec88fbb29bf3e6ad5d4
Programmer-Admin/binarysearch-editorials
/Level Order Traversal.py
440
3.859375
4
""" Level Order Traversal Simplest form of breadth-first search. Use a double-ended queue to do popleft() in constant time. """ from collections import deque class Solution: def solve(self, root): ans=[] q=deque([root]) while q: node = q.popleft() ans.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) return ans
5700c74126ecd0f198960c9a6c0315a6e28fe5ed
zzz686970/leetcode-2018
/744_nextGreatestLetter.py
700
3.609375
4
def nextGreatestLetter(letters, target): if not letters: return '' for letter in letters: if letter > target: return letter return letters[0] def nextGreatestLetter(letters, target): l, r = 0, len(letters) while l < r: mid = (l + r) // 2 if letters[mid] > target: r = mid elif letters[mid] <= target: l = mid + 1 return letters[l%len(letters)] assert "c" == nextGreatestLetter(["c", "f", "j"], 'a') assert "f" == nextGreatestLetter(["c", "f", "j"], 'c') assert "f" == nextGreatestLetter(["c", "f", "j"], 'd') assert "j" == nextGreatestLetter(["c", "f", "j"], 'g') assert "c" == nextGreatestLetter(["c", "f", "j"], 'j') assert "c" == nextGreatestLetter(["c", "f", "j"], 'k')
7fff49761051d9ad84bae2b16bdd8987d1c59c33
aelzeiny/WhenItRains
/sprites/apple.py
1,086
3.71875
4
import pygame from sprites.anim import Animation WIDTH = 32 HEIGHT = 32 class Apple(pygame.sprite.Sprite): def __init__(self, x, y): super().__init__() self.x = x self.y = y self.animation = self._load_anim() def update(self, dt: float): """ This function is called everytime 1/60th of a second passes. We should use this chance to make changes to the apple's position. :param dt elapsed in milliseconds """ self.animation.update(dt) # TODO(@JB): HUH, THE APPLE ISN'T FALLING. # PROBABILY BECAUSE WE DON'T CHANGE THE 'Y' VALUE def draw(self, display: pygame.Surface): img, offset_x = self.animation.render(WIDTH, HEIGHT, False) display.blit(img, (self.x + offset_x, self.y)) def _load_anim(self) -> Animation: apple_anim = Animation(24, should_loop=True) for i in range(2, 49): apple_file_name = 'apple-rotating-' + str(i) + '.png' apple_anim.add_frame('./apple/' + apple_file_name) return apple_anim
5b08942f3d98150706fda1d3ace5ed36291e713f
nguyenngochuy91/companyQuestions
/facebook/phoneScreen/cleanRoom.py
4,622
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 20 11:48:03 2019 @author: huyn """ #489. Robot Room Cleaner #Given a robot cleaner in a room modeled as a grid. # #Each cell in the grid can be empty or blocked. # #The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees. # #When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell. # #Design an algorithm to clean the entire room using only the 4 given APIs shown below. """ This is the robot's control interface. You should not implement it, or speculate about its implementation """ class Robot: def __init__(self,matrix,current,index=3):# facing up as initial self.matrix = matrix self.current = current self.directions = [(0,1),(1,0),(0,-1),(-1,0)] # + means we turning right self.index = index def move(self): """ Returns true if the cell in front is open and robot moves into the cell. Returns false if the cell in front is blocked and robot stays in the current cell. :rtype bool """ addX,addY = self.directions[self.index] x,y = self.current X,Y = x+addX,y+addY if X>=0 and Y>=0 and X<len(self.matrix) and Y<len(self.matrix[0]): if self.matrix[X][Y]!=0: self.current = X,Y return True return False def turnLeft(self): """ Robot will stay in the same cell after calling turnLeft/turnRight. Each turn will be 90 degrees. :rtype void """ if self.index==0: self.index= 3 else: self.index-=1 def turnRight(self): """ Robot will stay in the same cell after calling turnLeft/turnRight. Each turn will be 90 degrees. :rtype void """ if self.index==3: self.index= 0 else: self.index+=1 def clean(self): """ Clean the current cell. :rtype void """ x,y = self.current self.matrix[x][y]="X" # the clean wont know this #room = [ # [1,1,1,1,1,0,1,1], # [1,1,1,1,1,0,1,1], # [1,0,1,1,1,1,1,1], # [0,0,0,1,0,0,0,0], # [1,1,1,1,1,1,1,1] #] #robot =Robot(room,[1,3]) #print (robot.current) #print (robot.move()) #print (robot.current) #robot.turnLeft() #print (robot.move()) #print (robot.current) #robot.turnRight() #print (robot.move()) #print (robot.current) #robot.turnLeft() #print (robot.move()) #print (robot.current) #robot.turnLeft() #print (robot.move()) #print (robot.current) def cleanRoom(robot:Robot): """ :type robot: Robot :rtype: None """ visited= set() visited.add((0,0)) # we clean the current cell robot.clean() directions = [(0,1),(1,0),(0,-1),(-1,0)] currentIndex = 3 def proceed(currentCell,currentIndex): x,y = currentCell if robot.move(): # compute the cell cordinate addX,addY = directions[currentIndex] # check if this cell already fully visited X,Y = x+addX,y+addY newCell = (X,Y) # print ("newCell",newCell) if (X,Y) not in visited: # we clean this tile robot.clean() dfs(newCell,currentIndex) # after dfs, we have to go back ward for the robot # we turn left twice and move robot.turnLeft() robot.turnLeft() robot.move() robot.turnLeft() robot.turnLeft() # now we are back to our currentCell for our robot and with the same direction # print (127,currentCell) # this is dfs, basically where we will traverse, keep track,clean the room def dfs(currentCell,currentIndex): # we check all 4 cell around currentCell # we will try to move away from our position 3 times # move forward visited.add(currentCell) x,y = currentCell # print (133,currentCell,robot.current) for i in range(4): proceed(currentCell,currentIndex) currentIndex= (currentIndex+1)%4 # print (137,currentCell,robot.current) robot.turnRight() # if i==1: # break dfs((0,0),currentIndex) print (robot.matrix) #room =[[1,1,1],[1,1,1],[1,1,1]] room = [ [1,1,1,1,1,0,1,1], [1,1,1,1,1,0,1,1], [1,0,1,1,1,1,1,1], [0,0,0,1,0,0,0,0], [1,1,1,1,1,1,1,1] ] robot =Robot(room,[2,2]) cleanRoom(robot)
ffe524518f6b27828767c8e0f4da7bf6d29acf18
janeon/automatedLabHelper
/testFiles/primes/primes37.py
775
3.90625
4
def main() : print() n=eval(input("How many prime numbers would you like? ")) print() i=1 PRIME_CNT=0 TWIN=0 def isPrime(x) : i=1 if x<=1 : return False elif x==2 : return True else : while i<x-1 : i=i+1 if x%i==0 : return False return True print("The first", n, "primes are:") while n > PRIME_CNT : i=i+1 j=i-2 if isPrime(i)==True : print(i, end=" ") PRIME_CNT=PRIME_CNT+1 if isPrime(j) : TWIN=TWIN+1 print() print("Amongst these there are", TWIN, "twin primes.") print() main()