blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
6bad95aa579b14e36987dd32a6343e8b866f4387
HinnyTsang/slides
/py-type/complex.py
1,074
3.578125
4
# 1 OMIT from typing import Dict def inc(d: Dict[str, int]) -> Dict[str, int]: for k in d.keys(): d[k] = d[k] + 1 return d print(inc({ 'a': 1, 'b': 2, 'c': 3 })) # 2 OMIT from typing import Sequence, List, TypeVar T = TypeVar('T') # Declare type variable def pick_odd(s: Sequence[T]) ->...
7c5ace61a5e972b206819d62a8440e4858ffb73d
jeekiii/CS1-Python
/LinkedList/src/CorrLinkedList.py
666
3.984375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- class Node: def __init__(self, next, value): self.next = next self.value = value def get_next(self): return self.next def get_value(self): return self.value class LinkedList: def __init__(self): self.root = None def ...
9e7d52642b66e270b9027a949b9715e5bbd3a471
rmautia/passwordlocker
/run.py
10,187
4.21875
4
#!/usr/bin/env python3.7 """ Run module File that runs the application import the two class modules to be run """ from user import User from credentials import Credentials def create_user(name, password): """ function that creates a user account Args name: name of choice by user for their accou...
37086d2dc8746fe193b93f16d559115c1de58549
notnormasatall/lab_one_algorithms
/visualize_result.py
1,763
3.6875
4
from json import * import matplotlib.pyplot as plt file = open("results.json") data = loads(file.read()) # The dictionary helps to make the legend while generating graphs graph_order = {"random_time": ["Time for random array", "Randomly generated Array | Time"], "random_comparisons": ["Comparisons for ...
37ddfbd46c7770d039da0d8130fa42c33f3a704f
Sivascorner/Hello-World
/Thread1.py
639
3.8125
4
import threading import time class count_stuff(threading.Thread): """ A thread class that will count a number, sleep and output that number """ def __init__ (self, start_num, end): self.num = start_num self.end = end threading.Thread.__init__ (self) def run(self):...
4d0f69bfb6fc0d3cd29bbe93a3b8d4ee5bf80506
one-CC/sink
/src/location.py
1,781
3.5
4
# -*- coding: utf-8 -*- # @Time : 2020/10/8 16:26 # @Author : DH # @Site : # @File : location.py # @Software: PyCharm import numpy as np import time import matplotlib.pyplot as plt def trilateration(p1, p2, p3, d1, d2, d3): """ 用于三角定位,返回定位的估计值。 :param p1: 第一个点的坐标 :param p2: 第二个点的坐标 ...
b0e6b8a94dc1a34681aa93a8071ca6ef2c186117
etasycandy/Python
/Workshop4/Exercise_page125/Exercise_03_page_125.py
771
4.40625
4
""" Author: Tran Dinh Hoang Date: 31/07/2021 Program: Exersice_03_page_125.py Problem: 3. Assume that a file contains integers separated by newlines. Write a code segment that opens the file and prints the average value of the integers. * * * * * ===================================================...
6a4a31ff060f671940bcfe217eece5e0b9c8d8b6
etasycandy/Python
/Workshop2/Project_page62_63/project_04_page62.py
897
4.5625
5
""" Author: Trần Đình Hoàng Date: 12/07/2021 Program: project_04_page_62.py Problem: 4. Write a program that takes the radius of a sphere (a floating-point number) as input and then outputs the sphere’s diameter, circumference, surface area, and volume. Solution: Display result: Ente...
9526509ca61318e54207386ff30a26fafb015bc7
etasycandy/Python
/Workshop3/Exercise_page73/Exercise_04_page_73.py
545
3.921875
4
""" Author: Trần Đình Hoàng Date: 17/07/2021 Program: Exercise_04_page_73.py Problem: 4. Write a loop that outputs the numbers in a list named salaries. The outputs should be formatted in a column that is right-justified, with a field width of 12 and a precision of 2. Solution: Display result...
65d3458ab0963b3fedc6d7b12fb6222e7de10a78
etasycandy/Python
/Workshop2/Project_page62_63/project_07_page63.py
626
4.09375
4
""" Author: Trần Đình Hoàng Date: 12/07/2021 Program: project_07_page_63.py Problem: 7. Write a program that calculates and prints the number of minutes in a year. Solution: Display result: Enter of year: 2021 The number of minutes in 2021 is : 525600 minutes. """ def checkYear...
0d0e8ba176bb0cf80230826dfa84af394e4d98f0
etasycandy/Python
/Workshop3/Project_page_99-101/project_09_page101.py
769
3.921875
4
""" Author: Trần Đình Hoàng Date: 19/07/2021 Program: project_09_page101.py Problem: 9. Write a program that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program...
c0def1cd8db4b63a42a4d4f1502629620865273e
etasycandy/Python
/Workshop3/Exercise_page92/Exercise_02_page_92.py
454
4.0625
4
""" Author: Trần Đình Hoàng Date: 17/07/2021 Program: Exercise_02_page_92.py Problem: 2. The factorial of an integer N is the product of the integers between 1 and N, inclusive. Write a while loop that computes the factorial of a given integer N. Solution: Display result: Factorial o...
9bcf277fb8cb08404466089ae22802e4f4ab96f9
etasycandy/Python
/Workshop2/Exercise_page54/Exercise_05_page_54.py
306
4.0625
4
""" Author: Trần Đình Hoàng Date: 12/07/2021 Program: Exersice_05_page_54.py Problem: 5. Assume that the variable x has the value 55. Use an assignment statement to increment the value of x by 1. Solution: Add '+= 1' after x Display result: 56 Ex: """ x = 55 x += 1 print(x)
f1a4e371c45c07a6a31f58aa0759da1300c2b9cc
etasycandy/Python
/Workshop2/Exercise_page59/Exercise_02_page_59.py
497
4.28125
4
""" Author: Trần Đình Hoàng Date: 12/07/2021 Program: Exersice_02_page_59.py Problem: 2. The math module includes a pow function that raises a number to a given power. The first argument is the number, and the second argument is the exponent. Write a code segment that imports this function a...
28e4aba13957dfd391736f61ec59614207835de1
etasycandy/Python
/Workshop2/Exercise_page46/Exercise_02_page_46.py
526
4.0625
4
""" Author: Trần Đình Hoàng Date: 12/07/2021 Program: Exersice_02_page_46.py Problem: 2. Write a string that contains your name and address on separate lines using embedded newline characters. Then write the same string literal without the newline characters. Solution: Display: Name:...
15f68a04727a744e48cc7c5db2ca123c6faf250b
etasycandy/Python
/Workshop3/Exercise_page85/Exercise_05_page_85.py
645
4.1875
4
""" Author: Trần Đình Hoàng Date: 17/07/2021 Program: Exercise_05_page_85.py Problem: 5. Explain how to check for an invalid input number and prevent it being used in a program. You may assume that the user enters a number. Set Case: A valid number is a number between 0 and 10 other than that...
a095d552b6533477555712540ebb9b45970f8d8f
TanyoTanev/SoftUni---Python-Advanced
/ADV_Multidim lists - 05.Snake Moves.py
3,059
4.5
4
'''5. Snake Moves You are walking in the park and you encounter a snake! You are terrified, and you start running zigzag, so the snake starts following you. You have a task to visualize the snake's path in a square form. A snake is represented by a string. The isle is a rectangular matrix of size NxM. A snake start...
5c2f1cb935e4803fde8b5e90d4f98a3f5ffdbb4b
TanyoTanev/SoftUni---Python-Advanced
/ADV_Multidim lists - 08.Miner.py
4,511
4.28125
4
'''8. *Miner We get as input the size of the field in which our miner moves. The field is always a square. After that we will receive the commands which represent the directions in which the miner should move. The miner starts from position - 's'. The commands will be: left, right, up and down. If the miner has...
0678d009de615d046e53e5750141e5e774998664
TanyoTanev/SoftUni---Python-Advanced
/ADV_Comprehensions - 04.Capitals.py
714
4.03125
4
'''4. Capitals Using dictionary comprehension write a program that receives countries on the first line separated by comma and space ", " and their corresponding capital cities on the second line (again separated by comma and space ", ") and prints each country with their capital on a separate line ...
a872fc1db456387a30d7c8dbc17e5839d1adbc59
TanyoTanev/SoftUni---Python-Advanced
/ADV_Functions - 12. Recursion Palindrome.py
821
4.125
4
'''12.Recursion Palindrome Write a recursive function called palindrome which will receive a word and an index (always 0). Implement the function, so it returns "{word} is a palindrome" if the word is a palindrome and "{word} is not a palindrome" if the word is not a palindrome using recursion. Submit only the functi...
8c660fc9ad32c5cdae082e54a9539971326f971c
gagan3012/atmpython
/atm v2.py
2,552
3.90625
4
def verify_pin(pin): if pin == '1234': return True else: return False def log_in(): tries = 0 while tries < 4: pin = input('Please Enter Your 4 Digit Pin: ') if verify_pin(pin): print("Pin accepted!") return True else: print("I...
1b5cc8d471f2272e2de93fc9cf4939654ebeb0fa
EchoWho/StochasticGradientBoosting
/db/textmenu.py
1,099
3.640625
4
# Presents a numbered text menu for a series of items or from a GLOB string # # Output looks like the below where header = Select a dataset: # ----- Select a dataset: ----- # # 0: Exit # 1: helicopter_data # 2: mg_10 # 3: normalized_take_off_data # 4: projected_mocap_data # # Select a menu item: 1 # # Arun Venkatraman...
c99886efd9f294eb46048fc1d34ad7670d457333
amanprakash9299/TO_DO
/basic_to-do.py
3,000
3.546875
4
import tkinter from tkinter import * import sys import random from tkinter import messagebox root=Tk() root.title("To-Do") #Title of Root Window root.geometry("300x250+300+300") root.resizable(True,True) root.config(bg="light pink") #Empty list for some operations like asc_order and desc_order,remove,...
52380c3350946058a78cb49d30822a18de0b6e62
yuxuelian/PythonCode
/Python-sort.py
575
4.21875
4
#-*-coding:utf-8-*- #Python排序 #使用Python内置 sorted函数对list进行排序 list1=[1,23,234,1,123,2,34,456] list1=sorted(list1) print(list1) #字符串排序 list2=['bob', 'about', 'Zoo', 'Credit'] print(sorted(list2)) #忽略字符串的大小写进行排序 print(sorted(list2,key=str.lower,reverse=False)) L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa',...
9ddc0a7aba80f53d7acd4e2b447063dc7c221e99
yuxuelian/PythonCode
/Python-diedaiqi.py
1,055
4.3125
4
#-*-coding:utf-8-*- #Python迭代器 ''' 可以直接作用于for循环的数据类型有以下几种: 一类是集合数据类型,如list、tuple、dict、set、str等; ''' #引包 from collections import Iterable #判断是否可迭代 isinstance({},Iterable) # 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。 # 生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。 from collections import Iterator isinstanc...
047dc1cf84362de7fabd25852b5190a72430d118
yuxuelian/PythonCode
/01-helloWorld.py
494
4.15625
4
#-*- coding:utf-8 -*- '''#coding=utf-8''' ''' print("hello world"); print("hello world"); ''' """ ע """ print("hello world") #python3 #a=input(); #python2 a=raw_input() a_num=int(a) print(type(a)) print(type(a_num)) if a_num>18: print("ֵ18") elif a_num>16: print("ֵ16") elif a_num>14: print("ֵ <=16 >14")...
7ef7c98e2f27672a3796367104280ad96511ebfb
manasRK/algorithms-practice
/hackerrank/insertions-sort-2.py
1,763
4.34375
4
''' https://www.hackerrank.com/challenges/insertionsort2 In Insertion Sort Part 1, you sorted one element into an array. Using the same approach repeatedly, can you sort an entire unsorted array? Guideline: You already can place an element into a sorted array. How can you use that code to build up a sorted array, one...
c0b335df73961ec825de729f6504cd0ac4f5a06a
rcohen0511/hackerRank
/Djikstra.py
1,373
4.15625
4
# vertex should start with zero # if you are giving weight above 999 adjust min in program # result will be the shortest path and the distace to each vertex from source vertex in order def dijkstra(matrix, m, n): k = int(input("Enter the source vertex")) cost = [[0 for x in range(m)] for x in range(1)] offs...
164d072f1edcb96e208e8c6193e1ccec6afef610
USTH-Coders-Club/API-training
/callapi.py
527
3.8125
4
#import the library to make http request import requests #URL of the API URL = "https://ssd-api.jpl.nasa.gov/cad.api" distmax = input("set the maximum distance: ") vinfmax = input("set the maximum speed: ") #Params param = { 'dist-max': distmax, 'v-inf-max': vinfmax } #Make an API request and store date t...
3356f3cb445ee53ecfb67e05d88f0163829c3eca
ajeldorado/falco-python
/falco/check.py
9,399
3.53125
4
"""Module to hold input-checking functions to minimize repetition.""" import numpy as np import numbers class CheckException(Exception): pass # String check support string_types = (str, bytes) # Int check support int_types = (int, np.integer) def _checkname(vname): """Check internally that we can use vn...
2a20551d913bde130b896503ef4ffef9aed45c13
Selwinsam93/practicescripts
/fibonacci.py
395
3.8125
4
#get the user input #declare values for n1 and n2 vars and a flag #condition less than 0 as error #return n1 if values is 1 val = int(input("Number: ")) n1,n2 = 0,1 flag = 0 if val <= 0: print("Poda bundha") elif val == 1: print(n2) else: while val > flag: print(n1) nth = n1 + n2 ...
b73859af54dded77d4ccc745461d5bbe2b5280da
sak2km/colocation_ga
/colocation/data_processing/time_series.py
2,437
3.625
4
"""Process, reshape raw data from sensors """ from typing import List import numpy as np def trim_and_align(data_list: List[np.ndarray], interval: int) -> np.ndarray: """Trim a list of data, so they start and end at the same time Args: data_list (List[np.ndarray]): a list of data. Each ...
e7564c4b1b4d0f4c45148e70ae4345b4e0b0c2fb
DwordPtr/Project_Euler_Solutions
/prob6.py
395
3.703125
4
#This program finds the difference between the sum of the squares of the first 100 natural numbers and the square of the sum of the first 100 natural numbers SquareSum = 0 for i in range(1,101): SquareSum+=i**2 # sum the values of 1^2 - 100^2 n = 100 SumSquare = int((n*(n+1)/2)**2) # take the sum of 1-100 with calc...
911b5016e65d7f1304ec5fe352cb0782bbf1dc6e
aditidesai27/OpenOctober
/SoftwareDev/Python/karatsubaAlgo.py
559
3.59375
4
#Karatsuba Algorithm in Python import math def karatsuba(x, y): if x < 10 and y < 10: return x*y n = max(len(str(x)), len(str(y))) m = int(math.ceil(float(n)/2)) x_H = int(math.floor(x/10**m)) x_L = int(x % (10**m)) y_H = int(math.floor(y/10**m)) y_L = int(y % (10**m)) ...
e9c6b882839f0134614f1405eef09befe40b8fcb
Robin-Andrews/N-Queens-in-Python
/n_queens_gui.py
5,748
3.515625
4
""" GUI code for the N-Queens Problem using Codeskulptor/SimpleGUICS2Pygame By Robin Andrews - info@compucademy.co.uk https://compucademy.co.uk/blog/ """ try: import simplegui collision_sound = simplegui.load_sound("https://compucademy.co.uk/assets/buzz3x.mp3") success_sound = simplegui.load_sound("https:...
421448b69407e7e79f5f4ea40f136b1c80229a94
shawnhan108/Flight_planner
/price_analysis.py
6,285
4.09375
4
from notifications import Notification class NotificationAnalysis(Notification): def check_notify(self, flight_info): """ Takes a list of freshly scraped flights and check if the user should be notified. If yes, return a list of important data that needs to be displayed to the user. ...
30a217546e4450c82a863ca656f75a7b1ea30a98
kyler95/advent_of_code
/2020/day6/task7.py
580
3.71875
4
import string # read data from file file = open('input_6.txt', 'r') ans = 0 ans2 = 0 lines = list(file) lines.append('') any_yes = set() all_yes = set(string.ascii_lowercase) for line in lines: line = line.strip() if not line: ans += len(any_yes) ans2 += len(all_yes) any_yes = set()...
b169102c19eefa7b5f790a3583b6adcc34c36c60
camillebenoit/Sudoku_solver
/Sudoku/methods.py
6,335
3.8125
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 25 17:51:20 2021 @author: hello """ import typing as t from Sudoku import sudoku as sk from Sudoku import variable as vr def init_assigment(sudoku: sk) -> t.Dict: assignment = {} for i in range(9): for j in range(9): if sudoku.values[i][j]....
3f334bb82ff6733779d619a369cd4e9559baa07f
naoki-yoshida97/py_pra
/list41.py
1,016
3.90625
4
# n = int(input('整数n:')) # # if not (n<= -10 or n>=10): # print('その値は二桁未満です') # else: # print('その整数は二桁以上です') # mounth = input(int('季節を求めます/n月を入力してください')) # a = int(input('整数a:')) # b = int(input('整数b:')) # if a - b <= 0 : # print('絶対値は',b-a,'です') # else: # print('絶対値は',a-b,' desu') # t = a # a ...
7719fdb9bf37306c22d0d3933d0ddb472a5c59a0
ZhengLi95/User-Equilibrium-Solution
/model.py
15,400
3.625
4
from graph import TrafficNetwork, Graph import numpy as np class TrafficFlowModel: ''' TRAFFIC FLOW ASSIGN MODEL Inside the Frank-Wolfe algorithm is given, one can use the method `solve` to compute the numerical solution of User Equilibrium problem. ''' def __init__(self, graph= No...
4fc1d324cb2933e6af4134f4ea408a21992733f1
Ericknht/python-excersices
/binary_search_mio.py
761
3.921875
4
# -*- coding: utf-8 -*- def search_in_list(list_binary, number): fin = len(list_binary) print(fin) middle = len(list_binary)//2 start = 0 while True: if list_binary[middle] == number: print('si está el número {}'.format(number)) break elif list_binary[middle] < number: start = middle middle = (f...
0457456ff76e2a0434e23420a1b5b6a312bf7747
Ericknht/python-excersices
/palindrome_mio.py
444
4.09375
4
# -*- coding: utf-8 -*- def run(word): palindrome = word[::-1] if palindrome == word: return True return False if __name__ == '__main__': print('En este programa puedes ingresar una palabra y ver si es un palíndromo') word = str(input('Ingresa una plabra: ')) result = run(word) if result: prin...
5013d4b87e26d5cc38c90fc23b948912f267b4b4
KingsleyDeng/CoolPython
/国旗/国旗.py
565
3.90625
4
import turtle # 定义一个函数,可以画五角星 def picture(x1,y1,x,y): turtle.up() turtle.goto(x1, y1) turtle.down() #用于填充颜色 turtle.begin_fill() turtle.fillcolor("yellow") for i in range(5): turtle.forward(x) turtle.left(y) turtle.end_fill() # 速度为3 turtle.speed(3) # 背景红色 turtle.bgcolor("red")...
725d0461c0e357f4c40f868ef9efef8e2c19f9f0
santhosh6328/basicGuiPython
/gui_diagram.py
278
3.703125
4
import turtle def draw_square(): for i in range(4): brad.forward(100) brad.right(90) brad.right(10) window = turtle.Screen() window.bgcolor("red") brad = turtle.Turtle() brad.shape("turtle") brad.color("yellow") brad.speed(.1) for i in range(36): draw_square()
3ba2be1e89d26d66349a4f67ad79937fb4544a8b
KirillBaboshko/Klasswork
/prog17.py
756
3.640625
4
import random def PrintList(listarg): print("list:") for i in range(len(listarg) - 1): print(listarg[i], end=", ") print(listarg[len(listarg) - 1]) def ListReverse(listarg, index): templist = listarg[index:] templist.reverse() listarg = listarg[:index] + templist return listarg n ...
be45c4fd9ef59652e1807b68dbe52b9f51715e94
KirillBaboshko/Klasswork
/prog9.py
1,757
3.703125
4
n = int(input("Введите высоту ")) m = int(input("Введите ширину ")) for i in range(n): if i == 0 or i == (n - 1): print("*" * m) else: print("*", " " * (m - 2), "*", sep = "") ceil = int(input("Введите размер клетки ")) for i in range(8): for j in range(ceil): if(i % 2 == 0): ...
06db442be83ada7911cea1c2fdb18f8fa89ea8c6
KirillBaboshko/Klasswork
/prog25.py
314
3.578125
4
a = int(input("input a ")) n = int(input("input n ")) p = 1 operation = 0 for i in range(n): operation += 1 p *= a print(p, operation) res = 1 operation = 0 while n > 0: operation += 1 if n % 2 == 1: res *= a n -= 1 else: a *= a n //= 2 print(res, operation)
e2bcff36566e6fcf1c1f7bb53618b00c4eaf92bb
AndreaInfUFSM/elc117-2017a
/trabalhos/t2/svgcolors.py
1,234
3.5
4
#!/usr/bin/env python3 import itertools ''' Programacao funcional para gerar SVG: - gera uma lista de coordenadas de retangulos - define uma lista de estilos (cores), em qualquer quantidade - aplica os estilos aos retangulos, gerando uma lista com todos os dados para o SVG - coloca os dados no formato S...
0b461094f746c0e194024bcc9a083b82451b7d80
sikmak/SpecialCoursePython
/Ch2/area_and_circumference_func.py
477
3.90625
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 23 16:32:55 2016 @author: Никита """ import os from math import pi def cuircle_square(r): S = pi*r**2 return S def cuircle_length(r): L = 2*pi*r return L r=float(input("Введите радиус окружности: ")) print("Длина окружности: ...
726f4a4efda8097164ee484eaadad55023626261
sikmak/SpecialCoursePython
/Ch1/testing_ball.py
817
4.03125
4
# -*- coding: utf-8 -*- # Программа для вычисления положения мяча при вертикальном движении #1) Привет NameError: name 'Привет' is not defined v0 = 5 #Начальная скорость #2,3)SyntaxError: invalid syntax Если убрать # перед Начальная или = после v0 g = 9.81 # Ускорение свободного падения t = 0.6 # Время ...
1427a16438e46bebb4e2d12a4f89ce3c31908a99
sikmak/SpecialCoursePython
/Ch2/errors.py
881
4.25
4
# -*- coding: utf-8 -*- # Программа для вычисления положения мяча при вертикальном движении # с использованием функции def y(t): v0 = 5 # Начальная скорость g = 9.81 # Ускорение свободного падения return v0*t - 0.5*g*t**2 t = 0.6 # Время print (y(t)) t = 0.9 print (y(t)) """ 1)SyntaxErro...
3bec9330e35a397c9f4d1c1c69964e7a78b1e039
stan-online/shag
/shag/dz/sort.py
179
3.796875
4
def insertion(data): for i in range(len(data)): j = i - 1 key = data[i] while data[j] > key and j >= 0: data[j + 1] = data[j] j -= 1 data[j + 1] = key return data
53c066f5181b3737ecb655756cbedb8f6485cba9
drewtadams/PyVFrame
/src/lib/util/decorators.py
584
3.8125
4
from functools import wraps def ignore(ignore_except=Exception, default_val=None): """ Ignores any exception and provides a default return value Parameters: ignore_except (Exception, optional): exception to be caught default_val (object, optional): value to be returned if exception is caught Returns: wrapped...
3993dcbd76d1b42659cbdc1d7891c1893a420fa3
kuntalnr/python
/string_slicing.py
586
4.1875
4
mystr = "kuntal is a good boy" print(len(mystr)) # length of strings including spaces print(mystr[0:19]) # if I want to skip characters print(mystr[0:5:2]) # skips two characters print(mystr[0::2]) # skips two characters for the entire string print(mystr[:5:2]) # skips two characters till length 5 print(mystr[-4:-2])...
7b3e38b097103b8b92c59468e25e6822f55ee4ef
billstark/leetcode
/next_permutation.py
717
3.5
4
def nextPermutation(nums): changed = False for i in reversed(range(1, len(nums))): prev = i - 1 if nums[prev] < nums[i]: for j in reversed(range(prev + 1, len(nums))): if nums[prev] < nums[j]: temp = nums[j] nums[j] = nums[prev]...
e7d20a324316c6b244c31659f7c4d962dd30524d
Near-River/py_code
/test/test_02.py
442
3.796875
4
# -*- coding: utf-8 -*- # 打印杨辉三角 def triangles(n): i, L = 1, [] while i <= n: if i == 1: L = [1] elif i == 2: L = [1, 1] else: temp = [1] for j in range(1, i - 1): temp.append(L[j - 1] + L[j]) temp.append(1) ...
6c85767270080cc350d371f50975c0b382c140ee
Near-River/py_code
/oop/high_level/py_25.py
881
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # type(): dynamically created class object def fn(self, name): print('hello, %s!' % name) Hello = type('Hello', (object,), dict(sayHello=fn)) print(type(Hello)) h = Hello() print(type(h)) h.sayHello('tom') # metaclass: class ListMetaclass(type): # metaclass is a...
6178762c54d8572558d435d6b9b9314da3c1d555
Near-River/py_code
/io/py_34.py
353
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pickle # pickling: pickle d = dict(id='s001', name='Jack', age=21) print(d) pd = pickle.dumps(d) print(pd) nd = pickle.loads(pd) print(nd) print(id(d) == id(nd)) with open('pickle.txt', 'wb') as f: pickle.dump(d, f) with open('pickle.txt', 'rb') as f: n...
5a99206dcdc08f27d25d791ed8acfd863fef7f13
Near-River/py_code
/oop/high_level/py_22.py
1,001
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # customize class 1: class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'Student object (name=%s)' % self.name __repr__ = __str__ print(Student('Nate River')) class Fib(object): def __getitem_...
336f0da1ccd3d4d34a4c86ea09088931342b72f9
CodecoolBP20172/pbwp-2nd-tw-python-game-team-nine
/buttons.py
665
3.515625
4
from tkinter import * import numpy as np from random import randint from tkinter import messagebox import sys root = Tk() root.title("Tic Tac Toe v2.0b") buttons = [] for i in range(81): btn = Button(root, text="", font=("Arial 15 bold"), height=1, width=2,) btn.grid(row=int(i / 9), column=i % 9) buttons....
1b0741eaf9f0ad763d9fd3ed11699029fa75b29c
jparrieta/bandits
/python_version/posen_levinthal.py
11,916
3.71875
4
#!/usr/bin/env python # coding: utf-8 # # Tutorial on Posen and Levinthal (2012) # # In this tutorial, you will be introduced to a simple model that replicates the main finding from the paper by Hart Posn and Dan Levinthal, published in 2012 in Management Science. # # This tutorial provides a barebones descripti...
f8e27ada06039c7abc5f668f033860ca1d6762c2
hahasucky/Learn_Python_3_the_Hard_Way
/setter_test.py
1,445
3.640625
4
class Student : def __init__(self, first, last): self.first = first self.last = last @property def fullname(self): return "{} {}".format(self.first, self.last) @fullname.setter # setter should use the same name of the function.setter def fullname(self, input): first,...
0b84dd27454f77316383c0b414b8eb5fb20c65f0
hahasucky/Learn_Python_3_the_Hard_Way
/oop_tutorial_5.py
2,203
3.890625
4
import datetime my_date = datetime.date(2016,7,7) class Employee : #class variable raise_amount = 0.1 num_of_emps = 0 # @instance oper. def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay Employee.num_of_emps += 1 # __init__은 오...
75860942578df7fb852eea22e6513a60d4887ae0
muskaanmuskaan/Automatic-Cancer-Diagnostic
/Automatic Cancer Diagnostics.py
5,542
3.890625
4
import csv import math import operator import statistics from statistics import multimode import random def load_from_csv(file_path: str) -> list: """loads data from csv file and return matrix of list of lists. """ data = [] with open(file_path, newline="") as csvfile: reader = csv.reader(csvf...
5e8b41ee50ee1645af5cca416acb15ea71aa1489
liuwenrong/Config4Roger
/Script/py2Src/if.py
2,059
3.9375
4
#!/usr/bin/python2 # vim: set fileencoding=utf-8 : # -*- coding: utf-8 -*- # coding=utf-8 import sys, bd #tuple 元组 age = 25 name = 'Roger' print 'hello Roger' print '%s is %d years old' % (name, age) print 'Why is %s playing with that python?' %name zoo = ('wolf', 'elephant', 'penguin') print 'Number of anima...
6922132beadeb8cffa544963ed5c1fb8f416ac7d
sdyz5210/python
/tkinter/basic/test/test7.py
1,209
3.5625
4
#!/usr/bin/evn python # -*- coding: utf-8 -*- # python version 2.7.6 import Tkinter import ttk import time import threading #Define your Progress Bar function, def task(root): ft = ttk.Frame() ft.pack(expand=True, fill=Tkinter.BOTH, side=Tkinter.TOP) pb_hD = ttk.Progressbar(ft, orient='horizontal', mode=...
f4a653b3bc86918d26fdbec768121b619b4d6dcd
sdyz5210/python
/ml/test_numba.py
1,066
3.59375
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- from numba import jit import numpy as np import time SIZE = 2000 """ 给定n*n矩阵,对矩阵每个元素计算tanh值,然后求和。 因为要循环矩阵中的每个元素,计算复杂度为 n*n。 """ @jit def jit_tan_sum(a): # 函数在被调用时编译成机器语言 tan_sum = 0 for i in range(SIZE): # Numba 支持循环 for j in range(SIZE): tan...
0efb13aad4484be1c301272cf4a4ddff66d27212
sdyz5210/python
/high/filterDemo.py
188
3.6875
4
#!/usr/bin/python # -*- coding: utf-8 -*- #filter()也接收一个函数和一个序列 def is_odd(x): return x%2==1 f1 = filter(is_odd,range(1,11)) print '打印过滤后的列表',f1
6c1cf1e1c71acb2c31b9bd91802b11b946ee9ba8
sdyz5210/python
/high/propertyDemo.py
833
3.78125
4
#!/usr/bin/python # -*- coding: utf-8 -*- class Student(object): def get_score(self): return self._score def set_score(self,value): if not isinstance(value,int): raise ValueError('score must be an integer!') if value < 0 or value >100: raise ValueError('score must between 1~100!') self._score = value...
2079f2d7d85a9520d0857735ff2158aaf32abaca
sdyz5210/python
/ml/03-matplotlib/matplotlibDemo.py
534
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np # 导入绘图工具包 import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame def test(): N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) r = 15*np.random.rand(N) area = np.pi *r**2 # 绘制散点图 plt.s...
92c5dd51ead269a080f8279ba96d85acc60629a9
sdyz5210/python
/high/lambdaDemo.py
200
3.578125
4
#!/usr/bin/python # -*- coding: utf-8 -*- def f(x): return x*x map1 = map(f,range(1,11)) print map1 #使用匿名函数实现 print '打印匿名函数运行结果',map(lambda x : x*x,range(1,11))
052ea6a965f094454a98e14e2c2ec4439d965890
sdyz5210/python
/high/fnParam.py
301
3.734375
4
#!/usr/bin/python # -*- coding: utf-8 -*- #正常情况下求和 def calc_sum(*args): sum = 0 for x in args: sum = sum + x return sum def lazy_sum(*args): def sum(): ax = 0 for x in args: ax = ax+x return ax return sum f = lazy_sum(1,2,3,4) print '打印f=',f print '打印f()=',f()
c12e6e4a5ca97ba23d10e325f6a9160257b36f07
Sanket2701/File-Handling
/file.py
644
3.84375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: f=open("file.txt",'r') f.read() # In[22]: f=open("file.txt",'w') f.write("World with") f.close() # In[23]: f=open("file.txt","a") f.write(" Corona Virus") f.close() # In[21]: f=open("file.txt","r+") f.read() f.write("hi buddy") f.read() f.close() # In[24]:...
7d605b87c09ec4d4875060b7f90843f841ffdd47
FelipeGiori/Data_Visualization_TP2
/publisher_heatmap.py
2,271
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import pandas as pd import plotly.plotly as py import plotly.graph_objs as go # Load data games = pd.read_csv("data/vgsales.csv") # If a game was made for several platforms, makes sure that it has only one entry games = games[['Name', 'Publisher', 'Genre']] games = game...
22ca2e59ca40eab498aa5b6440a07ba86c39a14b
edmaldo/rail_fence_cipher
/encrypt_rail_fence.py
1,508
4.1875
4
"""Encrypt a Civil War 'rail fence' style cipher. Example message === 'Buy more sweet potatoes' Separate letters in zigzag rows === \/\/\/\//\/\/\ Rail fence style === B Y O E W E P T T E U M R S E T O A O S Make one line cip...
b6cfd8e10275ab7c4120a21d121d7b2f8ea9fbda
halleydeme/py_unit_four
/even_odd.py
786
4.4375
4
def even_or_odd(number): """ Create a function that will tell if a number is even or odd. Use two if statements to do this. :param number: could be any positive or negative integer :return: either "x is an even number" or "x is an odd number" """ if number % 2 == 0: return(str(number) +...
a59eebef96795f5ea0334b0ec80230d686c96f5a
rafiedev/kali18
/.github/kalix.py
223
3.71875
4
print("😍😍this is a table programme 😎") i=int(input("Enter the no. :")) for a in range(1,11): print("¦",i," x ",a," = ",i*a) a+=1 print("thx for the visit \n. visit again \n 🙏 ") print("@tiwariji264")
0ad39de833fc96947df685d893d1548b45a946a7
gauravnn/RottenTomatoesAPI
/RottenTomatoes.py
1,870
3.578125
4
""" This file provides a simple way of retreveing data using the RottenTomatoes API """ import requests import json class RottenTomatoes (): apikey = "d2ruyfuf5mfj7fnvywb3meck" @staticmethod def getMoviesURL (query_terms, page_limit = 30, page = 1): search_term = RottenTomatoes.__getURLStyleQuery (query_term...
505a39680dc0fd2e919144243b73aabbce3e0371
MohammedGhafri/caesar_cipher
/caesar_cipher/caesar_cipher.py
3,057
3.640625
4
import re import nltk nltk.download('words') def encrypt(str,key,state="encrypt"): """ str- String that will be encrypted using ASCII Code key-: Number of shifting encrypted_msg _ returned encrypted message """ if state == "encrypt": # Remove the special characters just for encryption ...
5923d1f81c80827b6184100b1399f1bf2ebb5a41
kevin-bigler/pytris
/old news/tetris_board.py
1,521
3.578125
4
"""Keeps track of the space where pieces are placed, etc""" import pygame from grid import Grid light_grey = (200, 200, 200) square_width = 30 square_height = 30 square_color = light_grey square_border_width = 3 class TetrisBoard: def __init__(self, width, height): self._grid = Grid(width, height, Squar...
c6eaa503a3f2b70e153b4a67ee3e612dc729f1cc
JakeMittleman/RL_Sonic
/Code/connection_gene.py
2,126
3.859375
4
""" This class represents a connection between either an input node and a hidden node or a hidden node and an output node. Input -> Hidden or Hidden -> Output """ class ConnectionGene: def __init__(self, in_node=None, out_node=None, weight=0.0, enabled=True, innovation=0): """ :param in_node: the...
438ab6f140b3d97b6b299bfc03a490ccc8e1648e
JakeMittleman/RL_Sonic
/Code/node_gene.py
1,058
3.59375
4
class NodeGene: """ A Node Gene represents a node, with a list of inputs, outputs and hidden nodes. The key thing to take away in the node class is that all of the input, output and hidden nodes are not representing any connections - they represent POSSIBLE connections. Each is a list of some kind...
1b0224212ac81b37e7dec74a9914ac7e6eae9a9e
L200183043/Praktikum-Algopro
/11_keg3.py
1,233
3.84375
4
rom Tkinter import* my_app = Tk(className= 'Simple Calculator') L1 = Label(my_app, text= 'Geometry', font= ('Arial', 24)) L1.grid(row=0, column=0, columnspan=3, sticky= 'w') L2 = Label(my_app, text= 'Calculate Area of a Cuboid, A brick for example, Formula : Length x Width x Height ') L2.grid(row=1, column=0, co...
571d9b1155189608695c6da613774fa2cb4acd4c
silveira/playground
/python/misc/binary_tree_traversal_preorder_non_recursive.py
532
3.59375
4
#!/usr/bin/env python LEFT = 0 RIGHT = 1 example_graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['', ''], 'D': ['G', ''], 'E': ['', 'F'], 'F': ['', ''], 'G': ['', 'H'], 'H': ['I', ''], 'I': ['K', ''], 'K': ['', ''] } def preorder(graph, root): stack = [] stack.append(ro...
6df7a0aacf71c62977e17de7b42f972560726264
silveira/playground
/python/misc/binary_search.py
904
4.03125
4
#!/usr/bin/env python # recursive binary search def binary_search_r(array, key, low, high): if(low>high): return None mid = (low+high)/2 if array[mid]==key: return mid elif array[mid]>key: return binary_search_r(array, key, low, mid-1) else: # array[mid]<key: return binary_search_r(array, key,...
f41cf47262c40fc20292305be008819d29c2a4db
ctorresmx/mistontli
/mistontli/players.py
2,792
3.8125
4
import random import time import copy from utilities import determine_win class BasePlayer: """Base player class, you can subclass this and override the 'get_move' method to implement your own type of player.""" symbols = ['X', 'O'] def __init__(self, name, symbol): self.name = name ...
dc12b67545b83116684859ae000413fbb734bc5f
mrluisjurado/Icecreamshop
/iceCreamShop.py
3,380
4.1875
4
print "\t\tEnjoy Ice Cream from my own Cream Shop\n\n" choice = "z" # initialize choice with any value that will # set the while loop to true scopePrice = "" iceCreamName = "" iceCreamFlavor = "9" def iceCremPrice(): print u""" a. 1 scoop cost you \u00A3 Pound ...
d6057eabc733d7a7d72a3eda66dfa95b1b4e725d
twadolowski/lab_11_2sem-Exercises
/Ex2.py
752
4.375
4
print("Introduce day:") day = int(input()) print("Introduce month:") month = int(input()) season = "" isDateCorrect = True if day>31 or month>12: isDateCorrect = False elif (month%2 == 0 and month<7) or (month%2==1 and month>8): if day>29 and month==2: isDateCorrect = False elif day>30: ...
2c66bcb2d49cd0ad9bbb69030e930ed2119d2d55
ShinCheung/jianzhioffer
/丑数.py
820
3.859375
4
# -*- coding:utf-8 -*- # 把只包含质因子2、3和5的数称作丑数(Ugly Number)。 # 例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。 # 求按从小到大的顺序的第N个丑数。 class Solution: def GetUglyNumber_Solution(self, index): # write code here if index <= 0: return 0 uglyList = [1] index2,index3,index5 = 0,0,0 ...
f3fa2090a6aa7956a835e52532e71e2f9d237625
ShinCheung/jianzhioffer
/数组中重复的数字.py
778
3.71875
4
# -*- coding:utf-8 -*- # 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 # 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 # 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。 from collections import Counter class Solution: # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0] # 函数返回True/False def duplicate(self, numbers, duplicat...
d89db5241b22f392155ee0aedea9a594165615d0
Thanujreddy17/Titanic-survival
/my titanic disaster.py
6,404
3.703125
4
# coding: utf-8 # ## Importing the required libraries # In[1]: import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # ### Reading the training and testing data set as a data frame # In[2]: train = pd.read_csv('titanic...
146ef623c6d531745cfa52e0073478b6daf51647
clouserw/codeeval
/100.py
486
4.09375
4
#! /usr/bin/python # Write a program which checks input numbers and determines whether a number is # even or not. # https://www.codeeval.com/open_challenges/100/ import sys if not len(sys.argv) == 2: print "Usage: ./100.py <filename>" sys.exit(1) try: with open(sys.argv[1]) as f: for line in f: ...
07095456da6647f3b2a289c7d33eedd7f005624e
Kimbsy/project-euler
/python/problem_018.py
947
3.828125
4
import csv """By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle in data/problem_018.csv: NOTE: As there are only 16384 ...
ceb0bf1e823ba32931903f316a3e63e9c298dbf2
Kimbsy/project-euler
/python/problem_067.py
1,052
3.6875
4
import csv """By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom in data/problem067.py a 15K text file containing a triangle with one-hu...
d2e10031ffeb5340aa9257952ba3b375970d6076
qnddkrasniqi/prod-python-practice
/advanced-syntax/generator_expressions.py
511
3.578125
4
def avoids(word, forbidden): for i in word: if i in forbidden: return False return True def avoids(word, forbidden): return not any(i in forbidden for i in word) def uses_all(word, required): for i in required: if i not in word: return False return True ...
43ab1c6afd07bac2c31470dc35dd7f7cc0c04588
ywby0003/aimgame-with-pygame
/osu.py
2,388
3.84375
4
import pygame #pygame module import math #Checking collisions in circle import random #giving circles a random spot #Defines screens and starts pygame pygame.init() width=800 height=900 display = pygame.display.set_mode((width,height)) #Displays screen #colours for circles red=(255,51,51) blue=(0,0...
0753efa7c7cffcf3c64b9fdcc992e3b34c7673f8
vshypko/coding_challenges
/problems/leetcode/mergeTwoLists.py
1,025
3.875
4
# 21 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: r...
0289e1d423ae7fda7f4ec36fdc247ed9d17aa45e
vshypko/coding_challenges
/problems/ctci/chapter1/isStringRotation.py
622
3.78125
4
# 1.9 class Solution: def __init__(self): # for testing purposes pass # O(len(s1) + len(s2)) runtime # O(len(s2)) space def isStringRotation(self, s1, s2): if len(s1) != len(s2): return False return self.isSubString(s1, s2 + s2) def isSubString(self, s1,...
fe1cbd3c320aa5d18aa6aeb2270a255027212b58
vshypko/coding_challenges
/problems/leetcode/longestWord.py
897
3.515625
4
# 720 class Solution: def longestWord(self, words): """ :type words: List[str] :rtype: str """ sorted_words = sorted(list(set(words)), key=len) same_length = list() i = 1 while i <= len(sorted_words): result = sorted_words[-i] ...
e57a58fbddecf4582aec87401ea41575b0f5825a
vshypko/coding_challenges
/problems/misc/people.py
4,446
3.625
4
# Name | Favorite Color | Birthday # Theo | Green | October 10, 2000 # Sherwin | Blue | May 3, 2003 # Daniel | Orange | December 2, 2003 # Sunny | Orange | January 4, 1999 # Aubrianna| Green | August 5, 1999 # 1-1) How would you represe...