blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
6e65ff440b1dbcc545fc5b6c9f7175804b8c828f
babuhacker/python_toturial
/dictionaries/directionaries.py
623
4.03125
4
'''Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value''' BlackShoes = {42: 2, 41: 3, 40: 4, 39: 1, 38: 0} print(BlackShoes) while (Tr...
fc0646d51fcc42c7eba49db76f7a2bd0783196cb
AdityaKuranjekarMYCAPTAIN/Python-Project-4
/most_freqChar.py
207
3.5
4
str1 = input("Please enter a string ") d1 = dict() for c in str1: if c in d1: d1[c] = d1[c] + 1 else: d1[c] = 1 print(d1) #..........>>>>>>>>>>>>>>>HAPPY CODING<<<<<<<<<<<<<<<<<<<<<...................
b89e31f39b80c6b7eb2751ebb8221db5b1d660f7
jeonghanlee/Work
/siteApps/ValveEvalTest-1-0/valveEvalApp/Db/Test.py
223
3.5
4
import re import sys #sample = '"","","","","","Test"' sample = sys.argv[1] samplelist = re.split('[,]', sample) samplelist = ['\"\"' if value == '' else value for value in samplelist] print (samplelist) print (sample)
1b31633ddf7ef1df1f0475a0583c77cd3f6e3030
jeonghanlee/Work
/Python/CodeExamples/Real-Time Simulations/realtime_ex_animation_discrete_system.py
1,215
3.703125
4
import datetime as dt import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # Create figure for plotting fig = plt.figure() ax = fig.add_subplot(1, 1, 1) xs = [] ys = [] xk = 0 # Initial Value for x # This function is called periodically from FuncAnimation def simulation(i, xs, y...
5fcb5228b0d58c4c4a82f4be0bb2e5a5cbda3ba3
jeonghanlee/Work
/Python/CodeExamples/Cresting Classes/classexample3.py
225
3.8125
4
class Car: def __init__(self, model, color): self.model = model self.color = color car1 = Car("Ford", "Green") print(car1.model) print(car1.color) car2 = Car("Volvo", "Blue") print(car2.model) print(car2.color)
d10310e00adb156878f52b160162f6deebb106f4
jeonghanlee/Work
/Python/CodeExamples/Error Handling/error_handling.py
404
3.703125
4
try: 10 * (1/0) except: print("The calculation failed") try: print(x) except: print("x is not defined") try: print(x) except NameError: print("x is not defined") except: print("Something is wrong") x=2 try: print(x) except NameError: print("x is not defined")...
e1de980a26b93cfeb087dc8da50e2ff91ae8b751
molnar-atesz/checkio
/count-neighbours.py
1,992
3.953125
4
def get_range_tuple(target, length): min = 0 if target == 0 else target - 1 max = target if target == length else target + 1 return (min, max+1) def count_neighbours(grid, row, col): count = 0 row_range = get_range_tuple(row, len(grid)-1) col_range = get_range_tuple(col, len(grid[0])-1) fo...
eae14c4d113c5f911bb643cfe265fd2b4a998097
mounika0407/study-guide
/solution.py
206
3.765625
4
number=50 guess=int(input('enter the number')) if (guess==50): print('congratulations') elif ( guess<50): print('number is little more') elif( guess>50): print('number is little less') print('done')
ed5eea4a5cbc26f616c13cb2251a3daf1d3c07f9
Pelinaslan/Programlama-Lab.
/hafta3_2.py
518
3.5
4
from sympy import FiniteSet #olasilik hesabi def probability(space,event): return len(event)/len(space) #asal mi kontrol fonksiyonu def check_prime(number): if number !=1: for factor in range(2, number): if number%factor ==0: return False else: return False ...
b768bb12f958d5444e23910a5d8b4ca2c7b2d549
Pelinaslan/Programlama-Lab.
/ODEV_2/180401049_hw_2.py
2,179
3.6875
4
import sys my_list=[] with open(sys.argv[1]+'input_hw_2.csv','r') as csv_file: for line in csv_file: my_list.append(int(line.split(";")[3].split("-")[1])) print(my_list) #listeyi siraladiktan sonra sirali listeyi histograma atariz ##listeyi siralama## def bubble_sort(my_list): n=len(my_list) #pr...
26c421b5e6c299b69a7ff93badb3b01463acbe33
Avenger-py/MiniProjects
/AreaOfPolygon.py
1,338
4.125
4
def polygon(): q=input("Are number of sides of polygon finite? (y/n): ") s=float() pi=3.141592 if q=="y": a=int(input("Enter number of sides of polygon: ")) if a==0 or a==1 or a==2 or a>4: print("Am i a joke to you?") else: if a==3: print("E...
b829f23fcedbc3a4f34610f9ac6bb338b526cdfb
sanuvaradh/Side_projects
/Google_Map_directions.py
1,170
3.625
4
''' Accessing Google APIs to access map related information. 1. Print Distance between source and destination. 2. Print Step by Step instructions to reach the destination from source. ''' import sys,re,subprocess import googlemaps as GoogleMaps def main(): try: source = str(raw_input('Please enter the ...
b06a2e53ae982a0d013b38968b99d0406aaaffc0
MrSameerKhan/Machine_Learning
/practice/reverse_list.py
1,288
4.40625
4
def reverse_a_list(): my_list = [1,2,3,566,6,7,8] original_list = my_list.copy() list_length = 0 for i in my_list: list_length += 1 for i in range(int(list_length/2)): main_value = my_list[i] mirror_value = my_list[list_length-i-1] my_list[i] = mirror_value ...
2c6fb1c822384688dab0f4f14bce369c01a029fb
tretyakovr/Lesson-01
/Task-04.py
1,246
4.15625
4
# Третьяков Роман Викторович # Факультет Geek University Python-разработки # Основы языка Python # Урок 1 # Задание 4: # Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. # Для решения используйте цикл while и арифметические операции. # В теоретической части преподаватель проговорился...
1f27a96c746cb8881ce76a51264183b90f7c2c6b
higashigawa/numbers
/main.py
522
3.703125
4
import numpy as np import time while True: print('Input number or press enter.') count = '' count = input() if count == '': count = 5 for i in range(int(count)): a = np.array([1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,20, 21,22,23,24,25,2...
2a18cc8fd70105eee7c47def0f4c4b8d1202fd04
weiiiiweiiii/AP-statistic-graphs
/Sources-For-Reference/Programs/Poisson.py
1,155
4.4375
4
# -*- coding: utf-8 -*- from scipy.stats import poisson import numpy as np import matplotlib.pyplot as plt import mpld3 #print "Welcome!" #print "This is a program that can help you plot graphs for poisson distributions" #Using poisson.pmf to create a list #rate = raw_input("Please enter the rate(rate should be an ...
36ebd723e8a734bbbe5121dce51c156ce9325290
EduardoVega04/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
697
3.875
4
#!/usr/bin/python3 """island_perimeter function""" def island_perimeter(grid): """ returns the perimeter of the island described in grid""" per = 0 for row in range(len(grid)): for column in range(len(grid[row])): if grid[row][column] == 1: per += 4 if ...
3dc84c5b2ae089b9a2932a77b14ed5c9655619d3
BedaSBa6koi/Homework-16.04.2020
/task20.py
546
3.90625
4
# Функция которая высчитывает являются ли введённые числа чётными или нет. Выводится в двух разных списках def counting(): digits = list(map(int, input('Enter the numbers ').split())) # digits = int odd = [] even = [] for i in digits: if i % 2 == 0: even.append(i) else: ...
9006bc67c13433a127a6171603674eb1b0e2ed71
agustbrokkur/PythonProjects
/Project Euler/euler007.py
1,258
3.765625
4
""" 10001st prime Problem 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ from math import floor, sqrt import time # Mine def numberedPrime(n): listi = [2, 3, 5, 7] limit = 180000 primes = [i for i in xrange(3, limit, 2...
9f3295bc5b19e6d3806be66ac85eab86e3256c86
agustbrokkur/PythonProjects
/Project Euler/euler010.py
960
3.5625
4
""" Summation of primes Problem 10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from math import floor, sqrt # Project Euler helper function def isPrime(n): if n == 1: return False if n < 4: return True if n % 2 == 0: return False if n < 9: ...
3540542d48a161f6acf983c392e1353fa58adf84
udiedric/collab-python-primer-2-itp
/first_data_types.py
475
3.875
4
val=25 fval=25.14342 str = "Hey There!" str2 = 'Ho There!' flag = True my_list = ["Chocolate", "Strawberry", "Pistachao"] my_tuple = ("Sprinkled","Glazed","Maple") my_map = {"donut":"glazed", "ice cream":"chocolate"} print (val) print (fval) print (str) print (str2) print (flag) print ("My favorite i...
2e7e4898f34ab6eef85da33e7995e832bc06a14b
saikumar-aks/Hackerrank-Algorithms
/designer_PDF_Viewer.py
250
3.6875
4
# problem :- https://www.hackerrank.com/challenges/designer-pdf-viewer/problem def designerPdfViewer(h, word): return max([h[ord(i)-97] for i in word])*len(word) h = list(map(int,input().split())) word = input() print(designerPdfViewer(h, word))
a3cf6695f407d0494518d218546afe96dd59650f
anchalgithub/Class-106
/graph.py
436
3.578125
4
#direct correlation #import plotly.express as px #import csv #with open("./data/IceCream.csv") as csv_file: #df=csv.DictReader(csv_file) #fig=px.scatter(df,x="Temperature", y ="Ice-cream Sales") #fig.show() #inverse correlation import plotly.express as px import csv with open("./data/coffee...
d54d7590c43510061f646c36aa9a7f65f9cb5ddf
ChuXiaoYi/python_high
/chapter08/property_test.py
784
3.859375
4
# -*- coding: utf-8 -*- # --------------------------------------------- # @Time : 2019/3/12 下午2:57 # @Author : cxy =.= # @File : property_test.py # @Software: PyCharm # @Desc : # --------------------------------------------- from datetime import date, datetime class User(objec...
67fc3570b3972b5ce34696840b6f1142ca7aedfb
Gordibueno/Python-Scripts
/confirm_end_string.py
130
3.71875
4
# confirm the end of a string string = "Bastian" target = "n" if string[-1] == target: print "Match" else: "Not a Match"
9613e778af05799d208153da34cafaa85b62c965
lawsie/guizero
/guizero/CheckBox.py
3,952
3.75
4
from tkinter import Checkbutton, IntVar from . import utilities as utils from .base import TextWidget class CheckBox(TextWidget): def __init__( self, master, text="", command=None, grid=None, align=None, args=None, visible=True, enabled=None,...
730bcb941e3b78ebabdeaae32bd2f9fcc8fcf9a1
JunchaoC/Calculator
/calc2.py
3,045
3.8125
4
from Tkinter import * mainUI = Tk() mainUI.title('Calculator') mainUI.geometry('210x200+300+400') #Use StringVar to track and update display, default/initial display is 0 display = StringVar() display.set('0') #Specify detail for display area textLabel = Label(mainUI) #Specify background color, and size of the dispa...
a248f0ad4216ecbe8760b0578b6a9164f9d08f1f
angelgarcan/toboggan
/AngelGarcia-TobogganChallenge.py
1,587
4.03125
4
#!/usr/bin/env python # coding: utf-8 # # Toboggan Trajectory Challenge # # ||| # |-|-| # |**Author**|Ángel García Alcántara<br><angelgarcan@gmail.com>| # |**Date**|March 5th 2021| # # <br> # # **Instructions:** https://docs.google.com/document/d/1Dzx6X71KsXjJrfeQr3UmTSD8RbYIOfeuSEvjUE0FM1g/edit# # # **Input (map)...
3118d09cf3963b943a81b04a96e9729cece878f6
ProfessorJas/Learn_Numpy
/ndarray_shape.py
302
4.46875
4
import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.shape) print() # This resize the array a = np.array([[1, 2, 3], [4, 5, 6]]) a.shape = (3, 2) print(a) print() # Numpy also provides a reshape function to resize an array a = np.array([[1, 2, 3], [4, 5, 6]]) b = a.reshape(3, 2) print(b)
94f86aa35c87cb8d793783e2cb1f8253e92c3a09
himanshu5223/airlines_assignment_task
/Airline_assignment_task.py
6,598
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Assignment solution_ # In[ ]: #Airline_case_study # In[ ]: Ans 1.1 In machine learning we need trainig dataset like we extract the data from the dataset.So X = [['priority boarding','extra leg room','food and beverages']] y = ['exact seating'] # here the d...
afa1c2ac506ac597cd93bfbf6946d6ea4a4d34a0
xinBrueck/Interview-Coding-Practice
/schedule_task_after_n_ms.py
804
3.890625
4
###This function is to define a schedule that ###take a function f and time t in ms ###run the function after t ms #####From the solution Daily Coding Problem######## #####we probably want to implement a thread to run the function #####instead of running the funtion in the scheduler #####since the function can run ar...
379551443a6bf1192521074c4f36d89db5b23e7f
DavidAbdelmalek/Problem-Solving
/leetcode/p528.py
809
3.875
4
from typing import List import random class Solution: """The idea is Prefix sum. 1. Cumulatively add items in list. (assume it is line of sums) 2. Pick a random num 3. Multiply random num by total cum sum to get target value 4. Sol: Try to get the range where the target can lay in...
4a3b924deea39f7f565b39c165e683a159c04080
Martin11Guzman/Rental-Agency
/core.py
10,173
3.9375
4
import sys from inventory import * import time from file_manipulation import * """ Presentation of program contains main(), menu(), rent(), return(), ceo(), rerun() Each function takes in user input that either calculates or writes data into files """ week_format = datetime.datetime.now().strftime("%Y-%m-%d --- Re...
c1ea3f3dcdf1c9a9797b9dba3c18a79c3237efe0
Ackleymilita/examplespygit
/linearsearch.py
276
3.5625
4
pos = -1 def search(l,n): i = 0 while i<len(l): if l[i] == n: globals()['pos'] = i return True i = i + 1 return False l = [5,8,4,6,9,2] n = 9 if search(l,n): print("Found at ",pos+1) else: print("Not Found")
0ae5e1ed8223fa7ab12e8c8884b73c9d10080ed1
Swadesh13/Tweet-Analysis
/src/tweet_extraction/utils.py
959
3.53125
4
# utils.py # Basic utils import json import os def get_creds() -> dict: ''' Get the credentials / tokens from the json file. Returns a dict of the tokens found in credentials.json ''' with open(os.path.join(os.getcwd(),"data/credentials.json")) as jsonf: creds = json.load(jsonf) ...
5c5356d208d2316d84aa881d362a3dc1acbdf363
rohitdhatwalia/GUI-Entry-widgets
/entry widgets.py
1,052
3.609375
4
from tkinter import * root = Tk() def getvals(): print("Submitting form") print(f"{uservar.get(), passvar.get()} ") with open("records.txt", "a") as f: f.write(f"{uservar.get(), passvar.get()}\n ") root.geometry("655x333") label = Label(text="login form",fg = "black",padx...
00472721c3e963bd1115521835ba76ca820bc495
alexthefatcat/CuratedCode-GIT
/Advanced_Python/test_Circles_UnitTest_Example.py
2,517
3.78125
4
# -*- coding: utf-8 -*- """Created on Fri Nov 15 09:08:23 2019@author: Alexm""" import unittest from Circles import circle_area from math import pi # Check some values should match, values are limited in range and type should be # python -m unittest class TestCircleArea(unittest.TestCase): def test_area(self): ...
2eb0a316a17c88315a5f61e664321386b629ad39
ThesisGeneticOptimizer/TGO
/Optimization/RevolutionaryGeneticAlgorithm/Knapsack.py
596
3.546875
4
import random numGuest = input("How many guest : ") arrGuest = [] values = [] total = 0 running = True check = True print("Type '0' to end") while check: inp = input("Input : ") if inp != "0": values.append(inp) else: check = False while running: ran = random.randint(0...
a6f75bbcc1c07958fdb65ec2738ce141b9a158dc
10125852/Python_Codes
/hourlyweather.py
2,623
3.734375
4
# Python code(Web scraping) to acquire Hourly Weather Data # Python 3 import bs4 as bs import urllib.request import pandas as pd import numpy as np import csv headers = ['Date', 'Time(EST)', 'Temp', 'Windchill', 'DewPoint', 'Humidity', 'Pressure', 'Visibility', 'WindDir', 'WindSpeed', 'GustSpeed', 'Precip', 'Events'...
bed56bb71903e3b132595fc06aa340292a184b15
rnsharma10/eupro
/problem 14.py
619
3.609375
4
n=1000000 #to keep track of already visited numbers less than currently visiting number counts=[0 for i in range(n+1)] maxlength=0 maxnumber=0 counts[1]=1 for i in range(2,n+1): number=i length=0 #counting the no. of terms while(number!=1 and number>=i): if number%2==0: number//=2 ...
0421105e9c2094cf1d02d6389196061e3beaefcd
yingtonglang/python
/A1033321_ch4_hw2.py
869
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import random count = 1 min = 0 max = 100 x = random.randint(1,99) print u'終極密碼Start!!!' print u'請輸入你猜的數字>>' n = input() while n!=x: if n>max: print u'你輸入的數字超過最大值,現在範圍是%d~%d' %(min,max) print u'請輸入你猜的數字>>' n = input() elif n<min: print ...
3c1579870be332e72130cbfcf82952e9efa536ea
mjh09/Sorting
/src/iterative_sorting/iterative_sorting.py
1,675
4.09375
4
# TO-DO: Complete the selection_sort() function below # def selection_sort( arr ): # # loop through n-1 elements # for i in range(0, len(arr)-1): # cur_index = i # # smallest_index = cur_index # # # TO-DO: find next smallest element # # # (hint, can do in 3 loc) # small...
dcbfa2622976db1440340929f1dfe2d3774c1c68
FernandoDeOliveira/numericCalculus
/atividadesP1.py
9,594
3.625
4
from numpy import e # import euler number from sympy import * # import trigonometric functions and differentials import matplotlib.pyplot as plt # import lib to plot graphics def exp(x, n=1000): """ work with dictionaries for factorial functions is more efficient if exist continuous recursions """ ...
8e1b8d13b02b159cb131e57feaf36ae2e8994632
wus4/25-TkinterAndMQTT
/src/m3_robot_as_mqtt_receiver.py
1,561
3.84375
4
""" Using a Brickman (robot) as the receiver of messages. """ # Same as m2_fake_robot_as_mqtt_sender, # but have the robot really do the action. # Implement just FORWARD at speeds X and Y is enough. import time import ev3dev.ev3 as ev3 class DriveSystem(object): """ Controls the robot's motion via GO and STOP ...
8f47b0ee9b272370e5df56cb93f099e1fd9914a6
concpetosfundamentalesprogramacionaa19/practica220419-daniel-alejandro-t
/problema1.py
917
3.859375
4
""" Problema 1 author: @daniel-alejandro-t """ ''' Se desea realizar un programa que permita calcular el valor mensual a pagar a un trabajador; así como también el valor de su descuento al Seguro Social (10% del total a pagar). El sueldo mensual del trabajador se obtienen mediante una multiplicación simple entre el...
1c64ddee2bf446d103e8a235a8c529bbdc50027b
Salazar-Prime/Touch_Lost_adb
/Learn_Tkinter/Advance/Drop_menu_learn.py
587
3.90625
4
# Learning to make drop down menu from Tkinter import * def doNothing(): print "doing nothing" root = Tk() drop_menu = Menu(root) root.config(menu=drop_menu) submenu = Menu(drop_menu) drop_menu.add_cascade(label="file", menu=submenu) submenu.add_command(label="New project...", command=doNothing) submenu.add_com...
b85e43cf42d9403016e4134ea4fa33c5921c4788
Salazar-Prime/Touch_Lost_adb
/Learn_Tkinter/Advance/MessageBox_learn.py
210
3.5
4
# insert a messag box from Tkinter import * import tkMessageBox root = Tk() tkMessageBox.showinfo('Tilte', 'Message write') a = tkMessageBox.askquestion('Question', 'What do you want') print a root.mainloop()
bbf33249764feef08abaade1f3a30dec14229b28
KELETOR/health-insurance-costs
/Health care comps.py
1,946
4.125
4
# create the initial variables below age = 28 sex = 0 bmi = 26.2 num_of_children = 3 smoker = 0 # Add insurance estimate formula below insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500 print(f"This Persons insurance cost is {insurance_cost} dolars\n") ...
e067eb36b5cb73e7ffa30acd0da8f9690f40b2dd
Purnimaprakash/purnima
/facto.py
157
4.1875
4
n=int(input("Enter the number:")) fact=1 while(n>0): fact=fact*n n=n-1 print("Factorial of the number is: ") print(fact)
4e3b1fbdfe12194e77d28b3dcebd47fae42e44c8
dongheelee1/oop
/polymorphism.py
592
4.4375
4
#Polymorphism: #Example of Method Overriding class Animal(object): def __init__(self, name): self.name = name def talk(self): pass class Dog(Animal): def talk(self): print("Woof") class Cat(Animal): def talk(self): print("Meow") cat = Cat('KIT') cat.talk() dog = ...
28979a6d76af315e774d634ab0dd6a3c72f4009e
innjuun/python-async-history
/async-history/3_yield-based-coroutines.py
926
3.875
4
# coroutine based on yield example def yield_based_coroutine(): print('callee 1') x = yield 1 print('callee 2: %d' % x) x = yield 2 # main routine에서 가져온 값을 x에 삽입, 2를 main routine으로 전달 print('callee 3: %d' % x) task = yield_based_coroutine() i = next(task) # callee 1 출력, i는 1이 됨 i = ta...
85df500c4bf8ff8051837ebe837fa3d8bcc7512c
dev-tabish-siddiqui/Projects
/assembler/pyasm-1.py
17,595
3.609375
4
#Copyright Tabish Siddiqui #!/usr/bin/env python #Import statements, re for regular expressions, Tkinter for GUI import re from Tkinter import * from tkFileDialog import askopenfilename #Matches a label (starts at the beginning of the line, and is alphanumeric, _ or . labelRe = re.compile("^([.a-z_0-9$]+)", re.IGNOR...
e1aa34deed827d162257d8f4c3bbe65c2bdc7d4e
xuyagang/pycon
/base/001_NameSpace.py
1,148
4.28125
4
# 1.若函数内部有和全局变量的同名变量被赋值,则函数内部的为局部变量,函数外的为全局变量 # 此时函数内和全局变量同名的局部变量一定要先赋值再调用,否则会报错,如例1所示 # (UnboundLocalError: local variable 'a' referenced before assignment) # 例1 # def fun(): # print(a) # a = 'xyz' # print(a) # a = 'abc' # fun() # 结果: # 直接报错 # ------------------------------------------- # 例2 #...
88dba46501f167f41b0bcd2c21e570c33fdba168
xuyagang/pycon
/Python_学习手册/Exercise/30_类的设计/无绑定方法是函数.py
452
3.609375
4
class Selfless: def __init__(self, data): self.data = data def selfless(arg1, arg2): return arg1 + arg2 def normal(self, arg1, arg2): return self.data + arg1 + arg2 X = Selfless(2) print(X.normal(3,4)) # 9 print(Selfless.normal(X, 3, 4)) # 9 print(Selfless.selfless(3,4)) # 7 # 非绑定方法...
e126b2149ba6db4ef4bb8e925343a975041e2d97
xuyagang/pycon
/web scrapy/exercise/threading_/04_守护线程.py
1,417
3.96875
4
''' 一个线程被设置为守护线程,那这个线程是“不重要的” 如果主线程结束了而该守护线程还没有运行完,它将被强制结束 python中通过 setDeamon 来将某个线程设置为守护线程 ''' import threading import time def target(second): print(f'Threading {threading.current_thread().name} is running') print(f'Threading {threading.current_thread().name} sleep{second} s') time.sleep(second) pr...
307a62eacfb3dcdaa022b829d37e1acff5c030b0
louizoslogic/Small-Python-Projects
/atm.py
2,242
3.84375
4
class atm: def __init__(self, user): self.transaction = '' self.user = user self.balance = 0 def deposit(self, amount): self.balance = self.balance + amount newtransaction = f'{self.user} deposited ${amount}: Total ${self.balance}' self.transaction = self.trans...
8b936b9d7203b88a5c96bfca1de8bf97caaa6ae3
louizoslogic/Small-Python-Projects
/compute_readability.py
1,723
3.640625
4
import string import argparse parser = argparse.ArgumentParser(description='Compute the grade level of a book') parser.add_argument('filename') args = parser.parse_args() textdoc = open(args.filename) textdoc = textdoc.read() def compute_gradelevel(textdoc): grade_level= { 1:'Kindergarten', ...
fcd5fc566df40b5e77e55c7d9382a76a831df88f
VanditoCodes/school-stuff
/misc/factorial_pyramid.py
304
3.78125
4
import math n = int(input("Kitne line chahiye bhiaya ")) for i in range(0,n+1): print(" "*(n-i), end= "") for j in range (0,i+1): print(int(math.factorial(i)/(math.factorial(i-j)*math.factorial(j))), end = " 15") if j == i: print()
40e38f28bb2abcf9fd522ac0ffc6ad411c362c48
VanditoCodes/school-stuff
/matplotlib/Plot2.py
560
3.640625
4
import numpy as np import matplotlib.pyplot as plt a = np.random.randint(1,10, (100)) b = np.arange(0,10,0.1) plt.plot(b,a, alpha = 5, antialiased = 'True', color = 'red', label = 'Black line', linestyle = "--", linewidth = 1, marker = 's') plt.legend() #Most attributes are self explanatory, and yet ''' al...
9b41b8e7b83fc9b9007ac20b6cbd0916e85f0748
VanditoCodes/school-stuff
/Numpy/numpy5.py
366
3.5625
4
#Statistics import numpy as np a = np.array([[1,2,3,4],[4,6,7,8]]) #Basic Statistics print(np.min(a)) print(np.max(a)) print(np.sum(a)) print(np.median(a)) print("\n\n") #Sorting b = np.random.randint(1,10, (2,5)) print(b) sort = np.sort(b) print(sort) #arranges each row in ascending order print("\...
c8727445ebf59b9e1294d3ab1daf71608666bb5a
VanditoCodes/school-stuff
/misc/some_number_thing.py
224
3.53125
4
n = int(input("Enter a number plss : ")) s = 0 p = 1 m = n while n>0: digit = n%10 s += digit n = n//100 m//10 while m>0: digit = m%10 p *= digit m = m//100 print (s,p,s+p)
2d3859b438118dafece443e09b0f55c288e66a51
VanditoCodes/school-stuff
/misc/snakes and ladders.py
1,298
4.09375
4
import random print("Greetings player! May i know your name?") name=input("Enter your name: ") print("Welcome",name,"! Would you like to play a game of snakes and ladders???") print("Press yes if you want to play, no if you don't want to play : ") choice=input("Enter your choice : ") a=0 while choice=="yes":...
79022fd3c11136cd3a7b99822028e17536dfba4d
SUNSHINEZZHANG/Closure
/Closure.py
213
3.671875
4
#!/usr/bin/env python #-*-coding:utf-8 -*- #闭包 def count(): fs=[] for j in range(1,4): def f(j): def g(): return j*j return g fs.append(f(j)) return fs f1,f2,f3 = count() print f1(),f2(),f3()
234226a6970ed7ffe28c873e022f60c8d89b3732
GavinYWu/p4-oompaloompas
/algorithms/challenge2.py
455
3.546875
4
# challenge 2 list1 = [5, 3, 4, 1, 2] def orderList(list): temp = list # create copy of list result = [] for j in range(len(temp)): # find minimum x times and append to min = 99999999999 for i in range(len(temp)): if temp[i] <= min: min = temp[i] re...
e87526ae5e152f0819ecd119521a6607626d6543
rafeeJ/AoC-2020
/d8/d8.py
3,370
3.703125
4
# Going to comment this one because I actually really enjoyed todays challenge. # Open the file, and create the 'program' which is just an array of commands. f = open('input.txt', 'r') program = [i.strip() for i in f] def read_line(line): """ Function to process a command Returns: Tuple containing (comm...
5fe41d76d9d5ed0c5e0098ece3803eeae94f5737
OlgaDrach/kolokviym-
/18.py
605
3.5625
4
#Знайти добуток всіх елементів масиву цілих чисел, менших 0. Розмірність #масиву - 10. Заповнення масиву здійснити за допомогою клавіатури. #Драч Ольга Олескандрівна, 122Д from random import randint d = 1 e = 0 for a in range(10): #Діапазон s = int(input()) if b < 0: #Умова e =+ 1 ...
223496a1ae4ed0e8b1b31ad3e2cdafde17cd69de
OlgaDrach/kolokviym-
/3.py
339
3.671875
4
#Створіть масив з п'яти прізвищ і виведіть їх на екран стовпчиком, #починаючи з останнього. #Драч Ольга Олескандрівна, 122Д a = ["Міщенко", "Сачук", "Перевертайло", "Алексеєв", "Пучкова"] s = a[::-1] for i in range(5): print(s[i])
95d699c96d04b9023a9af38dba5d89d82488f8bd
OlgaDrach/kolokviym-
/26.py
886
3.9375
4
# Напишіть програму аналізу значень температури хворого за добу: # визначте мінімальне і максимальне значення, середнє арифметичне. Заміри # температури виробляються шість раз на добу і результати вводяться з клавіатури у # масив T. #Драч Ольга Олескандрівна, 122Д f = 999 v = -272 e = 0 for a in range(6): #...
40a2fcb21f85fdaaa1e18e391346da4c4a817dd7
OlgaDrach/kolokviym-
/35.py
737
3.5
4
#Дан лінійний масив цілих чисел. Перевірте, чи є він упорядкованим по #спаданню. #Драч Ольга Олескандрівна, 122Д import numpy m = numpy.array([3,2,2]) #За зменшинням від - до + for j in range(len(m)-1): # Діапазон без останнього так як умова іде на 1 вперед if m[j] >= m[j+1]: #Умова m = True ...
34ed4cb931c3f21b4afed754e33b92c5fb91f543
OlgaDrach/kolokviym-
/14.py
632
3.75
4
#Сформуйте лінійний масив дійсних чисел, елементи якого є відстанями, #пройденими тілом при вільному падінні на землю за 1, 2, ..., 10 с. #Драч Ольга Олескандрівна, 122Д z = int(input()) d = list() for v in range(1,11): #Діапазон часу c = v*z #Якщо тіло рухаєтьсяя рівномірно, то кожний елемент масиву ...
a1423d9070f3b90227cfb4d3a560f489f7f22f65
ykataoka/top100Like
/572_SubtreeAnotherTree.py
1,104
3.90625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def isMatch(self, s, t): # if s == None and t == None, True # if s == None and t != None, False...
3eafde85c1d25999e25ebabb0201e7d931e2d14c
ykataoka/top100Like
/326_PowerofThree.py
1,054
3.9375
4
import math class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ # # Solution 1: Loop # # corner case: # if n == 0: # return False # if n == 1: # return True # # # Loop # while n % 3 =...
841f3c989c6c4699901267bf90cc7921440a490b
ykataoka/top100Like
/BasicSearch.py
917
3.90625
4
def binary_search(arr, ele): if len(arr) == 0: return False left, right = 0, len(arr) - 1 found = False while left <= right and found != True: mid = int((left + right) / 2) if arr[mid] == ele: found = True else: if arr[mid] < ele: r...
557f0194278562cdcb858ba5f4527aea1ee2fa45
ykataoka/top100Like
/StandardBinaryTree.py
2,291
3.703125
4
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if nums == []: return -1 # 1. find the pivot by binary search approach - O(logN) pivot = self.findPivot(nums, 0, len(nums)-...
3cb3d96c2a3ac83686ef3b42eff3b24f9ecd4c3e
ykataoka/top100Like
/226_InvertBinaryTree.py
447
3.828125
4
class Solution(): def InvertTree(self, root): if root is None: return # PreOrder Traversal should be good? # 1. swap the left and right node # 2. apply inverTree for the left node # 3. apply inverTree for the right node root.left, root.right = root.right,...
79bf9728b10e84a04e41df0011bbd6b992abccab
Feng00000/week1
/Qust/q3.py
217
3.625
4
import random list=[] for i in range(20): num=random.choice(range(10)) list.append(i) print("list长度",len(list)) print("未排序list",list) list[::2]=sorted(list[::2],reverse=True) print("排序list",list)
ab3b6dff2a37755074f7547a99770e3939679fb5
deare1300/python
/basic/grammer.py
1,570
3.640625
4
import os import sys import re def ifGrammar(): flag = 1 if flag == 2: print "flag == 2" elif flag == 3: print "flag == 3" else: print "else gramar" def whileGrammar(): i = 0 print "while" while i < 10: print i i += 1 print "end while...
ca9e22821f53b36efb8ce3efd97eb82516fa379a
MatPorter/Programowanie-IR
/Zestaw 1/fib_it.py
304
4.25
4
n = int(input("n = ")) def fibonacci(n): f_i_2 = 1 f_i_1 = 1 i = 3 if n == 1 or n == 2: return 1 else: while i in range(3, n+1): f_i = f_i_1 + f_i_2 f_i_2 = f_i_1 f_i_1 = f_i i+=1 return f_i print(fibonacci(n))
d2d768555b2a82d3b4ac2e0fdc7ee567cefa208d
qingzhuangyuanda/bilibilishixun
/demo2/demo2.py
5,627
3.953125
4
# -*- coding: utf-8 -*- """ @Time : 2021/1/26 12:40 @Auth : 张志强 @File :demo2.py @IDE :PyCharm @Type : @Remark : @History : """ ''' #namelist=[] #定义一个空的列表 namelist=["小张","小王","小李"] print(namelist[0]) textlst=[1,"测试"] print(type(textlst[0])) #判断数据类型 print(type(textlst[1])) ''' ''' ...
7ca7a57997e56ca1e59c7b127ce29c99bd382c2d
qingzhuangyuanda/bilibilishixun
/demo1/demo2.py
1,099
3.953125
4
# -*- coding: utf-8 -*- """ @Time : 2021/1/22 14:31 @Auth : 张志强 @File :demo2.py @IDE :PyCharm @Type : @Remark : @History : """ ''' print("标准化输出字符串") a=10 print("这是变量:",a) ''' ''' #格式化输出 age=10 print("我的名字是 %s,我的国籍是 %s"%("小张","中国")) print("我的年龄是: %d 岁"%age) print("aaa","bbb","ccc") print("www","baidu","com",sep=".") pr...
b3e478711601d5e6750d722886fe83f41916bfbe
doremon99/SVR
/SVR.py
934
3.671875
4
#Importing the libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #Importing the dataset dataset = pd.read_csv('Car_Purchasing_Data.csv', encoding = 'Latin-1') X = dataset.iloc[:,3:-1].values y = dataset.iloc[:,-1].values y = y.reshape(len(y),1) #Feature Scaling from sklearn.preprocessin...
0c479f9710ad7b3a914765748621caf9f91614c2
nickfrasco/C200
/Assignment9/bisect.py
507
3.625
4
f = lambda x: x**6 - x - 1 def sign(x): if x > 0: return 1 else: return -1 def bisect(f,a,b,tau): c = (a+b)/2 while (b-a)/2 > tau: print("{0: .5f} {1: .5f} {2: .5f} {3: .5f} {4: .5f}".format(a,b,c,b-c,f(c))) if f(c) == 0: return c elif f(a)*f(c) < 0...
cfce2d9e7bdf6f3ba1d4a1c85fbb93493d348ff6
nickfrasco/C200
/Assignment3/donor.py
4,038
3.796875
4
#This is the bank as a dictionary. #The key is the type and value is the number of pints. # bank["O+"] == 2 bank = {"A+":4, "A-":2, "O-":0, "O+":2, "B+":5, "B-":2, "AB+":4, "AB-":2} #1 Parameters donor's blood type donor_blood_type #Return a string of the types that can accept the blood #If the donor_blood_type is un...
18c9b527cffd2712f67ef69629df4924d816249e
nickfrasco/C200
/Assignment13/oreo.py
914
3.6875
4
p = {1:10,2:25,3:32,4:41,5:60,6:100,7:130,8:141} #INPUT number of tons of ore #OUTPUT minimum hours to process ore def ore(n): print(n) min = p[n] if n == 1: #base return 10 else: for i in range(1, n): temp = ore(n-i) + p[i] #come back to if temp < min: ...
10ff607bee26b985799a331506d2bb103a1d5798
nickfrasco/C200
/Assignment4/makeitrain.py
449
3.609375
4
# input parameter: dollar amount x # return value: list of quarters, dimes, nickels, and pennies # (in that order) def dollars(x): cent = x*100 quarters = cent/25 dimes = cent%25 / 10 nickels = cent%25%10 / 5 pennies = cent%25%10%5 dollars_list = [int(quarters), i...
dcd7bf193e062ff68a2810146fb9f875f019c4e3
nickfrasco/C200
/Assignment3/premetal.py
1,176
3.78125
4
import math # Data $/ounce gold = 1341.30 silver = 17.19 platinum = 1005.00 palladium = 1057.95 # function 1 # Parameters gold oz g_oz, silver oz s_oz, platinum oz pl_oz, palladium oz pa_oz # Return the $ amount of the holdings def cost(g_oz, s_oz, pl_oz, pa_oz): cost = (g_oz * 1341.30, s_oz * 17.19, pl_oz * 10...
a836e0b986e48291d8f02c848f31d248c5ee53fe
mateusz91t/machine-learning-0
/3.11_predicts_models_ML_practice.py
1,695
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 19 21:12:22 2021 @author: mattt """ # Linear Regression: an algorithm that allows to predict continuous values [wartości ciągłe] # Continuous values: real numbers [liczby rzeczywiste], e.g. temperature, speed # Discrete values[wartoci dyskretne]: categories, e.g. Male/Fe...
0f11fc9e9cd568a921b2c45ea4e66c7aaf1d8cd4
K1sna/Classical-Public-Key-Encryption-practice
/置换密码.py
932
3.734375
4
import math def Encrypt(msg, key):#加密 size = len(msg) result = [] for i in range(key): t = i while t < size: result.append(msg[t]) t += key return ''.join(result) def Decrypt(msg, key):#解密 numOfColums = int(math.ceil(len(msg)/float(key))) ...
7214e2bd74659f696e2ba12977e7dd1e58fcd9a9
flowingstr/DeepLearning
/CourseOne-Neural Networks and Deep Learning/assignment2_2.py
5,791
3.671875
4
import pylab import scipy import numpy as np from scipy import ndimage import matplotlib.pyplot as plt from DeepLearning.CourseOne.lr_utils import load_dataset # 显示图片 def show_pic(index, x, y, classes): plt.imshow(x[index]) pylab.show() print("It's a '" + classes[np.squeeze(y[:, index])].decode("utf-8") +...
ad56dc7b368603b7d2592573ed26503dcce41e4b
moncefelmouden/python-project-ui-2018
/dbDemo.py
1,594
4.21875
4
import sqlite3 import os.path def initDatabase(): db=sqlite3.connect('dbDemo.db') sql="create table travel(name text primary key,country text)" db.execute(sql) sql="insert into travel(name,country) values('Korea Ski-ing Winter Tour','Korea')" db.execute(sql) db.commit() db.close() ...
5137185f129595681d28e3ec08837a3d0bd51ff9
PeterZhu514/LeetCode
/001.py
491
3.578125
4
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i,num in enumerate(nums): x=target-num if x in nums and i!=nums.index(x): return sorted([i,nums.index(x)]) pri...
2249fb525b09a5b55ae393b9b820df8cf996814b
NLincoln/sorting-project
/sorting/MergeSort.py
516
4
4
def merge(left: list, right: list): result = [] while left and right: if left[0] <= right[0]: result.append(left[0]) left.pop(0) else: result.append(right[0]) right.pop(0) result += left result += right return result def merge_sort(a...
b17f5e3c7a62931b3595f788b6629526ba4691a2
melezhik/sparrow-plugins
/ds-hops/task.py
782
3.625
4
from typing import List # Write any import statements here def getSecondsRequired(N: int, F: int, P: List[int]) -> int: # Write your code here cnt = 0 print(f"frogs:{P} | N:{N} | F:{F} ") P.sort() max_frog_ind = P[-1] holes_sum = 0 if len(P) > 1: for i in range(F-1): holes = P[i+1] - P[i] - 1...
c3b6c3001df15742059cff4b7e20b408b2e8fadd
rachelkelly/tkrandom
/main.py
1,548
4.03125
4
#from www.pythonware.com/library/tkinter/introduction/hello-tkinter.htm #it's all given in 2.7 so some of my conversions might be flawnky #hella, hella adapted & slammed into place from my random hw generator. #make it work, shoooooooot. from tkinter import * class App: def __init__(self, master): frame = Frame(...
7ead133bce75f756defe10ecfbd867ce0d35bc93
onkaraman/thesis-app
/tq_file/file_parsers/file_parser.py
705
3.734375
4
from abc import ABC, abstractmethod class FileParser(ABC): """ Abstract class for inheriting parsing classes. A foreign file will be accepted as parsed, once it could be converted to JSON. """ @abstractmethod def handles_file_type(self, extension): """ :return: A string contai...
52008b5181e886e0656108dab34c19823d1caa07
brandonbloch/cisc327
/bCommands.py
2,983
4.21875
4
def find_account(number, accounts): """ This function takes in a account number and the master accounts list to check if the specified account number is in the master accounts list. """ for i in range(len(accounts)): if accounts[i][0] == number: return i+1 return 0 def wi...
657b9eed2c8cca942cff49c0feb80cd6fa93cac4
shenbaga-murugan/python4kids
/pbk_console_frontend.py
2,643
4
4
from phone_book import PhoneBook class PbkConsoleFrontend: """Console frontend for Phone Book Application""" pbk = PhoneBook() menu_handlers = {} def __init__(self): self.menu_handlers = { "1": self.handle_add, "2": self.handle_lookup, "3": self.handle_remove, "4": self.handle_list, "5": self.h...
8870d118c8e8e90d781a17f1021491fc5fe28d5c
Alexandra-Sontu/IF-WHILE-FOR-probleme
/problema 9 IF FOR.py
357
3.734375
4
"""Un numar natural se numeste numr perfect daca este gal cu suma divizorilor lui deoarece 6=1+2+3. Sa se afle numerele perfecte mai mici decat numarul natural n.""" n=int(input("introduceti numarul n:")) for p in range(1,n): s=0 for m in range(1,p): if(p%m==0): s+=m if s=...
66a2294e9bd3b65db1b924f20eec7daa88e7adfe
SrMarcelo/Project-Euler-Python
/6.py
158
3.609375
4
numbers = [num for num in range(1, 101)] sumOfSquares = sum([num ** 2 for num in numbers]) squareOfSum = sum(numbers) ** 2 print(squareOfSum - sumOfSquares)
f51784daf499d6a278537f663646758f7a5bb93b
SanJin1213/Python
/Numpy/code/index_numpy.py
628
3.953125
4
import numpy as np A = np.arange(1, 8) # print(A[2]) # # 3 B = np.arange(2, 14).reshape((3, 4)) # print(B[2]) # # 输出了第二行的所有元素 # # [10 11 12 13] # print(B[2, 3]) # 13 # print(B[2][3]) # 13 # # 逐列遍历矩阵 # for row in B: # print(row) # # [2 3 4 5] # # [6 7 8 9] # # [10 11 12 13] # # 逐行输出矩阵 # for column in B.T: # ...