blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d0578ce01323c857e044bae64306c3e5e5542c25
Rebaiahmed/Hackerrank_challenges
/Regex/Re.split.py
94
3.578125
4
import re list =re.split("[,.]+",input()) for i in list : if(i.isdigit()): print(i)
174b14c2a1c28d757eac0dffe72e1b2b0db742dc
supergravity/PythonLearning-
/MIT_Computation/Programming_Python/Week2/exercise_2.py
351
3.84375
4
def gcdRecur(a, b): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if (a == 0): return b elif (b == 0): return a else: if(b >= a): return gcdRecur(a,b%a) else: return gcdRecur(a%b,b) print(gcdRecur(144,45))
53abb9ea60d0c10f23471c97cd608d9e2a378b1d
Aasthaengg/IBMdataset
/Python_codes/p03108/s967526997.py
2,197
3.703125
4
class UnionFind(): #https://note.nkmk.me/python-union-find/ #note.nkmk.me 2019-08-18 def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) # 初期入力 import sys input = sys.stdin.readline #文字列では使わない N,M = map(int, input().split()) bridge =[] for i in range(M): a,b = map(int, input().split()) bridge.append((a,b)) all =N*(N-1)//2 #行き来できる島の組み合わせ ans =[0]*(M-1) +[all] #print(ans) #i 番目の橋が崩落した直後の不便さ=i+1番目がまだ残っているときの不便さ # ⇒最後の橋から順番に作り、できた時の不便さ uf =UnionFind(N) for i in range(M-1,0,-1): a,b =bridge[i] #事前につながっているかどうかで場合分け if uf.same(a-1,b-1): ans[i-1] =ans[i] #くっつけてから変化分を引く else: x_a =uf.size(a-1) x_b =uf.size(b-1) connection_bfo =x_a*(x_a -1)//2 +x_b*(x_b -1)//2 connection_aft =(x_a +x_b) *(x_a +x_b -1)//2 ans[i-1] =ans[i] -connection_aft +connection_bfo uf.union(a-1,b-1) [print(i) for i in ans]
0cd5bb5aa1d61e9042f226c140a267603984c85d
bmrahman24/Python-learner
/welcome.py
550
4.0625
4
#text_to_print="Hello world" #print(text_to_print) #number1 = 10 #number2 = 5 #result = number1 + number2 #print(result) # "number1=10 # print(number1) # # number1=15 # number1=18 # print(number1) # # number1= "Hello" # print(number1)" #name=input("what is your name ? ") #print("Welcome to python,", name,"!") number1=input("please type an integer and press enter:") number2=input("Pleae type another interger and press enter:") print("number1+number2=",number1+number2)
0c1a0e4d53e789094fceb4c78d61f01433fb659a
iPrograms/PowerAnalysisCPU
/args.py
5,451
3.578125
4
#!/usr/bin/env python2.7 ''' File name: args.py: process command line argument(s) Author: Manzoor Ahmed : Pierre Vachon Date created: 11/06/2017 Date last modified: 11/06/2017 Python Version: 2.7 Version 1.0 ''' import sys class InputChecker: def __init__(self): self.argv = sys.argv self.validArgs = False self.command = None self.validKey = False self.extension = False def arevalidArgs(self): if ( self.validArgs == True ) and ( self.validKey == True) and ( self.extension == True): return True else: return False def printUsage(self): print'+----------------------------------------------+' print'' print' rc4.py General Commands Manual' print'' print' NAME' print' rc4.py' print'' print' Usage: rc4.py [-eEdD][-k][-f file]' print'' print' Optional arguments:' print' -h, --help show this help message and exit' print' -sys, --sytem monitor system resources' print' -n,--noise monitor system resources with added noise' print'' print'+-----------------------------------------------+' def checkKey(self,k): if k.isdigit() and len(k) >8: return True else: return False def processCommand(self, args): valid = False if len(args) == 1: print('No arguments supplied!') elif len(args) == 2: if args[1] != "": if ( args[1] == '-h' ) or ( args[1] == '--help' ): self.printUsage() elif args[1] == '-e' or args[1] == '-E': self.command = 'encrypt' print(self.command) elif args[1] == '-d' or args[1] == '-D': self.command = 'decrypt' print(self.command) elif len(args) == 3: if ( args[2] == '-k' ) or ( args[2] == '--key' ) : print(args[2]) else: print 'Usage: did you want to run with -k option?' self.printUsage() elif len(args) == 4: if (args[3]) != "": if self.checkKey(args[3]) == True: self.validKey = True print(args[3]) else: print 'Invalid Key' elif len(args) == 5: if args[4] != "": if ( args[4] == '-f' ) or ( args[4] == '--file' ): print self.argv[4] else: print 'No Stream data provided!' elif len(args) == 6: if ((args[4] == '-f') or (args[4] == '--file')) and (self.checkKey(args[3]) == True) and \ ((args[2] == '-k' ) or ( args[2] == '--key')) and ((args[1] == '-e' or args[1] == '-E') or (args[1] == '-d' or args[1] == '-D')): if(args[5] != ""): if args[5].find(".") > 0: self.extension = True self.validArgs = True print 'valid command' return True else: print 'Invalid extension' else: print 'invalid command' # -sys, -system elif len(args) == 7: if ((args[4] == '-f') or (args[4] == '--file')) and (self.checkKey(args[3]) == True) and \ ((args[2] == '-k' ) or ( args[2] == '--key')) and ((args[1] == '-e' or args[1] == '-E') or (args[1] == '-d' or args[1] == '-D')): if(args[5] != ""): if args[5].find(".") > 0: self.extension = True if (args[6] != ""): if(args[6] == '-sys') or (args[6]) == '--system': self.validArgs = True print 'monitoring system resources, cpu.' return True else: print 'Invalid argument -> ' + args[6] else: print 'Invalid extension' # -n noise elif len(args) == 8: if ((args[4] == '-f') or (args[4] == '-file')) and (self.checkKey(args[3]) == True) and \ ((args[2] == '-k' ) or ( args[2] == '--key')) and ((args[1] == '-e' or args[1] == '-E') or (args[1] == '-d' or args[1] == '-D')): if(args[5] != ""): if args[5].find(".") > 0: self.extension = True if (args[6] != ""): if(args[6] == '-sys') or (args[6]) == '--system': if(args[7] !=""): if(args[7] == '-n') or (args[7] == '--noise'): self.validArgs = True print 'monitoring systemd resources with noise' self.validArgs = True return True else: print 'Invalid argument -> ' + args[7] else: print 'Invalid extension' else: print 'Unknown args found!'
a53855c25710b700969e308fe91f65fa5c72cbd5
hahahayden/CPE101
/Project1 Turn IN/skater.py
1,604
4.1875
4
# Project1 # # Name: Hayden Tam # Instructor: S.Einakian # Section:05 import math import funcs def main(): pounds=float(input("How much do you weigh (pounds)? ")) distance=float(input("How far away your profesor is (meters)? ")) object=(input("Will you throw a rotten (t)omato,banana cream (p)ie, (r)ock, (l)ight saber, or lawn (g)nome? ")) massObject=funcs.getMassObject(object) # Get the mass of the object massSkater=funcs.poundsToKG(pounds) # Convert pounds to kg for skater velObj=funcs.getVelocityObject(distance) # Get velocity of obj velocitySkater=funcs.getVelocitySkater(massSkater,massObject,velObj) # Get velocity of obj # Display comment based on the mass of thrown obj and distance thrown if (massObject<=.1): print("Nice throw! You're going to get an F!") elif((massObject>.1) and (massObject<=1.0)): print("Nice throw! Make sure your professor is OK.") elif (massObject>1.0): if (distance<20): print("Nice throw! How far away is the hospital?") elif (distance>=20): print("Nice throw! RIP professor.") # Print velcoity of skater print("Velocity of Skater:",velocitySkater,"m/s") # Display comment based on velocity if (velocitySkater<.2): print("My grandmother skate faster than you!") elif (velocitySkater>=.2)and (velocitySkater<1.0): pass elif (velocitySkater>=1.0): print("Look out for that railing!!!") if __name__=="__main__": main()
f3d9e126d310657b86a870044ef6df21c9868bcb
joyceyu6/coding_courses
/2021_4_19_to372/322.coin-change.py
2,052
3.78125
4
''' You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0 Example 4: Input: coins = [1], amount = 1 Output: 1 Example 5: Input: coins = [1], amount = 2 Output: 2 Constraints: 1 <= coins.length <= 12 1 <= coins[i] <= 231 - 1 0 <= amount <= 104 ''' # # @lc app=leetcode id=322 lang=python3 # # [322] Coin Change # # @lc code=start class Solution: def coinChange(self, coins: List[int], amount: int) -> int: coins.sort(reverse=True) # print(coins) result = [] dic = {} self.recursive(coins, amount, [], result, dic) if len(result) == 0: return -1 # print("result", result, dic) return min(result) def recursive(self, coins, amount, temp, result, dic): # print(coins, amount, temp, result) if amount == 0: result.append(len(temp)) return if len(coins) == 0: return if amount < 0: return if amount in dic: return current = coins[0] count = 0 l = amount // current # while count <= l: for i in range(l): temp.append(current) amount -= current while count < l: result_count = len(result) self.recursive(coins[1:], amount, temp, result, dic) if result_count != len(result): dic[amount] = min(result) temp.pop() amount += current count += 1 self.recursive(coins[1:], amount, temp, result, dic) # @lc code=end
4fbb490d83b8422cb97f2bab928c6be789ad35fd
ciesielskiadam98/pp1
/02-ControlStructures/PESEL.py
453
3.609375
4
pesel = input("Podaj PESEL: ") if (pesel[9] == "0" or pesel[9] == "2" or pesel[9] == "4" or pesel[9] == "6" or pesel[9] == "8"): plec = "Kobieta" else: plec = "Mężczyzna" a = pesel[0:2] #zmienna pomocnicza do przechowania elementów str jakos int b = pesel[2:4] #jak wyżej a = int(a) b = int(b) if b <= 12: wiek = 2018 - (1900 + a) else: wiek = 2018 - (2000 + a) print("Płeć: {}".format(plec)) print("Wiek: {}".format(wiek))
d7a631f66af089cb529c569fd99a4e89e4409e9e
akhasaya/Leetcode-practice
/remove_stones.py
1,128
3.625
4
# https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ # I coded this after reading the answer provided in leetcode # this code looks much cleaner than any code i have written before class Solution(object): def removeStones(self, stones): ls = len(stones) adj_list = [[] for i in range(ls)] for i1 in range(ls): for i2 in range(i1): if stones[i1][0] == stones[i2][0] or stones[i1][1] == stones[i2][1]: adj_list[i1].append(i2) adj_list[i2].append(i1) seen = [False] * ls ans = 0 for i in range(ls): if seen[i] == False: stack = [i] seen[i] = True while stack: elem = stack.pop() for nei in adj_list[elem]: if seen[nei] == False: stack.append(nei) seen[nei] = True ans += 1 return ans """ :type stones: List[List[int]] :rtype: int """
14224991630e9f7a12869e48d46d478714e83bc3
YangAusDu/python-notes
/process/self_defined_proccess.py
429
3.53125
4
from multiprocessing import Process class MyProcess(Process): def __init__(self,name): super(MyProcess,self).__init__() self.name = name def run(self): p = 1 while True: print("{}--------->self-defined, p: {}".format(self.name, p)) p +=1 if __name__ == "__main__": p1 = MyProcess("Shirely") p2 = MyProcess("Lucy") p1.start() p2.start()
a6446519a4745b3d5d72e3876025f1e8b56d8917
qxlei/item_based_movie_recommendation
/t.py
180
3.625
4
dic={'1': {'1': 5, '2': 3}, '2': {'1': 4}} for user, items in dic.items(): for i in items.keys(): print(i,'a') for j in items.keys(): print(j, 'bb')
ca469058c67bd106d90fddc1b88b5ffba3b66bcb
NelsonarevaloF/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py
2,213
3.578125
4
#!/usr/bin/python3 """in this module is the base function""" import json class Base: """This class will be the “base” of all other classes in this project.""" __nb_objects = 0 def __init__(self, id=None): """this initialize the values depending the value of size""" if id is not None: self.id = id else: Base.__nb_objects += 1 self.id = Base.__nb_objects @staticmethod def to_json_string(list_dictionaries): """returns the JSON string representation""" if list_dictionaries and list_dictionaries is not None: return (json.dumps(list_dictionaries)) else: return (json.dumps([])) @classmethod def save_to_file(cls, list_objs): """ writes the JSON string representation of list_objs to a file """ jlist = [] filename = cls.__name__ + ".json" if list_objs: for i in list_objs: jlist.append(i.to_dictionary()) st = cls.to_json_string(jlist) with open(filename, "w", encoding="utf-8") as myfile: myfile.write(st) @staticmethod def from_json_string(json_string): """ returns the list of the JSON string representation json_string """ if not json_string or len(json_string) == 0: return [] return json.loads(json_string) @classmethod def create(cls, **dictionary): """ returns an instance with all attributes already set """ if cls.__name__ == "Rectangle": dummy = cls(1, 1) elif cls.__name__ == "Square": dummy = cls(1) dummy.update(**dictionary) return dummy @classmethod def load_from_file(cls): """ returns a list of instances from a file """ filename = cls.__name__ + ".json" try: with open(filename, encoding="utf-8") as myfile: rd = myfile.read() dicst = cls.from_json_string(rd) inslist = [] for i in dicst: inslist.append(cls.create(**i)) return inslist except IOError: return []
6753341c5411df41eed409a1c366e5bc7ff8ce94
LucasDM19/botfair
/Stats.py
1,829
3.5625
4
""" Uma classe apenas para obter os dados do Json, com estatisticas. """ class SoccerStats(): def __init__(self, url='http://foob.ar/resource.json'): self.url = url def getStats(self): try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen import json try: with urlopen( self.url ) as url: data = json.loads(url.read().decode('utf-8').replace("localStorage.stats=JSON.stringify(","").replace("}]);","}]") ) #print(data) return(data) except AttributeError: url = urlopen( self.url ) data = json.loads(url.read().decode('utf-8').replace("localStorage.stats=JSON.stringify(","").replace("}]);","}]") ) return(data) except json.decoder.JSONDecodeError: #print("json provavelmente vazio!") return {} except http.client.RemoteDisconnected: print("Tem ninguem do outro lado da linha") return {} #Levenshtein distance in a recursive way (https://www.python-course.eu/levenshtein_distance.php) def LD(self, s, t): #from Levenshtein import distance #pip install python-Levenshtein #return distance(s, t) ''' From Wikipedia article; Iterative with two matrix rows. ''' if s == t: return 0 elif len(s) == 0: return len(t) elif len(t) == 0: return len(s) v0 = [None] * (len(t) + 1) v1 = [None] * (len(t) + 1) for i in range(len(v0)): v0[i] = i for i in range(len(s)): v1[0] = i + 1 for j in range(len(t)): cost = 0 if s[i] == t[j] else 1 v1[j + 1] = min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost) for j in range(len(v0)): v0[j] = v1[j] return v1[len(t)]
0407de5239993ae7db769eaaadc635c1591abeff
yonginggg/MassiveDatasetsML_school
/神经网络/前馈神经网络.py
1,852
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019/11/4 15:52 # @Author : YangYusheng # @File : 前馈神经网络.py # @Software: PyCharm # coding:utf-8 import numpy as np import pandas as pd class NeuralNetwork(): # 随机初始化权重 def __init__(self): np.random.seed(1) self.synaptic_weights = 2 * np.random.random((400, 1)) - 1 # 定义激活函数:这里使用sigmoid def sigmoid(self, x): return 1 / (1 + np.exp(-x)) # 计算Sigmoid函数的偏导数 def sigmoid_derivative(self, x): return x * (1 - x) # 训练模型 def train(self, training_inputs, training_outputs, learn_rate, training_iterations): # 迭代训练 for iteration in range(training_iterations): # 前向计算 output = self.think(training_inputs) # 计算误差 error = training_outputs - output adjustments = np.dot(training_inputs.T, error * self.sigmoid_derivative(output)) self.synaptic_weights += learn_rate * adjustments def think(self, inputs): # 输入通过网络得到输出 # 转化为浮点型数据类型 inputs = inputs.astype(float) output = self.sigmoid(np.dot(inputs, self.synaptic_weights)) return output if __name__ == "__main__": X = pd.read_csv("X_data.csv", header=None) y = pd.read_csv("y_label.csv", header=None) neural_network = NeuralNetwork() train_data = X training_inputs = np.array(train_data) training_outputs = np.array(y) # 参数学习率 learn_rate = 0.1 # 模型迭代的次数 epoch = 1500 neural_network.train(training_inputs, training_outputs, learn_rate, epoch) print("迭代计算之后权重矩阵W: ") print(neural_network.synaptic_weights)
26dff8a8b553e40a2128a74fb970363f95988e1e
saumil-jain/date_utils_web
/dateutils/datediff/models.py
1,605
3.578125
4
from django.db import models import datetime def process_input_date(input_date): """Parse the input date string and return a date object The object returned is of the type datetime.date. :param input_date: The date in the ISO format yyyy-mm-dd :return: A datetime.date object representing the input date :raise IndexError and ValueError """ try: input_date_data = input_date.split("-") year = int(input_date_data[0]) month = int(input_date_data[1]) day = int(input_date_data[2]) return datetime.date(year=year, month=month, day=day) except IndexError: raise ValueError("Invalid date format '{}'".format(input_date)) def calculate_date_diff_from_today(date_object): """Calculates the absolute difference between input date and today's date. :param date_object: The datetime.date object representing the input date :return: the absolute difference of the two dates as a datetime.timedelta object. """ today = datetime.date.today() difference = abs(today - date_object) return date_object, today, difference def add_days_to_date(date_object, days): """Adds days to a date The days can be negative, in which case the days will be subtracted. :param date_object: The datetime.date object to which days are to be added :param days: The number of days to be added; can be negative :return: The new datetime.date object """ return date_object + datetime.timedelta(days=days) def difference_between_two_dates(date_1, date_2): return abs((date_1 - date_2).days)
4fd296b0960827c87e7a4961ff8c607989f0e2f1
KoreyEnglert/another-in-class
/leap_year_error_handling.py
352
4.125
4
c = False; while not c: year = input("Enter a year to check: "); try: year = int(year); c = True; except: print("That is not an integer!"); if year % 4 == 0: if year % 100 == 0 and year % 400 != 0: print(str(year) + ' is not a leap year.'); else: print(str(year) + ' is a leap year.'); else: print(str(year) + ' is not a leap year.');
b8e6d62a98a1a3df450d87e8efb4cbcd1ed2f261
Nunez350/DeepLearningWithR
/multi_layer_neuron/Multiple_Neuron_Classification.py
4,634
3.609375
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from numpy import exp from numpy.random import uniform df = pd.read_csv("iris.csv") df = df.drop([df.columns[0]], axis=1) df = df.reset_index(drop=True) # Multiple Neuron Classification Normalized by Softmax Function def multiple_neuron_classification(input_cols, target_col, eta, iteration): # create a list to store historical accuracy accuracy = [] # declear inputs x = np.array(input_cols) # input dataset (dimension = number of individuals * number of features) X = np.insert(x, x.shape[1], 1, axis=1) # Matrix X: insert last column being the coefficients for bias (dimension = number of individuals * (number of features + 1)) # build target values arr_target = np.array(target_col) ls = np.array(list(set(arr_target))) t = np.zeros([len(arr_target), len(ls)]) for ix in range(len(ls)): t[np.where(arr_target == ls[ix]), ix] = 1 # get index of ones by row for comparison with output y to compute accuracy of classification t_one_ix = np.argmax(t, axis=1) # initialize random weights (dimension of weights = features * neurons) weights = uniform(low=1e-3, high=1e-2, size=[x.shape[1], t.shape[1]]) # initialize random bias (dimension of bias = 1 * neurons) bias = uniform(size=t.shape[1]) # Matrix W: insert last row for bias (dimension = (number of weights + 1) * number of neurons) W = np.insert(weights, weights.shape[0], bias, axis=0) # create a collection to store historical calculated weights & append the initially generated weights weights_variation = {} for neuron_ix in range(weights.shape[1]): neuron_name = "Neuron_" + str(neuron_ix + 1) weights_variation[neuron_name] = {} for weight_ix in range(weights.shape[0]): weight_name = "W" + str(weight_ix + 1) weights_variation[neuron_name][weight_name] = [] weights_variation[neuron_name][weight_name].append(weights[weight_ix][neuron_ix]) # learning process for i in range(iteration): # neuron activity/output: compute inner product of Matrix X & W inner_product = np.dot(X, W) # compute y by normalizing inner_product of X & W based on softmax function y = exp(inner_product) / exp(inner_product).sum(axis=1).reshape(t.shape[0], 1) # compute accuracy of classification y_one_ix = np.argmax(y, axis=1) acc = np.where(np.equal(t_one_ix, y_one_ix) == True)[0].size / t.shape[0] accuracy.append(acc) # initialize an empty array to translate out_class = np.zeros(t.shape) # compute error e e = t - y # update weights & bias for neuron in range(W.shape[1]): neuron_name = "Neuron_" + str(neuron + 1) # update weights for weight in range(W.shape[0] - 1): weight_name = "W" + str(weight + 1) W[weight, neuron] = W[weight, neuron] - eta * ((-e[:, neuron] * X[:, weight]).sum() / e.shape[0]) weights_variation[neuron_name][weight_name].append(W[weight, neuron]) # update bias W[W.shape[0] - 1, neuron] = W[W.shape[0] - 1, neuron] - eta * ((-e[:, neuron]).sum() / e.shape[0]) #return(weights_variation) return(accuracy, weights_variation) def accuracy_variation(accuracy_array): curve, = plt.plot(accuracy_array, color='k', linewidth=1) plt.xlim([-10, 1000]) plt.title("Accuracy Variation: Multiple Neuron Classification") plt.xlabel("Iteration") plt.ylabel("Accuracy") plt.show() def weights_variation(weight_variation): line_style = ["-", "--", "-.", ":"] color_platte = ["r", "g", "b"] for neuron in weight_variation.keys(): neuron_ix = int(neuron.replace("Neuron_", "")) - 1 for weight in weight_variation[neuron].keys(): weight_ix = int(weight.replace("W", "")) - 1 curve, = plt.plot(weight_variation[neuron][weight], label = neuron + ": " + weight, color = color_platte[neuron_ix], linestyle = line_style[weight_ix], linewidth=1) plt.legend(loc=2) plt.title("Variation of Weights: Multiple Neuron Classification") plt.xlabel("Iteration") plt.ylabel("Weight Value") plt.show() if __name__ == "__main__": outputs = multiple_neuron_classification(df[df.columns[:4]], df[df.columns[4]], 0.1, 1000) weights_variation(outputs[1]) accuracy_variation(outputs[0])
d545f1d7754437961a7f7ff6d492ebb217400ab6
Aditya7799/171IT204_Sem3
/DSA/Lab1/fib.py
89
3.859375
4
n=input("enter number: ") a=0 b=1 for i in range(n): print(a) temp=b b=a+b a=temp
e53f085278bac99953ce851b190fc2bf32dff3a4
apostlepaul/leetcode
/725_split_linked_list.py
1,258
3.75
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def splitListToParts(self, root, k): """ :type root: ListNode :type k: int :rtype: List[ListNode] """ total_node_num = 0 it = root while it != None: total_node_num +=1 it = it.next avg = int(total_node_num / k) odd = total_node_num % k res = [] it = root for i in range(k): if it == None: res.append(None) else: new_node = ListNode(it.val) res.append(new_node) new_node_it = new_node sub_len = avg if i < odd: sub_len = avg +1 if sub_len > 0: for i in range(sub_len-1): it = it.next if it != None: new_node_tmp = ListNode(it.val) new_node_it.next = new_node_tmp new_node_it = new_node_tmp it = it.next return res
779f4ac37fe780dbd8da90236d11c2abac63b397
hariharan-m/EC504
/Server/kdTree.py
4,950
3.5
4
import numpy as np import queue as Q class Node: def __init__(self, data, lchild=None, rchild=None): self.data = data self.lchild = lchild self.rchild = rchild class KdTree: def __init__(self): self.kdTree = None def create(self, dataSet, depth): # create kd tree, return root node if (len(dataSet) > 0): m, n = np.shape(dataSet) # get size of dataset midIndex = int(m / 2) # get mid point axis = depth % n # judge which axis to seg plane; # sortedDataSet = self.BubleSort(dataSet, axis) # Buble sort point along axis sortDataSet = dataSet[:] sortedDataSet = sorted(sortDataSet, key=lambda x: x[axis]) print("the sort dataSet is" + str(sortedDataSet)) # create the node of mid point node = Node(sortedDataSet[midIndex]) # print sortedDataSet[midIndex] leftDataSet = sortedDataSet[: midIndex] rightDataSet = sortedDataSet[midIndex+1:] print("the left dataSet is" + str(leftDataSet)) print("the right dataSet is" + str(rightDataSet)) # recursing on left and right children node.lchild = self.create(leftDataSet, depth+1) node.rchild = self.create(rightDataSet, depth+1) return node else: return None def preOrder(self, node): # preorder traversal of the tree if node != None: print("tttt->%s" % node.data) self.preOrder(node.lchild) self.preOrder(node.rchild) def search(self, tree, x): # searches and returns the closest point self.nearestPoint = None self.nearestValue = 0 def travel(node, depth=0): # recurse search if node != None: # base case n = len(x) axis = depth % n if x[axis] < node.data[axis]: travel(node.lchild, depth+1) else: travel(node.rchild, depth+1) distNodeAndX = self.dist(x, node.data) if (self.nearestPoint == None): self.nearestPoint = node.data self.nearestValue = distNodeAndX elif (self.nearestValue > distNodeAndX): self.nearestPoint = node.data self.nearestValue = distNodeAndX print(node.data, depth, self.nearestValue, node.data[axis], x[axis]) # find whether there is closer point by using radius if (abs(x[axis] - node.data[axis]) <= self.nearestValue): if x[axis] < node.data[axis]: travel(node.rchild, depth+1) else: travel(node.lchild, depth + 1) travel(tree) return self.nearestPoint def Ksearch(self, tree, x, k): # k nearest neighbors search que = Q.PriorityQueue() res = [] def travel(node, depth=0): # recurse search if node != None: # base case distNodeAndX = self.dist(x, node.data) if (que.qsize() < k): # trivial case que.put((-distNodeAndX, node.data)) else: temp = que.get() if (temp[0] < -distNodeAndX): que.put((-distNodeAndX, node.data)) else: que.put(temp) n = len(x) axis = depth % n if x[axis] < node.data[axis]: travel(node.lchild, depth+1) else: travel(node.rchild, depth+1) temp = que.get() que.put(temp) # find whether there is closer point by using radius if abs(x[axis] - node.data[axis]) <= abs(temp[0]) or que.qsize() < k: if x[axis] < node.data[axis]: # recurse travel(node.rchild, depth+1) else: travel(node.lchild, depth + 1) if (k > 0): travel(tree) while not que.empty(): res.append(que.get()[1]) return res def dist(self, x1, x2): # calculate Euclidean distance return ((np.array(x1) - np.array(x2)) ** 2).sum() ** 0.5 # dataSet = None def main(): global dataSet dataSet = [] with open("test_data.txt") as f: for line in f: arr = list(map(float, line.split())) dataSet.append(arr) print(dataSet) x = [3, 4] kdtree = KdTree() tree = kdtree.create(dataSet, 0) kdtree.preOrder(tree) print("The NN of " + str(x) + " is " + str(kdtree.search(tree, x))) print("The 3NN of " + str(x) + " is " + str(kdtree.Ksearch(tree, x, 3))) if __name__ == "__main__": main()
520119ee576866dc1a91a76aed4af5a88a900fbd
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/ndxshe013/question4.py
545
4.03125
4
import math def palindrome(a): s = str(a) if(s == s[::-1]): return True else: return False def prime(a): for i in range(2,int(math.sqrt(a))+1): if(a%i == 0): return False return True def main(): N = eval(input("Enter the starting point N:\n")) M = eval(input("Enter the ending point M:\n")) print("The palindromic primes are:") for i in range(N+1,M): if(palindrome(i) and prime(i)): print(i) main()
a5928c524079ff7de9b6eda462a91b1c86cd687b
jbanerje/Beginners_Python_Coding
/kth_element.py
169
3.953125
4
#Finding kth element in list userElement = [1,2,3,4,5] userChoice = int(input('Enter the kth element #: ')) print('Kth element is :', userElement[userChoice])
2e3c12e482f4f938157d166d4a02f9a8284f8f0b
JavierCamposCuesta/repoJavierCampos
/1ºDaw/ProgramacionPython/Python/ej_bucles3/ej1.py
1,674
4.09375
4
'''Ejercicio 1 Diseñar un programa que calcule el perímetro de una figura geométrica. Para ello debemos preguntar “¿Cuántos lados tiene la figura?”. Luego debemos pedir la longitud de cada uno de los lados y mostrar el perímetro. Se debe garantizar que los datos son correctos. Created on 17 Nov 2020 @author: estudiante ''' def calculaPerimetro(): lados=int(input("¿Cuantos lados tiene la figura?")) contador =0 perimetro=0 mayor=0 suma=0 if lados>0: while lados>contador: longitud=float(input("Introduce la longitud de un lado")) if longitud>0: if longitud>mayor: mayor=longitud perimetro=longitud+perimetro contador = contador +1 suma=longitud+suma else: print("La longitud tiene que ser positiva") if mayor>(suma-mayor): print("El poligo no es correcto, no puede cerrarse") else: print("El perimetro total es de: "+str( perimetro)) else: print("Tiene que ser un numero positivo") calculaPerimetro() def esUnPoligono(lado): esPoligono = True for i in range(0, len(lado)): if(lado[i] <= 0 ): esPoligono = False for i in range (0, len(lado)): sumaLados = 0 for j in range (0, len(lado)): if(j != i): sumaLados+= lado[j] if sumaLados <= i: esPoligono = False return esPoligono print(esUnPoligono([3,4,5])) print(esUnPoligono([3,4,5])) print(esUnPoligono([9,4,5])) print(esUnPoligono([3,15,5]))
61e943b502ab48f3cbaf6bbc5fb1c7b47a7fcf40
surenderpal/Durga
/Exception Handling/else_block.py
356
3.796875
4
# for x in range(10): # if x>5: # break # print('Current item',x) # else: # print('Congrats!!') # try: # print('try') # print(10/0) # except: # print('except') # else: # print('else') # finally: # print('finally') try: print('try') else: print('else') finally: print('finally') #i did change
df3526265cf2bc8fb9b4e56d203e669a0ea29ecf
Nihadkp/MCA
/Semester-01/Python-Programming-Lab/Course-Outcome-1-(CO1)/17-Sort-in-Dictionary/Sort_dictonary.py
791
4.0625
4
# user inpupt section - errror in this # """ dictCount = int(input("Enter the number of dictionary values")) # dictItem = {} # for i in range(dictCount) : # name = input() # values int(input()) # dictItem[name] = values # "" # dict1 = {} print(type(dict1)) limit = int(input("Enter the limit")) for i in range(limit) : dict1.update({input("Enter the key") : input("Enter the value")}) # dictItem = {'apple': 40, 'orange': 2, 'banana': 1, 'lemon': 3} l = list(dict1.items()) # dict to list conversion l.sort() print("\n Ascending order is", l) # sorted list l = list(dict1.items()) l.sort(reverse=True) # sorting in reverse order print("\nDescending order is", l) dict = dict(l) # list to dict print("\nDictionary", dict) print(("dict is" , dict1))
046b988c338ceda80b10adb08b16f22a56f8ab98
Yogesh-B/PROJECTS
/Python/Pract12.py
986
4.03125
4
# Using Function def isPrime(num): print('\nUsing Function') flag = False if num > 1: for i in range(2, num): if (num % i) == 0: flag = True break return flag def printMessage(number,result): if result: print(number, "is not a Prime Number.") else: print(number, "is a Prime Number.") number = int(input('Enter Number : ')) modNumber = abs(number); type = 3 if(type == 1): printMessage(number,isPrime(modNumber)) elif type == 2 : print('\nWithout Function') flag = False if modNumber > 1: for index in range(2,modNumber): if modNumber % index == 0: flag = True break printMessage(number,flag) else: print('\nList Comprehensions') primes = [index for index in range(2,modNumber) if modNumber % index == 0] if len(primes) == 0 : printMessage(number,False) else: printMessage(number,True)
78f79e9feb36c8783f3284163002733edcc434ad
crystalDf/Grokking-Algorithms-Chapter-04
/BinarySearch.py
452
3.890625
4
def binary_search(arr, item): if len(arr) == 0: return None mid = len(arr) // 2 guess = arr[mid] if guess == item: return guess if guess > item and mid > 0: return binary_search(arr[:mid], item) elif guess < item and mid < len(arr) - 1: return binary_search(arr[(mid + 1):], item) return None my_list = [1, 3, 5, 7, 9] print(binary_search(my_list, 3)) print(binary_search(my_list, -1))
58c93d9857d9dc866f7f736d5bf7b55c59d677b2
siva4646/DataStructure_and_algorithms
/python/backtracking/generate_paranthesis.py
874
3.875
4
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example 1: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2: Input: n = 1 Output: ["()"] """ class Solution(object): def generateParenthesis(self, n: int): result = [] openCounter = 0 closedCounter = 0 self.generateValue(result, openCounter, closedCounter, n, "") return result def generateValue(self, result, openCounter, closedCounter, n, temp_str): if len(temp_str) == 2*n: result.append(temp_str) return if openCounter < n: self.generateValue(result, openCounter+1, closedCounter, n, temp_str+"(") if closedCounter < openCounter: self.generateValue(result, openCounter, closedCounter+1, n, temp_str+")")
99ec918009a73d74c31892c4fdc017a960d20612
zxun1/hacker_rank
/nested-list.py
517
3.9375
4
# Get all students and scores students = [] for _ in range(int(raw_input())): name = raw_input() score = float(raw_input()) students.append([name,score]) # Find the second lowest score scores = [] for student in students: scores.append(student[1]) second_lowest_score = sorted(set(scores))[1] second_lowest_students = [] for student in students: if second_lowest_score == student[1]: second_lowest_students.append(student[0]) for name in sorted(second_lowest_students): print name
0c7e386aab0709747768ecf1c9d5d47b508cf50e
dettore/learn-python-exercises
/_beginners python 3 source files/33-functions.py
233
4
4
# Learning function # def is short for: define def PrintSomeStuff(): print('Stefan just ate some chicken.') print('Now is time for exercise.') def PrintSomeMoreStuff(): print('***** Second.') PrintSomeMoreStuff()
13e930bc684ffdd597be6a601e05d9609621417c
danielrhunt/python
/operator_practice.py
2,221
4.5
4
# #practicing with boolean logic # # print(5==5) #will print True # print(5==6) #will print False # # comparison operators include: # x != y #x does not equal y # x > y #x is greater than y # x < y #x is less than y # x >= y #x is greater than or equal to y, need that order for operators # x <= y #x is less than or equal to y, need that order # x is y #x is the same as y (even more powerful than equal sign) # x is not y #x is not the same as y (even more powerful than equal sign) # x == y #x equals y # # #remember to not use a single "=", because that's the assignment operator! # # #logical operators # #there are three logical operators: "and", "or", and "not" # xy = 5 # if xy is 5 and xy > 3: # print("xy is more than 3") # # xyx = 6 # if xyx is 5 or xyx > 5: # print("xyx is more than five") # # yxy = 7 # if yxy is not 7 and yxy is 7: # print("I don't know, I'm just trying stuff here") #conditionals and alternative execution #writing small program to prompt user for input of a number, and then determine if the number is odd or even #uses the modulo user_input = input("Please enter a number in numeric format:\n") user_input = (int(user_input)) #convert the user input into an integer if user_input % 2 == 0: #this basically says if it's divisible by two with no remainder, meaning it's even print("The number you entered is even") else: print("The number you enetered is odd") #writing small program to run forever until user terminates, so use While while True: user_input = input("Please enter a number in numeric format:\n") #by placing user input inside the While brackets, it prompts for user input every time through the loop #if didn't do this, it would keep the original user input and go into an infinite loop if user_input == "done": print("Okay, you're done.") break elif user_input == "Done": print("Okay, you're done.") break user_input = int(user_input) if user_input % 2 == 0: #this basically says if it's divisible by two with no remainder, meaning it's even print("The number you entered is even") continue else: print("The number you enetered is odd") continue
ee8b716c6ecdb46ddc1f42d2d9f5bd23133bb61b
Pramod123-mittal/python-prgs
/oops_eleven.py
880
4.21875
4
# polymorphism-->ability to take various forms print(5 + 6) print('5' + '6') # super keyword and overiding class A: classvar1 = 'i am a class variable inside class A' def __init__(self): self.var1 = 'i am inside class A"s constructor' self.classvar1 = 'instance variable in class A' self.special = 'special' class B(A): classvar1 = 'i am a class variable inside class B' def __init__(self): # here constructor overides if anu constructor overides then previous constructor will not run # super().__init__() self.var1 = 'i am inside class B"s constructor' self.classvar1 = 'instance variable in class B' super().__init__() print(super().classvar1) # if we want to use both the constructors then we have to use super keyword a = A() b = B() print(b.classvar1) print(b.special) print(b.var1)
741749f34a6a51c1dc95e930ff9b529510dcdee0
shenzhiyong17/python_homework
/data_structure/common/gen_rand.py
585
3.59375
4
#!/usr/bin/env python # date: 2016-2-2 import random import string def gen_rand_list(num, start=0, stop=1000): lst = [] for i in range(num): x = random.randint(start, stop) lst.append(x) return lst def gen_rand_string(length): s = string.letters + string.digits result = '' for i in xrange(length): result += s[random.randrange(len(s))] return result def disorder(array): n = len(array) for i in range(n - 1): t = random.choice(range(i + 1, n)) array[i], array[t] = array[t], array[i] return array
b8be002a273d2bd8d4a2e2770f584a2aeb63e0aa
faiztherocker/Python
/Word_count.py
1,065
3.71875
4
import operator """ #Set basics setone = {'again':1,'back':2} print(setone['again'])""" def start(): word_list = [] fr = open('FinalPaper.txt','r') content = fr.read() words = content.lower().split() for eachh_word in words: #print(eachh_word) word_list.append(eachh_word) clean_list(word_list) def clean_list(word_list): clean_word_list=[] for word in word_list: clean_char='~!@#$%^&*(){}[]:";<>,./'; for i in range(0,len(clean_char)): word=word.replace(clean_char[i]," ") if(len(word) > 0): clean_word_list.append(word) create_dictionary(clean_word_list) def create_dictionary(clean_word_list): word_count = {} for word in clean_word_list: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 #Write 0 to sort by key 1 for value for key,value in sorted(word_count.items(),key= operator.itemgetter(0),reverse=False): print(key + '-->[ ' + str(value) + ' ]') start()
5f925cc3b5ea02f94fcee3d4ad765f32d5711bda
petitviolet/project_euler
/48.py
256
3.5625
4
# -*- encoding:utf-8 -*- def num(n): return n ** n def order_10(n): s = str(n) return s[-10:] def main(): n = 0 for i in xrange(1, 1000): n += num(i) ans = order_10(n) print ans if __name__ == '__main__': main()
7fc81d71099e2a8910daf6ada29e6a36c26fe218
xing3987/python3
/base/面向对象/_30_eval.py
378
3.546875
4
# 执行函数 input_str = input("请输入计算题\n") print(eval(input_str)) # 警慎使用eval()函数,容易产生漏洞,特别是eval(input())直接执行用户输入的内容 #系统自带执行指令的方法 #__import__('os').system('pwd') # 如果input中输入导入os模块,执行系统命令就太可怕了: # eval("__import__('os').system('pwd')")
531e6fcb5bc1a461b53128c41588c6c89b6dbd8b
stefan9090/applied-AI-practicum
/exercises_6/cards.py
3,313
3.734375
4
import random import math from functools import reduce import operator def individual(min_val, max_val): """ This function returns an individual which consists of 10 unique numbers. """ value_list = [i for i in range(min_val, max_val+1)] #generate a list of 1 to 10 random.shuffle(value_list) #shuffle the list return value_list def fitness(individual, divider, target_sum, target_multiply): """ This function gets the fitness of an individual by calculating the average percentage off its intended target. """ sum_val = reduce(operator.add, individual[:divider], 0) multiply_val = reduce(operator.mul, individual[divider:], 1) sum_error = abs(target_sum - sum_val) sum_error = sum_error / target_sum multiply_error = abs(target_multiply - multiply_val) multiply_error = multiply_error / target_multiply #print(multiply_error, sum_error) #print(sum_error, multiply_error) return (multiply_error + sum_error)/2 * 100 def tournament(indiv1, indiv2, divider): val1 = fitness(indiv1, divider, 36, 360) val2 = fitness(indiv2, divider, 36, 360) #print(val1, val2) if val1 > val2: return indiv2 return indiv1 def mutate(indiv, divider, amount): """ This function mutates an individual bij swapping 2 entries in both piles. It also check wether or not the new generated individual is an unique child """ new_indivs = [] while len(new_indivs) < amount: index1 = random.randint(0, divider-1) index2 = random.randint(divider, len(indiv)-1) new_indiv = [] for i in indiv: new_indiv.append(i) new_indiv[index1] = indiv[index2] new_indiv[index2] = indiv[index1] if new_indiv not in new_indivs: new_indivs.append(new_indiv) return new_indivs def card_problem(divider): for x in range(100): population = [individual(1, 10) for _ in range(100)] for _ in range(100): new_population = [] for __ in range(25): indiv1 = population.pop(random.randint(0, len(population)-1)) #get 2 candidates voor the tournament indiv2 = population.pop(random.randint(0, len(population)-1)) new_population.append(tournament(indiv1, indiv2, divider)) # append the winner to the new_population list for i in range(len(new_population)): new_population += mutate(new_population[i], divider, 3) #we mutate every winnen 3 times so we get a population of 100(including tournament winners) again. population = new_population[:] #get best outcome based on the fitness function results = [] for i in population: results.append((fitness(i, divider, 36, 360), i)) #print(i) results.sort(key=lambda tup: tup[0]) print(results[0]) def main(): card_problem(5) #The variable is the divider. """ Wij verdelen de kaarten gelijk over beide stapels, omdat wij met deze verdeling precies kunnen uitkomen op 36 en 360. bij een andere verdeling lukte dit niet. De afwijkingen die wij zien met een divider van 5 zijn tussen de 0 en de 4 procent, dit kan komen door lokaal optima. """ if __name__ == '__main__': main()
a143d2c7b103e336f7498e312f85c4887314c5bc
abigail-hyde/flood-agh54-bjw68
/Task1D.py
1,047
3.53125
4
from floodsystem.geo import rivers_with_station from floodsystem.geo import stations_by_river from floodsystem.stationdata import build_station_list def run(): """Requirements for Task 1D""" # Create a list of stations stations = build_station_list() # Create list of rivers rivers = rivers_with_station(stations) # Display data from 10 rivers: river_display = rivers[:10] number_of_rivers = len(rivers) print('There are {} rivers with at least one station. The first ten rivers are {}' .format(number_of_rivers, river_display)) # Create River dictionary river_stations = stations_by_river(stations) # Display desired rivers print('The stations on the River Aire are {}'.format(river_stations['River Aire'])) print('The stations on the River Cam are {}'.format(river_stations['River Cam'])) print('The stations on the River Thames are {}'.format(river_stations['River Thames'])) if __name__ == "__main__": print("*** Task 1D: CUED Part IA Flood Warning System ***") run()
1b658c9bebc19e4e5135828b3321c766541f128d
museRhee/basicPython
/findNum.py
730
3.859375
4
''' enter m, and find n. enter 0, program exit. n satisfies the following condition. 1.sum of integers from 1 to n is same or less than m 2.n is the biggest one which satisfied the condition 1. ''' while (True) : m = int(input("Enter the number m: ")) if (m == 0) : #program exit if enter 0 print('Good-bye') break n =0 #initial value of count number totalSum = 0 #initial sum of totalSum #find n by totalSum while (True) : totalSum += n if (totalSum > m) : print('the number is', n-1) #n is over m. so n-1 break else : n += 1
bca74cd8cff526bd933971bbb0c0088c3376c3e4
kikijtl/coding
/Candice_coding/Leetcode/Remove_Duplicate_Array.py
1,371
3.671875
4
def removeDuplicates(A): n = len(A) if n == 0: return n i = 0 j = 0 while i < n and j < n: if A[j] == A[i]: j += 1 else: i += 1 A[i] = A[j] #return the length of array return i+1 def removeDuplicates2(A): n = len(A) if n <= 1: return n i = 0 j = 1 count = 0 while i < n and j < n: if A[j] == A[i]: count += 1 A[i+1] = A[j] j += 1 elif count > 0: i += 2 A[i] = A[j] j += 1 count = 0 else: i += 1 A[i] = A[j] j += 1 if count > 0: return i+2 else: return i+1 def removeElement(A, elem): n = len(A) if n == 0: return n i = 0 j = n-1 while i < n and j > i: if A[i] != elem: i += 1 continue if A[j] == elem: j -= 1 continue A[i] = A[j] i += 1 j -= 1 if j == i and A[i] != elem: return i+1 else: return i if __name__ == '__main__': A = [1,1,1,1,2,2,2,3] #l = removeDuplicates2(A) #print A[:l] elem = 1 nl = removeElement(A, elem) print A[:nl]
8353c22928b60f236cba618965664867310aaa04
EEJDX/AlgorithmExperiments
/naive.py
612
3.546875
4
def naive(a, b): x = a y = b z = 0 while x > 0: z = z + y x = x - 1 return z def rec_naive(a, b): print("count me!") if a == 0: return 0 return b + rec_naive(a-1, b) def russian(a, b): x = a; y = b z = 0 while x > 0: if x == 7 and z == 84: print(y) if x % 2 == 1: z = z + y y = y << 1 x = x >> 1 return z def countClique(n): return 2 + n + (n * (n - 1)) / 2 def clique(n): print ("in a clique...") for j in range(n): for i in range(j): print (i, " is friends with ", j)
521c70f3c4cc641772a908a1f8b7838f0fcec2e9
DeVinhoOne/python-currency-converter
/converter.py
1,047
3.546875
4
import requests from show_additional_info import show_additional_info print('\n\t\t===Currency Converter===') show_info = input('\tDo You need additional info?(y/n) ').lower() if show_info == 'y': show_additional_info() elif show_info == 'n': pass class Converter: def __init__(self): self.amount = float( input('\n\tHow much money do You want to convert? ')) self.base_currency = input('\tWhat is Your base currency? ').upper() self.rates = None self.convert() self.printer() def convert(self): req = requests.get('https://api.exchangeratesapi.io/latest', params={'base': self.base_currency}) self.rates = req.json()['rates'] def printer(self): print(f'\n{self.amount}{self.base_currency} converted into..\n') for currency, rate in self.rates.items(): converted_amount = round(rate * self.amount, 2) print(f'{currency}({round(rate, 2)}) ===> {converted_amount}') cc = Converter()
c70a383882f321c812e0fc70cc91e3b6b1600672
SkipDigit/battleship
/gui.py
872
3.59375
4
import tkinter as tk ''' top=tk.Tk() A1=tk.Button(top, text='A1') A2=tk.Button(top, text='A2') B1=tk.Button(top, text='B1') B2=tk.Button(top, text='B2') A1.grid(row=0,column=0) A2.grid(row=0,column=1) B1.grid(row=1,column=0) B2.grid(row=1,column=1) top.mainloop() ''' class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() def create_widgets(self): self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) A1=tk.Button(self, text='A1') A2=tk.Button(self, text='A2') B1=tk.Button(self, text='B1') B2=tk.Button(self, text='B2') A1.grid(row=0,column=0) A2.grid(row=0,column=1) B1.grid(row=1,column=0) B2.grid(row=1,column=1) def say_hi(self): print("hi there, everyone!") root = tk.Tk() app = Application(master=root) app.mainloop()
8a35f686e92f8a22f1b34b06d4218c6402bec33f
davidwarshaw/leetcode
/google/Flatten-Nested-List-Iterator.py
3,028
4.3125
4
#!/usr/bin/env python """ This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation """ class NestedInteger(object): def __init__(self, nested): self.items = nested self.is_list = True if type(nested) == list else False def __str__(self): if self.is_list: return '[' + ', '.join(map(lambda item: str(item), self.items)) + ']' else: return str(self.items.getInteger()) def isInteger(self): """ @return True if this NestedInteger holds a single integer, rather than a nested list. :rtype bool """ return not self.is_list def getInteger(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """ return self.items if self.isInteger() else None def getList(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer :rtype List[NestedInteger] """ return self.items if not self.isInteger() else None class NestedIterator(object): def __init__(self, nestedList): """ Initialize your data structure here. :type nestedList: List[NestedInteger] """ self.flattened = [] def flatten(sub_list): if sub_list.isInteger(): self.flattened.append(sub_list.getInteger()) return else: for item in sub_list.getList(): flatten(item) for item in nestedList: flatten(item) self.index = 0 def next(self): """ :rtype: int """ next_item = self.flattened[self.index] self.index += 1 return next_item def hasNext(self): """ :rtype: bool """ return self.index < len(self.flattened) # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next()) inputs = [[NestedInteger([NestedInteger(1), NestedInteger(1)]), NestedInteger(2), NestedInteger([NestedInteger(1), NestedInteger(1)])], [NestedInteger(1), NestedInteger([NestedInteger(4), NestedInteger([NestedInteger(6)])])], [NestedInteger(0)]] expecteds = [[1,1,2,1,1], [1,4,6], [0]] if __name__ == '__main__': for input, expected in zip(inputs, expecteds): i, actual = NestedIterator(input), [] while i.hasNext(): actual.append(i.next()) print(f"input: {input}") print(f"expected: {expected}") print(f"actual: {actual}") print(f"{actual == expected}") print()
cf51e04818edf0d092e808589e7c844a06e3a534
HARICHANDANAKARUMUDI/chandu
/vowel.py
269
4.125
4
val1=input() if val1>='a' and val1<='z' or val1>='A' and val1<='Z': if val1=='a' or val1=='e' or val1=='i' or val1=='o' or val1=='u' or val1=='A' or val1=='E' or val1=='I' or val1=='O' or val1=='U': print("Vowel") else: print("Consonant") else: print("Invalid")
c0d446274aa2210d354f1a798e5a0032713d73b0
LionWar22/Lista_de_exercicios
/ex04.py
1,148
4.25
4
# v = float(input("Velocidade em km/h: ")) # # t = float(input("Tempo em h : ")) # # s = v * t # # print("Distancia de {} Km".format(s)) #Aperfeiçoando o exercicio def calcDistancia(): #Função calcula a distancia v = float(input("Velocidade em km/h: ")) #As variaveis necessarias para o calculo são criadas dentro das funções t = float(input("Tempo em H: ")) print("Distancia: {} Km" .format(v * t)) # A impressão do resultado ocorre dentro da função def calcVelocidade(): #Função calcula a velocidade t = float(input("Tempo em H: ")) s = float(input("Distancia em Km: ")) print("Velocidade: {} km/h".format( s / t )) def calcTempo(): #Função calcula o Tempo v = float(input("Velocidade em km/h: ")) s = float(input("Distancia em Km: ")) print("Tempo: {} H".format( s / v )) opcao = int(input("[1]Calcular Distancia \n[2]Calcular Tempo \n[3]Calcular Velocidade \nDigite sua escolha:")) #Uma variavel armazena a opção do usuario if 1 == opcao: #Verifica qual opção o usuario escolhe e chama a função calcDistancia() elif opcao == 2: calcTempo() else: calcVelocidade()
72aa8888a7462e9ea15e7b555ab016d8474a113a
sukaran/NLTKBook
/ch2_exercises.py
19,500
3.546875
4
import nltk import re from nltk.corpus import gutenberg from nltk.corpus import brown from nltk.corpus import state_union from nltk.corpus import wordnet as wn from nltk.corpus import swadesh from nltk.book import text1 as mobydick #mobydick from nltk.book import text2 as sense_and_sensibility #sense_and_sensibility from nltk.corpus import names # male-female names from nltk.corpus import cmudict #pronouncing dictionary from nltk.corpus import stopwords # list of stopwords from matplotlib import pyplot import random from nltk.corpus import wordnet as wn #1 Create a variable phrase containing a list of words. Review the operations described in the previous chapter, including addition, multiplication, indexing, slicing, and sorting. tempPhrase = ["Create", "a", "variable", "phrase", "containing", "a", "list", "of", "words"] print(tempPhrase+tempPhrase) print(tempPhrase*3) print(tempPhrase[5]) print(tempPhrase[-4:]) print(sorted(w.lower() for w in set(tempPhrase))) #only sort puts capital letters first #2 Use the corpus module to explore austen-persuasion.txt. How many word tokens does this book have? How many word types? austen_persuasion = gutenberg.words('austen-persuasion.txt') print("Number of word tokens = ",len(austen_persuasion)) print("Number of word types = ",len(set(austen_persuasion))) #3 Use the Brown corpus reader nltk.corpus.brown.words() or the Web text corpus reader nltk.corpus.webtext.words() to access some sample text in two different genres. print(brown.categories()) news_data=brown.words(categories='news') religion_data=brown.words(categories='religion') #4 Read in the texts of the State of the Union addresses, using the state_union corpus reader. Count occurrences of men, women, and people in each document. What has happened to the usage of these words over time? print(state_union.fileids()) #cfd for inaugral address speeches for each president showing count of words american and citizen each speech cfd = nltk.ConditionalFreqDist((target,fileid[:4])for fileid in state_union.fileids() for w in state_union.words(fileid) for target in ['men','women'] if w.lower().startswith(target)) #cfd.plot() #5 Investigate the holonym-meronym relations for some nouns. Remember that there are three kinds of holonym-meronym relation, so you need to use: member_meronyms(), part_meronyms(), substance_meronyms(), member_holonyms(), part_holonyms(), and substance_holonyms(). house = wn.synsets('house') print(house) house = wn.synset('house.n.01') print(house.lemma_names()) print(house.definition()) print(house.examples()) print(house.member_meronyms()) print(house.part_meronyms()) print(house.substance_meronyms()) print(house.member_holonyms()) print(house.part_holonyms()) print(house.substance_holonyms()) food = wn.synsets('food') print(food) food = wn.synset('food.n.01') print(food.lemma_names()) print(food.definition()) print(food.examples()) print(food.member_meronyms()) print(food.part_meronyms()) print(food.substance_meronyms()) print(food.member_holonyms()) print(food.part_holonyms()) print(food.substance_holonyms()) #6 In the discussion of comparative wordlists, we created an object called translate which you could look up using words in both German and Spanish in order to get corresponding words in English. What problem might arise with this approach? Can you suggest a way to avoid this problem? translate = dict() de2en = swadesh.entries(['de','en']) es2en = swadesh.entries(['es','en']) translate.update(dict(de2en)) translate.update(dict(es2en)) print(translate) #one word could have multiple corresponding words or vice versa? #keep only one in dictionary??? #7 According to Strunk and White's Elements of Style, the word however, used at the start of a sentence, means "in whatever way" or "to whatever extent", and not "nevertheless". They give this example of correct usage: However you advise him, he will probably do as he thinks best. (http://www.bartleby.com/141/strunk3.html) Use the concordance tool to study actual usage of this word in the various texts we have been considering. See also the LanguageLog posting "Fossilized prejudices about 'however'" at http://itre.cis.upenn.edu/~myl/languagelog/archives/001913.html print(mobydick.concordance('however')) print(sense_and_sensibility.concordance('however')) #8 Define a conditional frequency distribution over the Names corpus that allows you to see which initial letters are more frequent for males vs. females (cf. 4.4). #cfd against last letters for all names to check well known fact that names ending in letter a are almost always female cfd = nltk.ConditionalFreqDist((fileid,name[1]) for fileid in names.fileids() for name in names.words(fileid)) cfd.plot() #9 Pick a pair of texts and study the differences between them, in terms of vocabulary, vocabulary richness, genre, etc. Can you find pairs of words which have quite different meanings across the two texts, such as monstrous in Moby Dick and in Sense and Sensibility? #already have news and religion data from brown corpus #concordance works on Text objects, so need to instantiate a Text with news and religion data news_data = nltk.Text(news_data) religion_data = nltk.Text(religion_data) #trying to find common words news_fd = nltk.FreqDist(news_data) religion_fd = nltk.FreqDist(religion_data) print(news_data.concordance('state')) print(religion_data.concordance('state')) #10 Read the BBC News article: UK's Vicky Pollards 'left behind' http://news.bbc.co.uk/1/hi/education/6173441.stm. The article gives the following statistic about teen language: "the top 20 words used, including yeah, no, but and like, account for around a third of all words." How many word types account for a third of all word tokens, for a variety of text sources? What do you conclude about this statistic? Read more about this on LanguageLog, at http://itre.cis.upenn.edu/~myl/languagelog/archives/003993.html. fdist1 = nltk.FreqDist(nltk.book.text3) print(fdist1) fdist1.most_common(50) fdist1.plot(50) fdist1.plot(50,cumulative=True) #true, most words in text are stop words!! #11 Investigate the table of modal distributions and look for other patterns. Try to explain them in terms of your own impressionistic understanding of the different genres. Can you find other closed classes of words that exhibit significant differences across different genres? #conditional frequency distributions cfd = nltk.ConditionalFreqDist((genre,word)for genre in brown.categories() for word in brown.words(categories=genre)) genres = ['news', 'religion', 'hobbies', 'science_fiction', 'romance', 'humor'] # check distribution of 5 w's 1 h general_words = ["who", "what", "when", "where", "why", "how"] #conditional frequency distributions with event_words cfd.tabulate(conditions=genres, samples=general_words) # most frequent in new is who, when;religion is who, what;hobbies is who, when,etc. #12 The CMU Pronouncing Dictionary contains multiple pronunciations for certain words. How many distinct words does it contain? What fraction of words in this dictionary have more than one possible pronunciation? words = [word for word,pron in cmudict.entries() ] wordset=set(words) cmu=cmudict.dict() print(len(words)) print(len(wordset)) more_than_one_pron=[word for word in wordset if len(cmu.get(word))>1] print(len(more_than_one_pron)/len(wordset)*100,"% words have more than one pronounciation") #13 What percentage of noun synsets have no hyponyms? You can get all noun synsets using wn.all_synsets('n'). no_hyp_nouns=[noun for noun in wn.all_synsets('n') if len(noun.hyponyms())==0] all_noun_words=[noun for noun in wn.all_synsets('n')] print("Percentage of noun having no hyponyms: ",len(no_hyp_nouns)/len(all_noun_words)*100) #weird: had to define all_nouns twice as on 2 operation it was blank, mutability maybe #14 Define a function supergloss(s) that takes a synset s as its argument and returns a string consisting of the concatenation of the definition of s, and the definitions of all the hypernyms and hyponyms of s. def supergloss(s): definitions=s.definition(); for hypo in s.hyponyms(): definitions+="\n"+hypo.definition() for hyper in s.hypernyms(): definitions+="\n"+hyper.definition() return definitions definitions = supergloss(wn.synset('car.n.01')) print(definitions) #15 Write a program to find all words that occur at least three times in the Brown Corpus. all_unique_words_brown=set(brown.words()) brown_fd=nltk.FreqDist(brown.words()) atleast_3times=[word for word in all_unique_words_brown if brown_fd[word]>2] print(atleast_3times) #16 Write a program to generate a table of lexical diversity scores (i.e. token/type ratios), as we saw in 1.1. Include the full set of Brown Corpus genres (nltk.corpus.brown.categories()). Which genre has the lowest diversity (greatest number of tokens per type)? Is this what you would have expected? brown_categories=brown.categories() print("Category, Tokens, Types, Lexical Diversity") for category in brown_categories: category_words = brown.words(categories=category) print(category,len(category_words),len(set(category_words)),len(category_words)/(len(set(category_words))*1.0)) #science fiction has least diversity score #17 Write a function that finds the 50 most frequently occurring words of a text that are not stopwords. most_freq_50_fd=nltk.FreqDist(brown.words(categories='news')) #fd that includes stop words print(most_freq_50_fd.most_common(50)) words=[word for word in most_freq_50_fd] for word in words: if word in stopwords.words('english') or not word.isalpha(): most_freq_50_fd.pop(word) #fd that excludes stop words print(most_freq_50_fd.most_common(50)) #18 Write a program to print the 50 most frequent bigrams (pairs of adjacent words) of a text, omitting bigrams that contain stopwords. # brown_word_bigrams = nltk.bigrams(brown.words(categories="romance")) bigrams_without_stopwords = [(a,b) for a,b in nltk.bigrams(brown.words(categories="romance")) if a not in stopwords.words('english') and b not in stopwords.words('english')] bigrams_without_stopwords_fd = nltk.FreqDist(bigrams_without_stopwords) print(bigrams_without_stopwords_fd.most_common(50)) #19 Write a program to create a table of word frequencies by genre, like the one given in 1 for modals. Choose your own words and try to find words whose presence (or absence) is typical of a genre. Discuss your findings. cfd = nltk.ConditionalFreqDist((genre,word)for genre in brown.categories() for word in brown.words(categories=genre)) # check distribution of "love","hate","death","life","marriage","work","children" general_words = ["love", "hate", "death", "life", "marriage", "work", "children","magic"] #conditional frequency distributions with event_words cfd.tabulate(conditions=brown.categories(), samples=general_words) #conclusion: belles_letters contains alot of refrences to life and work #learned category has a lot of refrences to work #lore contains a lot of refrences to life # religion contains most refrences to life death work and magic #20 Write a function word_freq() that takes a word and the name of a section of the Brown Corpus as arguments, and computes the frequency of the word in that section of the corpus. def word_freq(word,category): category_text=brown.words(categories=category) return sum(1 for wd in category_text if wd==word) print(word_freq("work","learned")) #21 Write a program to guess the number of syllables contained in a text, making use of the CMU Pronouncing Dictionary. # a unit of pronunciation having one vowel sound, with or without surrounding consonants, forming the whole or a part of a word; e.g., there are two syllables in water and three in inferno. #easiest guess - number of vowels = number of syllables #previous example #syllable = ['N','IH0','K','S'] this syllable contains one vowel cmu_dict = cmudict.entries() print(len(cmu_dict)) # print(cmu_dict['water']) # contains 2 vowels so two syllables #get a text print(len(brown.words(categories='hobbies'))) print(len(set(brown.words(categories='hobbies')))) brown_hobbies=sorted(set(brown.words(categories='hobbies'))) brown_hobbies_dict_words = [(word,pron) for word,pron in cmu_dict if word in brown_hobbies] print(len(brown_hobbies_dict_words)) def count_syllables(pron): return len([w for w in pron if re.findall("[aeiou]",w.lower())]) no_of_syll_per_word = [count_syllables(pron) for word,pron in brown_hobbies_dict_words] print("Number of syllables contained in brown corpus hobbies category: ",sum(no_of_syll_per_word)) #22 Define a function hedge(text) which processes a text and produces a new version with the word 'like' between every third word. def hedge(text): # test = 'this is a test sentence to insert like after every third word'.split() ids = [index-1 for index in list(range(3,len(text)+1,3))] for id in ids: text.insert(id,'like') return text test_text=hedge('this is a test sentence to insert like after every third word'.split()) print(test_text) #23 Zipf's Law: Let f(w) be the frequency of a word w in free text. Suppose that all the words of a text are ranked according to their frequency, with the most frequent word first. Zipf's law states that the frequency of a word type is inversely proportional to its rank (i.e. f × r = k, for some constant k). For example, the 50th most common word type should occur three times as frequently as the 150th most common word type. # Write a function to process a large text and plot word frequency against word rank using pylab.plot. Do you confirm Zipf's law? (Hint: it helps to use a logarithmic scale). What is going on at the extreme ends of the plotted line? def zipfs_law(text,n): text_fd=nltk.FreqDist(text) text_fd_common=text_fd.most_common(n) freqs=[y for x,y in text_fd_common] ranks=[1/freq for freq in freqs] pyplot.plot(ranks,freqs) zipfs_law(nltk.corpus.gutenberg.words('austen-sense.txt'),50) # zipfs_law(nltk.corpus.gutenberg.words('austen-sense.txt'),100) # zipfs_law(nltk.corpus.gutenberg.words('austen-sense.txt'),500) #looks inversely proportional but is the solution correct?? # Generate random text, e.g., using random.choice("abcdefg "), taking care to include the space character. You will need to import random first. Use the string concatenation operator to accumulate characters into a (very) long string. Then tokenize this string, and generate the Zipf plot as before, and compare the two plots. What do you make of Zipf's Law in the light of this? random_text='' for i in range(0,random.randrange(10000,1000000)): random_text+=random.choice("abcdefg ") # print(random_text) zipfs_law(random_text.split(' '),100) #yes it is almost inversely proportion #24 Modify the text generation program in 2.2 further, to do the following tasks: def generate_model(text, n): text_fd=nltk.FreqDist(text) text_fd_common=text_fd.most_common(n) rand_words = [word for word,index in text_fd_common] return rand_words # Store the n most likely words in a list words then randomly choose a word from the list using random.choice(). (You will need to import random first.) text = nltk.corpus.genesis.words('english-kjv.txt') genesis_rand_words = generate_model(text, 100) print(genesis_rand_words) print(random.choice(genesis_rand_words)) # Select a particular genre, such as a section of the Brown Corpus, or a genesis translation, one of the Gutenberg texts, or one of the Web texts. Train the model on this corpus and get it to generate random text. You may have to experiment with different start words. How intelligible is the text? Discuss the strengths and weaknesses of this method of generating random text. brown_romance=brown.words(categories='romance') brown_romance_rand = generate_model(brown_romance,200) print(brown_romance_rand,len(brown_romance_rand)) #we could use title case words to be start words. #sentences have to end in anyone of the punctuation marks def generate_sentence(text): start_words = set(word for word in brown_romance_rand if word.istitle()) punc_symbols = set(word for word in brown_romance_rand if not word.isalpha() and len(word) == 1) other_words = set(brown_romance_rand).difference(punc_symbols) other_words = list(other_words) start_words = list(start_words) punc_symbols = list(punc_symbols) limit_1 = random.randrange(1, len(other_words)) limit_2 = random.randrange(1, len(other_words)) if limit_1 < limit_2: rand_indices = list(range(limit_1, limit_2)) other_indexes = [random.choice(rand_indices) for id in rand_indices] wordlist = [other_words[id] for id in other_indexes] else: rand_indices = list(range(limit_2, limit_1)) other_indexes = [random.choice(rand_indices) for id in rand_indices] wordlist = [other_words[id] for id in other_indexes] wordlist.insert(0,random.choice(start_words)) wordlist.append(random.choice(punc_symbols)) print(" ".join(wordlist)) generate_sentence(brown_romance) #this method generated non sensical text with one title case word at start, one punctuation mark at the end and a random selection of words in between # Now train your system using two distinct genres and experiment with generating text in the hybrid genre. Discuss your observations. generate_sentence(brown_romance+brown.words(categories='religion')) #25 Define a function find_language() that takes a string as its argument, and returns a list of languages that have that string as a word. Use the udhr corpus and limit your searches to files in the Latin-1 encoding. latin1_files = [f for f in nltk.corpus.udhr.fileids() if re.search(r'Latin1',f)] def find_language(word,latin1_files): return sum([1 for file in latin1_files for w in nltk.corpus.udhr.words(file) if word in w]) word_count_latin1=find_language("human",latin1_files) print(word_count_latin1) word_count_latin1=find_language("rights",latin1_files) print(word_count_latin1) #26 What is the branching factor of the noun hypernym hierarchy? I.e. for every noun synset that has hyponyms — or children in the hypernym hierarchy — how many do they have on average? You can get all noun synsets using wn.all_synsets('n'). all_synsets=wn.all_synsets('n') hyper_counts=[len(syn.hypernyms()) for syn in all_synsets] average_num_hyper=sum(hyper_counts)/len(hyper_counts) print("branching factor of the noun hypernym hierarchy: ",average_num_hyper) #27 The polysemy of a word is the number of senses it has. Using WordNet, we can determine that the noun dog has 7 senses with: len(wn.synsets('dog', 'n')). Compute the average polysemy of nouns, verbs, adjectives and adverbs according to WordNet. #*.[nvas].* all_synsets = wn.all_synsets() synsets_per_word = [synst for synst in all_synsets] #28 Use one of the predefined similarity measures to score the similarity of each of the following pairs of words. Rank the pairs in order of decreasing similarity. How close is your ranking to the order given here, an order that was established experimentally by (Miller & Charles, 1998): car-automobile, gem-jewel, journey-voyage, boy-lad, coast-shore, asylum-madhouse, magician-wizard, midday-noon, furnace-stove, food-fruit, bird-cock, bird-crane, tool-implement, brother-monk, lad-brother, crane-implement, journey-car, monk-oracle, cemetery-woodland, food-rooster, coast-hill, forest-graveyard, shore-woodland, monk-slave, coast-forest, lad-wizard, chord-smile, glass-magician, rooster-voyage, noon-string.
5539d7df9d444008e030b596dc0668a513425ae5
AlexanderOnbysh/edu
/bachelor/generators.py
3,744
3.765625
4
# yield and yield from difference # yield def bottom(): return (yield 42) def middle(): return (yield bottom()) def top(): return (yield middle()) >> gen = top() >> next(gen) <generator object middle at 0x10478cb48> # ---------------------- # yield from # is roughly equivalent to # *** # for x in iterator: # yield x # *** def bottom(): return (yield 42) def middle(): return (yield from bottom()) def top(): return (yield from middle()) >> gen = top() >> next(gen) 42 # ---------------------- # yield from not iterable def test(): yield from 10 >> gen = test() >> next(gen) TypeError: 'int' object is not iterable # ---------------------- # yield from iterable object def test(): yield from [1, 2] >> gen = test() >> next(gen) 1 >> next(gen) 2 >> next(gen) StopIteration: # throw method in generators # gen.throw(exception, value, traceback) def test(): while True: try: t = yield print(t) except Exception as e: print('Exception:', e) >> gen = test() >> next(gen) >> gen.send(10) 10 >> gen.send(12) 12 >> gen.throw(TypeError, 18) Exception: 18 # g.close() send GeneratorExit to GeneratorExit def close(self): try: self.throw(GeneratorExit) except (GeneratorExit, StopIteration): pass else: raise RuntimeError("generator ignored GeneratorExit") # Other exceptions are not caught # async # Parallel async # asyncio.gather put all tasks in event loop import asyncio async def bottom(name, sleep): await asyncio.sleep(sleep) print(f"I'm bottom {name}") return 42 async def middle(name, sleep): print(f"I'm middle {name}") await bottom(name, sleep) async def top(name, sleep): print(f"I'm top {name}") await middle(name, sleep) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather(top('first', 3), top('second', 2), top('third', 1) )) I'm top first I'm middle first I'm top third I'm middle third I'm top second I'm middle second # sleep for 3 seconds I'm bottom third I'm bottom second I'm bottom first # If we call corutine that call other corutine # then task will be added sequatially to event loop # and no parallelism happens async def run(): names = ['first', 'second', 'third'] times = [3, 2, 1] for name, time in zip(names, times): await top(name, time) loop = asyncio.get_event_loop() loop.run_until_complete(run()) I'm top first I'm middle first # sleep for 3 seconds I'm bottom first I'm top second I'm middle second # sleep for 2 seconds I'm bottom second I'm top third I'm middle third # sleep for 1 seconds I'm bottom third # Create tasks from futures and put # them to event loop # await results from each task async def run(): loop = asyncio.get_event_loop() names = ['first', 'second', 'third'] times = [3, 2, 1] tasks = [] for name, time in zip(names, times): t = loop.create_task(top(name, time)) tasks.append(t) await asyncio.gather(*tasks) # equvalet to # for task in tasks: # await task loop = asyncio.get_event_loop() loop.run_until_complete(run()) I'm top first I'm middle first I'm top second I'm middle second I'm top third I'm middle third # sleep for 1 seconds I'm bottom third # sleep for 1 seconds I'm bottom second # sleep for 1 seconds I'm bottom first # Call later def hey_hey(n): print(n) def hey(): print('Hey!') loop = asyncio.get_event_loop() loop.call_later(10, lambda: hey_hey(42)) loop = asyncio.get_event_loop() loop.call_later(20, hey) # 20 seconds Hey # 10 seconds 42
30d6024e4d23a769faba97c186b42446c27d74b1
shen-huang/selfteaching-python-camp
/exercises/1901100142/1001S02E03_calculator.py
659
4.03125
4
operator=input('请输入运算符(+、-、*、/):') first_number=input('请输入第一个数字:') second_number=input('请输入第二个数字:') a=int(first_number) b=int(second_number) print('operator:',operator,type(operator)) print('first_number:',first_number,type(first_number),type(a)) print('second_number:',second_number,type(second_number),type(b)) print('测试加法str加法:',first_number+second_number) if operator=='+': print(a,'+',b,'=',a+b) elif operator=='-': print(a,'-',b,'=',a-b) elif operator=='*': print(a,'*',b,'=',a*b) elif operator=='/': print(a,'/',b,'=',a/b) else: print('无效的运算符')
361cd3e8e13a25c1a69376f12b9d4a86598b937b
Tammon23/30-Day-LeetCoding-Challenge-April-2020
/Min_Stack.py
1,185
3.9375
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self.minEl = None self.stack = [] def push(self, x: int) -> None: if len(self.stack) == 0: self.minEl = x self.stack.append(x) return if x >= self.minEl: self.stack.append(x) return self.stack.append(2*x-self.minEl) self.minEl = x return def pop(self) -> None: if len(self.stack) == 0: return y = self.stack.pop() if y < self.minEl: self.minEl = 2 * self.minEl - y def top(self) -> int: stackLen = len(self.stack) if not stackLen: return None peek = self.stack[stackLen - 1] if peek < self.minEl: return self.minEl return peek def getMin(self) -> int: if len(self.stack) == 0: return None return self.minEl # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
315bee72a88ca73d7ef58bd891b4535cf5922148
mveselov/CodeWars
/tests/beta_tests/test_data_reverse.py
621
3.625
4
import unittest from katas.beta.data_reverse import data_reverse class DataReverseTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(data_reverse( [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]), [1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]) def test_equals_2(self): self.assertEqual(data_reverse( [0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1]), [0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0])
4b23b8a6afb26eaeecaf19a84e2fd9de428b9e8f
rileyL6122428/data-science-from-scratch-notes
/09-exercises/basic_idea_grad_descent.py
1,646
4.09375
4
from functools import reduce from matplotlib import pyplot def sum_of_squares(vector): return reduce(lambda cumulative, next: cumulative + next ** 2, vector) print('sum of sqaures([1, 2]) = %s' % sum_of_squares([1, 2])) # gradient is the vector of partial derivative # gives the input direction in which the function most quickly increases # opposite direction of gradient minimizes # derivative of single var function f at x is the limit of difference quotient # as h -> 0 # geometrically represented as the slope of the tangent line a (x, f(x)) def difference_quotient(f, x, h): return (f(x + h) - f(x)) / h def square(num): return num ** 2 def square_prime(num): return 2 * num # We can use difference quotients to approximate single var gradients # for functions whose derivatives ain't easy to compute # x_vals = [ num for num in range(-10, 10) ] # square_primes = [ square_prime(x) for x in x_vals ] # approx_square_primes = [ difference_quotient(square, x, 0.00001) for x in x_vals ] # pyplot.plot(x_vals, square_primes, 'rx', label='Actual') # pyplot.plot(x_vals, approx_square_primes, 'b+', label='Approximate') # pyplot.legend() # pyplot.show() # When f is a function of many variables, it has multiple partial derivatives def partial_difference_quotient(f, vector, i, h): # compute the i'th partial difference quotient of f at v w = [ v_j + (h if j == i else 0) for j, v_j in enumerate(vector) ] return (f(w) - f(v)) / h def estimate_gradient(f, v, h=0.00001): return [ partial_difference_quotien(f, v, i, h) for i, _ in enumerate(v) ]
f371c6132d7d8a3b1ccc8cc7115f426aed949820
jooyoung0878/AI-project
/Classification regression/naive.py
1,962
3.546875
4
import numpy as np import matplotlib.pyplot as plt from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from utilities import visualize_classifier #input file containing data input_file = 'data_multivar_nb.txt' #load data data = np.loadtxt(input_file, delimiter=',') #X equal to all rows till second last columns, y equal to all rows only in last columns X, y = data[:, :-1], data[:, -1] #Create Naive Bayes classifier - Guarssian is anohter word for normal distribution classifier = GaussianNB() #Train the classifier classifier.fit(X,y) #Predict the values for training data y_pred = classifier.predict(X) accuracy = 100.0 * (y==y_pred).sum() / X.shape[0] print("Accuracy of Naive Bayes classifier = ", round(accuracy,2),"%") visualize_classifier(classifier, X, y) #Split data into training and test data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=3) classifier_new = GaussianNB() classifier_new.fit(X_train, y_train) y_test_pred = classifier_new.predict(X_test) accuracy = 100.0 * (y_test==y_test_pred).sum()/X_test.shape[0] print("Accuracy of new classifier = ",round(accuracy,2),"%") visualize_classifier(classifier_new, X_test, y_test) num_folds = 3 accuracy_values = cross_val_score(classifier, X, y, scoring='accuracy', cv=num_folds) print("Accuracy: " + str(round(100*accuracy_values.mean(),2)) + "%") precision_values = cross_val_score(classifier, X, y, scoring = 'precision_weighted', cv=num_folds) print("Precision: " + str(round(100*precision_values.mean(),2)) + "%") recall_values = cross_val_score(classifier, X, y, scoring ='recall_weighted', cv=num_folds) print("Recall: " + str(round(100*recall_values.mean(),2)) + "%") f1_values = cross_val_score(classifier, X, y, scoring = 'f1_weighted', cv=num_folds) print("F1: " + str(round(100*f1_values.mean(),2)) + "%")
edf8da572ce51e97a9fdc5911a2295c9893fc312
AlekseiBulygin/Python
/Geometry_alorithms/triangulate/wrapper_Shewchuk_mesh_generator.py
798
3.625
4
""" Triangulation between two polygons (convex or concave hull) Use Triangle - python wrapper around Jonathan Richard Shewchuk’s two-dimensional quality mesh generator. """ import matplotlib.pyplot as plt import triangle as tr polygon = [[0, 0], [0, 4], [2, 4], [2, 5], [3, 5], [3, 8], [6, 4], [6, 0]] offset_polygon = [[2, 1], [2, 3], [4, 3], [4, 1]] A = {'vertices': polygon + offset_polygon, 'segments': [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0], [8, 9], [9, 10], [10, 11], [11, 8]], 'holes': [[3, 2]]} # holes - point(s) coord(x, y) inside hole(must be circled in segments) B = tr.triangulate(A, 'pa1') # 'p' - create mesh with holes, print(B['triangles'].tolist()) # 'a1' - create new point for more small mesh tr.compare(plt, A, B) plt.show()
29aa6a97d9cbff5c0c67dc065dd8a01fe3cc0d4e
CNife/leetcode
/Python/leetcode/list.py
1,451
3.875
4
from typing import Optional, List class ListNode: def __init__(self, val: int): self.val: int = val self.next: Optional[ListNode] = None def __eq__(self, o: object) -> bool: return isinstance(o, ListNode) and self.val == o.val and self.next == o.next def __str__(self) -> str: return f"{self.val}->{self.next}" def __repr__(self): return f"ListNode(val={self.val},next={self.next})" def __getitem__(self, index: int) -> "ListNode": node = self for _ in range(index): if node: node = node.next else: raise IndexError("index out of range") return node def new_list(*nums: int) -> Optional[ListNode]: if nums: head = ListNode(nums[0]) node = head for num in nums[1:]: node.next = ListNode(num) node = node.next return head else: return None def new_cycle_list(nums: List[int], cycle_entry_index: int) -> Optional[ListNode]: if cycle_entry_index >= len(nums) or cycle_entry_index < 0: raise IndexError("cycle entry index out of range") head = ListNode(nums[0]) node, entry_node = head, head for i, num in enumerate(nums[1:]): node.next = ListNode(num) node = node.next if i + 1 <= cycle_entry_index: entry_node = entry_node.next node.next = entry_node return head
369b97985606b47fca998605d312eef0836fa36a
Anshelen/algorithms-explore
/sorts/quicksort.py
2,294
3.796875
4
""" Быстрая сортировка. Сложность в худшем случае О(n^2), обычно O(n*log n). Осуществляет неустойчивую сортировку на месте. """ from sorts.partitions import partition, three_way_partition def quick_sort_random(lst, l=0, r=None): """ Рекурсивный алгоритм быстрой сортировки с случайным выбором разделителя. """ r = len(lst) - 1 if r is None else r if len(lst) <= 1 or l >= r: return m = partition(lst, l, r) quick_sort_random(lst, l, m - 1) quick_sort_random(lst, m + 1, r) def quick_sort_no_tail_recursion(lst, l=0, r=None): """ Рекурсивный алгоритм быстрой сортировки без хвостовой рекурсии. Разделитель определяется случайным образом. """ r = len(lst) - 1 if r is None else r if len(lst) <= 1: return while l < r: m = partition(lst, l, r) quick_sort_no_tail_recursion(lst, l, m - 1) l = m + 1 def quick_sort_no_recursion(lst, l=0, r=None): """ Алгоритм быстрой сортировки без рекурсии. Разделитель определяется случайным образом. """ r = len(lst) - 1 if r is None else r if len(lst) <= 1: return q = [(l, r)] while q: l, r = q.pop(0) if l >= r: continue m = partition(lst, l, r) q.append((l, m - 1)) q.append((m + 1, r)) def quick_sort_3_way_partition(lst, l=0, r=None): """ Рекурсивный алгоритм быстрой сортировки с тройным разделением и случайным выбором разделителя. Тройное разделение значительно ускоряет алгоритм, если в списке много одинаковых элементов. """ r = len(lst) - 1 if r is None else r if len(lst) <= 1 or l >= r: return k1, k2 = three_way_partition(lst, l, r) quick_sort_3_way_partition(lst, l, k1 - 1) quick_sort_3_way_partition(lst, k2, r)
d737d104f521ce3eb127f2d8d2e73a17dae5b220
jbmenashi/coding-lessons
/Pathrise/SWEWorkshop2/merge_arrays.py
395
3.703125
4
def mergeArrays(arr1, arr2): i = 0 j = 0 arr3 = [] while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: arr3.append(arr1[i]) i = i + 1 else: arr3.append(arr2[j]) j = j + 1 while i < len(arr1): arr3.append(arr1[i]) i = i + 1 while j < len(arr2): arr3.append(arr2[j]) j = j + 1 return arr3
3bb47b2469d3be526b8f3be8396b991a901437db
burak-aytac/Python_exercises
/password_reminder.py
269
4.1875
4
my_name = "burak" new_name = input("Lütfen isminizi giriniz : ") password = "W@12" if new_name.lower() == my_name: print("Hello, {}! The password is : {}".format(my_name.upper(),password)) else: print("Hello, {}! See you later.".format(new_name.upper()))
cae6b5ecf988908a852804c6eee1ad517a9adff0
Maxim-Deriuha/education_py
/test/test14.py
170
3.65625
4
n = input() n = int(n[1:]) a ='' s=[] for i in range(n): a = input() r = a.find('#') if '#' in a: a=a[0:r] s.append(a.rstrip()) print(*s,sep='\n')
bf2bb12a25164db3fa245642c5c6286d834b57cb
tub212/PythonCodeStudy
/Python_Study/LAB/LAB_prime.py
699
4.125
4
"""prime number""" def is_prime(number): """ int -> int This programme is check prime number in range your input """ if number < 2: return False if number == 2: return True if not number & 1: return False for i in xrange(3, int(number**0.5)+1, 2): if number % i == 0: return False return True def countprime(checknumber): """ int -> int This programme is check prime number in range your input """ count = 0 for i in xrange(1, checknumber+1): answer = is_prime(i) if answer == True: count += 1 print count countprime(int(raw_input()))
546921bba4b751b42c1e6e6115062859c370235a
ThoughtProvoking/LPTHW
/oop_test.py
3,692
3.609375
4
import random from urllib.request import urlopen from sys import argv # store website url WORD_URL = 'http://learncodethehardway.com/words.txt' # create empty list WORDS = [] # create snippets and phrases dict PHRASES = { 'class %%%(%%%):': 'Make class named %%% that is-a %%%.', 'class %%%(object):\n\tdef __init__(self, ***)': 'class %%% has-a __init__ that takes self and *** params.', 'class %%%(object):\n\tdef ***(self, @@@)': 'class %%% has-a function named *** that takes self and @@@ params.', '*** = %%%()': 'Set *** to an instance of %%%.', '***.***(@@@)': 'From ***, get the *** function, call it with params self, @@@.', "***.*** = '***'": "From ***, get the *** attribute and set it to '***'." } # do they want to drill phrases first # check if 'english' was given as command line argument and set flag if len(argv) == 2 and argv[1] == 'english': PHRASE_FIRST = True else: PHRASE_FIRST = False # load up the words from the website for word in urlopen(WORD_URL).readlines(): # append each word to WORDS list WORDS.append(str(word.strip(), encoding='utf-8')) def convert(snippet, phrase): # create a list of random class names, with first letter capitalized, equal to number of '%%%' # equivalent to: # class_names = [] # for w in random.sample(WORDS, snippet.count('%%%')): # class_names.append(w.capitalize()) class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count('%%%'))] # create a list of random other names other_names = random.sample(WORDS, snippet.count('***')) # create empty lists results = [] param_names = [] for i in range(0, snippet.count('@@@')): # determine random number of parameters param_count = random.randint(1, 3) # create same random number of parameter names param_names.append(', '.join(random.sample(WORDS, param_count))) for sentence in snippet, phrase: # copy the sentence list result = sentence[:] # fake class names for word in class_names: # replace '%%%' with random class name (only first occurrence) result = result.replace('%%%', word, 1) # fake other names for word in other_names: # replace '***' with random other name (only first occurrence) result = result.replace('***', word, 1) # fake parameter lists for word in param_names: # replace '@@@' with random parameter name (only first occurrence) result = result.replace('@@@', word, 1) # append modified sentence to results list results.append(result) # return results list return results # keep going until they hit CTRL-D # try code first try: # infinite loop while True: # get the snippets, which are the keys of PHRASES dict snippets = list(PHRASES.keys()) # shuffle the snippets random.shuffle(snippets) for snippet in snippets: # get corresponding phrase phrase = PHRASES[snippet] # replace the '%%%', '***', and '@@@' in the snippets and phrases question, answer = convert(snippet, phrase) # switch the question and answer if user wants phrase first if PHRASE_FIRST: question, answer = answer, question # print the question print(question) # receive user answer input('> ') # print the actual answer print(f'ANSWER: {answer}\n\n') # handle possible End of File error except EOFError: print('\nBye')
6384ac2f2cf6ff08c2df8cbd61bf7e9c10290796
anonymous-acorn/python
/20200618 for문 리스트.py
318
4.125
4
for x in range(0,3): print(x) print("==========") a=[1,2,3,4] print(a) print("==========") for x in a: #[2,4,6,8] print(x) print("==========") for x in range(3): #엔트리에 x번 반복하기랑 기능 비슷 print("반복") print("==========") a.append(10) #리스트에 10추가 print(a)
94e20a1f2d830404727f4468aceabd3fc88c4e21
dgaldel/Puesta-en-producci-n-segura
/ejercicio1.py
1,398
4.15625
4
# hacer un pseudocodigo para introducir las edades de los 25 alumnos de la clase # y sacar la edad mayor , la edad menor , numero de edades pares , numero de edades # impares y el factorial del mayor primo import random contador = 0; mayor = 0; menor = 0; total_pares = 0; total_impares= 0; mayor_primo=0; boolean = 0; for contador in range(0, 25): print("Introduce una edad"); numero = random.randint(1, 20) #int(input()); print(numero); if contador == 0: mayor = numero; menor = numero; else : if numero > mayor: mayor = numero; if numero < menor: menor = numero; if (numero % 2) == 0: total_pares +=1; else : total_impares+=1; boolean = 0; if numero == 1 : boolean= 1; else : if numero == 2: boolean = 1; else : j = 2; for j in range(2,numero-1): if (numero % j) == 0: if numero > mayor_primo: boolean=1; if boolean == 0: if numero > mayor_primo: mayor_primo = numero; if mayor_primo != 0: print("mayor primo:"); print(mayor_primo); factorial_total = 1 while mayor_primo > 1: factorial_total *= mayor_primo mayor_primo -= 1 print("factorial:") print(factorial_total); print("mayor:") print(mayor); print("menor:") print(menor); print("total_pares:") print(total_pares); print("total impares:") print(total_impares);
118b5b95935e0002ead29be79fe91f4612cc8c6c
Dqvvidq/Nauka
/listy[].py
1,565
4.1875
4
#metoda upper print("Witaj") print("Witaj".upper()) #metoda replace print("Witaj".replace("j", "m")) #tworzenie listy fruit = ["mango", "banan", "gruszka"] print(fruit) #metoda append czyli dodawanie nowego elementu na koncu listy fruit.append("pomelo") fruit.append("figa") print(fruit) #w liscie mozna zapisywac dane dowolnego typu fruit.append(100) fruit.append(True) fruit.append(20.0) print(fruit) #listy mają indeksy od 0 do ... print(fruit[0]) print(fruit[1]) print(fruit[2]) print(fruit[3]) #listy są elementami modyfikowalnymi colors = ["fioletowy", "czerwony", "niebieski", "zołty"] print(colors) colors[2] = "biały" print(colors) #usuwanie elementu z listy farba = ["żółta","niebieska", "zielona"] print(farba) item = farba.pop() print(item) print(farba) #listy mozna połaczyc dzieki operatorom dodawania k = farba + colors print(k) # za pomocą in można sprawidzic czy element znajduje sie w liscie colors1 = ["czarny", "biały", "pomaranczowy"] print("czarny" in colors1) # żeby sprawdzić czy nie ma elementu na liście trzeba napisac przed in not (not in) print("różowy" not in colors1) print("czarny" not in colors1) # liczba elementów listy print(len(colors)) print(len(colors1)) # praktyczne wykorzystanie listy lista_zakupow = ["masło", "chleb", "jajka", "kisiel", "mąka"] zgadnij = input("Zgadnij element z listy: ") if zgadnij in lista_zakupow: print("Zgadłeś!!") else: print("nie zgadłes!")
2692cc19c897c4f562ea9f5ce39b9d379687e124
NinjaOnRails/del-unneeded-files
/delUnneededFiles.py
1,098
3.796875
4
#! /usr/bin/env python3 # delUnneededFiles - Deletes all files AND folders of certain size in KB import shutil, os folder = input("Enter path to the folder: ") size = int(input("Size in KB: ")) def delUnneededFiles(folder, size): filesFound = 0 for foldername, subfolders, filenames in os.walk(folder): for filename in filenames: currentFile = os.path.join(foldername, filename) if os.path.getsize(currentFile) > size: #os.unlink(currentFile) #send2trash.send2trash(currentFile) print(currentFile) filesFound += 1 if foldername == folder: continue totalSize = 0 for filename in os.listdir(foldername): totalSize = totalSize + os.path.getsize(os.path.join(foldername, filename)) if totalSize > size: #os.unlink(foldername) #send2trash.send2trash(foldername) print(foldername) filesFound += 1 print('Total files and folders found: ' + str(filesFound)) delUnneededFiles(folder, size)
94f7991fb39d9d512122f0fc838bae3762b13056
joaopalmeiro/pybites
/Beginner-Bites/019.py
372
3.640625
4
from datetime import datetime, timedelta NOW = datetime.now() class Promo: def __init__(self, name: str, expires: datetime) -> None: self.name = name self.expires = expires @property def expired(self) -> bool: return NOW > self.expires past_time = NOW - timedelta(seconds=3) promo = Promo("promo", past_time) print(promo.expired)
10991e261fcfa235304a189e0d236a36c1d36a78
inv-Karan/pytut
/dictionaries.py
227
3.859375
4
mydict = {'key1':123, 'key2':{'subkey2':100},'key3':[0,1,2], 'key4':['a','b','c']} print(mydict) print(mydict['key1']) mydict['key5'] = "NEW VALUE" print(mydict) print(mydict.keys()) print(mydict.values()) print(mydict.items())
4edc0b940d2de8528df9c30938c9e5282b5539e4
magedu-pythons/python-14
/zhangjingwen/week13/mysingleton.py
3,062
4.03125
4
# 1、python 中如何实现单例模式,尽可能多的写出实现方式 # 方法一:将单例类定义和实例化放在一个py文件中,使用时从该模块导入 class Singleton: def __init__(self): pass def foo(self): print('this is a singleton!') singleton = Singleton() # 方法二:使用装饰器 def Mysingleton(cls): _cls = [] def _singleton(*args, **kwargs): if cls not in _cls: _cls.append(cls(*args, **kwargs)) return _cls[0] return _singleton @Mysingleton # Singleton = mysingleton(Singleton) class Singleton: def __init__(self, x): self.x = x def foo(self): print('this is a singleton!') a = Singleton(2) b = Singleton(3) print(id(a)) # 56424176 print(id(b)) # 56424176 print(a.x) # 2 print(b.x) # 2 # 方法三 使用类方法实例化类,将类实例绑定到类属性上 import time import threading import logging class Singleton(object): _instance_lock = threading.Lock() def __init__(self, x): self.x = x time.sleep(1) @classmethod def instance(cls, *args, **kwargs): if not hasattr(Singleton, '_instance'): with Singleton._instance_lock: if not hasattr(Singleton, '_instance'): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance def task(args): obj = Singleton.instance(args) print(obj.x) logging.warning(obj) for i in range(5): t = threading.Thread(target=task, args=(i,)) t.start() obj = Singleton.instance(1) print(obj) # <__main__.Singleton object at 0x01283570> obj = Singleton(1) print(obj) # <__main__.Singleton object at 0x01283430> # 次方法实例化类的时候必须使用类方法 # 方法四 使用__new__方法 import threading import logging class Singleton(object): _instance_lock = threading.Lock() def __init__(self): pass def __new__(cls, *args, **kwargs): if not hasattr(Singleton, '_instance'): with Singleton._instance_lock: if not hasattr(Singleton, '_instance'): Singleton._instance = object.__new__(cls) return Singleton._instance obj1 = Singleton() obj2 = Singleton() print(obj1) print(obj2) def task(): obj = Singleton() logging.warning(obj) for i in range(5): t = threading.Thread(target=task) t.start() # 方法五 使用metaclass方式实现 import threading class Singleton(type): _instance_lock = threading.Lock() def __call__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): with Singleton._instance_lock: if not hasattr(cls, "_instance"): cls._instance = super(Singleton, cls).__call__(*args, **kwargs) return cls._instance class Foo(metaclass=Singleton): def __init__(self, name): self.name = name obj1 = Foo('name') obj2 = Foo('name') print(obj1, obj2)
d258dbad06e5ccfc18b1b691e5a9a68d14debc01
adrianrocamora/kng
/py/random/default.py
390
3.734375
4
import random # Random float x, 0.0 <= x <= 1.0 print(random.random()) # Random float x, 1.0 <= x <= 10.0 print(random.uniform(1, 10)) # Integer from 0 to 9 print(random.randrange(10)) # Even integer from 0 to 100 print(random.randrange(0, 101, 2)) # Single random element print(random.choice('abcdefghij')) # Shuffle a list items = [1, 2, 3, 4, 5, 6, 7] random.shuffle(items) print(items)
cbbdb3a33d762e15ffe63e0759ae2d9c0439d939
mary-tano/python-programming
/python_for_kids/book/Examples/hello3.py
1,598
3.8125
4
# Приветствие с кнопками from tkinter import * # Функция для события def button1Click() : Display.config(text="Это здорово!") def button2Click() : Display.config(text="Это радует!") def button3Click() : Display.config(text="Все возможно.") def button4Click() : Display.config(text="Это огорчает!") def button5Click() : Display.config(text="Это плохо!") def button6Click() : Display.config(text="Раз ты так думаешь ...") # Основная программа Window = Tk() Window.title("Привет!") Window.config(width=300, height=190) Display = Label(Window, text="Как это сделать?") Display.place(x=80, y=10, width=160, height=30) # Текст на кнопках Button1 = Button(Window, text="Супер", command=button1Click) Button2 = Button(Window, text="Хорошо", command=button2Click) Button3 = Button(Window, text="Так себе", command=button3Click) Button4 = Button(Window, text="Плохо", command=button4Click) Button5 = Button(Window, text="Ужасно", command=button5Click) Button6 = Button(Window, text="Не скажу", command=button6Click) # Позиционирование кнопок Button1.place(x=20, y=60, width=120, height=30) Button2.place(x=160, y=60, width=120, height=30) Button3.place(x=20, y=100, width=120, height=30) Button4.place(x=160, y=100, width=120, height=30) Button5.place(x=20, y=140, width=120, height=30) Button6.place(x=160, y=140, width=120, height=30) # Цикл событий Window.mainloop()
4bd3f36470010a6623e71bd4589a339169041515
HudaFiqri/belajarPython
/LAB/ChatBot/#1 tanya waktu/Chat Bot tanya waktu.py
819
3.890625
4
from datetime import * while True: data = input('>>> ') if (data == 'jam?' or data == 'jam'): if (datetime.now().hour < 12): print('sekarang jam {jam}:{menit} pagi'.format(jam=datetime.now().hour, menit=datetime.now().minute)) elif (datetime.now().hour < 15): print('sekarang jam {jam}:{menit} siang'.format(jam=datetime.now().hour, menit=datetime.now().minute)) elif (datetime.now().hour < 18): print('sekarang jam {jam}:{menit} sore'.format(jam=datetime.now().hour, menit=datetime.now().minute)) elif (datetime.now().hour < 24): print('sekarang jam {jam}:{menit} malam'.format(jam=datetime.now().hour, menit=datetime.now().minute)) elif (data == 'exit'): break else: print('input masukkan salah')
014b0be9368afce938098731a55561d32e294e76
jeromesolomon/scu-coen283-os-scheduling-simulator
/scu-coen283-os-scheduling-simulator/os-scheduling/os-scheduling/RR.py
1,881
4
4
import Process import Machine from collections import deque class RR: def __init__(self, quantum): self.myQueue = deque() self.size = 0 self.quantum = quantum def __str__(self): """ Private method used to print a queue neatly. :return: a string """ mystring = "" if len(self.myQueue) == 0: mystring += "\t" + "<empty>" + "\n" else: for p in self.myQueue: mystring += "\t" + str(p) + "\n" return mystring def add(self, item): """ Method to add an item to the queue :param item: item to be added :return: """ item.quantum = self.quantum # give the item the quantum item.preempt = False self.myQueue.append(item) self.size += 1 def get(self): """ Method to remove an item from the queue and return it :return: frontmost item in queue """ if self.isEmpty(): return None self.size -=1 return self.myQueue.popleft() def peek(self): """ Method to return the frontmost item from the queue without removal :return: frontmost item in queue """ return self.myQueue[0] def isEmpty(self): """ Method to return whether the structure is empty :return: True if structure is empty, False otherwise """ return len(self.myQueue) == 0 def isNotEmpty(self): """ Method to return whether the structure is not empty :return: False if structure is empty, True otherwise """ return len(self.myQueue) > 0 def toQueue(self): """ Method to "queueify" the structure :return: The items in the structure as a queue """ return self.myQueue
053bbb9c336b4c31d8d1488b2ba7c8dbcb792bca
AdrianPratama/AdrianSuharto_ITP2017_Exercise5
/Exercise5-3.py
418
3.875
4
def hypotenuse(a,b): try: return (a+b).sqrt() except TypeError: return None c = int(input("Please input number 1 here")) d = int(input("Please input number 2 here")) hypotenuse(c,d) e = str(input("Please input string 1 here")) f = str(input("Please input string 2 here")) hypotenuse(e,f) g = int(input("Please input integer here")) h = str(input("Please input string here")) hypotenuse(g,h)
333d24643a325626604de8b0103e4d2384668a60
codingeverybody/parallel-study-python-ruby
/Comment/1.py
240
3.59375
4
''' 조건문 예제 egoing 2015 ''' # user input password input = 33 real_egoing = 11 #real_k8805 = "ab" if real_egoing == input: print("Hello!, egoing") #elif real_k8805 == input: # print("Hello!, k8805") else: print("Who are you?")
bfc20910104361da115de3bee5fe97ad99b605be
lux-ed/Python_katas
/7_kyu/complementary_dna.py
620
3.625
4
#In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". # My solution def dna_strand(dna): dicti = {"A":"T", "T":"A", "C":"G", "G":"C"} return "".join(dicti[x] for x in dna) #dna_strand("ATTGC") #Clever def dna_strand1(dna): return dna.translate(str.maketrans('ATCG', 'TAGC')) #dna_strand1("TAACG") #NOTES ON maketrans() translate_from = 'aeiou' translate_to = '6510_' sentence = 'I see you are getting the hang of it' print(sentence.translate(str.maketrans(translate_from, translate_to))) #for it to work, translate_from and translate_to must have the same length.
587bcaaf30d9f61742ed32c4d854e13140d9a37d
demelue/easy-medium-code-challenges
/Python/String/reverse_words_in_string.py
1,072
3.90625
4
def reverse_words_in_string_v1(s): s = s.split(' ')[::-1] out = [] for i in range(len(s)): out.append(s[i] + ' ') return ''.join(out) def reverse_words_in_string_v2(s): s = reversed(s.split(' ')) out = [] for val in s: out.append(val + ' ') return ''.join(out) def reverse_word(s,i,j): while i < j: t = s[i] s[i] = s[j] s[j] = t i += 1 j -= 1 return s def reverse_words_in_string_v3(s): slist = list(s) slist.append(' ') end_index = 0 start_index = 0 i = 0 while i < len(s.split(' ')): #number of words while slist[end_index] != ' ': end_index += 1 slist = reverse_word(slist, start_index, end_index - 1) end_index += 1 start_index = end_index i += 1 return ''.join(reverse_word(slist, 0, len(slist)-1)).strip(' ') if __name__ == '__main__': s = "the sky is blue" print(reverse_words_in_string_v1(s)) print(reverse_words_in_string_v2(s)) print(reverse_words_in_string_v3(s))
d2b337d937b591d2e0db292ddd479806330a4683
DL-py/pandas-notebook
/024创建DataFrame.py
1,045
3.765625
4
""" 创建DataFrame: """ import pandas as pd import numpy as np pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) # 通过字典来创建: # 生成的DataFrame数据的列表可能不是按字典顺序的,可以通过columns关键字加以指定,同样可以指定 # index的值 DataFrame = pd.DataFrame({'id': [100, 101, 102], 'color': ['red', 'blue', 'green']}, index=['a', 'b', 'c'], columns=['id', 'color']) # 通过列表来创建: # pandas会默认将相同类型的数据放到一列 DataFrame1 = pd.DataFrame([[100, 'red'], [101, 'blue'], [102, 'green']], columns=['id', 'color']) # 利用numpy中的数组数据来创建: arr = np.random.rand(4, 2) DataFrame = pd.DataFrame(arr, columns=['one', 'two']) print(DataFrame) # 创建一个Series: Series = pd.Series(['round', 'square'], index=['c', 'b'], name='shape') print(Series) # 将DataFrame与Series连接: DataFrame = pd.concat([DataFrame1, Series], axis=1) print(DataFrame) # Series的name将会变成列名
f9aebc368fbc8ddea9a0e3a8f04dcb123a963964
cvmsprogclub/2016-cyoas
/10.py
4,466
4.1875
4
score = 0 print("THIS IS A FIVE QUESTION MULTIPULE CHOICE QUIZ. YOUR GRADE WILL BE PRINTED AT THE END OF THE QUIZ, AS WELL AS A COMMENT. TEST VERSION 1.1.1") print() user = input("START THE TEST?") if user == "Yes": print("QUESTION 1: WHICH OF THE AIRCRAFT ARE MADE OUT OF COMPOSITE MATERIALS?") print("A: Boeing 777") print("B: Boeing 737 MAX") print("C: Boeing 747-8") print("D: None of the above.") user = input() prompt = True while prompt is True: if user == "A" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is D.") score = score + 0 elif user == "B" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is D.") score = score + 0 elif user == "C" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is D.") score = score + 0 elif user == "D" : print("GOOD JOB!") score = score + 1 else: print("NOOOOO, WHAT ARE YOU DOING!") score = score - 1 print() print("QUESTION 2: WHICH OF THESE FLAPS ARE ABLE TO TILT UPWARDS?") print("A: FOWLER FLAPS") print("B: ZAP FLAPS") print("C: FAIREY-YOUNGMAN FLAPS") print("D: GURNEY FLAPS") user = input() if user == "A" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is C.") score = score + 0 elif user == "B" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is C") score = score + 0 elif user == "C" : print("GOOD JOB!") score = score + 1 elif user == "D" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is C") score = score + 0 else : print("NOOOOO, WHAT ARE YOU DOING!") score = score - 1 print() print("QUESTION 3: WHICH FLIGHT SUCCESSFULLY DITCHED IN THE HUDSON RIVER?") print("A: US AIRWAYS FLIGHT 1559") print("B: US AIRWAYS FLIGHT 1549") print("C: SCANDIVADIAN FLIGHT 751") print("D: NONE OF THE ABOVE") user = input() if user == "A" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is B.") score = score + 0 elif user == "B" : print("GOOD JOB!") score = score + 1 elif user == "C" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is B") score = score + 0 elif user == "D" : print("YOU ARE SOOOOOOOO DUMB!") print("The answer is B") score = score + 0 else : print("NOOOOO, WHAT ARE YOU DOING!") score = score - 1 print() print("QUESTION 4: WHICH THRUST REVERSER TYPE IS USED ON THE BOMBARDIER CRJ SERIES?") user = input() if user == "Target" : print("GOOD JOB!") score = score + 1 else : print("YOU ARE SOOOOOOOO DUMB!") print("THE ANSWER IS: Target") score = score + 0 print() print("QUESTION 5: THE AIRBUS A320 SERIES HAVE A _______ WINGLET") user = input() if user == "blended" : print("GOOD JOB!") score = score + 1 else : print("YOU ARE SOOOOOOOO DUMB!") print("THE ANSWER IS: blended") score = score + 0 score = score * 20 strScore = str(score) print("YOU GRADE IS " + strScore + " %") if score == 100 : print("GOOD JOB!") elif score <= 60 and score > 0: print("TRY AGAIN, DUMMY") elif score <= 0 : print("YOU'RE SCUM TIER!") else : print("AT LEAST YOU TRIED") print("RETAKE?") user_now = input() if user_now == "Yes": prompt = True else: print("VISIT www.xkcd.com NOW!!!!!") quit() else: print("VISIT www.xkcd.com NOW!!!!!") quit()
94fed23a7ffddeaa52530895c9d36daa4685e16f
Joycici/Coding
/Python/Exercise/ex25.py
1,633
4.15625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' Exercise 25: Even more Practise This is not a script which can be run. ''' """ __author='Joycici' __version__='1.0' """ ''' import os #获取当前工作目录 >>>os.getcwd() #更改当前工作目录 >>>os.chdir('d:\') >>>os.getcwd() 可以import当前目录下的.py文件 import a or from a import * ''' # 空格拆分 def break_words(stuff): """This function will break up words for us.""" #这个可以通过help(ex25)获取到 words = stuff.split(' ') return words # 单词排序 def sort_words(words): """Sorts the words.""" return sorted(words) # 删除并取第一个单词 def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) print word # 删除并取最后一个单词 def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print word # 调用break_words返回切分后的单词并排序 def sort_sentence(sentence): """Takes in a full sentence and returns the sorted words.""" words = break_words(sentence) return sort_words(words) # 切分后打印第一个单词和最后一个 def print_first_and_last(sentence): """Prints the first and last words of the sentence.""" words = break_words(sentence) print_first_word(words) print_last_word(words) # 切分排序后,删除并打印第一和最后一个单词 def print_first_and_last_sorted(sentence): """Sorts the words then prints the first and last one.""" words = sort_sentence(sentence) print_first_word(words) print_last_word(words)
45f8a960818baaecd10dbb13caf1f99b00754a73
CrazyJ36/python
/tk_minimal_example.py
466
4.09375
4
#!/usr/bin/env python3 from tkinter import * # Create Tk root(whole window) widget. # One root per program, initialized before any widgets. root = Tk() # text Label as child view of root window widget = Label(root, text="Window Text") # Pack first widget. Sizing widget to fit into given text, and make it visible. widget.pack() # Window or widgets won't appear until to Tkinter loop is started. root.mainloop() # The loop stays running until the window is closed
d0db99420c24dd128cdf5e9de3081ea42d04ede1
mjbrann4/python_training
/py_data_sci_1/9_df_manipulation/10_groupby_transformation.py
833
3.75
4
import pandas as pd # apply distinct transformations to distinct groups # changes dataframes in place def zscore(series): return (series - series.mean()) / series.std() auto = pd.read_csv('data/auto-mpg.csv') print(auto.head()) # apply to one series z = zscore(auto['mpg']) print(z.head()) # we can calculate z scores grouped by year z_year = auto.groupby('yr')['mpg'].transform(zscore).head() print(z_year.head) # we use apply when we don't need full aggregation or transformation def zscore_with_year_and_name(group): df = pd.DataFrame( {'mpg': zscore(group['mpg']), 'year': group['yr'], 'name': group['name']}) return df # note this function is called 13 times, once for each year b/w 1970-82 z2 = auto.groupby('yr').apply(zscore_with_year_and_name) print(z2.head()) print(z2.shape)
e7a5747be56ec1f10dbfd7ee22a0df21db71ed3e
iamvimal28/data_structures_and_algorithms
/python/selectionsort.py
485
4.0625
4
#Selection sort has the time complexity for O(n^2) (Big O of n squared) def selection_sort(arr, arr_len): for i in range(0,arr_len-1): minimum = i #Assuming minimum value index to be id for j in range(i+1,arr_len): if arr[j]< arr[minimum] : minimum = j #Swapping elements temp = arr[i] arr[i] = arr[minimum] arr[minimum] = temp arr = [6,1,7,3,6,9,0] # unsorted array arr_length = len(arr) # array length print(arr) selection_sort(arr,arr_length) print(arr)
aa4e7a672f093f69e651e5377059de81f88d21d4
StjepanPoljak/tutorials
/python/data-model/dictionary-ex.py
1,808
4.15625
4
#!/usr/bin/env python3 # NOTE: this is just an example of how dict works # internally; subclass dict only if you want to # extend it. class MyDict(dict): def __missing__(self, key): raise Exception("Key {} not found.".format(key)) def __getitem__(self, key): val = dict.__getitem__(self, key) return val def __setitem__(self, key, value): dict.__setitem__(self, hex(key), hex(value)) dict.__setitem__(self, key, value) mydict = MyDict() mydict[10] = 15 print(mydict) # {'0xa': '0xf', 10: 15} print(10 in mydict) # True print("0xa" in mydict) # True print(mydict[10]) # 15 print(mydict["0xa"]) # 0xf try: print(mydict[4]) except: print("Exception: Key 4 not found") # Exception: Key 4 not found. mydict.update({10: 8}) print(mydict) # {'0xa': '0xf', 10: 8} # Note: Using dict.update() produces some unexpected # results here. So usually, one has to hack around # with providing custom update(), __init__() etc. # This is why it is better to use UserDict for # subclassing, if you have high expectations from # your own dict type. del mydict[10] print(mydict) # {'0xa': '0xf'} from collections import UserDict # UserDict is an implementation of MutableMapping # which uses dict for internal storage; subclass # this if you want dict-like behaviour but override # some of the methods. You can access the dict # in UserData via self.data. from collections.abc import MutableMapping # Subclass MutableMapping if you want dict-like # behaviour and you want to control exactly how # data is stored. class MyUserDict(MutableMapping): pass # equivalent of nop try: myuserdict = MyUserDict() except TypeError as terror: print(terror) # Can't instantiate abstract class MyUserDict with abstract methods __delitem__, __getitem__, __iter__, __len__, __setitem__
86c4f3b39dfb97ec9d23051be16eee2e0541a107
Gootle/Python
/HOMEWORK/BMI1.py
2,434
3.8125
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def bmi_app() SyntaxError: invalid syntax >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print(bmi_value) >>> bmi_app <function bmi_app at 0x02A96270> >>> bmi_app() tall177 weight262 19.789970953429727 >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print('your BMI is {}'.format(round(bmi_value, 2))) if bmi_valume < 18.5 SyntaxError: invalid syntax >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print('your BMI is {}'.format(round(bmi_value, 2))) if < 18.5: print('eat more') elif bmi_valume >=18.5 and bmi_valume<=24: SyntaxError: invalid syntax >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print('your BMI is {}'.format(round(bmi_value, 2))) if bmi_valume < 18.5: print('eat more') elif bmi_valume >=18.5 and bmi_valume<=24: print('you are OK') else: print('you\d better do some exercise') >>> bmi_app() tall180 weight299 your BMI is 30.56 Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> bmi_app() File "<pyshell#18>", line 6, in bmi_app if bmi_valume < 18.5: NameError: name 'bmi_valume' is not defined >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print('your BMI is {}'.format(round(bmi_value, 2))) if bmi_valume < 18.5: print('eat more') elif bmi_valume >= 18.5 and bmi_valume <= 24: print('you are OK') else: print('you\d better do some exercise') >>> bmi_app() tall180 weight299 your BMI is 30.56 Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> bmi_app() File "<pyshell#21>", line 6, in bmi_app if bmi_valume < 18.5: NameError: name 'bmi_valume' is not defined >>> def bmi_app(): height = input('tall') weight = input('weight2') bmi_value = int(weight)/(int(height)/100)**2 print('your BMI is {}'.format(round(bmi_value, 2))) if bmi_valume < 18.5: print('eat more') elif bmi_valume >= 18.5 and bmi_valume <= 24: print('you are OK') else: print('you\d better do some exercise')
ae2e6f62dda7e7e2a7a47b475607d3287bd32be1
VSNorman/PZ_1
/PZ_1_1.py
600
4.21875
4
# Поработайте с переменными, создайте несколько, выведите на экран, # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. a = 'Гулять' b = 'Вася' print(f"{a}, {b}") Number_1 = int(input("Введите любое число - ")) Number_2 = int(input("А теперь другое любое число - ")) vopros = input("Как дела?") print(f"{vopros} - Ну, бывай! Удачи!")
abc4a138da96e28eef96d1db715b4c40e649c2c8
baaanan01/practice3-4
/23_3.py
366
3.546875
4
strs = input().split(' ') d = ['а', 'у', 'е', 'ы', 'а', 'о', 'э', 'я', 'и', 'ю'] c = 0 check = False for el in strs: i = 0 for e in el: if e in d: i += 1 if c == 0: c = i else: if c != i: print('Пам парам') check = True if not check: print('Парам пам-пам')
03a4b965384ef86d5f45959172255835efc5f006
Martins-Okounghae/Data_Structure
/hash_table.py
1,079
4.59375
5
#Accessing values in dictionary print("----------------------------------") print("Declaring a dictionary") print("------------------------------------") dict = {'Name':'Zara', 'Age': 7, 'Class': 'First'} print("----------------------------------") print("Accessing the dictionary with its key") print("------------------------------------") # Accessing the dictionary with its key print("dict['Name']: ", dict['Name']) print("dict['Age']: ", dict['Age']) print("----------------------------------") print("Updating Dictionary") print("------------------------------------") # Updating Dictionary dict = {"Name" : "Zara", "Age":"7", "Class": "First"} dict['Age'] = 8 # updating a dictionary dict['School'] = "DPS School" # Add new entry print("dict['Age']: ", dict['Age']) print("dict['School']: ", dict['School']) # Delete Dictionary Elements dict2 = {"Name":"Zar", "Age":7, "Class": "First"} del dict2['Name'] # remove entry with key 'Name' print("dict2", dict2) dict2.clear() # remove all entries in dict del dict2 # delete entire dictionary
19152ca23faac5b6ef69cf18d486d31d79b215b2
prathameshk03/The-Drinking-Game
/The Drinking Game 3.0.py
3,265
4.03125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 8 20:30:07 2021 @author: Dell The Drinking Game 3.0 Added=>menu driven,activity addition possible, display activity list,bug fixes """ import random names = [] actions = ["dances","sings","gets slapped by person to their right", "gets slapped by person to their left","massages the feet of person to right(3 min)", "massages feet of person to left(3 min)","kisses person to their right", "kisses person to their left","removes their t-shirt","does 50 push-ups", "does 50 squats","becomes a murga for 3 min","stands on one leg for 3 min EACH", "gets to slap person to their right","gets to slap person to their left", "gets to slap person straight forward","gets slapped by person straight forward", "has to jump 100 times","gets slapped by everyone","gets to slap everyone"] def intro_module(): print("\nWelcome to The Drinking Game by Prathamesh Kulkarni!\n" "Enter total number of people participating and then enter the names.\n" "The actions are already fed up in the system and I'll be choosing random person out of you and make you do a random action.\n" "The rules are fairly simple for you drunkards-\n" "Everone has to take a sip when any name is called.\n" "YOU HAVE TO DO WHAT I TELL YOU TO DO!\n" "Press Enter everytime to display new action\n") intro = input("Press Enter key to begin: ") if intro != '': intro = '' return intro def input_module(): num = input("\nEnter the number of drinkers: ") if num.isnumeric() == False or num == '0': print("Please enter valid number you moron!") input_module() else: print("\nEnter your names below\n") for i in range(int(num)): temp = input("Drinker " + str(i+1) + ":") print() names.append(temp) def game(): name = random.choice(names) action = random.choice(actions) to_do = name + " drinks and " + action + "!" to_do = to_do.capitalize() print (to_do) def start(): input_module() loop = '' while loop == '': game() loop = input() def add_action(): new_action = input("\nEnter the activity you wish to add: ") actions.append(new_action) def menu(): if intro_module() == '': while True: print("\nBelow are your choices:") print("1.Start the Game\n2.Add an activity\n3.Show activities list\n4.Exit") choice = int(input("\nEnter your choice: ")) if choice == None: continue if choice == 4: print("Adios Amigos!") break elif choice == 1: start() elif choice == 2: add_action() elif choice == 3: print() print(actions) else: print("Invalid choice you moron!") if __name__ == '__main__': menu()
cabfc267708a4ad2cdfcfea0989a4240824b19e1
IPanhui/python
/learn/07_面向对象/ph_03_设置对象属性.py
436
3.640625
4
class Cat: def eat(self): print("%s爱吃鱼" %self.name) def drink(self): print("%s爱喝水" %self.name) #创建猫对象 tom = Cat() # 可以使用 .属性名 利用赋值语句就可以了 tom.name = "Tom" tom.eat() tom.drink() print(tom) # 再创建一个猫对象 lazy_cat = Cat() lazy_cat.name = "大懒猫" lazy_cat.drink() lazy_cat.eat() print(lazy_cat) lazy_cat2 = lazy_cat print(lazy_cat2)
0783aa3975d1b51b720fef98f39cb2800ae1ef66
adrija24/languages_learning
/Python/Day 4/To pop an element.py
98
3.9375
4
"""To pop an element""" num=[6,0,-6,-1,9] n=int(input("Enter position: ")) num.pop(n-1) print(num)
2703b4ec05cf824b3a9ee3aa972e8f43547a8436
liujwplayer/python
/c3.py
774
3.828125
4
import time import datetime #创建停车场对象 class Park(object): pass def printo(self): self.start() print('开始计时') #当前线程休眠 time.sleep(2) print('购物中') self.end() print('结束计时') print('输出计费单') self.money() #费用计算 def money(self): time_difference = (self.end - self.start).seconds/60 print('费用计算为:'+str(time_difference * 0.1)) #开始的时间纳入 def start(self): now_time = datetime.datetime.now() self.start = now_time #结束的时间纳入 def end(self): now_time = datetime.datetime.now() self.end = now_time park = Park() park.printo()
f3cc986b4c129cc5f741a3560bc022ba204b1880
2226171237/Algorithmpractice
/字节/反转链表 II.py
1,865
3.78125
4
''' 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 说明: 1 ≤ m ≤ n ≤ 链表长度。 示例: 输入: 1->2->3->4->5->NULL, m = 2, n = 4 输出: 1->4->3->2->5->NULL 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-linked-list-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None def reverseList(head): '''翻转链表''' if head==None or head.next==None: return head,head newhead=head node=head.next head.next=None end = head while node: nextnode=node.next node.next=newhead newhead=node node=nextnode return newhead,end class Solution(object): def reverseBetween(self, head, m, n): """ 先断链,在翻转,后拼接 :type head: ListNode :type m: int :type n: int :rtype: ListNode """ if None==head: return None node=head prev=None for _ in range(m-1): prev=node node=node.next if prev: prev.next=None subhead=node for _ in range(m+1,n+1): node=node.next tailhead=node.next if node else None if node: node.next=None subhead,subend=reverseList(subhead) if prev: prev.next=subhead if subend: subend.next=tailhead return head if prev else subhead if __name__ == '__main__': head=ListNode(1) head.next=ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) s=Solution() head=s.reverseBetween(head,1,1) print(head)
0db0e6a29f4407c68f16cb885db6abb04cf2986e
talesritz/Learning-Python---Guanabara-classes
/Exercises - Module III/EX102 - Fatorial def() True.py
1,316
4.28125
4
#Crie um programa que tenha uma função fatorial() que receba dois parâmetros: o primeiro que indique o número a calcular e o outro chamado show, que será um valor lógico (opcional) indicando se será mostrado ou não na tela o processo de cálculo do fatorial. def cabecalho(msg): print('='*40) print('{:^40}' .format(msg)) print('='*40) print() def fatorial(num, show=False): """ Função Fatorial :param num: recebe um número inteiro para efetuar o cálculo de fatorial do mesmo :param show: (True) Mostra a conta do fatorial, (False) Apenas mostra o resultado :return: retorna o valor int() do cálculo fatorial se for diferente de 0 e 1 (números que não possuem cálculo por si próprios) """ if num == 0: return 'Fatorial: 0' elif num == 1: return 'Fatorial: 1' else: if show == False: fat = 1 for count in range(num, 1, -1): fat *= count return (f'Fatorial: {fat}') else: fat = 1 for count in range(num, 1, -1): print(f'{count} x ', end='') if count-1 == 1: print(f'{count-1}: ', end='') fat*= count return fat cabecalho('EX102 - Fatorial def() Opcional') num = int(input('Digite um número: ')) print(fatorial(num))
c2bb7f1942fdaa30152dac04c6302895ff15b844
brineryte/ztm_python
/practice_exercises/ex_password_checker.py
231
3.546875
4
from getpass import getpass print('Login') print() user = input('Please enter user name') password = getpass(prompt='Please enter password', stream=None) print(f'{user}, your password {password} is {len(password)} letters long')
46d51048a78a4f9245d6adc018d6c1067dd47433
hunter-cameron/Bioinformatics
/python/compare_two_lists.py
3,290
3.640625
4
#!/usr/bin/env python import argparse import sys import os description = """ Author: Hunter Cameron Date: Oct 19, 2015 Description: Small utility for comparing two lists. It outputs the elements that are only present in one of the lists and elements that are present in both. Allows each list of elements to be output to a different file handle or standard out/error. """ ## READ ARGS parser = argparse.ArgumentParser(description=description) parser.add_argument("l1") parser.add_argument("l2") parser.add_argument("-l1_out", help="path or stdout/stderr to write elements that are only in l1") parser.add_argument("-l2_out", help="path or 'stdout'/'stderr' to write elements that are only in l2") parser.add_argument("-both_out", help="path or 'stdout'/'stderr' to write elements that are in both lists") args = parser.parse_args() itm_dict = {} for indx, lst in enumerate([args.l1, args.l2]): indx += 1 with open(lst, 'r') as IN: for line in IN: itm = line.rstrip() # check if item already in dict try: # if it was already found in this list, raise error if itm_dict[itm] >= indx: raise ValueError("Duplicate name(s) in list {}. Example: '{}'".format(str(indx), itm)) else: itm_dict[itm] += indx # add new item to list except KeyError: itm_dict[itm] = indx """ parse the lists; in l1 but not l2 = 1 in l2 but not l1 = 2 in both = 3 """ l1 = [] l2 = [] both = [] for k, v in itm_dict.items(): if v == 1: l1.append(k) elif v == 2: l2.append(k) elif v == 3: both.append(k) else: print((k, v)) raise Exception("This should have never happened...") def open_output_fh(arg): """ Opens and returns a FH depending on the argument supplied """ if arg: if arg == "stdout": return sys.stdout elif arg == "stderr": return sys.stderr else: try: fd = os.open(arg, os.O_WRONLY | os.O_CREAT | os.O_EXCL) except OSError: print("Cowardly refusing to overwrite path {}. Exiting.".format(arg)) sys.exit("Exited with error status.") return os.fdopen(fd, 'w') else: return sys.stdout ## WRITE THE OUTPUTS TO THE APPROPRIATE PLACES # write both both_fh = open_output_fh(args.both_out) both_fh.write("{} items in both lists:\n".format(str(len(both)))) for i in both: both_fh.write(i + "\n") # write l1 only l1_fh = open_output_fh(args.l1_out) # print a blank line if this is a fh we have already written to if args.l1_out == args.both_out: l1_fh.write("\n") l1_fh.write("{} items in List 1 only:\n".format(str(len(l1)))) for i in l1: l1_fh.write(i + "\n") # write l2 only l2_fh = open_output_fh(args.l2_out) # print a blank line if this is a fh we have already written to if args.l2 == args.both_out or args.l2 == args.l1_out: l2_fh.write("\n") l2_fh.write("{} items in List 2 only:\n".format(str(len(l2)))) for i in l2: l2_fh.write(i + "\n") ## NOTE -- all FH are still open, they will all close when the program ends. ## This is done this way as a shortcut to avoid closing stdout/stderr.
f2f85020abe494365e1b3732e28d3b732354a879
venkatesh-vk/Project-eluer-Python
/1.Multiples of 3 and 5.py
348
4.09375
4
''' If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' #try using arthmetic progression n=int(input("Enter")) a=[] for i in range(1,n+1): if i%3==0 or i%5==0: a.append(i) print(sum(a))
51ef79a6c359b3efd74217546352bb03d1a56dfe
Melo15Zhang/python
/4-4/helloworld.py
166
3.75
4
# -*- coding: utf-8 -*- print("Hello", ",", "Python") # print会在,后面自动加上一个空格 name = input("Please enter your name: \n") print("hello,", name)
2abbb1dd6d30d7ddca433ac42ce20ad3c61d0652
jonathanxqs/Leetcode_rhap
/64.py
527
3.53125
4
class Solution(object): def reverseString(self, s): """ :type s: str :rtype: str """ return s[::-1] # #字符串的反转 # def reverse (s): # rt = '' # for i in range(len(s)-1, -1, -1): # rt += s[i] # return rt # def reverse2 (s): # li = list(s) # li.reverse() # rt = "".join(li) # return rt # def reverse3 (s): # return s[::-1] # def reverse4 (s): # return "".join(reversed(s)) # from functools import reduce # def reverse5 (s): # return reduce(lambda x,y:y+x,s)
bd83846e565390d79da82a00ee598bef52b81aaf
chasecolford/Leetcode
/problems/1160.py
1,259
3.953125
4
""" You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once). Return the sum of lengths of all good strings in words. Example 1: Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. Example 2: Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. Note: 1 <= words.length <= 1000 1 <= words[i].length, chars.length <= 100 All strings contain lowercase English letters only. """ class Solution(object): def countCharacters(self, words, chars): """ :type words: List[str] :type chars: str :rtype: int """ ans = 0 freq = collections.Counter(chars) for w in words: flag = True letters = collections.Counter(w) for l in letters: if letters[l] > freq[l]: flag = False break if flag: ans += len(w) return ans
6c5edbce0eec8779c5639d4064575722bf201734
varunmuriyanat/programming_machinelearning
/code/12_classifiers/plot_perceptron_model.py
2,289
3.84375
4
# Plot the model function of a perceptron on a dataset with two input variables. import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import seaborn as sns sns.set() def sigmoid(z): return 1 / (1 + np.exp(-z)) def forward(X, w): weighted_sum = np.matmul(X, w) return sigmoid(weighted_sum) def classify(X, w): return np.round(forward(X, w)) def loss(X, Y, w): y_hat = forward(X, w) first_term = Y * np.log(y_hat) second_term = (1 - Y) * np.log(1 - y_hat) return -np.average(first_term + second_term) def gradient(X, Y, w): return np.matmul(X.T, (forward(X, w) - Y)) / X.shape[0] def train(X, Y, iterations, lr): w = np.zeros((X.shape[1], 1)) for i in range(iterations): w -= gradient(X, Y, w) * lr return w # Uncomment one of the next three lines to decide which dataset to load x1, x2, y = np.loadtxt("linearly_separable.txt", skiprows=1, unpack=True) # x1, x2, y = np.loadtxt('non_linearly_separable.txt', skiprows=1, unpack=True) # x1, x2, y = np.loadtxt('circles.txt', skiprows=1, unpack=True) # Train classifier X = np.column_stack((np.ones(x1.size), x1, x2)) Y = y.reshape(-1, 1) w = train(X, Y, iterations=10000, lr=0.001) # Plot the axes sns.set(rc={"axes.facecolor": "white", "figure.facecolor": "white"}) ax = plt.figure().gca(projection="3d") ax.set_zticks([0, 0.5, 1]) ax.set_xlabel("Input A", labelpad=15, fontsize=30) ax.set_ylabel("Input B", labelpad=15, fontsize=30) ax.set_zlabel("ŷ", labelpad=5, fontsize=30) # Plot the data points blue_squares = X[(Y == 0).flatten()] ax.scatter(blue_squares[:, 1], blue_squares[:, 2], 0, c='b', marker='s') green_triangles = X[(Y == 1).flatten()] ax.scatter(green_triangles[:, 1], green_triangles[:, 2], 1, c='g', marker='^') # Plot the model MARGIN = 0.5 MESH_SIZE = 50 x, y = np.meshgrid(np.linspace(x1.min() - MARGIN, x1.max() + MARGIN, MESH_SIZE), np.linspace(x2.min() - MARGIN, x2.max() + MARGIN, MESH_SIZE)) grid = zip(np.ravel(x), np.ravel(y)) z = np.array([forward(np.column_stack(([1], [i], [j])), w) for i, j in grid]) z = z.reshape((MESH_SIZE, MESH_SIZE)) ax.plot_surface(x, y, z, alpha=0.75, cmap=cm.winter, linewidth=0, antialiased=True) plt.show()