blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7b89c6de806c4e915e3426cdcbbbe24e3d831854
SoenMC/Programacion
/Ejercicio9.py
283
3.984375
4
##Realizar un programa que solicite ingresar dos números distintos y muestre por pantalla el mayor de ellos. num1=int(input("Ingrese el primer valor ")) num2=int(input("Ingrese el segundo valor ")) print("El valor mayor es ") if num1>num2: print(num1) else: print(num2)
69d8acfd6f631a9ce5d778c2c4c0be083dc3ca82
dwhitena/corporate-training
/10-week/week1/lesson3/example1/main.py
8,124
3.5625
4
from math import sqrt import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import statsmodels.api as sm from sklearn import linear_model import torch from torch.autograd import Variable def squared_error(prediction, observation): """ Calculates the squared error. Args: prediction - the prediction from our linear regression model observation - the observed data point Returns: The squared error """ return (observation - prediction) ** 2 def ols_fit(x, y): """ Calculates the intercept and slope parameters using OLS for a linear regression model. Args: x - feature array y - response array Returns: The intercept and slope parameters """ # calculate the mean of x and y mean_x = np.mean(x) mean_y = np.mean(y) # Using the derived OLS formula to calculate # the intercept and slope. numerator = 0 denominator = 0 for i in range(len(x)): numerator += (x[i] - mean_x) * (y[i] - mean_y) denominator += (x[i] - mean_x) ** 2 slope = numerator / denominator intercept= mean_y - (slope * mean_x) return intercept, slope def sgd_fit(x, y, learning_rate, epochs): """ Calculates the intercept and slope parameters using SGD for a linear regression model. Args: x - feature array y - response array learning_rate - learning rate epochs - the number of epochs to use in the SGD loop Returns: The intercept and slope parameters and the sum of squared error for the last epoch """ # initialize the slope and intercept slope = 0.0 intercept = 0.0 # set the number of observations in the data N = float(len(y)) # loop over the number of epochs for i in range(epochs): # calculate our current predictions predictions = (slope * x) + intercept # calculate the sum of squared errors for this epoch error = sum([data**2 for data in (y-predictions)]) / N # calculate the gradients for the slope and intercept slope_gradient = -(2/N) * sum(x * (y - predictions)) intercept_gradient = -(2/N) * sum(y - predictions) # update the slope and intercept slope = slope - (learning_rate * slope_gradient) intercept = intercept - (learning_rate * intercept_gradient) return intercept, slope, error def sm_ols_fit(x, y): """ Calculates the intercept and slope parameters using OLS for a linear regression model, with statsmodels. Args: x - feature array y - response array Returns: The intercept and slope parameters """ # add a constant column to the x values which # represents the intercept x = sm.add_constant(x) # define the OLS model model = sm.OLS(y, x) # train the model results = model.fit() return results.params[0], results.params[1] def sklearn_ols_fit(x, y): """ Calculates the intercept and slope parameters using OLS for a linear regression model, with scikit-learn. Args: x - feature array y - response array Returns: The intercept and slope parameters """ # define the model lr = linear_model.LinearRegression() # train the model lr.fit(x[:, np.newaxis], y) return lr.intercept_, lr.coef_[0] def sklearn_sgd_fit(x, y): """ Calculates the intercept and slope parameters using SGD for a linear regression model, with scikit-learn. Args: x - feature array y - response array Returns: The intercept and slope parameters """ # define the model lr = linear_model.SGDRegressor(max_iter=1000) # traing the model lr.fit(x[:, np.newaxis], y) return lr.intercept_[0], lr.coef_[0] class PyTorchLRModel(torch.nn.Module): def __init__(self, input_dim, output_dim): # call class constructor super(PyTorchLRModel, self).__init__() # use the nn package to create a linear layer self.linear = torch.nn.Linear(input_dim, output_dim) def forward(self, x): # Define the "forward" pass of this model. Think of this # for now as just the method that takes data input and # passes this through the model to create output (i.e., a prediction). out = self.linear(x) return out def pytorch_sgd_fit(x, y, learning_rate, epochs): """ Calculates the intercept and slope parameters using SGD for a linear regression model, with pytorch. Args: x - feature array y - response array learning_rate - learning rate used in SGD epochs - number of epochs for the SGD loop Returns: The intercept and slope parameters """ # create the model using only one "node", which will # correspond to our single linear regression model input_dimension = 1 output_dimension = 1 # define the model model = PyTorchLRModel(input_dimension, output_dimension) # our error/loss function criterion = torch.nn.MSELoss() # define our SGD optimizer optimiser = torch.optim.SGD(model.parameters(), lr = learning_rate) # loop over our epochs, similar to our previous implementation for epoch in range(epochs): # increment the epoch count epoch +=1 # define our feature and response variables features = Variable(torch.from_numpy(x[:, np.newaxis]).float()) response = Variable(torch.from_numpy(y[:, np.newaxis]).float()) #clear the gradients optimiser.zero_grad() # calculate the predicted values predictions = model.forward(features) # calculate our loss loss = criterion(predictions, response) # implement our gradient-based updates to our # parammeters (putting them "back" into the model # via a "backward" update) loss.backward() optimiser.step() # extract the model parameters to return params = [] for param in model.parameters(): params.append(param.data[0]) return params[1].item(), params[0][0].item() def main(): # import the data data = pd.read_csv('../data/Advertising.csv') # scale the feature and response scaler = MinMaxScaler() data_scaled = scaler.fit_transform(data[['TV', 'Sales']]) # fit our model using our various implementations int_ols, slope_ols = ols_fit(data_scaled[:, 0], data_scaled[:, 1]) int_sgd, slope_sgd, _ = sgd_fit(data_scaled[:, 0], data_scaled[:, 1], 0.1, 1000) int_sm_ols, slope_sm_ols = sm_ols_fit(data_scaled[:, 0], data_scaled[:, 1]) int_sk_ols, slope_sk_ols = sklearn_ols_fit(data_scaled[:, 0], data_scaled[:, 1]) int_sk_sgd, slope_sk_sgd = sklearn_sgd_fit(data_scaled[:, 0], data_scaled[:, 1]) int_pt_sgd, slope_pt_sgd = pytorch_sgd_fit(data_scaled[:, 0], data_scaled[:, 1], 0.1, 1000) # output the results delim = "-----------------------------------------------------------------" print("\nOLS\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_ols, slope=slope_ols)) print("\nSGD\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_sgd, slope=slope_sgd)) print("\nstatsmodels OLS\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_sm_ols, slope=slope_sm_ols)) print("\nsklearn OLS\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_sk_ols, slope=slope_sk_ols)) print("\nsklearn SGD\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_sk_sgd, slope=slope_sk_sgd)) print("\npytorch SGD\n{delim}\n intercept: {intercept}, slope: {slope}" .format(delim=delim, intercept=int_pt_sgd, slope=slope_pt_sgd)) if __name__ == "__main__": main()
bae410bd7e1f82f1ea72fece670db39c9df53708
helloworld-push/python-start
/test53.py
244
3.53125
4
string = str(input()) k = string.find('f') string2 = string[-1::-1] if string.find('f') == -1: print() elif string.find('f', k + 1) == -1: print(string.find('f')) else: print(string.find('f'), (len(string) - 1 - string2.find('f')))
1a7c48054418adef604c72fa24c62904e6a41525
Oli-4ction/pythonprojects
/dectobinconv.py
556
4.15625
4
"""************************* Decimal to binary converter *************************""" #function def function(): #intialize variables number = 0 intermediateResult = 0 remainder = [] number = int(input("Enter your decimal number: ")) base = int(input("Choose the number format: ")) #loops while number != 0: remainder.append(number % base) number = number // base remainder.reverse() for result in remainder: print(result, end = "") #output function()
7a436252377593128ac3dc1748ecc6f67a912b49
SeanPlusPlus/ProjectEuler
/051-100/055_lychrel.py
673
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time # https://projecteuler.net/problem=55 def is_palindrome(n): if n == flip(n): return True return False def flip(n): return int(str(n)[::-1]) def lychrel(n, iterations=0): if iterations == 50: return False x = n + flip(n) if not is_palindrome(x): iterations += 1 return lychrel(x, iterations) return True def main(): i = 0 for n in range(10001): if not lychrel(n): i += 1 print i if __name__ == "__main__": start_time = time.time() main() print("--- %s seconds ---" % "%.2f" % (time.time() - start_time) )
61a1c1869bac27b2cf437bdcbb1b5fb0df4b7757
dawtrey/ma314
/MergeSort.py
757
4.125
4
def Merge(left, right): leftIndex, rightIndex = 0, 0 result = [] while leftIndex < len(left) and rightIndex < len(right): if left[leftIndex] < right[rightIndex]: result.append(left[leftIndex]) leftIndex += 1 else: result.append(right[rightIndex]) rightIndex += 1 result += left[leftIndex:] result += right[rightIndex:] return result def MergeSort(A): # base case, list of length 1 is sorted if len(A) <= 1: return A # divide list in half and sort recursively m = len(A) // 2 left = MergeSort(A[:m]) right = MergeSort(A[m:]) return Merge(left, right) A = [6,4,3,8,1,5,2,7] print(MergeSort(A))
ee7e93a06b3a41e2a2c249bb47ef9100767b380a
Najurk/python-stuff
/ex16.py
208
3.890625
4
# Read a string: a= (input()) # Print a string: print (a[2]) #1 print(a.strip()[-2]) #2 print (a[:5]) #3 print (a[:-2]) #4 print(a[::2]) #5 print(a[1::2]) #6 print(a[::-1]) #7 print(a[::-2]) print(len(a))
895520e400808db084c6574956c11b22ae19c917
mariohinojosa/Python-John-Zelle-book
/Chapter_6/4.py
367
3.875
4
def main(): number = int(raw_input("Enter the number")) sum1 = sumN(number) sum2 = sumNcubes(number) print "The sum of the numbers is", sum1 print "The sum of the cubes of the numbers is", sum2 def sumN(n): sum = 0 for i in range(1,n+1): sum = sum + i return sum def sumNcubes(n): sum = 0 for i in range(1,n+1): sum = sum + (i*i*i) return sum main()
62f8a5e2f0f6d1c9ae821240e661f976005e778c
fgolemo/mcdp
/src/mcdp_maps/repr_map.py
2,306
3.5
4
# -*- coding: utf-8 -*- def repr_map_invmultvalue(letter, c_space, c_value): c = c_space.format(c_value) return "%s ⟼ %s / (%s)" % (letter, letter, c) def repr_map_multvalue(letter, space, value): c = ' %s' % space.format(value) return '%s ⟼ %s × %s' % (letter, letter, c) def repr_map_invmultdual(letter, value, space): return repr_map_multvalue(letter, value, space) def repr_map_joinn(letter, n): elements = get_string_list_of_elements(letter, n) start = "⟨" +", ".join(elements) + "⟩" transformed = " ∧ ".join(elements) return '%s ⟼ %s' % (start, transformed) def repr_map_meetn(letter, n): elements = get_string_list_of_elements(letter, n) transformed = " ∨ ".join(elements) start = get_string_vector(letter, n) return '%s ⟼ %s' % (start, transformed) def get_string_vector(letter, n): """ Returns ⟨r₁, ..., rₙ⟩ """ elements = get_string_list_of_elements(letter, n) start = "⟨" +", ".join(elements) + "⟩" return start def get_string_list_of_elements(letter, n): """ Returns ["r1", "r2", ...] """ def sub(i): # indices = list("₁₂₃₄₅₆₇₈₉") # ₀ indices = [str(_+1) for _ in range(n)] if i >= len(indices): return '%d' % i return indices[i] elements = [letter + sub(i) for i in range(n)] return elements def repr_map_product(letter, n): start = get_string_vector(letter, n) elements = get_string_list_of_elements(letter, n) transformed = "⋅".join(elements) return "%s ⟼ %s" % (start, transformed) def plusvaluedualmap_repr(letter, space, value): c = space.format(value) return '%s ⟼ %s - %s if %s ≽ %s, else ø' % (letter, letter, c, letter, c) def plusvaluemap_repr(letter, space, value): label = '+ %s' % space.format(value) return '%s ⟼ %s %s' % (letter, letter, label) def minusvaluemap_repr(letter, space, value): label = '- %s' % space.format(value) return '%s ⟼ %s %s' % (letter, letter, label) def sumn_repr_map(letter, n): start = get_string_vector(letter, n) elements = get_string_list_of_elements(letter, n) transformed = " + ".join(elements) return "%s ⟼ %s" % (start, transformed)
34e35ba98aa80cdb922aef510c2cdad742242307
SaeSimcheon/employee_or_farm
/Chapter4/5. 회의실 배정/DH.py
1,163
3.5625
4
''' 회의실 배정(그리디) : 그리디 문제는 정렬과 같다라고 함. 1. 같은 시간에 시작하면 끝나는 시점이 빠른 회의 선택 >> 2번에서 sort하기 때문에 할 필요 없나?(그렇네) 2. 회의 끝나는 시점,시작 시점으로 Sort 3. 시작하는 시점이 빠르면 선택 sort 함수도 key = lambda 가능하네? sort vs sorted 1. sort : list 만 가능 sorted : 모든 iterable에 가능 (list,tuple,dic,문자열) 2. sort 원본 리스트 순서 변환 sorted 원본 영향 없음 3. sort가 새로운 복사본을 만들지 않아 좀더 빠름. ''' import sys #sys.stdin = open("in3.txt","r") ''' n = 5 arr = [[1,4],[2,3],[3,5],[4,6],[5,7]] ''' n = int(input()) dic = dict() for i in range(n): k,v = map(int,input().split()) if k not in dic.keys(): dic[k] = v else: if dic[k] > v: dic[k] = v arr = [] for k,v in dic.items(): arr.append([k,v]) arr = sorted(arr, key = lambda x:(x[1],x[0])) x = -1 ans = 0 for i in arr: if i[0] >= x: x = i[1] ans += 1 print(ans) ''' '''
086544b7c2645a388f8a1cb7c54c29aedc00ca49
460314244/corepython
/chapter6/6-14.py
732
4.1875
4
import random while True: dict1={'scissons':2,'fist':3,'colth':1} for i in dict1: print i,dict1[i] people1=int(raw_input('Please input a number between 1-3:')) people2=random.randint(1,3) print 'PC input a number between 1-3 : ',people2 iswin=people1-people2 if iswin==1 or iswin==-1: a=max(people1,people2) if people1==a: print 'You Win!!!' else: print 'You are SB!!' elif iswin==0: print 'You are double SB!!!' else : a=min(people1,people2) if people1==a: print 'You Win!!' else: print 'You are SB!!' print '----------------------------------------------------------'
890f0851dd3ac1bc7a6aad8c580f47bf2dbf85d0
nlandy/AdventofCode2020
/day1/day1_problem2.py
698
3.5
4
from collections import defaultdict with open('input_day1.txt') as f: array = [int(line) for line in f] def twosum(target, array): pair_dict = defaultdict(lambda : -1) pair = [] for i in range(len(array)): if(pair_dict[array[i]] != -1): pair = [array[pair_dict[array[i]]], array[i]] break else: pair_dict[target - array[i]] = i return pair three_sum_target = 2020 for i in range(len(array)): two_sum_target = 2020 - array[i] pair = twosum(two_sum_target, array[:i] + array[i+1:]) if pair: trio = pair + [array[i]] break code = trio[0] * trio[1] * trio[2] print('The code is {}.'.format(code))
b267fd041fa7455343e30bab48eb35bf9d1565be
hyperac1d/Web-Python-Exercises
/countme.py
2,749
3.671875
4
print("Enter as many words as you can in the word BREAKER") breaker = ['ark', 'eke', 'err', 'era', 'bee', 'rare', 'reek', 'bake', 'bark', 'bare', 'beer', 'beak', 'bear', 'baker', 'brake', 'break', 'barker', 'beaker', 'bearer', 'breaker', 'are', 'ear', 'ere', 'bar', 'bra', 'rake', 'rear'] count = 0 #for x in breaker: # word = str(input("Word: ")) # if(word.lower() in breaker): # count = count +1 word1 = str(input("Word: ")) if (word1.lower() in breaker): count = count+1 word2 = str(input("Word: ")) if (word2.lower() in breaker): count = count+1 word3 = str(input("Word: ")) if (word3.lower() in breaker): count = count+1 word4 = str(input("Word: ")) if (word4.lower() in breaker): count = count+1 word5 = str(input("Word: ")) if (word5.lower() in breaker): count = count+1 word6= str(input("Word: ")) if (word6.lower() in breaker): count = count+1 word7 = str(input("Word: ")) if (word7.lower() in breaker): count = count+1 word8 = str(input("Word: ")) if (word8.lower() in breaker): count = count+1 word9 = str(input("Word: ")) if (word9.lower() in breaker): count = count+1 word10 = str(input("Word: ")) if (word10.lower() in breaker): count = count+1 word11= str(input("Word: ")) if (word11.lower() in breaker): count = count+1 word12 = str(input("Word: ")) if (word12.lower() in breaker): count = count+1 word13 = str(input("Word: ")) if (word13.lower() in breaker): count = count+1 word14 = str(input("Word: ")) if (word14.lower() in breaker): count = count+1 word15 = str(input("Word: ")) if (word15.lower() in breaker): count = count+1 word16 = str(input("Word: ")) if (word16.lower() in breaker): count = count+1 word17 = str(input("Word: ")) if (word17.lower() in breaker): count = count+1 word18 = str(input("Word: ")) if (word18.lower() in breaker): count = count+1 word19 = str(input("Word: ")) if (word19.lower() in breaker): count = count+1 word20 = str(input("Word: ")) if (word20.lower() in breaker): count = count+1 word21 = str(input("Word: ")) if (word21.lower() in breaker): count = count+1 word22 = str(input("Word: ")) if (word22.lower() in breaker): count = count+1 word23 = str(input("Word: ")) if (word23.lower() in breaker): count = count+1 word24 = str(input("Word: ")) if (word24.lower() in breaker): count = count+1 word25 = str(input("Word: ")) if (word25.lower() in breaker): count = count+1 word26 = str(input("Word: ")) if (word26.lower() in breaker): count = count+1 word27 = str(input("Word: ")) if (word27.lower() in breaker): count = count+1 print('You got', count,' number of words in the word BREAKER')
626b545e7818c2113bb90cb328d98507fee0011e
Soengmou/usfEP
/usfEP/euler_pole.py
1,543
3.515625
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 21:12:02 2015 Euler_pole Utilities for calculating Euler Pole @author: rNick Voss """ import matplotlib.pylab as plt from mpl_toolkits.basemap import Basemap class pole: ''' attributes: location velocity angular velocity components model ' modeled velocities' uncertianty info: optional string desribing pole ''' def __init__(self,location,velocity,angularvelocity,model,uncertainty = None,info = None): self.location = location self.velocity = velocity self.ang_vel = angularvelocity self.uncertianty = uncertainty self.info = info self.model = model def plot(self): ''' plot the pole on a map ''' # set up orthographic map projection with # perspective of satellite looking down at 50N, 100W. # use low resolution coastlines. map = Basemap(projection='ortho',lat_0=self.location[1],lon_0=self.location[0],resolution='l') # draw coastlines, country boundaries, fill continents. map.drawcoastlines(linewidth=0.25) map.drawcountries(linewidth=0.25) map.fillcontinents(color='coral',lake_color='aqua') # draw the edge of the map projection region (the projection limb) map.drawmapboundary(fill_color='aqua') # draw lat/lon grid lines every 30 degrees map.scatter(self.location[0],self.location[1],latlon = True,marker = '*',s = 20) plt.show()
1e993de38724f8dfc91414a94ca54e57f5dff6b5
kubenetic/szoszmosz-tree
/christmas_tree.py
1,461
3.71875
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import random TREE_HEIGHT = 40 BOUGH_REDUCING = 4 tree = list() def get_block(placeholder = ' '): global TREE_HEIGHT return [placeholder] * (TREE_HEIGHT * 2 + 2) def draw_tree(): global tree global TREE_HEIGHT global BOUGH_REDUCING l = TREE_HEIGHT r = TREE_HEIGHT + 1 for num in range(TREE_HEIGHT, 0, -1): bough = get_block() bough[l] = '/' bough[r] = '\\' if (num + 1) % 2 == 0 and l - 1 < r: ornament_pos = random.randint(l, r) if bough[ornament_pos] == ' ': bough[ornament_pos] = '*' l -= 1 r += 1 if num % (BOUGH_REDUCING * 2) == 0 and r - l > BOUGH_REDUCING * 2: l += BOUGH_REDUCING r -= BOUGH_REDUCING tree.append(bough) bottom_start = tree[-1].index('/') bottom_end = tree[-1].index('\\') + 1 bottom = get_block() for pos in range(bottom_start, bottom_end): bottom[pos] = '-' tree.append(bottom) def draw_bole(): global TREE_HEIGHT global tree bole = get_block() bole[TREE_HEIGHT - 2] = bole[TREE_HEIGHT + 2] = '|' tree.append(bole) def draw_ground(): global tree ground = get_block('_') tree.append(ground) def draw_all(): draw_tree() draw_bole() draw_ground() if __name__ == '__main__': draw_all() for bough in tree: print(''.join(bough))
3d870676857a49f4121652c837f67e6d0364339e
jessizanelato/desafio-fifa
/main.py
2,139
3.84375
4
# coding: utf-8 # Todas as perguntas são referentes ao arquivo `data.csv` # Você ** não ** pode utilizar o pandas e nem o numpy para este desafio. import csv import sys data = open("data.csv") # **Q1.** Quantas nacionalidades (coluna `nationality`) diferentes existem no arquivo? def q_1(): return count_different_values_by_column_name('nationality') # **Q2.** Quantos clubes (coluna `club`) diferentes existem no arquivo? def q_2(): return count_different_values_by_column_name('club') # **Q3.** Liste o primeiro nome dos 20 primeiros jogadores de acordo com a coluna `full_name`. def q_3(): names = [] lines = csv.DictReader(data) i = 1 for line in lines: if i > 20: break first_name = line['full_name'].split(' ')[0] names.append(first_name) i += 1 return names # **Q4.** Quem são os top 10 jogadores que ganham mais dinheiro (utilize as colunas `full_name` e `eur_wage`)? def q_4(): return build_top_10_by_value('eur_wage') # **Q5.** Quem são os 10 jogadores mais velhos? def q_5(): return build_top_10_by_value('age') # **Q6.** Conte quantos jogadores existem por idade. Para isso, construa um dicionário onde as chaves são as idades e os valores a contagem. def q_6(): count_age = {} lines = csv.DictReader(data) for line in lines: age = line['age'] if age not in count_age: count_age[age] = 1 count_age[age] += 1 return count_age def count_different_values_by_column_name(column_name:str): values = [] lines = csv.DictReader(data) for line in lines: if line[column_name] not in values: values.append(line[column_name]) return len(values) def build_top_10_by_value(value: str): name_value = {} lines = csv.DictReader(data) for line in lines: name_value[line['full_name']] = float(line[value]) top_10 = [] i = 1 for key, value in sorted(name_value.items(), key=lambda item: (item[1], item[0]), reverse=True): if i > 10: break top_10.append(key) i += 1 return top_10 q_1()
ce51cf6eab8905c6edd65871035dc2d4c4b1259a
abbas1001/Data-Science-Porfolio
/python/python_practice_exercieses/marksheet.py
720
4
4
""" Write a python program to make a mark sheet """ def stars(n): for i in range(n): print("*", end='') def pr(subject, name): return print(f"Marks in {subject} = {name}") phyics = input('Enter Physics Marks : ') chemistry = input('Enter Chemistry Marks : ') bio = input('Enter Biology Marks : ') islamiat = input('Enter Islamiat Marks : ') urdu = input('Enter Udru Marks : ') total = int(phyics) + int(chemistry) + int(bio) + int(islamiat) + int(urdu) percent = (total * 100) / 500 stars(35) print() pr('Phyics', phyics) pr('Chemistry', chemistry) pr('Biology', bio) pr('Islamait', islamiat) pr('Urdu', urdu) stars(35) print() print('Total = ' + str(total)) print('Percentage = ' + str(percent))
68ae374ec28ed1e8e896855865985f308e66a489
zongtong009/MY_CODEpy
/python123/day05.py
647
3.546875
4
""" 埃拉托色尼筛选法 埃拉托色尼筛选法是一个很漂亮的示例算法。 在 i7 CPU(单线程)处理器下它可以在1s之内生成10 ^ 9以内的所有素数,因此,当这种筛选算法被应用的时候,它的速度是非常惊人的。 而我用了最基础的版本(未进行分割),仅仅只是删除了在数组中的偶数。 """ import numpy as np def eratosthenes(n): n = (n + 1) >> 1 p = np.ones(n, dtype=np.int8) i, j = 1, 3 while i < n: if p[i]: p[j * j >> 1::j] = 0 i, j = i + 1, j + 2 return p.sum() res = eratosthenes(1000000) print(res)
e7eccac2e6031e762a798eb5614709fa9ad4de2f
Cica013/Exercicios-Python-CursoEmVideo
/Pacote_Python/Ex_python_CEV/exe058.py
1,308
4.09375
4
# Melhore o jogo do desafio 28 onde o computador vai "pensar" em um número entre 0 e 10. só que agora o jogador vai # tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer. condicao = True while condicao == True: print('Sou seu computador... Acabei de pensar em um número entre 0 e 10.') print('Vamos ver se você consegue adivinhar...') lista = [] for c in range(1, 11): lista += [c] from random import choice maquina = choice(lista) escolha = int(input('Digite o número que acha que eu pensei: ')) cont = 0 while escolha != maquina: if escolha > maquina: print('Menos...') elif escolha < maquina: print('Mais...') escolha = int(input('Digite outro número: ')) cont += 1 print(f'Acertou!!!... Você precisou de {cont} chances para advinhar. :)') continuar = str(input('Quer continuar? (S/N)')).strip()[0] while continuar not in 'SsNn': print('Digite somente (S) ou (N).') continuar = str(input('Quer continuar? (S/N)')).strip()[0] if continuar in 'Ss': print('Obáaa... Bora jogar denovo então.') elif continuar in 'Nn': print('Ok então, até a próxima!!!') condicao = False
4aab90393147e46f252b05f794687773c192f1a5
dlehdduq/scc_study
/study3/test.py
806
3.5625
4
a = 'spartacodingclub@gmail.com' b = 'spartacodingclubgmail.com' list = ['사과','감','감','배','포도','포도','딸기','포도','감','수박','딸기'] dic = {"사과":0,"감":0,"배":0,"포토":0,"딸기":0} #채워야하는 함수 def check_mail(s): ## 여기에 코딩을 해주세요 mail_list = s.split('@'); if len(mail_list) == 1: return "@가 없습니다 ==> FALSE" else: return True; print(check_mail(a)); def count_list(a_list): result = {} for element in a_list: if element in result: result[element] += 1 else: result[element] = 1 return result #결과값 print(count_list(list)) import random def get_lotto(): lotto_range = range(1,47) lotto_nums = random.sample(lotto_range,6) return lotto_nums print(get_lotto())
9a003f070890e939a2e65cfa915a850decd50c70
antho1810/CursoPython
/Estrutura_Datos/listas.py
904
4.375
4
''' las listas son estructuras de datos que se usan para almacenar valores. Se asemejan a los vectores Append(<obj>) Este método nos permite agregar nuevos elementos a una lista/vector. Remove(<indice>) El método remove va a remover un elemento que se le pase como parámentro de la lista a donde se le esté aplicando. Index(<dato>) Index devuelve el número de indice del elemento que le pasemos por parámetro. Count(<dato>) Para saber cuántas veces un elemento de una lista se repite podemos utilizar el metodo count(). Reverse() También podemos invertir los elementos de una lista. ''' def main(): lista = [1, 2, 3, 4, 5, 6, 7, 8, 9] listaLetra = ['a', 'b', 'c', 'd'] lista.reverse() print(listaLetra.count('c')) listaLetra.remove('b') lista.remove(4) print(lista) print(listaLetra) print(listaLetra.index('d')) main()
b41e96328a216b6be1fde4f26f45a2af60182143
SherifElbishlawi/My-Codewars-Katas-Python-Solutions
/6kyu/Backspaces in string/BackspacesInString.py
467
4.3125
4
# Assume "#" is like a backspace in string. This means that string "a#bc#d" actually is "bd" # # Your task is to process a string with "#" symbols. # # Examples # "abc#d##c" ==> "ac" # "abc##d######" ==> "" # "#######" ==> "" # "" ==> "" def clean_string(s): output_string = '' for x in s: if x != '#': output_string += x else: output_string = output_string[:-1] return output_string
24f98fdf4da0fe5620f03d1d2e0ce52c18b8c776
ODCenteno/python_100days
/day_9_dicts/secret_auction_program.py
1,825
3.953125
4
import os from art import logo from countdown import count_down # Give a warm welcome to the program and bring the logo def welcome(): print(logo) print(f'Get fun while you bid with your friends') def getting_bids(): players_bid = {} add_player = True # main logic of the program to add players and bids to while add_player: try: player_name = input(f'Enter the player\'s name: ').title().strip() new_bid = float(input(f'Type {player_name}\'s bid: $ ')) players_bid[player_name] = new_bid except ValueError: print(f'That is not a valid input') continue # If ther is a value error input will start again to ask player's name and bid bid_finished = False # variable to start/stop the next while loop while not bid_finished: more_players = input('Is there any other player?[Y/N]: ').lower().strip() if more_players == 'y': bid_finished = True os.system('clear') elif more_players == 'n': add_player = False # Stops this loop bid_finished = True # Stops main loop else: print(f'That\'s not a valid option') # If there is a ValueError we ask for the answer again return players_bid def max_bid(bids): get_highest_bid = 0 winner = '' for name, bid in bids.items(): if bid > get_highest_bid: get_highest_bid = bid winner = name os.system('clear') count_down() # Prints a countdown before display the winner print(f'{"*"*80}\n\nThe winner is {winner}, who\'s bid was ${get_highest_bid}\n\n{"*"*80}\n\n') if __name__ == '__main__': welcome() bids = getting_bids() winner = max_bid(bids)
6a913f06c5fbf030d68c2b90be1d3a19e2dd9fa2
renamez4/project-1
/lecture 1/ARITHMETICOPERATORS.py
570
3.875
4
x = 15 y = 4 # output : x+y = 19 print('x+y =',x+y) # output L x-y = 11 print('x-y=',x-y) # output : x*y = 60 print('x*y=',x*y) # output : x/y =3.75 print('x%y=',x%y) # output : x%y=3 print('x % y =',x//y) # output : x ** y=50625 print('x**y=',x**y) print(5+18//2-25%4) x=10 y=12 #output : x>y is False print('x>y is',x>y) #output :x< y is true print('x<y is',x<y) #output : x==y is False print('x==y is',x==y) #output : x !=y is True print('x!=y is',x!=y) #output : x>=y is False print('x>=y is',x>=y) #output :x<=y is True print('x <=y is',x<=y) x=10 print(not x)
5805846dbad83509ce6ebdb8410f557f9e690778
fdrio/Python-SQL-Server
/debug.py
357
3.609375
4
from functools import wraps from time import time def timer(fn): @wraps(fn) def wrap(*args, **kw): time_start = time() result = fn(*args,**kw) time_end = time() print('function:{}\took:{} \n args:{} \n kwargs:{}'\ .format(fn.__name__,time_end-time_start,args,kw)) return result return wrap
1f8747ee3c0c248f7b2e81360c1be74e164d8e48
SparkCat23/PythonCode
/project_21_08_17/lista01/test_ex08_apaga.py
666
3.765625
4
# -*- coding: utf-8 -*- # Exercícios by Nick Parlante (CodingBat) # H. apaga # seja uma string s e um inteiro n # retorna uma nova string sem a posição n # apaga('kitten', 1) -> 'ktten' # apaga('kitten', 4) -> 'kittn' def apaga(s, n): s = s[:n]+s[n+1:] return s def test_ex08(): print ('Apaga') assert apaga('kitten', 1) == 'ktten' assert apaga('kitten', 0) == 'itten' assert apaga('kitten', 4) == 'kittn' assert apaga('Hi', 0) == 'i' assert apaga('Hi', 1) == 'H' assert apaga('code', 0) == 'ode' assert apaga('code', 1) == 'cde' assert apaga('code', 2) == 'coe' assert apaga('code', 3) == 'cod' assert apaga('chocolate', 8) == 'chocolat'
6dcbc35c022d6414cc1be8629a1a89cdf2499db6
mamiaokui/python_utils
/convert_point.py
2,462
3.5625
4
import sys import collections import math def validate(arr): if len(arr) != 3: return False for i in arr: try: float(i) except ValueError: return False return True def find_next_filled(index, max_value, format_point): for i in range(index, max_value + 1): value = format_point.get(i) if value is None or len(value) != 8: continue return i return -1 if __name__ == "__main__": path = sys.argv[1] points = [] with open(path) as f: lines = f.readlines() for line in lines: result = line.split() #print(result) if validate(result): print(result) points.append(map(float, result)) max_value = -1 for i in points: if i[0] > max_value: max_value = int(i[0]) format_point = {} for i in points: result = format_point.get(int(i[0])) if result is None: result = [] result.append(i[1]) result.append(i[2]) format_point[int(i[0])] = result last_filled_index = -1 last_filled_value = None for i in range(max_value): if format_point.get(i) is None: if last_filled_index == -1: print("error code 1") exit(0) index = find_next_filled(i, max_value, format_point) if index == -1: print("error code 2") exit(0) arr = format_point.get(index) distance_long = index - last_filled_index distance_short = i - last_filled_index calc = [] for j in range(8): temp = last_filled_value[j] + (arr[j] - last_filled_value[j]) / distance_long * distance_short calc.append(round(temp, 3)) format_point[i] = calc last_filled_index = i last_filled_value = calc else: last_filled_index = i last_filled_value = format_point.get(i) od = collections.OrderedDict(sorted(format_point.items())) with open(sys.argv[2], "w+") as f: for k, v in od.iteritems(): # for i in range (0, len(v)/2): # temp = v[i] # v[i] = v[i+4] # v[i+4] = temp str_convert = ' '.join(str(e) for e in v) print str_convert, f.write(str_convert + "\n")
e2603952810fb9190340dabc745ae0369eaa4b6f
lkloh/playground-for-python
/what_is_class.py
462
3.796875
4
class Shape(): def __init__(self, a, p): self.area = a self.perimeter = p def get_area(self): return self.area def __str__(self): return "Area %d, perimeter %d" % (self.area, self.perimeter) class Test: def __init__(self, s): self.shape = s def __str__(self): return "Test: " + str(self.shape) @classmethod def pi_approx(cls, shape): enhanced_shape = cls(shape) return str(enhanced_shape) s = Shape(1, 2) print Test.pi_approx(s)
8bfb849435276f2c83cc9f4d59a07a0c0cbda03e
HACKER-BYTE-HUE/TikTok-Code
/UpsideDownWord.py
881
4.125
4
# these are the only letters that can be used to make a word that works with the mirror trick accepted_letters = set('BCDEHIKOX') # open the dictionary file and split the words into a list and make them all uppercase with open('words.txt', 'r') as dictionary_file: words = [word.upper() for word in dictionary_file.read().split('\n')] # this is like a filter that only lets words that are only made up of the accepted letters words = [word for word in words if set(word).issubset(accepted_letters)] # sort the words by the length (key=len) because sorting by default is alphabetical # reverse=True because sort will put the lowest value first ex: [0, 3, 4, 4, 5] we want the highest value first words.sort(key=len, reverse=True) # takes the first 15 words in the list and prints out the length along with the word itself for word in words[:15]: print(len(word), word)
aa69f1730f4be9ffad9f77d14f14a2c464359d78
MahamedYusuf-UIA/is105-lab
/Lab4/Lab4_Original.py
7,310
3.9375
4
# We import functions so that we can use them even though they are defined elsewhere (standard module) import random import math import itertools from collections import defaultdict """ This is our own code that we have tried to make before looking at the solution, we have of course gotten some help from the WWW. This code is missing some key elements, like beeing able to sort the winning hand, for example it will put out [4D, 8H,, 7D, AC, 4S] instead of [4D, 4S, AC, 8H, 7D]. A lot of the functions will be a lot like udacitys vertion but our code will be different from theirs. """ def poker(hands): # Return a list of winning hands: poker([hand,...]) => [hand,...] # This code will Return the top hands (winning hands). It also uses the allmax function which is defined under print hands print "Winner:" return allmax(hands, key = hand_rank) def allmax(iterable, key=lambda x:x): # Returns a list of all items equal to the max of the iterable. maxi = max(iterable, key=key) return [element for element in iterable if key(element) == key(maxi)] def winning_hands(hands): # Calculates which hand is the best, taking into count the ranks and values of the cards result = [] max_hand = max(hands, key = hand_rank) for hand in hands: if hand_rank(max_hand) == hand_rank(hand): result.append(hand) return result def hand_rank(hand): # We had problems making a optimal solution for this so ended up bein a large chunk of code # But the point is that it works. # The code takes care of the well used "hand", it takes care of the ace problem and # sets a value for the different kind of hands you can have (flush, straight etc.) suits = [s for r, s in hand] nr_dif_suits = len(set(suits)) ranks = ['--23456789TJQKA'.index(r) for r, s in hand] ranks.sort(reverse = True) nr_dif_ranks = len(set(ranks)) if ranks == [14, 5, 4, 3, 2]: ranks = [5, 4, 3, 2, 1] flush = (nr_dif_suits == 1) straight = (ranks == range(ranks[0], ranks[0] -5, -1) ) if flush and straight: return (8, max(ranks)) elif ranks.count(ranks[2]) == 4: return (7, ranks[2]) elif ranks.count(ranks[2]) == 3 and nr_dif_ranks == 2: return (6, ranks[2]) elif flush: return (5, )+ tuple(ranks) elif straight: return (4, max(ranks)) elif ranks.count(ranks[1]) == 2 and ranks.count(ranks[3]) == 2: max_pair = max(ranks[1], ranks[3]) min_pair = min(ranks[1], ranks[3]) other_card = [r for r in ranks if(r != min_pair and r != max_pair)][0] return (2, max_pair, min_pair, other_card) elif nr_dif_ranks == 4: the_pair = [r for r in ranks if ranks.count(r) == 2][0] other_card = [r for r in ranks if r != the_pair] return (1, the_pair)+tuple(other_card) else: return (0, ) + tuple(ranks) def group(items): # It returns a list of count, it will also sort it so the highest comes first groups = [(items.count(x), x) for x in set(items)] return sorted(groups, reverse = True) def unzip(pairs): # It packs up a list return zip(*pairs) def card_ranks(cards): # Returns a list of the ranks, sorted with higher first # note to self: might need a sort function here for the ace problem, might solve our sorting problem ranks = [] for r, s in cards: if r == "T": ranks.append(11) elif r == "Q": ranks.append(12) elif r == "K": ranks.append(13) elif r == "A": ranks.append(14) else: ranks.append(int(r)) ranks.sort(reverse = True) return ranks def straight(ranks): # Checks if we have a straight, a straight can only be if all the cards in the hand # Have eather +1 or -1 in rank (value) to the other card in front of it. return sorted(ranks, reverse=True)==ranks and len(set(ranks))==len(ranks) def flush(hand): # Checks if we have a flush, flush means that all the card in the hand have the same # Colour, which is what this code does. Also have a look on udacitys code. return [ e[1] for e in hand] == [hand[1][1] for e in range (len(hand))] def two_pair(ranks): # For-loop the ranks # Set is to find 2 types of symbol # two pairs is only possible by having the same ranks t = [] for r in set(ranks): if ranks.count(r) == 2: t.append(r) if len(t) == 2: return tuple(t) else: return None def kind(n, ranks): # In the case we only have a pair the value will be 1, so return the pair first then # the other cards in order, with highcard first if no value is found if (len(set(ranks)) == (5-n) or len(set(ranks)) == (4-n)): if (ranks[0] == ranks[4-n] or ranks[1] == ranks[4-n]): return ranks[0] else: return ranks[4] else: return None deck = [r+s for r in '23456789TJQKA' for s in 'SHDC'] def deal(numhands, n = 5, deck = [r+s for r in '23456789TJQKA' for s in 'SHDC']): # Returns a list of numhands hands consisting of n cards each. random.shuffle(deck) deck = iter(deck) return [[next(deck) for card in range(n)] for hand in range(numhands)] """ From here to downwards, we have copied the code from Udacity. That is because the task tells us to copy the shuffle functions from Udacity. """ def hand_percentages(n = 700*1000): "Sample n random hands and print a table of percentages for each type of hand" counts = [0]*9 for i in range(n/10): for hand in deal(10): ranking = hand_rank(hand)[0] counts[ranking] += 1 for i in reversed(range(9)): print('%14s: %6.3f'%(hand_names[i], 100.*counts[i]/n)) def all_hand_percentages(): "Prints an exhaustive table of frequencies for each type of hand." counts = [0]*9 n = 0 deck = [r+s for r in '23456789TJQKA' for s in 'SHDC'] for hand in itertools.combinations(deck, 5): n += 1 ranking = hand_rank(hand)[0] counts[ranking] += 1 for i in reversed(range(9)): print('%14s: %7d %6.3f'%(hand_names[i], counts[i], 100.*counts[i]/n)) def shuffle1(deck): # O(N**2) # incorrect distribution N = len(deck) swapped = [False] * N while not all(swapped): i, j = random.randrange(N), random.randrange(N) swapped[i] = swapped[j] = True deck[i], deck[j] = deck[j], deck[i] def shuffle2(deck): # O(N**2) # incorrect distribution? N = len(deck) swapped = [False] * N while not all(swapped): i, j = random.randrange(N), random.randrange(N) swapped[i] = True deck[i], deck[j] = deck[j], deck[i] def shuffle2a(deck): # http://forums.udacity.com/cs212-april2012/questions/3462/better-implementation-of-shuffle2 N = len(deck) swapped = [False] * N while not all(swapped): i = random.choice(filter(lambda idx: not swapped[idx], range(N))) j = random.choice(filter(lambda idx: not swapped[idx], range(N))) swapped[i] = True deck[i], deck[j] = deck[j], deck[i] def shuffle3(deck): # O(N) # Incorrect distribution. N = len(deck) for i in range(N): j = random.randrange(N) deck[i], deck[j] = deck[j], deck[i] def shuffle(deck): # Knuth method. n = len(deck) for i in range(n-1): j = random.randrange(i, n) deck[i], deck[j] = deck[j], deck[i] def factorial(n): return 1 if (n <= 1) else n*factorial(n-1) # The ammount of players / hands we want to deal out. print poker(deal(3))
39ca88c0296414a2400977481c174e7aafb17a40
haell/AulasPythonGbara
/mundo_TRES/ex108.py
687
3.734375
4
# Adapte o código do desafio #107, criando uma função adicional chamada moeda() que consiga mostrar os números como um valor monetário formatado. from fex107.moeda import moeda, dobro, diminuir, aumentar, metade from fex107.util import ln from rich import print preco = float(input("Digite o preço: R$\033[32m ")) taxa = float(input("\033[mDigite a taxa: ")) metade_preco = f"A metade de {moeda(preco)} é {moeda(metade(preco))}" ln(y=len(metade_preco)+2) print(metade_preco) print(f"Diminuindo {taxa:.1f}%, temos {moeda(diminuir(preco, taxa))}") print(f"O dobro de {moeda(preco)} é {moeda(dobro(preco))}") print(f"Aumentando {taxa:.0f}%, temos {moeda(aumentar(preco, taxa))}")
d00e988176024cc8ae64eedfab861a0a2cbaf408
bchoi0000/Project1001
/Testscript101.py
433
3.671875
4
class testclass: def __init__(self, y, z): self.f = y*3 self.g = z*2 #print(self.f) #print(self.g) class childclass(testclass): def __init__(self, a, b): #self.a = a #self.b = b super().__init__(a,b) print(self.f) print(self.g) class child2class(testclass): def __init__(self, c, d): pass #obj1 = testclass(1,2) obj2 = childclass(10,60)
313aeb33a9572d1f79259d5d9fbe684f7f3a5be5
himoon/my-first-coding
/practice/6_289p_1.py
110
3.796875
4
def is_odd(arg): if arg % 2 == 1: return True return False print(is_odd(3)) print(is_odd(2))
6017ea71c01c95ea47b158f0ab68c2860e22a68f
SG-325/Homework_Course_Python_2
/Homework_1/home_1.py
1,126
3.5
4
from random import randint as r check = "yes" while check.lower() == "yes": random_number = str(r(1000,9999)) print("\nrandom number =", random_number) count = 0 while True: p = 0 while p == 0: try: user_choice = input("\nGuess the 4-digit number.") if not user_choice.isdigit(): raise ValueError(f"{user_choice} is not a digit or integer. Try again.") if len(user_choice) != 4: raise TypeError(f"Length of {user_choice} isn't equal 4. Try again.") p = 1 except ValueError as v: print(v) except TypeError as t: print(t) bulls = 0 cows = 0 for i in range(4): if random_number[i] in user_choice: bulls += 1 if random_number[i] == user_choice[i]: cows += 1 bulls = bulls - cows count += 1 if cows == 4: print(f"You have ({cows} cows, {bulls} bulls).") print("\nYou won!!!") break else: print(f"For this time you have ({cows} cows, {bulls} bulls).") print(f"You tried to guess {count} time.") check = input("\nIf you want to continue the game enter 'yes'. Otherwise enter 'no'.") print("\nThanks for the game:)")
ee851923609c8f53d25545155f156ecd528f504c
bach2o/NguyenNgocBach-fundamentals-c4e15
/Session5/Homework/đếm số.py
1,051
3.734375
4
nums = [1,4,6,2,4,31,4,6,10] print(nums) while True: try: # Nhập đúng số num_to_find = int(input("Enter a number? ")) # Nhập số cần tìm number_count = 0 # Số số tìm được while True: ask = input('Would you like to use count() function or NOT? (Y/N)').lower() # Có muốn dùng count() không? if ask == 'y': number_count = nums.count(num_to_find) # Đếm số số bằng count(). Rất nhanh và gọn. break elif ask == 'n': for index, num in enumerate(nums): # Đoạn code lấy từ linear_search2, đã modify if num == num_to_find: number_count +=1 break else: print('Please enter the correct command! (Y/N) ') print(num_to_find, 'appears', number_count, 'time(s) in my list. ') # In ra kết quả except ValueError: # Nhập các ký tự khác print('Oops! That was no valid number. Try again...')
bea805e3a6090abd30ebdfc9bd6ddc6caf1842e8
cu-swe4s-fall-2019/hash-tables-sahu0957
/test_hash_tables.py
5,104
3.5625
4
import unittest import hash_tables import hash_functions import random class TestLPHashTables(unittest.TestCase): def test_hash_table_ascii_add(self): # We add one word to a table of size 1, which should end # up at index 0 regardless of its hash r = hash_tables.LinearProbe(1, hash_functions.h_ascii) r.add('sample1', 'value1') self.assertEqual(r.T[0], ('sample1', 'value1')) def test_hash_table_search(self): r = hash_tables.LinearProbe(1, hash_functions.h_ascii) r.add('sample1', 'value1') self.assertEqual(r.search('sample1'), 'value1') def test_hash_table_full(self): # If the hash table is full, it should submit a "False" r = hash_tables.LinearProbe(1, hash_functions.h_ascii) r.add('sample1', 'value1') self.assertEqual(r.add('sample2', 'value2'), False) def test_hash_table_search_last_index(self): # A test to make sure the last index is return the expected value r = hash_tables.LinearProbe(5, hash_functions.h_ascii) r.add('sample1', 'value1') r.add('sample2', 'value2') r.add('sample3', 'value3') r.add('sample4', 'value4') r.add('sample5', 'value5') self.assertEqual(r.search('sample5'), 'value5') def test_hash_table_search_rolling(self): # A test to see if we will return the proper value when hashing # Using the rolling polynomial strategy r = hash_tables.LinearProbe(5, hash_functions.h_rolling) r.add('sample1', 'value1') r.add('sample2', 'value2') r.add('sample3', 'value3') r.add('sample4', 'value4') r.add('sample5', 'value5') self.assertEqual(r.search('sample5'), 'value5') def test_hash_table_add_rolling_None(self): # If we try to add a None object, it should raise an error r = hash_tables.LinearProbe(5, hash_functions.h_rolling) with self.assertRaises(TypeError): r.add(None, None) def test_hash_table_add_ascii_None(self): # If we try to add a None object, it should raise an error r = hash_tables.LinearProbe(5, hash_functions.h_ascii) with self.assertRaises(TypeError): r.add(None, None) def test_hash_table_search_notpresent(self): # If we try to add a None object, it should raise an error r = hash_tables.LinearProbe(5, hash_functions.h_ascii) r.add('sample1', 'value1') r.add('sample2', 'value2') self.assertEqual(r.search('sample3'), None) class TestCHHashTables(unittest.TestCase): def test_chainedhash_ascii_addone(self): # a one-word, one-value key should always go in the first slot r = hash_tables.ChainedHash(1, hash_functions.h_ascii) r.add('sample1', 'value1') self.assertEqual(r.T[0], [('sample1', 'value1')]) def test_chainedhash_rolling_addone(self): # a one-word, one-value key should always go in the first slot r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') self.assertEqual(r.T[0], [('sample1', 'value1')]) def test_chainedhash_rolling_add_fulltable(self): # two one-word, one-value key should always go in the first slot # and a collision will result in the second going to the same spot # with a different index r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') r.add('sample2', 'value2') self.assertEqual(r.T[0][1], ('sample2','value2')) def test_chainedhash_ascii_search_singleentry(self): # search should return value of single entry input r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') self.assertEqual(r.search('sample1'), 'value1') def test_chainedhash_ascii_search_notpresent(self): # search should return value None when key isn't present r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') self.assertEqual(r.search('sample2'), None) def test_chainedhash_ascii_search_last(self): # search should return value of the last sample added r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') r.add('sample2', 'value2') r.add('sample3', 'value3') r.add('sample4', 'value4') r.add('sample5', 'value5') self.assertEqual(r.search('sample5'), 'value5') def test_chanedhash_collision(self): # in a table of 1, all samples will hash to the same spot # search should return the values regardless of this r = hash_tables.ChainedHash(1, hash_functions.h_rolling) r.add('sample1', 'value1') r.add('sample2', 'value2') r.add('sample3', 'value3') r.add('sample4', 'value4') r.add('sample5', 'value5') self.assertEqual(r.search('sample5'), 'value5') if __name__ == '__main__': unittest.main()
0dfc51561f305c69792565caba58c28de5e197f8
JasonG-FR/python-text-calculator
/fibonacci.py
766
3.6875
4
#FIBONACCI import time import logging num0 = 0 num1 = 1 hi = 0 print(_("Press Control-C to stop.")) try: while True: num = num0 + num1 #set variable num to the sum of num0 and num1. if hi == 0: num0 = num hi = 1 else: #every other time this loops it will run this instead of the previous block num1 = num # set num1 to num hi = 0 #next time it wont do this block it'll do the previous one print(num, end=", ", flush=True) #print the current number time.sleep(0.5) except KeyboardInterrupt: #if ctrl-c print(_("Thanks for using Palc's FIBONACCI function!")) except Exception as e: #if an error occurs print(_("An error occured.")) logging.err("Exception %s" % e)
b1c45d9d166809afd26a9722f1ab06d7353857a7
lly1997/pythonTest
/main.py
806
3.734375
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import turtle import os turtle.right(0) num=0 for num in range(4): turtle.forward(100) turtle.circle(100, 90) num=num+1 os.system("pause") def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. def sya(numbser): print(numbser) print("this is my python") print("hello") def sayhello(): sya(12) print("lialiyong") # Press the green button in the gutter to run the script. # sayhello() # sayhello() # See PyCharm help at https://www.jetbrains.com/help/pycharm/
c01c69f9d7c65db5d5e00125f944f2119c8efaf7
Tiezzi96/SlidingPuzzle
/main.py
24,024
3.890625
4
from __future__ import print_function from __future__ import generators import sys import time import os import psutil from copy import deepcopy import random import bisect import pickle infinity = 1.0e400 def update(x, **entries): """Update a dict; or an object with slots; according to entries. >>> update({'a': 1}, a=10, b=20) {'a': 10, 'b': 20} >>> update(Struct(a=1), a=10, b=20) Struct(a=10, b=20) """ if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x class Problem: """The abstract class for a formal problem. You should subclass this and implement the method successor, and possibly __init__, goal_test, and path_cost. Then you will create instances of your subclass and solve them with the various search functions.""" def __init__(self, initial, goal=None): """The constructor specifies the initial state, and possibly a goal state, if there is a unique goal. Your subclass's constructor can add other arguments.""" self.initial = initial self.goal = goal def successor(self, state): """Given a state, return a sequence of (action, state) pairs reachable from this state. If there are many successors, consider an iterator that yields the successors one at a time, rather than building them all at once. Iterators will work fine within the framework.""" pass # abstract def goal_test(self, state): """Return True if the state is a goal. The default method compares the state to self.goal, as specified in the constructor. Implement this method if checking against a single self.goal is not enough.""" return state == self.goal def path_cost(self, c, state1, action, state2): """Return the cost of a solution path that arrives at state2 from state1 via action, assuming cost c to get up to state1. If the problem is such that the path doesn't matter, this function will only look at state2. If the path does matter, it will consider c and maybe state1 and action. The default method costs 1 for every step in the path.""" return c + 1 class Node: """A node in a search tree. Contains a pointer to the parent (the node that this is a successor of) and to the actual state for this node. Note that if a state is arrived at by two paths, then there are two nodes with the same state. Also includes the action that got us to this state, and the total path_cost (also known as g) to reach the node. Other functions may add an f and h value; see best_first_graph_search and astar_search for an explanation of how the f and h values are handled. You will not need to subclass this class.""" def __init__(self, state, parent=None, action=None, path_cost=0): "Create a search tree Node, derived from a parent by an action." update(self, state=state, parent=parent, action=action, path_cost=path_cost, depth=0) if parent: self.depth = parent.depth + 1 self.cammino=0 self.camminoimp=0 def __repr__(self): """(pf) Modified to display depth, f and h""" if hasattr(self,'f'): return "<Node: f=%d, depth=%d, h=%d\n%s>" % (self.f, self.depth, self.h, self.state) else: return "<Node: depth=%d\n%s>" % (self.depth,self.state) def path(self): "Create a list of nodes from the root to this node." x, result = self, [self] while x.parent: result.append(x.parent) x = x.parent self.cammino+=1 self.camminoimp+=x.state.hu return result def expand(self, problem): "Return a list of nodes reachable from this node. [Fig. 3.8]" return [Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state)) for (action, next_state) in problem.successor(self.state)] class PuzzleState: """ The board is NxN so use N=4 for the 15-puzzle, N=5 for the 24-puzzle, etc The state of the puzzle is simply a permutation of 0..N-1 The position of the blank (element zero) is stored in r,c """ def __init__(self,board,N,r,c): self.board=board self.r=r self.c=c self.N = N self.hu = 0 def __getitem__(self,(r,c)): return self.board[r*self.N+c] def __setitem__(self,(r,c),val): self.board[r*self.N+c]=val def move(self,direction): ch=deepcopy(self) c,r = ch.c,ch.r if direction == 'left' and self.c != 0: ch[(r,c)], ch[(r,c-1)] = self[(r,c-1)],self[(r,c)] ch.c = c-1 elif direction == 'right' and c != self.N-1: ch[(r,c)],ch[(r,c+1)] = self[(r,c+1)],self[(r,c)] ch.c = c+1 elif direction == 'up' and self.r != 0: ch[(r,c)],ch[(r-1,c)] = self[(r-1,c)],self[(r,c)] ch.r = r-1 elif direction == 'down' and r != self.N-1: ch[(r,c)],ch[(r+1,c)] = self[(r+1,c)],self[(r,c)] ch.r = r+1 else: return None return ch def misplaced(self): """Misplaced tiles heuristic""" blank = self.r*self.N+self.c return sum([idx!=val for idx,val in enumerate(self.board) if idx!=blank]) def lcheuristic(self): m = self.manhattan() m += self.LCH() m += (self.LCV()) return m def potlch(self): a = range(16) listup = [] listdown = [] for j in range(self.N): for i in range(self.N): l = [] l1 = [] d = i u = i while u != 3: u += 1 if a[j * self.N + u] is not 0: l.append(a[j * self.N + u]) while d != 0: d -= 1 if a[j * self.N + d] is not 0: l1.append(a[j * self.N + d]) listup.append(l) listdown.append(l1) return (listup, listdown) def potlcv(self): a = range(16) listup = [] listdown = [] for i in range(self.N): for j in range(self.N): l = [] l1 = [] d = j u = j while u != 3: u += 1 if a[u * self.N + i] is not 0: l.append(a[u * self.N + i]) while d != 0: d -= 1 if a[d * self.N + i] is not 0: l1.append(a[d * self.N + i]) listup.append(l) listdown.append(l1) return (listup, listdown) def LCH(self): linearconflict = 0 listup, listdown = self.potlch() for j in range(self.N): for i in range(self.N): if self[(j,i)] != 0: k=i u=i casella=self[[j,i]] while k != 3: k += 1 for l in range(len(listdown[self[(j,i)]])): if self[(j,k)]==listdown[self[(j,i)]][l] and j is (self[(j,i)]//4): linearconflict+=1 while u != 0: u -= 1 for l in range(len(listup[self[(j,i)]])): if self[(j, u)] == listup[self[(j,i)]][l] and j is (self[(j,i)]//4): linearconflict += 1 return linearconflict def LCV(self): linearconflict = 0 listup, listdown = self.potlcv() for j in range(self.N): for i in range(self.N): if self[(i,j)] != 0: k=i u=i a=range(16) col=-1 row=-1 for n in range(self.N): for m in range(self.N): if a[m*self.N+n] is self[(i,j)]: col=n row=m while k != 3: k += 1 for l in range(len(listdown[col*self.N +row])): if self[(k,j)]==listdown[col*self.N +row][l] and j is (self[(i,j)] % 4): linearconflict+=1 while u != 0: u -= 1 for l in range(len(listup[col*self.N +row])): if self[(u, j)] == listup[col*self.N +row][l] and j is (self[(i,j)] % 4): linearconflict += 1 return linearconflict def manhattan(self): """Manhattan distance heuristic""" m=0 blank = self.r*self.N+self.c for index,value in enumerate(self.board): if index != blank and index != value: r = index // self.N c = index % self.N rr = value // self.N cc = value % self.N # print('misplaced',value,rr,r,cc,c) m += abs(r-rr) + abs(c-cc) assert(m>=0) return m def __str__(self): # forza un dato ad essere una stringa """Serialize the state in a human-readable form""" s = '' for r in xrange(self.N): for c in xrange(self.N): if self[(r,c)]>0: s += '%3d' % self[(r,c)] else: s += ' ' s += '\n' return s def __repr__(self): return self.__str__() class Puzzle(Problem): """Base class - For 8-puzzle use Puzzle(3) -- a 3x3 grid""" def __init__(self, N, seed,scrambles=10): self.N = N self.actions = ['left','right','up','down'] self.make_initial_state(seed,scrambles) self.dict1 = {} self.dict2 = {} self.dict3 = {} self.dict4 = {} self.dict5 = {} self.dict6 = {} def make_initial_state(self,seed,scrambles): """ To ensure a solution exists, start from the goal and scramble it applying a random sequence of actions. An alternative is to use the permutation parity property of the puzzle but using the scrambling we can roughly control the depth of the solution and thus limit CPU time for demonstration """ seen = {} ns=0 x = range(self.N*self.N) for r in range(self.N): for c in range(self.N): if x[r*self.N+c]==0: row,col=r,c self.initial = PuzzleState(x,self.N,row,col) R = random.Random() R.seed(seed) while ns<scrambles: index = R.randint(0,len(self.actions)-1) a = self.actions[index] nexts = self.initial.move(a) if nexts is not None: serial = nexts.__str__() if serial not in seen: seen[serial] = True self.initial = nexts ns += 1 print('Problem:', self.__doc__, 'Initial state:') print(self.initial) print('==============') def successor(self, state): """Legal moves (blank moves left, right, up, down). Implemented as a generator""" for action in self.actions: nexts = state.move(action) if nexts is not None: yield (action,nexts) def goal_test(self, state): """For simplicity blank on top left""" return state.board==range(self.N*self.N) def h(self,node): """No heuristic. A* becomes uniform cost in this case""" return 0 def graph_search(problem, fringe): """Search through the successors of a problem to find a goal. The argument fringe should be an empty queue. If two paths reach a state, only use the best one. [Fig. 3.18]""" counter = 0 closed = {} fringe.append(Node(problem.initial)) max_depth=0 while fringe: node = fringe.pop() # Print some information about search progress if node.depth>max_depth: max_depth=node.depth if max_depth<50 or max_depth % 1000 == 0: pid = os.getpid() py = psutil.Process(pid) memoryUse = py.memory_info()[0]/1024/1024 print('Reached depth',max_depth, 'Open len', len(fringe), 'Node expanse', counter, 'Memory used (MBytes)', memoryUse) if problem.goal_test(node.state): return node, counter serial = node.state.__str__() if serial not in closed: counter += 1 closed[serial] = True fringe.extend(node.expand(problem)) return None def best_first_graph_search(problem, f): """Search the nodes with the lowest f scores first. You specify the function f(node) that you want to minimize; for example, if f is a heuristic estimate to the goal, then we have greedy best first search; if f is node.depth then we have depth-first search. There is a subtlety: the line "f = memoize(f, 'f')" means that the f values will be cached on the nodes as they are computed. So after doing a best first search you can examine the f values of the path returned.""" f = memoize(f, 'f') return graph_search(problem, PriorityQueue(min, f)) def astar_search(problem, h=None): """A* search is best-first graph search with f(n) = g(n)+h(n). You need to specify the h function when you call astar_search. Uses the pathmax trick: f(n) = max(f(n), g(n)+h(n)).""" h = h or problem.h h = memoize(h, 'h') def f(n): return max(getattr(n, 'f', -infinity), n.path_cost + h(n)) return best_first_graph_search(problem, f) def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary.""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn class Queue: """Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.""" def __init__(self): abstract def extend(self, items): for item in items: self.append(item) class PriorityQueue(Queue): """A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x).""" def __init__(self, order=min, f=lambda x: x): update(self, A=[], order=order, f=f) def append(self, item): bisect.insort(self.A, (self.f(item), item)) def __len__(self): return len(self.A) def pop(self): if self.order == min: return self.A.pop(0)[1] elif self.order is max: return self.A.pop(len(self.A)-1)[1] else: return self.A.pop()[1] def fmin(self): return self.A[0][0] class PuzzleManhattan(Puzzle): """Manhattan heuristic""" def h(self, node): return node.state.manhattan() class PuzzleLinearConflict(Puzzle): def h(self, node): return node.state.lcheuristic() class PuzzleDPreflected(Puzzle): def disjointpattern(self): dict1=pickle.load(open('DP1-2-3-new.p', 'rb')) print('scaricato file DP1-2-3-new.p: ', len(dict1)) dict2 = pickle.load(open('DP4-5-8-9-12-13-new.p', 'rb')) print('scaricato file DP4-5-8-12-13-new.p: ', len(dict2)) dict3 = pickle.load(open('DP6-7-10-11-14-15-new.p', 'rb')) print('scaricato file DP6-7-10-11-14-15-new.p: ', len(dict3)) dict4 = pickle.load(open('DP4-8-12-new.p', 'rb')) print('scaricato file DP4-8-12-new.p: ', len(dict4)) dict5 = pickle.load(open('DP1-2-3-5-6-7-new.p', 'rb')) print('scaricato file DP1-2-3-5-6-7-new.p: ', len(dict5)) dict6 = pickle.load(open('DP9-10-11-13-14-15-new.p', 'rb')) print('scaricato file DP9-10-11-13-14-15-new.p: ', len(dict6)) self.dict1 = dict1 self.dict2 = dict2 self.dict3 = dict3 self.dict4 = dict4 self.dict5 = dict5 self.dict6 = dict6 def h(self, node): board = node.state.board board1 = [] board2 = [] board3 = [] board4 = [] board5 = [] board6 = [] list1 = [] list2 = [] list3 = [] list4 = [] list5 = [] list6 = [] for p in range(len(board)): if board[p] is 1 or board[p] is 2 or board[p] is 3: list = [] list.append(board[p]) list.append(p) list1.append(list) if board[p] is 4 or board[p] is 5 or board[p] is 8 or board[p] is 9 or board[p] is 12 or board[p] is 13: list = [] list.append(board[p]) list.append(p) list2.append(list) if board[p] is 6 or board[p] is 7 or board[p] is 10 or board[p] is 11 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list3.append(list) if board[p] is 4 or board[p] is 8 or board[p] is 12: list = [] list.append(board[p]) list.append(p) list4.append(list) if board[p] is 1 or board[p] is 2 or board[p] is 3 or board[p] is 5 or board[p] is 6 or board[p] is 7: list = [] list.append(board[p]) list.append(p) list5.append(list) if board[p] is 9 or board[p] is 10 or board[p] is 11 or board[p] is 13 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list6.append(list) list1.sort() list2.sort() list3.sort() list4.sort() list5.sort() list6.sort() for p in range(len(list1)): e = list1[p][1] e1 = list4[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 board1.append(row) board4.append(row1) col = e % 4 + 1 col1 = e1 % 4 + 1 board1.append(col) board4.append(col1) for p in range(len(list2)): e = list2[p][1] e1= list3[p][1] e2 = list5[p][1] e3 = list6[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 row2 = e2 // 4 + 1 row3 = e3 // 4 + 1 board2.append(row) board3.append(row1) board5.append(row2) board6.append(row3) col = e % 4 + 1 col1 = e1 % 4 + 1 col2 = e2 % 4 + 1 col3 = e3 % 4 + 1 board2.append(col) board3.append(col1) board5.append(col2) board6.append(col3) board1 = map(str,board1) board1 = ''.join(board1) board1 = int(board1) board2 = map(str, board2) board2 = ''.join(board2) board2 = int(board2) board3 = map(str, board3) board3 = ''.join(board3) board3 = int(board3) board4 = map(str, board4) board4 = ''.join(board4) board4 = int(board4) board5 = map(str, board5) board5 = ''.join(board5) board5 = int(board5) board6 = map(str, board6) board6 = ''.join(board6) board6 = int(board6) h1 = self.dict1[board1] h2 = self.dict2[board2] h3 = self.dict3[board3] h4 = self.dict4[board4] h5 = self.dict5[board5] h6 = self.dict6[board6] hfirst = h1+h2+h3 hsecond = h4+h5+h6 h = max(hfirst, hsecond) return h class PuzzleDP(Puzzle): def disjointpattern(self): dict1 = pickle.load(open('DP1-2-3-new.p', 'rb')) print('scaricato file DP1-2-3-new.p: ', len(dict1)) dict2 = pickle.load(open('DP4-5-8-9-12-13-new.p', 'rb')) print('scaricato file DP4-5-8-9-12-13-new.p: ', len(dict2)) dict3 = pickle.load(open('DP6-7-10-11-14-15-new.p', 'rb')) print('scaricato file DP6-7-10-11-14-15-new.p: ', len(dict3)) self.dict1 = dict1 self.dict2 = dict2 self.dict3 = dict3 def h(self, node): board = node.state.board board1 = [] board2 = [] board3 = [] list1=[] list2= [] list3 = [] for p in range(len(board)): if board[p] is 1 or board[p] is 2 or board[p] is 3: list = [] list.append(board[p]) list.append(p) list1.append(list) if board[p] is 4 or board[p] is 5 or board[p] is 8 or board[p] is 9 or board[p] is 12 or board[p] is 13: list = [] list.append(board[p]) list.append(p) list2.append(list) if board[p] is 6 or board[p] is 7 or board[p] is 10 or board[p] is 11 or board[p] is 14 or board[p] is 15: list = [] list.append(board[p]) list.append(p) list3.append(list) list1.sort() list2.sort() list3.sort() for p in range(len(list1)): e = list1[p][1] row = e // 4 + 1 board1.append(row) col = e % 4 + 1 board1.append(col) for p in range(len(list2)): e = list2[p][1] e1= list3[p][1] row = e // 4 + 1 row1 = e1 // 4 + 1 board2.append(row) board3.append(row1) col = e % 4 + 1 col1 = e1 % 4 + 1 board2.append(col) board3.append(col1) board1 = map(str,board1) board1 = ''.join(board1) board1 = int(board1) board2 = map(str, board2) board2 = ''.join(board2) board2 = int(board2) board3 = map(str, board3) board3 = ''.join(board3) board3 = int(board3) h1 = self.dict1[board1] h2 = self.dict2[board2] h3 = self.dict3[board3] h = h1+h2+h3 return h
90c399a0a56af82d76b91741d7a7cfeff7c498de
mharizanov/pong-clock
/pypong-clock/event.py
1,482
3.953125
4
#!/usr/bin/python """ A lightweight event handler class Usage: Add Event() as a field to your class in __init__ self.score = Event() Assign a delegate to the event in your code: ball.score += delegate """ class Event: def __init__(self): self.handlers = set() # set ignores duplicates during add def add_handler(self, handler): """ Adds the handler passed in to the list""" #print 'handler = ', handler self.handlers.add(handler) #print len(self.handlers) return self def remove_handler(self, handler): """ Removes the handler passed in from the list. """ try: self.handlers.remove(handler) except: raise ValueError("This is not an event currently being handled") return self def __call__(self, *args, **kwargs): """ Will call the function added with handle""" for handler in self.handlers: #print handler handler(*args, **kwargs) def __len__(self): """ Returns the number of handlers. :return: int """ return len(self.handlers) def __str__(self): """ String representation of the delegates :return: str """ retval = '' for handler in self.handlers: retval = retval + ' ' + str(handler) return retval __iadd__ = add_handler # += support __isub__ = remove_handler # -= support
f9a35e20f1ea3bd640f3308dbf9e52c3bafcd8c7
gabrigode/twitch-songrequest-text
/script.py
1,604
3.515625
4
from urllib.request import urlopen import json import requests import time import os f = open('music.txt', 'w', encoding='utf-8') #CREATES A MUSIC.TXT AND IF ALREADY EXISTS REWRITES HIM print ('--------------------------TWITCH-SONGREQUEST-WRITE-----------------------------------------------------') check = True while check == True: try: channelName = input('Channel name:') channel_url = f'https://api.nightbot.tv/1/channels/t/{channelName}' channel_load = urlopen(channel_url) jsonList = json.load(channel_load) #LOADS THE SITE'S JSON channel_id = jsonList['channel']['_id'] #SEARCHS FOR THE CHANNEL'S ID print (f"Channel's id: {channel_id}") check = False except OSError: print('Channel not found, try again') continue def Music(): r = requests.get("https://api.nightbot.tv/1/song_requests/queue", headers={"Nightbot-Channel":channel_id}) #REQUESTS API DATA AND APPLY CHANNEL'S ID IN HTTP HEADER try: musicName = (r.json()['_currentSong']['track']['title']) #LOADS AS JSON AND SEARCHS FOR SONG'S NAME f = open('music.txt', 'r', encoding='utf-8') if (f.read()) == musicName: pass else: f = open('music.txt', 'w', encoding='utf-8') #PUTS THE NAME IN A TEXT FILE IF NOT ALREADY THERE print (f"Now playing: {musicName}") f.write(musicName) f.close() except TypeError: print ('Nothing playing...') pass while True: Music() time.sleep(10)
7b60d97076baad7219391a7cf817131b337bdd6b
chankruze/MathPy
/LCM.py
1,254
3.75
4
# Created by chankruze # Python Program to find the L.C.M. of two input number # define a function def lcm(x, y): """This function takes two integers and returns the L.C.M.""" # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm # Initial Value num_01 = 24 num_02 = 58 while True: try: # Note: Python 2.x users should use raw_input, the equivalent of 3.x's input input_01 = int(input("Enter first number: ")) input_02 = int(input("Enter second number: ")) except ValueError: print("/////////////////////////////////////////////////////") print("// Sorry, I did't understant that. //") print("// You must fill out a valid value to proceed ! //") print("/////////////////////////////////////////////////////") continue else: #input was successfully parsed! #we're ready to exit the loop. break num_01 = input_01 num_02 = input_02 print() print(">_The L.C.M. of" + str(num_01) + " and " + str(num_02) + " is " + str(lcm(num_01, num_02)))
826c795f7f3c2871e87bdb5a505d6d8c90435b1a
mrevilg/Clock-Conversion
/ClockString.py
534
4.1875
4
# from 24 hour to 12 hour format # obtain data as string from user user_input = input("Please input any 24hr time in the following format: hh:mm - ") # split string at ":" user_input = user_input.split(":") # convert hr:mm from string to int _hr = int(user_input[0]) _min = int(user_input[1]) # handle AM/PM ampm = "" if _hr == 12: ampm = "PM" elif _hr == 0: ampm = "AM" _hr = 12 elif _hr >= 12: ampm = "PM" _hr = _hr - 12 else: ampm = "AM" # display converted time print(str(_hr) + ":" +str(_min) + " " + ampm)
fb55f62c6cecf3f2ecd74af7e4b57312235e361f
eldorbaxtiyorov/python-darslar
/20-functions/javoblar-20-06.py
351
3.828125
4
""" 18/12/2020 Dasturlash asoslari #20-dars: FUNKSIYADAN QIYMAT QAYTARISH Muallif: Anvar Narzullaev Web sahifa: https://python.sariq.dev """ def fibonacci(n): sonlar = [] for x in range(n): if x == 0 or x == 1: sonlar.append(1) else: sonlar.append(sonlar[x - 1] + sonlar[x - 2]) return sonlar print(fibonacci(10))
436f82a2795ea5173f42d80b70c5f318f77d2b49
hizkiawilliam/random-python-programs
/Encrypt Decrypt v3.3.py
5,424
3.59375
4
""" PROGRAM ENCRYPTER DECRYPTER v3.3 by : Hizkia William Eben Program dibuat menggunakan Python v3.6.6 Merupakan modifikasi Tugas LAB Dasar-dasar Pemrograman Modul 4 Tujuan penggunaan untuk mengenkripsi dan dekripsi code Menggunakan prinsip Caesar Cypher yang dikembangkan Change log: v1.0 - Program akhir LAB DDP1 Modul 4 v2.0 - Program dapat berjalan terus - Opsi Enkripsi atau Dekripsi v3.0 - Function Enkripsi dan Dekripsi - Comment untuk setiap line - Mendukung enkripsi/dekripsi kalimat v3.2 - User friendly - Change log - Help menu - Cara kerja v3.3 - Menggabung fungsi encrypt dan decrypt jadi satu Cara Kerja : (lihat bawah program) """ print("<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>") print("<<< Program Enkripsi Dekripsi >>>") #judul print("<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>\n") #define fungsi untuk enkripsi def encrypt(pesan,choice): hasil = "" #buat variabel hasil berupa string kosong reverse2 = "" #reverse2 string kosong untuk diisi string hasil reverse1 count = 0 #counter sebagai check point pesan yang direverse for i in range(len(pesan)): #loop setiap isi pesan split = pesan[count:count+key1:] #memotong string menjadi bagian2 sesuai key 1 reverse1 = split[::-1] #membalik bagian yang telah dipotong count+=key1 #memastikan loop dimulai dari huruf key+1 reverse2 = reverse2 + reverse1 #memasukan potongan tadi kedalam string kosong reverse 2 for i in range(len(reverse2)): #loop untuk melakukan Caesar Cypher if 97 <= ord(reverse2[i]) <= 122: #memastikan pesan hanya berupa alfabet if choice == 1: code = ord(reverse2[i])%97 + key2 #menggeser ascii code setiap huruf sebanyak +key 2(encrypt) elif choice == 2: code = ord(reverse2[i])%97 - key2 #menggeser ascii code setiap huruf sebanyak -key 2(decrypt) hasil += chr((code%26) + 97) #memasukan huruf kedalam hasil, memastikan ord tetap dialfabet setelah digeser success = True #membuat variabel bantuan else: print("Tidak bisa mengenkripsi non-alphabet \n") #error handling jika memasukkan selain alfabet success = False break if success == True: return hasil #return hasil akhir while(1): #looping memulai program try: print(" Menu ") print("===============") print("|1. Enkripsi |") print("|2. Dekripsi |") print("|3. Bantuan |") print("===============") choice = int(input("Masukkan pilihan : ")) #input pilihan if choice == 1 or choice == 2: #memastikan input hanya '1' atau '2' #meminta input key1 = int(input("Masukkan Key 1\t : ").lower()) #input key 1 key2 = int(input("Masukkan Key 2\t : ").lower()) #input key 2 pesan = input("Masukkan Pesan\t : ").lower() #input pesan(dapat berupa kalimat) pesan_split = pesan.split() #memecah kalimat menjadi kata-kata final = "" #string kosong untuk output if key1 == 0: key1 += key2 for i in pesan_split: #loop untuk setiap kata pada kalimat final += encrypt(i,choice) #kata tersebut diproses fungsi encrypt final += " " #menambah spasi agar output menjadi kalimat print("Hasil enkripsi\t :",final,"\n") #print output akhir elif choice == 3: print("-Pilih 1 untuk melakukan enkripsi, 2 untuk dekripsi") print("-Masukkan key 1") print("-Masukkan key 2") print("-Masukkan pesan yang akan dienkripsi/dekripsi\n") else: #error handling jika pilihan diluar '1' atau '2' print("Pilihan tidak sesuai!\n") except: print("Pilihan tidak sesuai!\n") #error handling jika pilihan diluar angka """ <<< Cara Kerja >>> 1. Input yang berupa kalimat dipecah menjadi kata 2. Setiap kata tersebut diproses masing-masing dalam fungsi Encrypt/Decrypt 3. Di dalam fungsi tersebut, terjadi beberapa proses: 1. Melakukan proses pemenggalan dan pembalikan kata Memenggal pesan sesuai key 1 Pesan masuk = bertanggungjawab Kunci = 3 Pesan terpenggal = ber tan ggu ngj awa b Setelah itu tiap segment dibalik. Pesan dibalik = reb nat ugg jgn awa b Terakhir, setelah tiap segment dibalik, pesan kembali disatukan Hasil akhir = rebnatuggjgnawab 2. Melakukan proses enkripsi Caesar Cypher Menggeser setiap ord kata berdasarkan key 2 Kunci = 3 Input proses = rebnatuggjgnawab Output proses = uheqdwxjjmjqdzd 4. Memasukkan setiap kata yang telah diproses ke dalam variabel final 5. Mencetak output dari final """
1f91eac012d6516ef79d0411b4317727dba5b673
Deepa1996/python-assignment-2
/pgm5.py
144
4
4
list1=['EWT','SOIS','BDA','VLSI','ES'] str=input("enter the string") if str in list1 : print("SOIS is found") else : print("SOIS not found")
f65147f67fe710172e04a509f979255866536892
VBakhila/project-euler-python
/009.py
185
3.640625
4
from lib import pythagoreanTriples def main(n): return next(a * b * c for a, b, c in pythagoreanTriples() if a + b + c == n) if __name__ == '__main__': print(main(1000)) # 31875000
7966adb1c767bb4894b92969ddae9fbd38d24c36
zivzone/NCTU_Programming_Language_Exercise
/hw6/Q2.py
408
3.625
4
n = 7 graph = "" for i in range(0 , n - 1): line = "" #for j in range(0 , n - i -1): # line = line + " " line = line + " " * (n - i -1) line = line + "*" #for j in range(0 , 2 * i - 1): # line = line + " " line = line + "+" * (2 * i -1) line = line + "*\n" graph = graph + line graph = graph.replace("**" ,"*") graph = graph + "*" * (n * 2 - 1) print(graph)
d06e437e68cae0cd38bfc002afd03915d87b0a78
kavitshah8/PythonSandBox
/tutoring/crypto.py
813
3.859375
4
""" crypto.py Implements a simple substitution cypher """ alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" cipher = {'':'',} def main(): keepGoing = True while keepGoing: response = menu() if response == "1": plain = raw_input("text to be encoded: ") print encode(plain) elif response == "2": coded = raw_input("code to be decyphered: ") print decode(coded) elif response == "0": print "Thanks for doing secret spy stuff with me." keepGoing = False else: print "I don't know what you want to do..." def menu(): def encode(plain): length = len(plain) plain = plain.upper() for c in plain: return encoded def decode(coded): length = len(plain) plain = plain.upper() return decoded
d6cfbb92f185b994a24387085909bb6572c38ed0
msheikomar/pythonsandbox
/Python/B11_T3_Comprehension_MapAndLambda.py
554
4.375
4
num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] my_list = list() for n in num: my_list.append(n * n) print(my_list) # List Comprehension my_list = [n * n for n in num] print(my_list) # How to use map and lambda instead of list comprehension my_list = map(lambda n: n * n, num) print(my_list) # ***********To be fixed # Key Takeaway # If you see map and lambda function in you code. # It can be converted to list comprehension bcz 99% of time they can be. # Map will run each element from the list through the function. # Lambda is an anonymous function
6579d6d31177facd034911350703f25d455f6ac3
ScottishGuy95/google_foo.bar
/solar-doomsday/solution.py
725
3.578125
4
# Google foo.bar 2020 Challenge # solar-doomsday - Challenge 1 # When run in foo.bar, it handles testing the values import math def solution(area): panels = [] # Stores the area of each panel remainder = area # Store the current total area while remainder != 0: # Loop until there is no more area sqRoot = int(math.sqrt(remainder)) # Passes the current area to get its square root sqRoot = sqRoot * sqRoot # Get the area of that panel panels.append(sqRoot) # Add the panel size to list remainder -= sqRoot # Remove the panel area from the remainder return panels
af4edc53134382acbaefa69c63945a7bea0de67c
Reena-Kumari20/FunctionQuestions
/ATM_in_function/without_split.py
268
3.6875
4
def without_split(string): a=[] b=" " i=0 while i<len(string): if string[i]==" ": a.append(b) b=" " else: b=b+string[i] i=i+1 if b: a.append(b) return a string=("my name is reena sara sarmishtha anzum bharti") print(without_split(string))
50ae45873713e5d1eb2d64b27e3f3021a8f92ca8
naumy-code/python_project
/doc/collect/str_test/reverse_str.py
1,261
3.734375
4
""" 反转字符串 """ import re class reverse: def strReverse(self, strDemo): strList = [] for i in range(len(strDemo) - 1, -1, -1): strList.append(strDemo[i]) return ''.join(strList) def test(self): string = '1A234F5D' new_str = ''.join(re.findall(r'.{2}', string)[::-1]) return int(new_str, 16) def split_str(self, string, length): """ 按照指定长度分割输入字符串,并以列表形式返回 :param string: 待分割字符串 :param length: 指定分割长度 :return: 分割后的字符串列表 """ str_lst = re.findall(r'.{' + str(length) + '}', string) str_lst.append(string[(len(str_lst) * length):]) return str_lst def reverse_lst(self, string_lst): """ 将列表中的字符串反转 :param string_lst: 字符串列表 :return: 反转后的字符串列表 """ reverse_str_lst = [] for each in string_lst: reverse_str_lst.append(each[::-1]) reverse_str_lst.append(each[::-2]) return reverse_str_lst if __name__ == '__main__': code = 'DFCEABCG' case = reverse() print(case.test())
64073b2e37699acc4c7311480e0c8524b6631a04
ywtail/Aha-Algorithms
/1_3.py
499
3.734375
4
# coding:utf-8 # 快速排序(从小到大) inputs=map(int,raw_input().split()) n=len(inputs) def quicksort(left,right): if left>right: return base=inputs[left] i=left j=right while i!=j: while inputs[j]>=base and i<j: j-=1 while inputs[i]<=base and i<j: i+=1 #print i,j if i<j: inputs[i],inputs[j]=inputs[j],inputs[i] inputs[left],inputs[i]=inputs[i],inputs[left] #print inputs quicksort(left,i-1) quicksort(i+1,right) quicksort(0,n-1) for x in inputs: print x,
11ab9d206c773b4234c70b473f29fb534203f16b
AKLeee/LeetCode_OJ
/Permutations_II#106/PermutationsII.py
835
3.640625
4
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] if len(nums) is 0: return result used = [False]*len(nums) nums.sort() per = [] self.findpermutation(nums, used, per, result) return result def findpermutation(self, nums, used, per, result): if len(per) == len(nums): result.append(list(per)) return for i in range(len(nums)): if used[i]: continue if i > 0 and (nums[i] == nums[i-1]) and (used[i-1] == False): continue used[i] = True per.append(nums[i]) self.findpermutation(nums, used, per, result) used[i] = False per.pop() if __name__ == '__main__': print Solution().permuteUnique([1,1,2])
39fb7691cc196f8e6941a94ce791783c451f6c81
dipsuji/Phython-Learning
/practiceset/queue_implementation_usingdeque.py
334
3.859375
4
# Importing the library from collections import deque # Creating a Queue queue = deque([]) print(queue) # Enqueuing elements to the Queue queue.append(7) # [1,5,8,9,7] queue.append(0) # [1,5,8,9,7,0] print(queue) # Dequeuing elements from the Queue queue.popleft() # [5,8,9,7,0] # Printing the elements of the Queue print(queue)
1fd6b09257f19addacc67f59ed52824999d73ea7
YKyo/AOJ-ITP1
/ITP1_9_A.py
197
3.625
4
W = input() T = [] counter = 0 while True: InputList = input() if InputList=="END_OF_TEXT": break T += InputList.split() for i in T: if i in W and W in i: counter += 1 print(counter)
0d83775457f807a442989badc0c7568bf4065cf7
sandrogaoyun/upgraded-garbanzo
/田忌赛马.py
1,147
3.640625
4
""" 现在我们将齐王的马抽象为一个列表 [3,6,9],田忌的马抽象为另一个列表 [2,5,8], 分别代表各自的下、中、上等马。 设计一个函数 race(),将两个列表作为参数传递给 race(), 将背景资料的策略抽象为代码使田忌赢得比赛,函数返回每轮对阵情况 """ import itertools qi_wang = [3, 6, 9] tian_ji = [2, 5, 8] #期望输出结果[(3, 5), (6, 8), (9, 2)] def race (p1, p2): match = [] #每局比赛, 比如((3, 2), (6, 5), (9, 8)) p1_l = [] #p1所有派遣马匹的方式 p2_l = [] #p2所有派遣马匹的方式 p2_l = list(itertools.permutations(p2, 3)) for i in range (0, len(p2_l)): p1_l.append(p1) match_win = 0 for i in range (0, len(p2_l)): #每局比赛,包括三轮 game_win = 0 game = [] for j in range (0, len(p2_l[i])): #每轮比赛, if p1_l[i][j] < p2_l[i][j]: game_win += 1 game.append((p1_l[i][j], p2_l[i][j])) if game_win >= 2: match_win += 1 match.append(game) print (match) race (qi_wang, tian_ji)
bebfef1324e30f33b5476876365e858d23adaa64
aparna-narasimhan/python_examples
/Strings/add_binary_strings.py
1,122
3.78125
4
''' Add binary strings "1000","10" -> "1010" ''' def add(A,B): #Convert the given numbers to decimal #Add the numbers #Convert number to decimal #Return the number num_A = atoi(A) num_B = atoi(B) print("num_A", num_A) print("num_B", num_B) dec_A = bin_to_dec(num_A) dec_B = bin_to_dec(num_B) print("dec_A", dec_A) print("dec_B", dec_B) result = dec_to_bin(dec_A+dec_B) print(result) def bin_to_dec(num): pow = 0 res = 0 while num > 0: digit = num % 10 res += digit * (2 ** pow) pow += 1 num = num // 10 return res def dec_to_bin(num): stack = [] res = "" while num > 0: rem = num % 2 stack.append(rem) num = num // 2 print("stack", stack) while len(stack) > 0: res += str(stack.pop()) return res def atoi(s): #Use a dictionary atoi_dict = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6,'7': 7, '8': 8, '9': 9} result = 0 for ch in s: result = result * 10 + atoi_dict[ch] #print(result) return(result) add("1000","10")
c8a85f4c8a15eb32230c78a777f5b7b65c48472b
AdamZhouSE/pythonHomework
/Code/CodeRecords/2108/60775/241875.py
226
3.53125
4
def count(num): count = 0 while num > 0: if num % 10 == 1: count += 1 num = num // 10 return count n = int(input()) count1 = 0 for i in range(n+1): count1 += count(i) print(count1)
e583e826c2f2d91f3f4117f88cb1107f87e80e33
abhishektandon-github/programming-lab-csc6l2-17208
/program3.py
205
4
4
def gcd(a,b): if (b == 0): return a return gcd(b, a%b) a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) print('GCD of', a, 'and', b, 'is', gcd(a, b))
86f6e565a7240006f0189388fc78c948585f8fbc
japarker02446/BUProjects
/CS521 Data Structures with Python/Homework3/japarker_hw_3_5.py
788
3.5625
4
# -*- coding: utf-8 -*- """ japarker_hw_3_5.py Jefferson Parker Class: CS 521 - Spring 1 Date: February 3, 2022 Read the contents of a student record file. Read each row into a tuple. Store each tuple into a single list. Print the LIST of tuple values. """ # Import needed modules. from os.path import exists # Initialize variables INPUT_FILE = "cs521_3_5_input.txt" student_tuple = () student_list = [] # Open and read the content of the input file. if exists(INPUT_FILE): infile = open(INPUT_FILE, "r") for line in infile: student_tuple = line.strip().split(',') student_list.append(student_tuple) infile.close() print("Student records: ", student_list) else: print("ERROR: input file ", INPUT_FILE, " not found.")
d4c23b40a2d57e9a1a620739bd4829d05a8d814e
RicardoHernandezVarela/algoritmos-basicos-con-python
/Operaciones.py
485
4.0625
4
numero1 = float(input("Escribe un número real ")) numero2 = float(input("Escribe otro número real ")) operacionDeseada = input("¿Qué operación deseas realizar con estos números, 1 = suma, 2 = multiplicación, 3 = división ") if operacionDeseada == "1": suma = numero1 + numero2 print(suma) elif operacionDeseada == "2": multiplicacion = numero1 * numero2 print(multiplicacion) elif operacionDeseada == "3": division = numero1 / numero2 print(division)
f3ec5feab5000a80b26f8b2bc52380fed0dc113b
sumitchans/cards
/cards.py
3,953
3.859375
4
import random from functools import cmp_to_key def sort_data(arr, arr1): for i in range(len(arr)-1, -1, -1): if arr[1][i] > arr1[1][i]: return 1 elif arr[1][i] < arr1[1][i]: return -1 return 0 class CardGame: cards_value = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] cards = {"A": 1, "K": 12, "Q": 11, "J": 10, "9": 9, "8": 8, "7": 7, "6": 6, "5": 5, "4": 4, "3": 3, "2": 2} cards_order = ["2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"] def __init__(self, num_of_players=4): self.num_of_players = num_of_players def check_series(self, player_cards): """ Function to check the series of the card :param player_cards: :return: """ order = [] for i in player_cards: order.append(self.cards_order.index(i)) # print(order, player_cards) order.sort() for p in range(0, len(order)-1): if order[p] != order[p+1]-1: # print("false") return False # print("true") return True def check_order(self, player_cards): """ Function to check the order of the order :param player_cards: :return: """ if len(player_cards) == 3: if player_cards[0] == player_cards[1] == player_cards[2]: return 1 elif self.check_series(player_cards): return 2 elif player_cards[0] == player_cards[1] or player_cards[1] == player_cards[2] or \ player_cards[0] == player_cards[2]: return 3 else: return 4 return -1 def get_winner(self, player_cards): """ Function to deciced winner :param player_cards: :return: """ pld = {} player_data = [] i = 0 for pl in player_cards: player_data.append(sorted([self.cards_order.index(p) for p in player_cards[pl]])) pld[pl] = sorted([self.cards_order.index(p) for p in player_cards[pl]]) i += 1 result = sorted(pld.items(), key=cmp_to_key(sort_data)) winner = [] max_arr = result[len(result)-1] winner.append(max_arr[0]) for i in range(len(result)-2, -1, -1): if result[i][1] == max_arr[1]: winner.append(result[i][0]) return winner def start_game(self, player_cards=None): """ Function to start game and return winner :return: """ num_of_players = self.num_of_players total_cards = list(self.cards.keys()) * 4 if self.num_of_players * 3 > len(total_cards): return "Game is not possible" if not player_cards: player_cards = {} for i in range(0, num_of_players): player_cards[chr(65+i)] = [] for pl in player_cards: for i in range(0, 3): player_cards[pl].append(total_cards.pop()) random.shuffle(total_cards) print(player_cards) player_rank = {} for pl, crs in player_cards.items(): player_rank[pl] = self.check_order(crs) print(player_rank) max_order = min(player_rank.values()) top_players = {} for pl, order in player_rank.items(): if order == max_order: top_players[pl] = player_cards[pl] winner = self.get_winner(top_players) print(winner) while len(winner) != 1 and total_cards: top_players = {} for pl in winner: top_players.update({pl: [total_cards.pop()]}) random.shuffle(total_cards) winner = self.get_winner(top_players) return winner if __name__ == "__main__": num_of_player = 4 print(CardGame(num_of_player).start_game())
e98b8d8d2edb24c8c9ed2e53e222d529530822a3
NOBarbosa/Exercicios_Python
/Mundo2/ex053.py
334
3.921875
4
#Detector de Palíndromo frase = str(input('Digite uma frase: ')).strip().upper() palavra = frase.split() junto = ''.join(palavra) inverso = '' for letra in range(len(junto)-1, -1, -1): inverso += junto[letra] if junto == inverso: print('{} é palindromo'.format(frase)) else: print('{} não é palindromo'.format(frase))
a463b3157458faff9c05d3dfc463a0ea6ad362dc
Harshit-Poddar90/hacktoberfest2K
/2k20/scripts2020/felipe_souza.py
528
4.03125
4
""" A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar. There are also numeric palindromes, including date/time stamps using short digits 11/11/11 11:11 and long digits 02/02/2020. Sentence-length palindromes ignore capitalization, punctuation, and word boundaries. """ def is_palindrome(word): """ This function receives a string named as word and return if the word is a palindrome or not """ return word == word[::-1]
807fff9a01618b3bf74e752a210047fa44cf83bc
huhuzwxy/leetcode
/sort/148_sort_list.py
2,340
3.5625
4
#问题: #将一个链表排序,时间复杂度为O(nlogn),空间复杂度为0(1) #Input: 4 -> 2 -> 1 -> 3 #Output:1 -> 2 -> 3 -> 4 #思路: #时空复杂度决定所用排序方法为 归并排序 #利用快慢指针找链表中点 #快慢指针在链表中常用,(1)找链表中点(快一次走两步,慢一次走一步)(2)判断链表中是否有环(同1)(3)找链表中倒数第k个结点(快慢指针差k个结点)(4)单链表反转(快慢差1,每次都只走一步) class ListNode: def __init__(self,x): self.val = x self.next = None def print(self): while self: print(self.val) self = self.next class Solution: def sortList(self, head): if head == None or head.next == None: return head mid = self.findmid(head) l1 = head l2 = mid.next mid.next = None #注意设置mid.next = None,不然l1为整个链表,将中点后设置为空。 l1 = self.sortList(l1) l2 = self.sortList(l2) return self.mergesort(l1, l2) #快慢指针找链表中点或者判断链表是否有环,一个一次走一步,一个一次走两步。 def findmid(self, head): #链表为空或只有一个时直接返回 if head == None or head.next == None: return head slow = head fast = head #链表值有两个时,slow指向第一个,直接找到中点 while fast.next and fast.next.next: slow = slow.next fast = fast.next.next return slow def mergesort(self, l1, l2): heada = current = ListNode(0) if l1 == None or l2 == None: return l2 or l1 while l1 and l2: if l1.val <= l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next if l1: current.next = l1 else: current.next = l2 return heada.next if __name__ == '__main__': a = ListNode(4) a.next = ListNode(2) a.next.next = ListNode(1) a.next.next.next = ListNode(3) ListNode.print(a) s = Solution() result = s.sortList(a) ListNode.print(result)
8b73c895ba1c05023077e6667d96373139200765
Cybr0/Python
/lesson_8/le_8_3_3_input_and_output_serialization_pickle.py
924
3.65625
4
import pickle import reprlib class Person(object): def __init__(self, name, age, siblings=None): self.name = name self.age = age self.siblings = siblings or [] @reprlib.recursive_repr() def __repr__(self): return 'Person({name!r}, {age!r}, {siblings!r})'.format_map(self.__dict__) @staticmethod def make_siblings(first, second): first.siblings.append(second) second.siblings.append(first) p = Person('John', 19,) p2 = Person('Mellisa', 23,) Person.make_siblings(p, p2) with open('le_8_dir/example8_2.pkl', 'wb') as data: pickle.dump((p, p2), data) with open('le_8_dir/example8_2.pkl', 'rb') as data: people = pickle.load(data) print(people) print('---------') pickle_str = pickle.dumps([12, 11]) print(pickle_str) print(type(pickle_str)) pickle_str = pickle.loads(pickle_str) print('---------') print(pickle_str) print(type(pickle_str))
dc0e9b409eaf384eea0c6b64da96750bd3462799
heitorchang/reading-list
/algoritmos_cormen_pt/ordenacao/my_heapsort.py
5,016
3.859375
4
class Heap: def __init__(self, value): self.value = value self.left = None self.right = None def max_heapify(self): L = getattr(self, 'left', None) R = getattr(self, 'right', None) left_val = getattr(L, 'value', float('-inf')) right_val = getattr(R, 'value', float('-inf')) if left_val > right_val and left_val > self.value: self.value, self.left.value = self.left.value, self.value self.left.max_heapify() elif right_val > left_val and right_val > self.value: self.value, self.right.value = self.right.value, self.value self.right.max_heapify() # if L and self.left.value > self.value # self.value, self.left.value = self.left.value, self.value # self.left.max_heapify() # elif R and self.right.value > self.value and self.right.value > self.left.value: # self.value, self.right.value = self.right.value, self.value # self.right.max_heapify() # if L and self.left.value > self.value: # largest = "L" # largest_value = self.left.value #else: # largest = "self" # largest_value = self.value #if R and self.right.value > largest_value: # largest = "R" #if largest == "L": # self.value, self.left.value = self.left.value, self.value # self.left.max_heapify() #elif largest == "R": # self.value, self.right.value = self.right.value, self.value # self.right.max_heapify() def build_max_heap(self): q = [] visited = [self] q.insert(0, self) while q: node = q.pop() L = getattr(node, 'left', None) R = getattr(node, 'right', None) if L: q.insert(0, node.left) visited.insert(0, node.left) if R: q.insert(0, node.right) visited.insert(0, node.right) #return visited for node in visited: node.max_heapify() def all_but_top(self): q = [] visited = [] q.insert(0, self) while q: node = q.pop() if node.left: q.insert(0, node.left) visited.append(node.left.value) if node.right: q.insert(0, node.right) visited.append(node.right.value) return visited def show_tree(self): q = [] q.insert(0, self) repr = "" levels = [1,2,4,8,16,32] trigger = [1,3,7,15,31,63] ct = 0 while q: if ct in trigger: repr += "\n" node = q.pop() repr += str(node.value) + " " L = getattr(node, 'left', None) R = getattr(node, 'right', None) if L: q.insert(0, node.left) if R: q.insert(0, node.right) ct += 1 print(repr) # return str(self.value) def __repr__(self): return str(self.value) def make_heap_node(A, i): root = Heap(A[i]) if 2*i < len(A): root.left = Heap(A[2*i]) if (2*i) + 1 < len(A): root.right = Heap(A[(2*i) + 1]) return root def array_to_heap(arr_zero_indexed): arr_len_zero = len(arr_zero_indexed) arr = [0] + arr_zero_indexed arr_len = len(arr) heaps = [] for i in range(arr_len): # make each element a unique heap heaps.append(Heap(arr[i])) for i in range(arr_len // 2, 0, -1): # connect heaps if 2 * i < arr_len: # print("connect heap left ", i, "to", 2 * i) heaps[i].left = heaps[2 * i] if 2 * i + 1 < arr_len: # print("connect heap right ", i, "to", 2 * i + 1) heaps[i].right = heaps[2 * i + 1] return heaps[1] def test_heap(): h = Heap(16) h.left = Heap(4) h.right = Heap(10) h.left.left = Heap(14) h.left.right = Heap(7) h.right.left = Heap(9) h.right.right = Heap(3) h.left.left.left = Heap(2) h.left.left.right = Heap(8) h.left.right.left = Heap(1) return h def test_heap_2(): h = Heap(4) h.left = Heap(1) h.right = Heap(3) h.left.left = Heap(2) h.left.right = Heap(16) h.right.left = Heap(9) h.right.right = Heap(10) h.left.left.left = Heap(14) h.left.left.right = Heap(8) h.left.right.left = Heap(7) return h def my_heapsort(A): result = [] h = array_to_heap(A) for i in range(len(A)): h.build_max_heap() # print("top of heap", h.value) result.insert(0, h.value) rest = h.all_but_top() # print("rest", rest) if rest: h = array_to_heap(rest) return result
57a0c135f1c41f43167cd7681d192234900d3034
clnFind/DayDayAlgorithm
/str_left_rotate.py
1,903
3.921875
4
# -*- coding: utf-8 -*- import time """ 使用两种方法实现 字符串左移 n 位 第一种借鉴网络上的代码 第二种自己实现的 """ class Solution: def __init__(self, strs, n): self.strs = strs self.n = n def left_rotate_string(self): if len(self.strs) < self.n or self.n < 1: return self.strs str_list = list(self.strs) self.reverses(str_list) length = len(self.strs) index = length - self.n front_list = self.reverses(str_list[:index]) print(front_list) behind_list = self.reverses(str_list[index:]) print(behind_list) result = ''.join(front_list) + ''.join(behind_list) return result def reverses(self, alist): if alist == None or len(alist) <= 0: return '' start_index = 0 end_index = len(alist) - 1 while start_index < end_index: alist[start_index], alist[end_index] = alist[end_index], alist[start_index] start_index += 1 end_index -= 1 return alist def reverse_str(strs, n): """ 使用内置方法实现reverse 内置方法 效率更高 :param strs: :param n: :return: """ if len(strs) < n or n < 1: return strs s_reverse = list(strs) s_reverse.reverse() index = len(strs) - n front = s_reverse[:index] front.reverse() back = s_reverse[index:] back.reverse() return ''.join(front) + ''.join(back) if __name__ == '__main__': test = '123456' t1 = time.time() s = Solution(test, 2) print(s.left_rotate_string()) t2 = time.time() print("使用循环迭代耗时: ", t2-t1) t3 = time.time() l = reverse_str(test, 2) print(l) t4 = time.time() print("使用内置reverse耗时: ", t4-t3) if t4-t3 < t2-t1: print(True)
7679503495abfdf8ec0ee631baa36aa4e1dc01bb
juanhurtado4/CS-2-Tweet-Generator
/markov_sentence_generator.py
4,621
3.546875
4
import random import sys import re import string def get_clean_data(raw_data): ''' raw_data: String Function cleans raw_data from punctuations, numbers, spaces etc, to only leave words Returns list ''' crowd_reaction_removed = re.sub('\(\w*\)', '', raw_data) crowd_reaction_removed = re.sub('\(\w*\s\w*\)', '', crowd_reaction_removed) numbers_removed = re.sub('\d\w*', '', crowd_reaction_removed) # punctuationless_data = ''.join([char for char in numbers_removed # if char not in string.punctuation])# Removes punctuation from data # import pdb; pdb.set_trace() # old # clean_data = re.split('\s*', punctuationless_data)[:-1] # Splits data based on whitespace # clean_data = re.split('\s*', punctuationless_data) # Splits data based on whitespace clean_data = re.split('\s*', crowd_reaction_removed) # Splits data based on whitespace return clean_data def get_random_word(histogram): ''' Histogram: Key Value pair. Key: String, Value: Int Returns a single word at random ''' rand_num = random.random() cummulitive_wght = 0 for key, value in histogram.items(): word_probability = value / sum(histogram.values()) cummulitive_wght += word_probability if rand_num <= cummulitive_wght: random_word = key break return random_word def sentence_generator(num_words_in_sentence, histogram): ''' Num_words_in_sentence: Int Histogram: Key Value pair. Key: String | Value: Int Function generates a sentence from a markov_chain Returns a string ''' sentence = '' counter = 0 list_of_words = list(histogram) starting_word = random.choice(list_of_words) while counter != num_words_in_sentence: rand_word = get_random_word(histogram[starting_word]) sentence += rand_word + ' ' starting_word = rand_word counter += 1 return sentence.strip().capitalize() def get_histogram(word_list): # result = {} # for index, word in enumerate(word_list): # try: # next_word = word_list[index + 1] # except: # break # if word not in result: # result[word] = {next_word: 1} # else: # if next_word not in result[word]: # result[word].update({next_word: 1}) # else: # result[word][next_word] += 1 # return result # def get_histogram(word_list): # Second order markov chain implemented below # result = {} # for index, word in enumerate(word_list): # try: # next_word = word_list[index + 1] # after_next = word_list[index + 2] # next_state = next_word + ' ' + after_next # except: # break # if word not in result: # result[word] = {next_state: 1} # Implement as tuple or string # else: # if next_state not in result[word]: # result[word].update({next_state: 1}) # else: # result[word][next_state] += 1 # return result result = {} order = 10 for index, word in enumerate(word_list): try: next_state = ' '.join(word_list[index + 1: index + 1 + order]) except: break if word not in result: result[word] = {next_state: 1} # Implement as tuple or string else: if next_state not in result[word]: result[word].update({next_state: 1}) else: result[word][next_state] += 1 return result def test_frequency(): ''' Function test sentence generator ''' from dictionary_histogram import get_histogram as test markov_chain = {'one': {'fish': 1}, 'fish': {'two': 1, 'red': 1, 'blue': 2}, 'two': {'fish': 1}, 'red': {'fish': 1}, 'blue': {'fish': 1}} # list_of_words = get_clean_data(sentence_generator(1000, markov_chain)) list_of_words = sentence_generator(1000, markov_chain).lower().split(' ') histogram = test(list_of_words) return histogram if __name__=='__main__': # with open('obama_speech.txt') as file: with open('short_version_obama_speech.txt') as file: # with open('one_fish_text.txt') as file: raw_data = file.read().lower() clean_data = get_clean_data(raw_data) # print(clean_data) histogram = get_histogram(clean_data) print(histogram) # print(sentence_generator(10, histogram)) # print(test_frequency())
0794a3460362805a44abc2b90de4143ad0c10225
zzz136454872/leetcode
/isIdealPermutation.py
1,478
3.703125
4
from typing import List # 775. 全局倒置与局部倒置 class Solution1: def isIdealPermutation(self, nums: List[int]) -> bool: res1 = 0 n = len(nums) for i in range(n - 1): if nums[i] > nums[i + 1]: res1 += 1 def mergeSort(start, end): if start >= end - 1: return 0 mid = (start + end) // 2 res = mergeSort(start, mid) res += mergeSort(mid, end) i = start j = mid tmp = [] while i < mid and j < end: if nums[i] < nums[j]: tmp.append(nums[i]) i += 1 else: tmp.append(nums[j]) j += 1 res += mid - i if i < mid: tmp += nums[i:mid] if j < end: tmp += nums[j:end] for k in range(end - start): nums[k + start] = tmp[k] return res tmp = mergeSort(0, len(nums)) return tmp == res1 # nums = [1, 0, 2] # nums = [1, 2, 0] # print(Solution().isIdealPermutation(nums)) # 更快一些的方法 class Solution: def isIdealPermutation(self, nums: List[int]) -> bool: for i in range(len(nums)): if abs(nums[i] - i) > 1: return False return True nums = [1, 0, 2] print(Solution().isIdealPermutation(nums))
650010b2c2f59c08f6bc6a6633902d7a460c0725
ermeydan-coder/Python-IT-Fundamentals
/workshop_exercises/4_not_valid_number_message.py
351
4.125
4
'''cKullanıcıdan girdi alan ve girilen değer sayı değilse "sayı" is not valid number mesajı veren bir fonksiyon yazın''' def get_integer(prompt): while True: tempt = input(prompt) if tempt.isnumeric(): return tempt print("{0} is not a valid number".format(tempt)) get_integer("Please enter a number: ")
6006b3d2026674d94b84318eb129cebbcb35ebd5
davearch/coding-patterns
/extras/merge_sort.py
2,020
4.0625
4
# O(n * log(n)) # merge sort is a divide and conquer fast sorting algorithm # 2 major subroutines: # - split(arr) # - merge(left, right) from linked_list import Node, LinkedList class Solution: def sortList(self, head): if head is None or head.next is None: return head # get middle... yield a mid midpos = (self._list_length(head) - 1) // 2 mid = self._get_node_at_pos(head, midpos) # cut list in half nexttomiddle = mid.next mid.next = None # split and merge leftSortedNode = self.sortList(head) rightSortedNode = self.sortList(nexttomiddle) return self.merge(leftSortedNode, rightSortedNode) def merge(self, p, q): # recursive solution - (n-1) comparisons result = None if not p: return q if not q: return p if p.data <= q.data: result = p result.next = self.merge(p.next, q) else: result = q result.next = self.merge(p, q.next) return result def _list_length(self, node): if node is None: return 0 count = 0 while node: node = node.next count += 1 return count def _get_node_at_pos(self, head, pos): if pos == 0: return head count = 0 while head: if count == pos: return head head = head.next count += 1 return None # utility function to print list def printList(head): if not head: print(" ") return curr = head while curr: print(curr.data, end=" ") curr = curr.next print(" ") if __name__ == "__main__": llist = LinkedList() llist.append(15) llist.append(10) llist.append(5) llist.append(20) llist.append(3) llist.append(2) s = Solution() sorted_list = s.sortList(llist.head) printList(sorted_list)
8dec675b4a2e26f8c8327e6faaaa399212ac5554
KLC2018/Sunghun-Study-2-day
/practice3.py
73
3.71875
4
a = int(input()) for b in range(1,10): print("%d * %d = %d" %(a,b,a*b))
77c5096b56fc1b94da811678715c2af6d132af00
Ahmad-Bamba/PythonHomework
/Grades.py
452
3.90625
4
# Test Grade Program # Ahmad Bamba # 9/12/2016 def parselettergrade(grade): if grade >= 91: return "A" elif grade >= 81: return "B" elif grade >= 71: return "C" elif grade >= 61: return "D" else: return "F" score = int(input("What did you get on the test? ")) print ("Your letter grade is: " + parselettergrade(score)) x = input("Press ENTER to close ") print "Closing..."
77cd5b0e645f35dfeb67faee25ddc4fcef9528e7
Biiinggg/210CT
/Week 3/Exercise 1.py
273
4.125
4
txt = input("Enter a string: ") lst = txt.split() ##Split takes Strng input and splits up the words into List lst.reverse() ## Reverses the order of the List str = ' '.join(lst) ## Adds the items from the list to a String, adding a space between each entry print(str)
61a40297963770b5e0146680419e63e8b26e228c
KhuneSintWaiWai10/Sample
/starpattern.py
145
3.828125
4
num_rows = int(input("Enter the number of rows")); k = 1 for i in range(0, num_rows): for j in range(0, k): print("* ", end="") k = k + 1 print()
4f8b8ffea08be3ab3e4fd50286fcfbcd239b7ca5
haidarontor/python
/tuples_variable.py
315
3.765625
4
tuple = ('laptop','desktop','talha','rifat',78783,-83787,888.9399) var_tuple= (1,2,3,4,5,6) print tuple print tuple[3] print tuple[2:4] print tuple[2:] print tuple*4 print tuple + var_tuple string_tuple1= ("world","one","two","three") string_tuple2= ('four','five','six') print string_tuple1 + string_tuple2
7ef2750c3c87a5acd28d8e55d19296b66a45a056
emmanuelq2/python-algorithms
/tries/rway_tries.py
3,933
3.8125
4
# -*- coding: utf-8 -*- class RWaySt(object): """ R-way trie symbol table. It runs O(L) for insertion and search hit. It may run sublinear time O(LogL) for searching if item was not found since it stops searching after the first symbol mismatch. Also it uses (R + 1)N space where R is a radix (256 for ASCII and 65535 for Unicode) which may use huge amount of space while processing a lot of items. """ class Node(object): def __init__(self, value=None): self.value = value self.has_value = False # we use ASCII table by default self.children = [None] * 256 def __getitem__(self, item): return self.children[item] def __setitem__(self, key, value): self.children[key] = value def __init__(self): self.root = self.Node() def __setitem__(self, key, value): def put(node, l, key, value): if node is None: node = self.Node() if l == len(key): node.value = value node.has_value = True else: c = ord(key[l]) node[c] = put(node[c], l + 1, key, value) return node self.root = put(self.root, 0, key, value) def __getitem__(self, item): node = self._get_node(self.root, item) if node.has_value: return node.value else: raise KeyError(item) def _get_node(self, node, key): for i in xrange(len(key)): node = node[ord(key[i])] if node is None: raise KeyError(key) return node def __delitem__(self, key): def delete(node, l, key): if node is None: raise KeyError(key) if l == len(key): node.value = None node.has_value = False else: c = ord(key[l]) node[c] = delete(node[c], l + 1, key) # if all the children links are null - remove this node if not any(node.children) and not node.has_value: node = None return node children = delete(self.root, 0, key) self.root = children if children is not None else self.Node() def __iter__(self): """ Iterate over items (key, value) pairs """ return self._collect(self.root, '') def _collect(self, node, key): if node is None: return if node.has_value: yield (key, node.value) for n, child in enumerate(node.children): # Python 2 does not support "yield from" statement, so we do this: for item in self._collect(child, key + chr(n)): yield item def items_with_prefix(self, prefix): try: node = self._get_node(self.root, prefix) items = [] for item in self._collect(node, prefix): items.append(item) return items except KeyError: return [] def longest_prefix(self, prefix): def search(node, prefix, length, d): if node is None: return length if node.has_value: length = d if len(prefix) == d: return length return search(node[ord(prefix[d])], prefix, length, d + 1) return prefix[:search(self.root, prefix, 0, 0)] if __name__ == '__main__': st = RWaySt() st['by'] = 'BY' st['age'] = 'AGE' st['s'] = 'S' st['shell'] = 'SHELL' st['she'] = 'SHE' assert st['s'] == 'S' assert st['shell'] == 'SHELL' del st['she'] assert list(iter(st)) == [('age', 'AGE'), ('by', 'BY'), ('s', 'S'), ('shell', 'SHELL')] assert st.items_with_prefix('a') == [('age', 'AGE')] assert st.longest_prefix('shellsort') == 'shell'
c0fce4424d21dab882057a3b39c2614ff1dc9ab8
jeremyfix/ros_rgb_pcl
/test_kinect/nodes/read_xyzrgb.py
1,547
3.609375
4
#!/usr/bin/python # In this script, we demonstrate how to read a pointcloud XYZ RGB # with python # For fun, we generate an image # This demonstration is to be used with gen_xyzrgb.py where we generate # points with x,y in [0, 1] import rospy from sensor_msgs.msg import PointCloud2, PointField, Image from cv_bridge import CvBridge import sensor_msgs.point_cloud2 as pc2 import struct import numpy as np def unpack_rgb(rgb_float, big_endian=False): # Get the bytes of the float rgb_float fmt = "f" if(big_endian): fmt = "!" + fmt packed = struct.pack(fmt , rgb_float) integers = [ord(c) for c in packed] return integers[0], integers[1], integers[2] def pcl_cb(points_msg, bridge, image_pub): gen = pc2.read_points(points_msg, skip_nans=True) # The point cloud we use as an input is generating x,y in [0,1] # And the size (100 x 100) is actually choosen to get a filled image :) # because of the way we generate the data in gen_xyzrgb.py # by the way, this is just an example. height = 50 width = 50 cv_image = np.zeros((height,width,3), np.uint8) for x,y,z,rgb in gen: (r,g,b) = unpack_rgb(rgb) cv_image[height - 1 - round(y*height), round(x*width), :] = (r,g,b) image_pub.publish(bridge.cv2_to_imgmsg(cv_image, "bgr8")) rospy.init_node("read_xyzrgb") bridge = CvBridge() image_pub = rospy.Publisher("image",Image, queue_size=1) xyzrgb_pub = rospy.Subscriber("points", PointCloud2, lambda msg: pcl_cb(msg, bridge, image_pub)) rospy.spin()
21f1b2e0ca8c69d1be720569719c7bb2e12c5b78
sumit-jaswal/data_structures_and_algos
/binary_search_iterative_approach.py
505
4.125
4
# Binary Search # Searching for an element in a sorted list by dividing it into sublists based on the location of the element to be found # Iterative approach def binary_search_iterative(array,search): lower = 0 higher = len(array) while(lower<=higher): half = (lower+higher)//2 if(search>array[half]): lower = half+1 elif(search<array[half]): higher = half-1 else: return True return False array = [23,45,67,89,123,323,578] search = 67 print(binary_search_iterative(array,search))
1ce454e9b402e405cb05ed73847368a7194c3542
AlexChingEraser/leetcode-problem
/isValid_有效的括号.py
1,194
3.8125
4
# 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 # # 有效字符串需满足: # # # 左括号必须用相同类型的右括号闭合。 # 左括号必须以正确的顺序闭合。 # # # 注意空字符串可被认为是有效字符串。 # # 示例 1: # # 输入: "()" # 输出: true # # # 示例 2: # # 输入: "()[]{}" # 输出: true # # # 示例 3: # # 输入: "(]" # 输出: false # # # 示例 4: # # 输入: "([)]" # 输出: false # # # 示例 5: # # 输入: "{[]}" # 输出: true # class Solution: # def isValid(self, s: str) -> bool: # 有点类似判断回文字符串 class Solution: def isValid(self, s: str) -> bool: # bracket = {'(': ')', '{': '}', '[': ']'} d = {")": "(", "]": "[", "}": "{"} l = [] for i in s: if d.get(i) is None: l.append(i) elif len(l) == 0 or d.get(i) != l[-1]: return False elif d.get(i) == l[-1]: l.pop() if len(l) == 0: return True else: return False if __name__ == '__main__': s = Solution() print(s.isValid("([)]"))
d7e549a0579eed3fb2b99f8e1a49650ff9fe3996
cjmking2010/python_study
/Crossin/lesson61.py
302
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Filename: lesson61.py # Author: peter.chen import time starttime = time.time() print 'start:%f' % starttime for i in range(10): print i time.sleep(1) endtime = time.time() print 'end:%f' % endtime print 'total time:%f' % (endtime - starttime)
f458489a25ae1d392752025ddf69892835f81d81
mxtm/cmps-200-fall-2018
/exam3/power.py
800
3.953125
4
# Maxwell Richard Tamer-Mahoney ID #: 201804029 from polynom import Polynom def power1(p, d): # A fun iterative version of raising a polynomial to a power. result = p # We use d - 2 instead of d - 1 because we are initializing our result to p already for i in range(d - 2): # Multiply result variable by itself! result *= result return result def power2(p, d): # A more fun recursive version of raising a polynomial to a power. if d == 1: # A polynomial raised to power 1 is itself return p else: # Otherwise, get the polynomial to the desired power / 2 x = power2(p, d / 2) # Multiply this by itself to get the desired result return x * x p1 = Polynom([(1, 0), (1, 1)]) print(p1) print(power1(p1, 4)) print(power2(p1, 4))
c460ec91c186c79a7411df9f47bf088a98155e25
SmischenkoB/campus_2018_python
/Tihran_Katolikian/1/GettheMiddleCharacter.py
276
3.78125
4
import math s = input('Enter a string: ') if len(s) == 0: # nothing to print pass else: if len(s) % 2 == 0: rightMiddleIndex = int(len(s) / 2) print(s[rightMiddleIndex - 1:rightMiddleIndex + 1]) else: print(s[math.floor(len(s) / 2)])
cdebcf9ca1a1e50ff7fa3ece3280ec27f4265644
league-python-student/level0-module3-AmazingEma
/_01_elif/_4_own_adventure/own_adventure.py
922
4.1875
4
from tkinter import simpledialog, messagebox, Tk # TODO Tell the user a story, but give them options so they can decide the # path of the plot. # Use pop-ups, if statements, and your imagination to make an interesting # story w = Tk() w.withdraw() one = simpledialog.askstring("", "What is full of holes but still holds water?") if one == "A Sponge": two = simpledialog.askstring("","I shave everyday but my beard stays the same. What am I?") if two == "A Barber": messagebox.showinfo("You are a riddle superstar") else: messagebox.showinfo("you are pretty good at riddles") else: three = simpledialog.askstring("","there is a one story house where everything is yellow what color are the stairs?") if three == "There are no stairs": messagebox.showinfo("you are ok at riddles") else: messagebox.showinfo("you should work on your cognitive thinking skills")
cf1f5d7647441ec4be88d8ef2639a6529dcdbf99
joshloyal/ClumPy
/clumpy/rules.py
7,506
3.546875
4
import numpy as np import prim from sklearn.multiclass import OneVsRestClassifier from sklearn.tree import _tree, DecisionTreeClassifier from sklearn.preprocessing import Imputer from clumpy import importance from clumpy.preprocessing import process_data def train_decision_tree(X, cluster_labels, max_depth, ova=False): """train_decision_tree Train a single decision tree to distinguish clusters. """ if ova: decision_tree = OneVsRestClassifier( estimator=DecisionTreeClassifier( max_depth=max_depth, random_state=123)) else: decision_tree = DecisionTreeClassifier( max_depth=max_depth, random_state=123) decision_tree.fit(X, cluster_labels) return decision_tree def leave_paths(tree, class_name, feature_names=None): """leave_paths Create a list of paths to each leaf node of a scikit-learn decision tree. Parameters ---------- tree : decision tree classifier The decision tree to be broken down into decision paths. The tree is assumed to be trained in a binary classification fashion as of now. class_name : list of strings A list of the positive and negative class names, i.e. ['not cluster', 'cluster']. feature_names : list of strings, optional (default=None) Names of each of the features Returns ------- leaf_paths : list of list of tuples A list of the leaf paths. A typical leaf path will look like [('<=', 0.8, 'x0'), ('>', 0.2, 'x1'), ('cluster', 1234)] where the last element corresponds to the class of that data partition and the number of samples of that class in the training dataset. """ if not isinstance(tree, _tree.Tree): tree = tree.tree_ def recurse(tree, child_id, lineage=None): if lineage is None: values = tree.value[child_id][0, :] class_id = np.argmax(values) lineage = [[class_name[class_id], values[class_id]]] if child_id in tree.children_left: parent_id = np.where(tree.children_left == child_id)[0].item() split_type = '<=' else: parent_id = np.where(tree.children_right == child_id)[0].item() split_type = '>' if feature_names is not None: feature = feature_names[tree.feature[parent_id]] else: feature = 'X[{0}]'.format(tree.feature[parent_id]) threshold = round(tree.threshold[parent_id], 4) lineage.append((split_type, threshold, feature)) if parent_id == 0: lineage.reverse() return lineage else: return recurse(tree, parent_id, lineage) leaf_nodes = np.argwhere(tree.children_left == _tree.TREE_LEAF)[:, 0] leaf_paths = [[node for node in recurse(tree, child_id)] for child_id in leaf_nodes] return leaf_paths def get_best_path(leaf_paths, class_name): """get_best_path Determine the best path to use as the description from all the paths in a decision tree. This is simply chosen as the partition with the most samples (may be good to have a threshold of leaf purity) We could do an OR on the different partitions. """ leaves = [(idx, path[-1]) for idx, path in enumerate(leaf_paths) if path[-1][0] == class_name] best_path_idx = sorted(leaves, key=lambda x: x[1][1])[-1][0] return leaf_paths[best_path_idx] def trim_path(leaf_path, categorical_columns=[]): """trim_path Trim the path and turn it into a human readable string. This will combine multiple cuts on the same variable by taking maximums when (<=) and minimums when (>). """ rules = leaf_path[:-1] features_used = np.unique([rule[2] for rule in rules]) description = '' for feature in features_used: feature_group = [rule for rule in rules if rule[2] == feature] feature_group = sorted(feature_group, key=lambda x: x[1]) if len(feature_group) > 3: feature_group = [feature_group[0], feature_group[-1]] if len(feature_group) == 1: op = feature_group[0][0] feature_val = feature_group[0][1] if feature in categorical_columns: feature, feature_val = feature.rsplit('_', 1) if op == '<=': op = '!=' else: op = '==' else: op = feature_group[0][0] description += '{} {} {}'.format( feature, op, feature_val) else: description += '{} < {} <= {}'.format( feature_group[0][1], feature, feature_group[1][1]) description += ' AND\n' return description[:-4] def tree_descriptions(data, cluster_labels, categorical_columns=[], feature_names=None, max_depth=10): """tree_descriptions Determine 'human readable' descriptions for clusters using the rules of a decision tree algorithm. Specifically, a multi-class decision tree is fit in a one-vs-all fashion to the clusters of the dataset. Then the decision path that contains the partition with the largest number of members of the cluster is chosen as the rules to display. This decision path is extracted and turned into a human readable sentence for interpretation by the user. Parameters ---------- X : pd.DataFrame of shape [n_samples, n_features] Data array to fit the decision tree algorithm cluster_labels : array-like of shape [n_samples,] The labels [0 - n_classes] of the corresponding clusters feature_names : dict of lists of strings (optional) The names of each feature in the dataset for a particular cluster max_depth : int, optional (default=5) Depth of the decision tree. This controls how many rules are generated. Returns ------- leaf_descriptions : list of strings The descriptions of each cluster. The position in the list corresponds to the cluster_id. """ leaf_descriptions = [] for cluster_id in np.unique(cluster_labels): cluster_features = feature_names[cluster_id] X, num_features, cat_features = process_data( data[cluster_features], categorical_columns=[var for var in cluster_features if var in categorical_columns], cat_preprocessing='onehot') tree = train_decision_tree( X, cluster_labels == cluster_id, max_depth=max_depth, ova=False) cluster_name = 'cluster {}'.format(cluster_id) leaf_paths = leave_paths( tree, class_name=['not_cluster', cluster_name], feature_names=num_features + cat_features) best_path = get_best_path(leaf_paths, cluster_name) leaf_descriptions.append(trim_path(best_path, categorical_columns=cat_features)) return leaf_descriptions def prim_descriptions(data, cluster_labels, feature_names=[]): boxes = [] for cluster_id in np.unique(cluster_labels): cluster_features = feature_names[cluster_id] p = prim.Prim(data, cluster_labels == cluster_id, threshold=0.5, threshold_type='>', include=cluster_features) boxes.append(p.find_box()) return boxes
cf553032083d34d76dc35dcfd380cac70de68396
terasakisatoshi/pythonCodes
/Queue/priority-queue.py
595
3.875
4
import Queue class Job(object): def __init__(self,priority,description): self.priority=priority self.description=description print("New Job",description) return None def __cmp__(self,other): return cmp(self.priority,other.priority) def main(): q=Queue.PriorityQueue() q.put(Job(3,"Mid-level-job")) q.put(Job(10,"Low-level-job")) q.put(Job(1,"High-level-job")) while not q.empty(): next_job=q.get() print("processing job:",next_job.description) if __name__ == '__main__': main()
05e52223728d7f5c0245b46ddcfec18bc3650eb7
youssefarizk/ExercismPython
/word-count/word_count.py
481
3.984375
4
def word_count(sentence): from string import punctuation #clearing punctuation for char in sentence: if char in punctuation: sentence = sentence.replace(char,' ') sentence = sentence.lower().split() wordCount = {} for word in sentence: if word in wordCount.keys(): wordCount[word] += 1 else: wordCount[word] = 1 return wordCount print word_count('hello @my name is youssef Youssef youssef Youssef')
81b9d07ae43406e4b08234c13db91bfcde7b3c55
KleinTong/Daily-Coding-Problem-Solution
/snakes_and_ladders/main.py
971
3.84375
4
from random import randint def find_smallest_turns(snakes, ladders): def make_dice(): return randint(1, 6) def helper(pos, turns): nonlocal smallest_turns if turns > 1000: return if pos > 100: return if pos == 100: if turns < smallest_turns: smallest_turns = turns i = pos + make_dice() if i in snakes: next_pos = snakes[i] helper(next_pos, turns + 1) elif i in ladders: next_pos = ladders[i] helper(next_pos, turns + 1) else: helper(i, turns + 1) smallest_turns = float('inf') helper(0, 0) print(smallest_turns) if __name__ == '__main__': snakes = {16: 6, 48: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78} ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100} find_smallest_turns(snakes, ladders)
9aa96bfcf3bb671407bef1bb45c24f1386cd61f2
Reginald-Lee/biji-ben
/uoft/CSC108/Week 2/Lab/trace.py
941
3.765625
4
import media import random # make a new 100 by 100 picture pic = media.create_picture(100, 100) # get 2 random numbers between 0 and 99 to use as coordinates x = random.randint(0, 99) y = random.randint(0, 99) # get the pixel at this x,y coordinate pix = media.get_pixel(pic, x, y) # get the red, blue and green values of this pixel red = media.get_red(pix) green = media.get_green(pix) blue = media.get_blue(pix) # introduce a new colour new_color = media.orange # make a 10 x 10 rectangle of the new colour inside our # picture, starting with our x and y as the upper # left corner. (In this case, it doesn't matter if some # of the rectangle is outside the picture, as long as # the x,y corner is inside.) media.add_rect_filled(pic, x, y, 10, 10, new_color) # display the picture media.show(pic) # the colours should have changed in our pixel red = media.get_red(pix) green = media.get_green(pix) blue = media.get_blue(pix)
c7da11e825b49375a5f2f05718fb8960d158f411
john-a-m/brilliancy
/chess.py
4,538
3.671875
4
#TODO implement captures as possible moves class Piece(object): def __init__(self, color, x, y): self.color = color self.x = x self.y = y class Rook(Piece): value = 5 def get_moves(self, grid): for move in _get_horizontal_moves(grid, self): yield move for move in _get_vertical_moves(grid, self): yield move class Knight(Piece): value = 3 def get_moves(self, grid): moves = [ (self.y + 2, self.x + 1), (self.y + 2, self.x - 1), (self.y - 2, self.x + 1), (self.y - 2, self.x - 1), (self.x + 2, self.y + 1), (self.x + 2, self.y - 1), (self.x - 2, self.y + 1), (self.x - 2, self.y - 1) ] for move in moves: x, y = move if x >= 0 and x < len(grid) and y >= 0 and y < len(grid): yield _move_piece(self, grid, x, y) class Bishop(Piece): value = 3 def get_moves(self, grid): for move in _get_vertical_moves(grid, self): yield move class Queen(Piece): value = 9 def get_moves(self, grid): for move in _get_horizontal_moves(grid, self): yield move for move in _get_vertical_moves(grid, self): yield move for move in _get_diagonal_moves(grid, self): yield move class King(Piece): value = float("inf") def get_moves(self, grid): moves = [ (self.x, self.y - 1), (self.x + 1, self.y - 1), (self.x + 1, self.y), (self.x + 1, self.y + 1), (self.x, self.y + 1), (self.x - 1, self.y + 1), (self.x - 1, self.y), (self.x - 1, self.y - 1) ] for move in moves: x, y = move if x >= 0 and x < len(grid) and y >= 0 and y < len(grid): yield _move_piece(self, grid, x, y) class Pawn(Piece): value = 1 def get_moves(self, grid): moves = [(self.x, self.y + 1)] if self.is_first_move: moves.append((self.x, self.y + 2)) for move in moves: x, y = move if x >= 0 and x < len(grid) and y >= 0 and y < len(grid): yield _move_piece(self, grid, x, y) def _get_horizontal_moves(grid, piece): index = piece.x - 1 while index >= 0 and grid[piece.y][index] is None: yield _move_piece(piece, grid, x, y) index -= 1 index = piece.x + 1 while index < len(grid) and grid[piece.y][index] is None: yield _move_piece(piece, grid, x, y) index += 1 def _get_vertical_moves(grid, piece): index = piece.y - 1 while index >= 0 and grid[index][piece.x] is None: yield _move_piece(piece, grid, x, y) index -= 1 index = piece.x + 1 while index < len(grid) and grid[index][piece.x] is None: yield _move_piece(piece, grid, x, y) index += 1 def _get_diagonal_moves(grid, piece): #TODO needs len(grid) #up left x, y = piece.x - 1, piece.y - 1 while x >= 0 and y >= 0 and grid[y][x] is None: yield _move_piece(piece, grid, x, y) x -= 1 y -= 1 #down right x, y = piece.x + 1, piece.y + 1 while x >= 0 and y >= 0 and grid[y][x] is None: yield _move_piece(piece, grid, x, y) x += 1 y += 1 #up right x, y = piece.x + 1, piece.y - 1 while x >= 0 and y >= 0 and grid[y][x] is None: yield _move_piece(piece, grid, x, y) x += 1 y -= 1 #down left x, y = piece.x - 1, piece.y + 1 while x >= 0 and y >= 0: yield _move_piece(piece, grid, x, y) if grid[y][x] is not None and grid[y][x].color != piece.color: break x -= 1 y += 1 def _move_piece(piece, grid, x, y): #TODO put bounds checking in here new = [[s for s in row] for row in grid] new[piece.y][piece.x] = None new[y][x] = piece return new BLACK = 0 WHITE = 1 ##grid = [ ## [Rook(WHITE), Knight(WHITE), Bishop(WHITE), King(WHITE), Queen(WHITE), ## Bishop(WHITE), Knight(WHITE), Rook(WHITE)], ## [Pawn(WHITE) for _ in range(8)], ## [None] * 8, ## [None] * 8, ## [None] * 8, ## [None] * 8, ## [Pawn(BLACK) for _ in range(8)], ## [Rook(BLACK), Knight(BLACK), Bishop(BLACK), Queen(BLACK), King(BLACK), ## Bishop(BLACK), Knight(BLACK), Rook(BLACK)] ## ]
344aba9d993dafa04573268217a0e2dba7771738
vaschuck/Hangman
/Hangman/The value of life/stage_6.py
1,533
3.96875
4
import random def create_word_hint(word, hidden): index = 0 word_hint = '' while index < len(word): if hidden[index]: word_hint += word[index] else: word_hint += '-' index += 1 return word_hint def gen_word(): words = ['python', 'java', 'kotlin', 'javascript'] word = random.choice(words) return word def gen_hidden(word): hidden = [] for _ in word: hidden.append(False) return hidden def change_hidden(word, hidden, letter): index = 0 while index < len(word): if letter == word[index]: hidden[index] = True index += 1 def main(): print('H A N G M A N') magic_word = gen_word() open_letters = gen_hidden(magic_word) word_set = set(magic_word) guessed_letters = '' tries = 8 guesses = 0 while guesses < tries: hidden_word = create_word_hint(magic_word, open_letters) print() print(hidden_word) if hidden_word == magic_word: print('You guessed the word!') print('You survived!') break guess = input('Input a letter: ') if guess in guessed_letters: print('No improvements') guesses += 1 elif guess not in word_set: print('No such letter in the word') guesses += 1 else: guessed_letters += guess change_hidden(magic_word, open_letters, guess) else: print('You are hanged!') main()
ddafb40c31dd550bfb0fde03cd8c742985b8a1d2
E-menu/Raspberry_python_app
/functions/saveOrder.py
783
3.8125
4
# Import tkinter library to show MessageBox from tkinter import messagebox # end # Save order in arrays def saveOrder(mealName,price,bill,nextMealsPrices,nextMealsNames): # Saving info about an order in arrays nextMealsPrices.append(price) nextMealsNames.append(mealName) # To test app in terminal print("Aktualnie zamowione mealsNames : " + str(nextMealsNames)) print("Aktualnie zamowione mealsPrices : " + str(nextMealsPrices)) # end # Actual bill will be ... newBill = bill[0] +float(price) bill[0]=newBill # To test app in terminal print("Aktualny rachunek wynosi : "+str(bill)) print("\n") # end messagebox.showinfo("Powiadomienie","Dodano do zamówienia !\nAktualna cena zamówienia: {} zł.".format(newBill))
a4ce1131a343c617b4bb88dd04794e009ea054a2
georgedav/Maths-Programs
/primes.py
270
3.640625
4
def prime(n): if (n<2)or(int(n)!=n): return False for i in range(2,1+int(n**0.5)): if n%i==0: return False return True def primes(m,n): A=[] for i in range(m,n+1): if prime(i): A.append(i) return A
dd15cd3e1a58968528f437ec41b8a6e4c59869a8
ShulaevIvan/homework_py
/homework.py
4,415
3.59375
4
class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = [] self.courses_in_progress = [] self.grades = {} self.average = 0 def rate_lec(self, lec, course, grade): if isinstance(lec, Lecturer) and course in lec.courses_attached and course in self.courses_in_progress: if course in lec.grades and grade <= 10: lec.grades[course] += [grade] elif grade <= 10: lec.grades[course] = [grade] else: return 'Ошибка' sum = 0 length = 0 for k in lec.grades.values(): for i in k: sum = sum + i length += 1 lec.average = round(sum / length) def __lt__(self, obj): if not isinstance(obj, Student): print('ошибка') return return self.average < obj.average def __str__(self): out = f'Имя: {self.name}\nФамилия: {self.surname}\nСредняя оценка за домашние задания: {self.average}\nКурсы в процессе изучения: {self.courses_in_progress}\nЗавершенные курсы:{self.finished_courses}' return out class Mentor: def __init__(self, name, surname): self.name = name self.surname = surname self.courses_attached = [] class Reviewer(Mentor): def rate_hw(self, student, course, grade): if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress: if course in student.grades and grade <= 10: student.grades[course] += [grade] elif grade <= 10: student.grades[course] = [grade] else: return 'Ошибка' sum = 0 length = 0 for k in student.grades.values(): for i in k: length += 1 sum = sum + i student.average = round(sum / length) def __str__(self): out = f'Имя: {self.name}\nФамилия: {self.surname}' return out class Lecturer(Mentor): grades = {} average = 0 def __lt__(self, obj): if not isinstance(obj, Lecturer): print('Ошибка') return return self.average < obj.average def __str__(self): out = f'Имя: {self.name}\nФамилия: {self.surname}\nСредняя оценка: {self.average}' return out best_student = Student('Ruoy', 'Eman', 'your_gender') student_one = Student('Илья', 'Родионов', 'мж') student_two = Student('Максим', 'Журавлёв', 'мж') lecturer = Lecturer('Ruoy', 'Eman') lecturer_one = Lecturer('Михаил', 'Фокин') lecturer_two = Lecturer('Иван', 'Громов') reviewer = Reviewer('Some', 'Buddy') best_student.courses_in_progress += ['Python', 'Git'] student_one.courses_in_progress += ['Python', 'Git'] student_two.courses_in_progress += ['Python', 'Git'] best_student.finished_courses += ['Введение в программирование'] student_one.finished_courses += ['Введение в программирование'] student_two.finished_courses += ['Введение в программирование'] lecturer.courses_attached += ['Python'] reviewer.courses_attached += ['Python'] reviewer.rate_hw(student_one, 'Python', 5) reviewer.rate_hw(student_two, 'Python', 6) reviewer.rate_hw(best_student, 'Python', 7) student_one.rate_lec(lecturer, 'Python', 8) student_two .rate_lec(lecturer, 'Python', 9) best_student.rate_lec(lecturer, 'Python', 10) students_arr = [best_student, student_one, student_two] lecturer_arr = [lecturer, lecturer_one, lecturer_two] def average_all(arr, courses): sum_grade = 0 i = 0 for j in arr: for k, value in j.grades.items(): if courses in k: sum_grade += sum(value) / len(value) i += 1 return round(sum_grade / i) print(lecturer) print(student_one) print(reviewer) print(f'Средняя оценка студентов по Python: {average_all(students_arr, "Python")}') print(f'Средняя оценка лекторов по Python: {average_all(lecturer_arr, "Python")}')
eb25657f7957621091c8af497e5f587494c74cbe
eKarakoleva/Python-BMSTU-labs
/calculator.py
6,273
3.53125
4
from tkinter import * from tkinter.ttk import Button, Entry, Style def set_text(text): entry.insert(END, text) return def get_text(): try: equ = entry.get() total = str(eval(equ)) entry.delete(0,END) entry.insert(0,total) except: entry.delete(0, END) entry.insert(0, "Error") def ten_to_five_int(number): dev_result = int(number) res_array = [] while int(dev_result) >= 5: res = dev_result % 5 dev_result = dev_result // 5 res_array.append(str(res)) res_array.append(str(dev_result)) total = list(reversed(res_array)) return total def ten_to_five(): try: number = entry.get() if ("." not in number): total = ten_to_five_int(number) total = "".join(total) entry.delete(0, END) entry.insert(0, total) else: all_parts = number.split(".") work_value = float("0."+all_parts[1]) res_array = [] i=7 while i > 0: mult = work_value*5 temp = mult%1 res_array.append(str(int(mult))) work_value = temp i-=1 total_whole_part = ten_to_five_int(all_parts[0]) total_whole_part = "".join(total_whole_part) total_after_dot = "".join(res_array) total_after_dot = float("0."+ total_after_dot) entry.delete(0, END) entry.insert(0, total_after_dot + int(total_whole_part)) except: entry.delete(0, END) entry.insert(0, "Error") def five_to_ten_int(number,count_1): res = 0 count = count_1 for i in number: res += (int(i) * (5 ** count)) count -= 1 return res def five_to_ten(): try: number = entry.get() invalid = {"6", "7", "8","9"} input = set(list(number)) if(not bool(invalid&input)): if ("." not in number): res = five_to_ten_int(number,len(number)) entry.delete(0, END) entry.insert(0, res) else: number = number.split(".") res_whole_part = five_to_ten_int(number[0],len(number[0])-1) res_after_dot = five_to_ten_int(number[1],-1) final = res_whole_part+res_after_dot entry.delete(0, END) entry.insert(0, final) else: entry.delete(0, END) entry.insert(0, "Error...wrong system") except: entry.delete(0, END) entry.insert(0, "Error") def clear(): entry.delete(0, END) def clear_last(): entry.delete(len(entry.get()) - 1, END) def info(): top = Toplevel() top.title("About this application...") text = "Hello, it's me!\nElena Karakoleva\nBauman MSTU" msg = Message(top, text=text , pady = 10) msg.pack() button = Button(top, text="Dismiss", command=top.destroy) button.pack() self = Tk() menubar = Menu(self) commandmenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Commands", menu=commandmenu) commandmenu.add_command(label="+", command=lambda:set_text("+")) commandmenu.add_command(label="-", command=lambda:set_text("-")) commandmenu.add_command(label="*", command=lambda:set_text("*")) commandmenu.add_command(label="/", command=lambda:set_text("/")) commandmenu.add_command(label="Cls", command=lambda:clear()) commandmenu.add_command(label="Cls_last", command=lambda:clear_last()) commandmenu.add_separator() commandmenu.add_command(label="Exit", command=self.quit) systemmenu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Systems", menu=systemmenu) systemmenu.add_command(label="10->5", command=lambda:ten_to_five()) systemmenu.add_command(label="5->10", command=lambda:five_to_ten()) info_menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="About", menu=info_menu) info_menu.add_command(label="Elena Karakoleva \nBauman MSTU") self.config(menu=menubar) Style().configure("TButton", padding=(0, 5, 0, 5), font='serif 10') entry = Entry(self) entry.grid(row=0, columnspan=4, sticky=W + E) cls = Button(self, text="Cls", command=lambda:clear()) cls.grid(row=1, column=0) bck = Button(self, text="Cls_last",command=lambda:clear_last()) bck.grid(row=1, column=1) lbl = Button(self) lbl.grid(row=1, column=2) clo = Button(self, text="") clo.grid(row=1, column=3) sev = Button(self, text="1", command=lambda:set_text("1")) sev.grid(row=2, column=0) eig = Button(self, text="2", command=lambda:set_text("2")) eig.grid(row=2, column=1) nin = Button(self, text="3", command=lambda:set_text("3")) nin.grid(row=2, column=2) div = Button(self, text="/", command=lambda:set_text("/")) div.grid(row=2, column=3) fou = Button(self, text="4", command=lambda:set_text("4")) fou.grid(row=3, column=0) fiv = Button(self, text="5", command=lambda:set_text("5")) fiv.grid(row=3, column=1) six = Button(self, text="6", command=lambda:set_text("6")) six.grid(row=3, column=2) mul = Button(self, text="*", command=lambda:set_text("*")) mul.grid(row=3, column=3) one = Button(self, text="7", command=lambda:set_text("7")) one.grid(row=4, column=0) two = Button(self, text="8", command=lambda:set_text("8")) two.grid(row=4, column=1) thr = Button(self, text="9", command=lambda:set_text("9")) thr.grid(row=4, column=2) mns = Button(self, text="-", command=lambda:set_text("-")) mns.grid(row=4, column=3) zer = Button(self, text="0", command=lambda:set_text("0")) zer.grid(row=5, column=0) dot = Button(self, text=".", command=lambda:set_text(".")) dot.grid(row=5, column=1) equ = Button(self, text="=", command=lambda:get_text()) equ.grid(row=5, column=2) pls = Button(self, text="+", command=lambda:set_text("+")) pls.grid(row=5, column=3) ten_five = Button(self, text="10->5",command=lambda:ten_to_five()) ten_five.grid(row=6, column=0) dot = Button(self, text="5->10", command=lambda:five_to_ten()) dot.grid(row=6, column=1) equ = Button(self, text="Info", command=lambda:info()) equ.grid(row=6, column=2) self.mainloop()
b2ecc5573d8dc1f5892a912611a262674bbd0d4b
Israel7777/PythonPixeloperations
/get_RGB_RGBA_Value_of_Pixel.py
640
4.0625
4
#Importing pillow library of python for image processing from PIL import Image #method to get RGB-RGBA Value for a specific pixel in a image def to_getRGBARGB(): #place the image in the same path as the code img = Image.open('[imagename].[format]') #ex: testpicture.jpg #enter the pixel value x,y = (<pixel x value>,<pixel y value>) ex: 300,300 #pixel read as co-ordinates of image coordinate = x, y #RGB/RGBA Caught in list list1 = list(img.getpixel(coordinate)) print(list1) #main method def main(): to_getRGBARGB() #call to main method if __name__ == "__main__": main()
b828c0900fc491e0e88cf3c22cfae4ed13a9fa4c
manojinukolunu/Everyday
/Project Euler/problem7.py
460
3.84375
4
import math def testPrime(num): i=2 while i<=math.sqrt(num): if num%i==0: return False i=i+1 return True def genPrimes(): sum1=0 i=1 prime=False count=1 while True: num=2*i+1 if testPrime(num) and num<2000000: sum1=sum1+num count=count+1 elif num>=2000000: break i=i+1 return sum1 print genPrimes()+2