blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
bcb6c373ab2f5868b63efbfee4ba31a6f8695c19
cameliahanes/testFP14.11.2016
/menu.py
1,420
3.78125
4
''' Created on 14 nov. 2016 @author: Camelia ''' from tests import * from operations import * from copy import deepcopy def mainn(): m = "" m += "1 - Add a new phone; \n" m += "2 - Find phones from a certain manufacturer; \n" m += "3 - increase the price of a phone with a given amount; \n" ...
9c7fb903d464e6d714b01b32d1f69c444a5674c3
codeAligned/DataStructures-1
/BinaryTree.py
1,423
3.875
4
class Node(object): def __init__(self, data=None, parent=-1, left=None, right=None): self.data = data self.parent = parent self.left = left self.right = right def get_data(self): return self.data def get_parent(self): return self.parent def get_left(self): return self.left def get_right(self): ...
34666e02727ce0b8afd72d8b235f4c19949e6ff6
edu-athensoft/stem1401python_student
/sj200917_python2m6/day07_201029/exception_11.py
464
4.09375
4
""" module 7. exception handling Raise multiple exceptions pay attention to the order in which exceptions raise keyword: assert """ print("Start") try: num = int(input("Enter a number: ")) if num <= 0: raise ValueError("That is not a positive number!") assert num % 2 == 0 except AssertionError...
68190c6204161d031ecdecdcb02c72cef96e362a
NicholasZXT/DataAnalysis
/PythonGrammar/multiprocess_basic.py
20,792
4.15625
4
""" Python 并行编程 """ import os from time import sleep import random # 多线程相关 import threading from queue import Queue as TQueue # 这个队列是线程安全的 # 多进程相关 from multiprocessing import Process, Pool, Semaphore, Condition, current_process from multiprocessing import Queue as MQueue from concurrent.futures import ThreadPoolExecut...
173a2faecae89895b5bdadc486a40da3a1ff716b
yodeng/sw-algorithms
/python/sort_search/insertion_sort.py
609
4.1875
4
#!/usr/bin/env python # encoding: utf-8 """ @author: swensun @github:https://github.com/yunshuipiao @software: python @file: insertion_sort.py @desc: 插入排序 @hint: 和冒泡排序一样,存在一样的优化点 """ def insertion_sort(array): for i in range(1, len(array)): for j in range(i, 0, -1): if array[j - 1] > arr...
b8fd91963e6d7bb413c77b1d87b28b5e2804ef22
CharlesLuoquan/knowledge
/testPY/towardsOffer/002-替换空格/code.py
980
3.796875
4
''' 题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 思路 先遍历找到多少个空格,然后开辟数组填充 ''' class Solution: def replaceSpace(self, s): s_len = len(s) space_count = 0 for i in s: if i == ' ': space_count += 1 s_len += 2 * space_count...
cceeed20e00ecbd8f8b89575a45f7fdfe8508164
matrixproduct/Rock-Paper-Scissors
/game.py
1,334
3.765625
4
import random def play(shapes, user_shape, comp_shape, scr): if user_shape == comp_shape: scr += 50 print(f'There is a draw ({user_shape})') else: l = len(shapes) comp_ind = shapes.index(comp_shape) user_win = [shapes[(comp_ind + i) % l] for i in range(1, (l-1) // 2 + 1)...
233b4fb8caceb53e4b0fe740c3c293f569b0ba78
SRCinVA/Unbeatable_tic_tac_toe
/player.py
6,642
4.03125
4
import math import random class Player: # this is a "base" player for use later on. def __init__(self, letter): # "letter" is x or o self.letter = letter #we want all players to get their next move given a game (??) def get_move(self, game): pass # just a placeholder in code. class...
8af0597f7ae742252d29c2cbc0e456ac92dea8ab
SREELEKSHMIPRATHAPAN/python
/python1/co1/18prgrm.py
230
3.625
4
dic={83:'agna',90:'amal',86:'nidhi',88:'mayuri',89:'rasik'} newdic=sorted(dic.values()) print(newdic) newdic=sorted(dic.keys()) print(newdic) newdic=sorted(dic.items()) print(newdic) newdic.sort(reverse=True) print(newdic)
ab8c22fa5b0aecd281799d77c33f4e9702273026
lianfy/ichw
/pyassign3/tile.py
4,896
3.875
4
#!/usr/bin/env python3 """tiles.py: Description of how to pave tiles. __author__ = "Lian Feiyue" __pkuid__ = "1800011733" __email__ = "1800011733@pku.edu.cn" """ import turtle def conflict(a, b, c, d, x, y, count): """定义冲突函数, 如不冲突,可以铺x方向长度为c y方向长度为d的一块砖 count函数用来标记该砖是否被铺过 没铺过为"ym",铺过为"ymwc" ...
2e9008795ff266266ce42c850e3c529e5e2f7aa5
Dasaradhreddy08/DS-Python
/Queue_handson.py
265
3.84375
4
from Queue import Queue q = Queue() for val in range(6): q.enqueue(val + 1) print(q.size()) print(q.peek()) print(q.dequeue()) print(q.is_empty()) print(q.size()) print(q.peek()) for val in range(2): q.dequeue() print(q.size())
3704d5faf77fdb6e7401cd3ea0d399963ab6edfb
haradahugo/cursoemvideopython
/ex068.py
1,035
3.71875
4
## Jogo do Par ou Ímpar from random import randint c = 0 while True: print('\nVAMOS JOGAR PAR OU ÍMPAR!') computador = randint(0, 10) player = int(input('Digite aqui um número inteiro: ')) esc = str(input('Você escolher par ou ímpar [P / I]? ')).upper() s = player + computador if esc == 'P' and ...
7fc6838b24ad9467741fb82fff1d8396bf376dc4
systemquack/csc-212-s16-code-examples
/pa-1/draw-maze.py
2,021
3.78125
4
import Tkinter as tk import sys # draw all vertical walls, line by line def draw_v_walls(canvas, dx, data, l, t): y = t for bin_str in data["v_walls"]: x = l + dx for j in range(data["n"]-1): if bin_str[j] == '1': canvas.create_line(x, y, x, y+dx) x += dx...
b21ab2134253eaf36c93531445e90e77206ee4ae
heroes0710/jake-the-dog
/SSS.py
170
3.828125
4
d=int(input(('please the number between 2 and 9'))) def dan(d): a=0 for x in range(9): a=a+1 b=d*a print(d,"x",a,"=",b) print() dan(d)
a7faec82ac43da7033a2719f98d91d20030f055d
KaushikGhosh27/Python-programs
/Panagram.py
320
4.46875
4
def panagram(phrase): word='abcdefghijklmnopqrstuvwxyz' for letter in word: if word not in phrase: print("It is not a panagram") break else: print("It is a panagram") break ph=raw_input("Enter a string: ") panagram(ph)
04fd8bae1db360830b7cf31a129fccba2b18f0c3
natestutte/Scholarship-Picker
/scholarship_picker.py
4,993
3.515625
4
# Scholarship Picker # Designed and developed by Nate Stutte # # Project created 8.6.2020 # Last update was 8.7.2020 # # Repo : https://github.com/magfmur/Scholarship-Picker import random import sys scholarships = [] scholarshipspool = [] scholarshipstrashpool = [] def create_scholarship_dict(): f = import_fi...
03763ff9ea33917138335fffbb0f41a85117b317
ryanbrown358/learning-python
/functions.py
554
4.03125
4
#functions #create a function def sayHello(name = "John"): print("Hello", name) sayHello() # return a value def getSum(num1, num2): total = num1 + num2 return total numSum = getSum(1,2) print(numSum) def addOneTwoNum(num): num = num + 1 print("Value inside function", num) return num =...
db93f199bf89582789c2f87e5e755edf1de369b0
AbdullahAleiti/Python-CMD-Tools
/Time.py
428
3.71875
4
from datetime import datetime def getTime(toggle): time = datetime.now() year = time.year month = time.month day = time.day hour = time.hour minutes = time.minute seconds = time.second if toggle: print "%s/%s/%s %s:%s:%s" % (year, month, day, hour, minutes, seconds) else:...
5d05edbe244538ee7b35a17bd43fcac20264c41c
Aritra1704/Python_basics
/third_program02.py
252
3.6875
4
def print_name(name): """ This will print a name""" return "This is my name: %s" % name def print_age(age): return str(age) def main(): """ This is the main function """ print "F2 executed" if __name__ == '__main__': main()
f6b24c1d7530de42036bb66172f2477f5e8664b3
hojunee/20-fall-adv-stat-programming
/sol7/ex16-6.py
675
3.90625
4
class Time(object): def __init__(self, h, m, s): self.hour = h self.minute = m self.second = s def mul_time(time, num): mul = Time(time.hour, time.minute, time.second) mul.hour *= num mul.minute *= num mul.second *= num if mul.second >= 60: mul.minute += (mul.s...
ed7d3decba35e3e59878eddb5d35bd3b94725e52
junyechen/PAT-Advanced-Level-Practice
/1150 Travelling Salesman Problem.py
3,848
3.609375
4
""" The "travelling salesman problem" asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?" It is an NP-hard problem in combinatorial optimization, important in operations research an...
5ac82530cb40c2c6e79640cec04280167583ac65
PasHyde/relate
/shingle.py
1,465
4.5625
5
# Assign length of the shingles length = 2 def shingle_letters(string): '''Function to divide a string (text) into shingles. The string is divided (tokenized) into smaller units called shingles of character length k (default length = 2). These partially overlaps to one another. The last characters (...
5a9526447eee5d9e9e26c224725950f87c8091a3
uu64/leetcode
/solution/python3/5.longest-palindromic-substring.py
359
3.5
4
# # @lc app=leetcode id=5 lang=python3 # # [5] Longest Palindromic Substring # # @lc code=start class Solution: def longestPalindrome(self, s: str) -> str: for i in range(len(s), 0, -1): for j in range(0, len(s)-i+1): tmp = s[j:j+i] if tmp == tmp[::-1]: ...
eb83581995c562b269d6e5eacc44d23af3ae77a5
blackmaggot/Euie-JPP-Python
/exircises/fifth.exircise.py
544
3.6875
4
# coding=utf-8 __author__ = 'WiktorMarchewka' import math import cmath def quadratic(a,b,c): #obliczanie delty delta=b**2-4*a*c #warunek ktory zaklada ze delta jest mniejsza od zera, obliczanie x1 i x2 if delta <0: x1=(-b+cmath.sqrt(delta))/2*a x2=(-b-cmath.sqrt(delta))/2*a retur...
67f260227e26bdc72d105833d2a8482552a48e26
hussam-z/ch1
/find the ciriminal algorithm(done).py
1,195
4.03125
4
msg = input("{+} Please Enter the Message => ") letters = "abcdefghijklmnopqrstuvwxyz" # the letters for the caesar cipher msg = msg.lower() # make all the laetter message lower for key in range(len(letters)): msg_decrypted = '' for letter in msg : if letter in letters : nu...
10936eb697410a66f082b3e8edf6889809118b75
Xikan1911/python
/.github/workflows/6.6_slowary.py
426
3.953125
4
world = { 'oka': 'murom', 'nile': 'egypt', 'nuke': 'follaut' } for name, worlds in world.items(): print("The " + name.title() + " runs through " + worlds.title() + ".") world = { 'oka': 'murom', 'nile': 'egypt', 'nuke': 'follaut' } for v in world.keys(): print(v.title()) world = { ...
6e8c60f573713cc5392a4c98245d3c2f89ad6d17
zakaria2905/cryptographie
/Cryptographie.py
4,738
3.6875
4
from itertools import product import time import os def Menu(): #Déclaration du menu principal reponse = 1 while (reponse < 4) and (reponse != 0) : print("\nMenu : ") print("------") print("") print("01. Crypter un message") print("02. Déc...
a03ea39af1980ff20691ea92fc4f896430daea4b
wangyunpengbio/LeetCode
/competition/1038-binarySearchTreetoGreaterSumTree.py
1,315
3.734375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 相当于中序遍历,逆向累加求和,再赋值回去 def bstToGst(self, root: TreeNode) -> TreeNode: # 中序遍历 def inorderTraversal(root: TreeNode) ->...
b9afab99d195361995ffac416266c3fb2f97575a
bl-deepakchawla/ML-Followship-Program
/Python Datastructure/16. WAP to check multiple keys exists in a dictionary.py
328
3.640625
4
def check_multiple_keys_dict(l_dic, l_keys): if all(k in l_dic for k in l_keys): print("Keys", l_keys, " are exists in dictionary,", l_dic) else: print("Keys", l_keys, " are not exists in dictionary,", l_dic) g_dic = {1: 11, 2: 22, 3: 33, 4: 44} g_kyes = (4, 3) check_multiple_keys_dict(g_dic, ...
53375db7f503c96df4fed00b5adca4422c019000
jdlambright/Hello-World
/data structures class/Mergesort.py
820
4.09375
4
def merge_sort(array): if len(array)<=1: return array midpoint = int(len(array)/ 2) left,right = merge_sort(array[:midpoint]), merge_sort(array[midpoint:]) return merge(left,right) def merge(left,right): result = [] left_pointer = right_pointer = 0 while left_pointer < len(left)...
3ed35cbd9f3223c638c8feeae74c7158fe3a7261
jaronjlee/algorithms
/non_constructible_change.py
295
3.59375
4
def nonConstructibleChange(coins): if len(coins) == 0: return 1 coins.sort() maxChange = coins[0] if maxChange > 1: return 1 for coin in coins[1:]: if coin > maxChange + 1: return maxChange + 1 elif coin <= maxChange + 1: maxChange += coin return maxChange + 1
857394dd063536dcb965eec868bd5de8616455b6
63070086/Pyhon
/13Candy.py
211
3.546875
4
"""Mod Division""" def mode(): """input num""" numb1 = int(input()) numb2 = int(input()) div_mode = numb1/numb2 mod_mode = numb1%numb2 print("%d %d"%(div_mode, mod_mode)) mode()
18317eb298c16a0b5e4d005a8e978d74505e09ce
shiftypanda/tutorial-bit-python
/week-2/polysum.py
1,827
4.25
4
# A regular polygon has n number of sides. Each side has length s. # # The area of a regular polygon is: # The perimeter of a polygon is: length of the boundary of the polygon # Write a function called polysum that takes 2 arguments, n and s. # This function should sum the area # and square of the perimeter of the re...
0576d448ff22e80a96ad5c283c2bae782818605a
yafengstark/python-book
/用户输入.py
60
3.75
4
name = input("Please intput your name:") print('Hello'+name)
6b881b401f8cf9f7c1118135e3fa70d21a982b57
hejibo/virtual-reality-course
/Vizard/teacher in a book code snippets (R4)/basic scripting example.py
1,073
3.671875
4
import viz viz.go() ############################################## # ##Add a model. #balloon = viz.add( 'art/balloon.ive' ) ##Set the position of the balloon. #balloon.setPosition( 0, 1.8, 1 ) ## # # ################################ #Add an empty array for the balloons. balloons = [] #Use a loop ...
f0fa6c895c800e46b9c444622afdf98245741e97
wizardkeven/Path-Planning-approaching-dir
/print_path.py
3,870
3.78125
4
# ----------- # User Instructions: # # Modify the the search function so that it returns # a shortest path as follows: # # [['>', 'v', ' ', ' ', ' ', ' '], # [' ', '>', '>', '>', '>', 'v'], # [' ', ' ', ' ', ' ', ' ', 'v'], # [' ', ' ', ' ', ' ', ' ', 'v'], # [' ', ' ', ' ', ' ', ' ', '*']] # # Where '>', '<', '^'...
b824f55f6bb90782ca79d34b42e5385934662379
wangwang1994/copy_paste_report
/批量处理.py
15,754
3.671875
4
import os import re import pprint gongsimingcheng = input('请输入抽检公司名称:') rule = re.compile('^[a-zA-z]{1}.*$') filename = input('请输入文件路径:') os.chdir(filename) filelist = os.listdir() def get_docx_xlsx(filepath): docx_and_xlsx = [] filelist1 = os.listdir(filepath) for file in filelist1: if file.ends...
2f659a36b6760cea0b7165ae61a7e5353e0fc469
Akhil-64/Data-structures-using-Python
/deletion linked list.py
1,160
3.890625
4
class node: def __init__(self,data): self.data=data self.next=None def get_next(self): return self.next def get_data(self): return self.data class linked_list: def __init__(self): self.head=None def deletion_beg(self): if self.head==None: ...
ed1427cc006c11698d3d187c08293d968db1e4b7
lechodiman/iic2233-2017-1
/Tareas/T04/my_random.py
388
3.71875
4
from random import uniform def weighted_choice(choices): '''Returns a random selection from the weighted choices choices : [(choice_1, weight_1), (choice_n, weight_n)]''' total = sum(w for c, w in choices) r = uniform(0, total) upto = 0 for c, w in choices: if upto + w >= r: ...
3e4e43a01d0ad60bfac962f33ce75799189b7eca
FrankCasanova/Python
/Sentencias iterativas/4.2.4-114.py
1,241
4.125
4
#mejora del programa de los menús de diferentes calculos de un circulo from math import pi radio = int(input('Radio: ')) opción = '' repetir = '' while opción != 'd': if repetir == 'y': radio = int(input('Número: ')) print('Escoge una opción: ') print('a) Calcular el diámetro.') print('b)...
2e2feb74b1ef679e6e0caee86f5b90af008c4ee2
dcsheive/Python-Fundamentals
/functions_intermediate1.py
207
3.59375
4
def randInt(min=0, max=100): import random max +=1 max -=min return int(max*random.random()+min) print(randInt()) print(randInt(max=50)) print(randInt(min=50)) print(randInt(min=50, max=500))
bcb2d1ac731fc2cdcb943613a673743f469116a8
amartya-dev/dfbs
/database/initialize.py
1,789
3.71875
4
# Firstly check if database and tables exist if not then create from database.connection import Connection TABLE_FILE = 'table_file.txt' DATA_SEATS = 'data_seats.txt' DATA_FLIGHTS = 'data_flights.txt' TABLE_NAMES = [ 'bookings', 'flights', 'person', 'seats' ] class Initialize: def __init__( ...
5975a785b6e270121d571fc484003a2144829559
pranav300/attendancesystem
/linkedlist.py/queue.py
763
3.859375
4
queue=[10] def push(k,last): if last-first>=10: print("overflow"); else : queue[last]=k; last+=1; def pop(first,last): if first>=last: print("underflow"); last=0; first=0; else: j=first; first+=1; return queue[j]; c=1 first=last=0 w...
63e85276958b4342795f90751f9aee17ee5f8842
marinepal/Intern-Courses
/edx Intro CS and Python/Problem_2_3.py
638
3.59375
4
balance, annualInterestRate = 3392, 0.2 monthlyInterestRate = annualInterestRate / 12.0 low, high = round(balance / 12.0, 3), round(balance * (1 + monthlyInterestRate) ** 12 / 12.0, 3) tempBalance = balance while True: fixedMonthlyPayment = round((low + high) / 2.0, 3) tempBalance = balance for i in range(1...
1369fd07caef230def72f5a2c1100d0111e7e8c3
leoskarpa/K-Coloring-Algorithm
/helper.py
131
3.6875
4
def f(l3): l3.append(-1) l = [[0, 1, 2, 3], [1, 2, 3, 0], [4, 7]] l2 = [0, 1] s = set(tuple(sorted(x)) for x in l) print(s)
b16651fc9ea38aff5f963ac1c014d5f24841c52a
zzz686970/leetcode-2018
/1137_tribonacci.py
1,564
3.578125
4
import functools from time import time def tribonacci(n): a, b, c = 0, 1, 1 for _ in range(n): a, b, c = b, c, a+b+c return a ## maximum recursion depth exceeded def fibs(n): fibs = [0, 1, 1] for i in range(3, n+1): fibs.append(fibs[-1] + fibs[-2] + fibs[-3]) return fibs[n] ## maximum recursion depth ex...
76b6991bc6f701dfa042a11d265a210e803730c6
Kyle-Everett10/cp_1404_pracs
/practical_9/sort_files.py
1,244
3.625
4
import shutil import os def main(): os.chdir("C:\\Users\\kaeve\\Documents\\Files to transfer") print("Currently in{}".format(os.getcwd())) for dir_name, dir_list, file_list in os.walk(os.getcwd()): extension_types_and_directory = create_directories(file_list) move_files(file_list, extensio...
8768ed707dbfe17d38ecd6ccbe44fb2b69ff236b
NikhilJaveri/Academic-Projects
/Real Time Immersive Sound Scaping/ard2py.py
3,159
3.65625
4
import serial # import Serial Library import numpy # Import numpy import matplotlib.pyplot as plt #import matplotlib library from drawnow import * Y_array = [] P_array = [] R_array = [] arduinoData = serial.Serial('com3', 115200) #Creating our serial object named arduinoData plt.ion() #Tell matplotlib you want intera...
7f4caf08a1369dd9f661f5338cc8526e173411d2
ayush1612/5th-Sem
/SL-lab/Lab-1/assignment/prg2.py
204
4.25
4
# creating a tuple with numbers tup = (1,2,3) # print one item of the tuple print("First Item of the Tuple : ",tup[0]) # Convert this tuple to a list ls = [] for i in tup: ls.append(i) print(ls)
2b132d5fbfa7f6dc6f3033095a5e6de9f315db7c
PrasamsaNeelam/CSPP1
/cspp1-practice/m8/GCD using Recursion/gcd_recr.py
572
3.8125
4
''' Author: Prasamsa Date: 7 august 2018 ''' def gcd_recur(a_input, b_input): ''' a, b: positive integers returns: a positive integer, the greatest common divisor of a & b. ''' if b_input > a_input: a_input, b_input = b_input, a_input if b_input % a_input == 0: return a_input ...
3231aa95223b038a426c8db49aea4c793001cc7c
qianjinfighter/py_tutorials
/earlier-2020/python_mod_tutorials/py_thread/threading_local.py
832
3.78125
4
# -*- coding: utf-8 -*- """ threading.local 是为了方便在线程中使用全局变量而产生 每个线程的全局变量互不干扰 """ from threading import local, enumerate, Thread, currentThread local_data = local() local_data.name = 'local_data' class TestThread(Thread): def run(self): print currentThread() print local_data.__dict__ loc...
c02ca2cb199c3125e3e75b057ab5f26e4747efba
aaronkyl/digitalcrafts-python-exercises-flex-02
/week1/20180301-thurs/degree_conversion.py
80
3.78125
4
celcius = int(input("Temperature in Celsius? ")) print(celcius * 1.8 + 32, "F")
618f516f8a84be72de2f290164b5dffaaabf4806
Aynas/14co12
/linearregression.py
938
3.65625
4
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib as mpl #mpl.use('TkAgg') import matplotlib.pyplot as plt dataset=pd.read_csv('Salary_Data.csv') X=dataset.iloc[:,:-1].values y=dataset.iloc[:,1:].values #splitting the dataset into training and test sets from sklearn.model_selection imp...
1c52eccafa1eaa2aec5c997696e45d2e7c8a289c
mascot6699/Code-X
/EPI/bst.py
936
3.90625
4
# Inorder traversal iterative. s is used as a stack. def bst_in_sorted_order(tree): s, result = [], [] while s or tree: if tree: s.append(tree) tree = tree.left else: tree = s.pop() result.append(tree.data) tree = tree.right return ...
1638d7089064781986a263d1875371bbdbb2a20f
AliAsghar1090/official-assignment-01
/9.py
223
4.09375
4
# 9. Triangle area base = float(input("ENTER BASE:")) height = float(input("ENTER HEIGHT:")) area = 1/2*(base*height) print("Area of a Triangle with Height", height, "and Base", base, "is", area )
884180ebf78e289c49ccebab05f6ed181e554212
HsiangHung/Code-Challenges
/leetcode_solution/dynamical programming/#53.Maximum_Subarray.py
445
3.5
4
# 53 Maximum Subarray (easy) # https://leetcode.com/problems/maximum-subarray/ # class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ dp = {0: nums[0]} maxsubarray = nums[0] for i in range(1, len(nums)): dp...
a05d98ac6305c0387bce1f2b9cc2150b3b769d9e
huiyanglu/LearnCodewars
/5 kyu/5kyu_productFib.py
2,208
3.9375
4
""" Product of consecutive Fib numbers https://www.codewars.com/kata/5541f58a944b85ce6d00006a The Fibonacci numbers are the numbers in the following integer sequence (Fn): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... such as F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (fo...
6d63d8b2a5bfd3723954789c0d6a5735390b4cfe
Deeptiii/Coding
/Two Pointer/Pair with Target Sum.py
1,046
3.96875
4
# Problem Statement # # Given an array of sorted numbers and a target sum, find a pair in the array whose sum is equal to the given target. # Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. # Example 1: # Input: [1, 2, 3, 4, 6], target=6 # Output: ...
bb8afa261a1a323891605be42670ab1b9331b672
Liujiuzhen/leetcod
/简单/1.py
504
3.6875
4
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ hashtable={} for i,num in enumerate(nums): if target-num in hashtable.keys(): return [hashtable[target-num],i...
0afcbe1951ee231f9eb265ba9937c382ad61cde1
lsy-GitHub-Vc/Git_Repository_pro
/定制类__枚举类__元类.py
18,629
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #Author:lsy ''' 定制类:python的class中有许多特殊用途的函数,可以帮助我们定制类 ''' '''(1) __str__ : 将实例转换成我们看的懂的数据(看的到实例内的属性) ''' class str_1(object): def __init__(self,name): self.name = name def __str__(self): return 'Student object (name: %s)' % self.name print...
0fac99a0e680e34fb9f6417f9186dbe4f6d572b3
libratears/PyWeather
/weather.py
659
3.578125
4
# -*- coding: utf-8 -*- ''' Created on 2013-9-23 @author: tuyun ''' import urllib2 import json from cityDict import city def getWeatherByCityName(cityname): citycode = city.get(cityname) if citycode: url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode) content = urllib2.url...
f016f961dfea6e1a193332e1b0ed3ffaf1d6bd22
DataXujing/PyTorchIntroduction
/Chapter2/ex_2_11.py
892
4.1875
4
""" 为了能够现实下列代码的执行效果,请在安装PyTorch之后,在Python交互命令行界面, 即在系统命令行下输入python这个命令回车后,在>>>提示符后执行下列代码 (#号及其后面内容为注释,可以忽略) """ import torch t1 = torch.rand(3, 4) # 产生一个3×4的张量 t1 # 打印张量的值 t1.sqrt() # 张量的平方根,张量内部方法 torch.sqrt(t1) # 张量的平方根,函数形式 t1 # 前两个操作不改变张量的值 t1.sqrt_() # 平方根原地操作 t1 # 原地操作,改变张量的值 torch.sum(t1) # 默认对所有的元素求和 ...
e55636f457554299af428d5f1309b6fc19bc7cba
lyf1006/python-exercise
/6.字典/6.4/people_list.py
355
3.5
4
relative1 = {'first_name' : 'John' , 'last_name' : 'Smith' , 'age' : 27 , 'city' : 'Paris'} relative2 = {'first_name' : 'Jack' , 'last_name' : 'Smith' , 'age' : 22 , 'city' : 'China'} relative3 = {'first_name' : 'Mary' , 'last_name' : 'Smith' , 'age' : 19 , 'city' : 'Milan'} people = [relative1, relative2, relative3] ...
448441dc11ce72248c880129a2e61108c9d1f17c
Gau7ham/Send-Emails-Using-Speech-Recognition
/main.py
1,968
3.671875
4
import smtplib # Simple Mail Transfer Protocol import speech_recognition as sr #speech_recognition is named as sr import pyttsx3 # it is python text to speech from email.message import EmailMessage# to structure the email message listener = sr.Recognizer()# this functions recognizes whatever we are saying engine = p...
d217b41e7e1d52454749d20385ca85935012328d
ChallengerCY/Python-PythonTuple
/PythonTuple/TupleDemo1.py
1,225
4.125
4
#元组 #元组与列表一样,也是一种序列,唯一不同的地方是元组不能修改(字符串也是如此) #创建元组的方法很简单,用逗号分割一些值,就自动创建了元组 print(1,2,3) print((1,2,3)) #空元组用()表示 print(()) #表示只有一个值的元组 print(42,) print((42,)) #元组最好用括号+逗号方式,只有括号没有用 print(3*(40+2)) print(3*(40+2,)) #一、tuple函数 #tuple函数与list函数功能基本一致,将一个序列作为参数并且把它转换为元组,如果参数是元组就原样返回 print(tuple([1,2,3])) print(tuple("abc"))...
29be223a3561c09e0db459290859d4aba4d36fcc
sailskisurf23/sidepeices
/lettercount.py
172
3.984375
4
s = 'heLlo'.lower() l = 'l'.lower() result = 0 for x in s: if x == l: result += 1 # Print the number of times letter is in the inputted string print(result)
6616739aff03681b58c396c1c78f7af631d184b4
cyberninjaz/vincent_wayne
/Vince - Coding, 2021/Python/Random Number Generator.py
638
4.09375
4
score = 0 while score == 0: a = input ("What is your starting number for generating? : ") a = int (a) b = input ("What is your ending number for generating? : ") b = int (b) import random print ("Your random number is",random.randint (a, b)) print (" ") print ("Would you like to...
f75c66a3274b1d78009f1d7fcd8e1dd2eb4b30d9
thecubic/python_koans
/python 2/koans/triangle.py
1,145
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # triangle(a, b, c) analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'sca...
243a006d1de0aac932b27dd2cb14aaf24f05b345
npstar/HackBulgaria
/week0/2/count_words-test.py
327
3.53125
4
import unittest from count_words import count_words class CountWordsTest(unittest.TestCase): def test_empty_arr(self): result= {} self.assertEqual(result,count_words([])) def test_arr(self): result={"python":2} self.assertEqual(count_words(["python", "python"]),result) if __name__ == '__main__': unittest...
aba2c52564b65dc02ecd3adde9d1fc3a49a73917
shai2707/learning
/package_A/calculator.py
532
4
4
def add(x,y): return x + y def sub(x,y): return x - y def mulp(x,y): return x * y def devide(x,y): return x / y operator = input("select operator +-*/ ") num1 = int(input("enter your frist number ")) num2 = int(input("enter your second number " )) if operator == '+': print(num1, "+", num2,"=", a...
431c86c6ff79ad323347ab707830053c513bb4ce
Cenibee/PYALG
/python/fromBook/chapter6/sort/61-largest-number/61-m.py
765
3.515625
4
from typing import List from functools import cmp_to_key class Solution: def largestNumber(self, nums: List[int]) -> str: def template(str1: str, str2: str) -> int: if str1 + str2 >= str2 + str1: return -1 else: return 1 nums = [str(x) for x ...
2372c0aab49788147946bf38fb3dce8380f840f0
mamare-matc/Intro_to_pyhton2021
/week12-filetransfer-server.py
1,035
3.53125
4
#!/env/bin/env python3 import socket #create a socket (TCP/IP) myServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #define an IP and Port serverIp = '172.20.1.1' serverPort = 5000 myServerInfo = (serverIp, serverPort) BUFFER_SIZE = 4096 separator = "<separator>" #binding the server info s = socket.soc...
912eb113bd96ad7393f9e3e89130a30245f16905
majsylw/Introduction-to-programming-in-python
/Laboratory 11/6. Cyfry parzyste i nieparzyste.py
1,021
4.03125
4
''' Napisz program, który pozwoli na sprawdzenie czy we wpisanej przez uzytkownika liczbie całkowitej jest więcej liczb parzystych czy nieparzystych. Na potrzeby tego zadania możesz założyć, że użytkownik zawsze wpisze liczbę całkowitą (ale uwzględnij że może być to liczba ujemna). Przykładowe wywołania: Podaj liczbę...
f1b05e13950cb7249f7a3d32348927b61945c276
jilliandanielle/python_pairing_projects
/week1_project1/candy_store.py
1,541
3.953125
4
candy_stock = { 'gummy worms': 456 , 'gum': 217, 'chocolate bars': 156, 'licorice' : 722, 'lollipops': 316 } while True: try: user_initial = int(input("\nEnter the number of how you would like to proceed:\n1. Check current stock levels.\n2. Candy Sales.\n3. Candy Shipment.\n4. Quit...
3d9445f195e014f906fea93e1d058b8243b46d2d
gsailesh/Learnings_2019
/MITx_6.00.1x/Week3/exercises/fibonacci_with_dict.py
266
3.546875
4
''' Efficient Fibonacci computation ''' d = {1:1, 2:2} def fib_efficient(n, d=d): if n in d: return d[n] else: ans = fib_efficient(n-1, d) + fib_efficient(n-2, d) d[n] = ans return ans print(fib_efficient(640,d)) print(d)
28896231ab95d70341af4ce821cc865837cfaa36
wzz482436/1807-2
/03day/12-存家具2.py
2,008
3.625
4
class Home(): def __init__(self,area,address,price,hometype): self.area = area self.address = address self.price = price self.hometype = hometype self.jiaju = []#存放家具 self.dengs = []#存放灯 def __str__(self): msg = "家的面积是%d地址是%s价格是%d万户型是%s"%(self.area,self.address,self.price,self.hometype) return msg...
b6d571414ad9aa3cec3f2e2133bbe7bb4af68398
CH-YYK/leetcode-py
/LeetCode-606-construct-string-from-binary-tree.py
493
3.515625
4
class Solution: def tree2str(self, t): if not t: return "" string = self.preOder(t, "") return string[1:-1] def preOder(self, t, string): if not t.left and not t.right: return string + "({})".format(t.val) string += "("+str(t.val) string =...
9877ee8e96ddd432be304c33990b7fa397994151
youngod2020/Algorithm
/Python/Diagonal_Difference.py
1,029
4.15625
4
## 문제 # Given a square matrix, calculate the absolute difference between the sums of its diagonals. # For example, the square matrix arr is shown below: # 123 # 456 # 989 # 1+5+9 = 15 # 3+5+9 = 17 # |15 - 17| = 2 ## 정답 #!/bin/python3 import math import os import random import re import sys # # Complete the 'diag...
1650ba01c08658b1106e36db669c93a5de7c8612
andreplacet/reinforcement-python-3
/exe07.py
190
4.15625
4
# Exercicio 7 numeros = [] for _ in range(5): num = int(input(f'Digite o primeiro {_ + 1}º número: ')) numeros.append(num) print(f'O maior numero digitado foi {max(numeros)}')
b4f093cd575cf02a58ab9f5974196b306804b392
rajivnagesh/pythonforeverybodycoursera
/assignment13.py
861
4.1875
4
#In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. #The program will prompt for a URL, read the XML data from that URL using urllib #and then parse and extract the comment counts from the XML data, #compute the sum of the numbers in the file. from urllib.r...
bcc05f1f7cfa0e93177b43f67e724c6ff16adff1
Rptiril/pythonCPA-
/chapter-5-practice-set_sets-dict/Qno_6_dict.py
591
4.09375
4
# Create an empty dictionary. # Allow 4 friends to enter their favorite language as keys and their names as values. # Assume that the names are unique. # MyDict = {"C":"Dennis Ritchie", "C++":"Bjarne Stroatop", "Python":"Guido van Rossum", # "SQL":"Donald and Boyce"} # print(MyDict['C++']) FavLang = {} ...
fcabaecc7c066b8140286c127e66dd1a05db1ab4
tjhobbs1/python
/Module4/input_validation/validation_with_if.py
928
4.375
4
""" Program: validation_with_if.py Author: Ty Hobbs Last date modified: 09/18/2019 The purpose of this program is to take a last name, first name and three test scores and return the average of those three scores. It then displays the results to the user. If the user puts in a negative test score it will return a -...
7e3f686fe4e5c80696bdb5d823389ce463d77950
JakubMlocek/Introduction_to_Computer_Science
/Cwiczenia3/zad2.py
774
3.5
4
def czytesamecyfry(pierwsza, druga): pierwsza = sorted(pierwsza) druga = sorted(druga) #print(pierwsza) #print(druga) return pierwsza == druga def czytesamecyfryv2(pierwsza, druga): wielokrotnosccyfr = [0 for _ in range(10)] wielokrotnosccyfrdruga = [0 for _ in range(10)] whil...
52b915eb36411af0506f770031379f0477c883fe
RaianePedra/CodigosPython
/MUNDO 2/DESAFIO69.py
884
4.15625
4
'''Exercício Python 69: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre: A) quantas pessoas tem mais de 18 anos. B) quantos homens foram cadastrados. C) quantas mulheres tem menos de 20 anos.''' t...
9ccfea86f52ffbd53282ee4a868f1e0bff0bab47
Ameya221/Triangle567
/TestTriangle.py
1,727
4.03125
4
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html ha...
09952d0d179155e0f0c736984a0f58cfdae53e70
marco-zietzling/advent-of-code-2020
/day05/day05.py
1,097
3.90625
4
print("advent of code 2020 - day 5") def extract_row(passport): row_code = passport[0:7] row_code = row_code.replace("B", "1") row_code = row_code.replace("F", "0") return int(row_code, 2) def extract_col(passport): col_code = passport[7:10] col_code = col_code.replace("R", "1") col_code...
200df8ad4b0fd8da24bd0270f821d3692d60e5c5
Fdrewnowski/sample-projects
/wirtual-world-game/Turtle.py
723
3.59375
4
import Animal from random import randint class Turtle(Animal.Animal): def __init__(self, world, age, x, y): super().__init__(world, age, 'T', 2, 1, x, y) def action(self, ch): random = randint(0, 3) if random == 2: super().action(ch) def if_reflected_at...
41464293aec0e53bdef2fbbf76676be3ad4f6e88
brendanhasz/probflow-v2
/src/probflow/parameters.py
32,152
3.796875
4
"""Parameters. Parameters are values which characterize the behavior of a model. When fitting a model, we want to find the values of the parameters which best allow the model to explain the data. However, with Bayesian modeling we want not only to find the single *best* value for each parameter, but a probability d...
47ed28fa66c3d1679ad7992a1d1cb2ab0650f718
cppignite/python
/MatchingGame/main.py
1,164
3.859375
4
from random import randint def main(): won = False hiddenarray = ['x'] * 10 array = initarray() while not won: printarray(hiddenarray) first = int(input("Enter number of 1st card: ")) - 1 hiddenarray[first] = array[first] printarray(hiddenarray) second = int(inpu...
21442df33b6aba4effada89bca208ea93ad1162e
wjaram01/Project-1
/Proyecto/Cadena.py
2,234
4.09375
4
# ________________________________________________________________________________________________________________ # 4. OPERACIONES DE CADENAS # ________________________________________________________________________________________________________________ class Cadena: def __init__(self, cadena): s...
0fb9ac544510c7e77c7c8a73bb68248ce4a30ea3
edem98/python-course-code
/TicTacToe/Oriented Object implementation/tictactoe.py
3,808
3.828125
4
class Player: def __init__(self,name,sign): self.name = name self.sign = sign def __str__(self): return self.name class Board: def __init__(self,size=3): self.size = size self.board = [] def create_board(self): self.board = [["a" for y in range(self....
13229b7c7c23c2d2ca9bf5b65e277ac3023188a8
u1718/codeval
/moderate/double_squares.py
3,273
3.96875
4
#!/bin/env python """Double Squares Challenge Description: Credits: This challenge appeared in the Facebook Hacker Cup 2011. A double-square number is an integer X which can be expressed as the sum of two perfect squares. For example, 10 is a double-square because 10 = 3^2 + 1^2. Your task in this problem is, given...
8b121bbcb1a762405a113f2c8e02216d4a9c2038
emberbillow/MultifractalSpectrum
/fileList.py
1,127
3.734375
4
#-*-coding:utf-8-*- import platform import os class FileList(): """ Return the list of files of a specific type in a file folder (e.g.: tif) """ def __init__(self, dir_name, file_type='.tif'): self.dir_name = dir_name self.file_type = file_type self.file_list = []...
41fd69f9470c7ed7534f78b01acd6824cb86d19d
honokame/1e-programing
/kadai6.py
454
3.65625
4
# coding: utf-8 import math print('二次方程式y=ax^2+bx+cの係数を入れてください') a=input('a:') b=input('b:') c=input('c:') d=math.pow(b,2) e=4*a*c if d < e: print('解なし') elif a == 0: if b == 0: print('なし') elif a == 0: x1 = -c/b print ('解は %0.2f です '%(x1)) else: f=math.sqrt(d-e) x3 = (-b + f / (2...
07cc5ef0e123a11b2696fa323e0693449810319c
FranBrinckfeldt/calculadora-py
/vista/calculadora.py
6,432
4.09375
4
from geometria.Circulo import Circulo from geometria.Triangulo import Triangulo while True: print("""¿Qué cálculo desea realizar? 1: Sumar 2: Restar 3: Multiplicar 4: Dividir 5: Calcular el área 6: Calcular el perimetro 0: Salir""") while True: try: opcion = int...
6f11d11e96593ba2061c7d8fca12e423a4ce1de3
824zzy/Leetcode
/A_Basic/Simulation/L1_289_Game_of_Life.py
1,114
3.5
4
""" https://leetcode.com/problems/game-of-life/ The key to in-place operation is almost always to properly code the matrix so that the info is kept. For this problem, when we mark a cell live (i.e. 1) or dead (i.e. 0), we can overshoot the numbers. Namely, when changing 1 to 0 we overshoot it to -1; when changing 0 t...
ed13c556fdaae1195698e228eb21d11408c4f420
flacode/ds_and_algorithms
/palindrome.py
1,077
4.09375
4
from stacks.stack_linked_list import LinkedListStack from queues.queue_array import Queue def is_palindrome_stacks(word): """ >>> is_palindrome_stacks("madam") True >>> is_palindrome_stacks("racecar") True >>> is_palindrome_stacks("palace") False """ S = LinkedListStack() word...
5c808b7a693fbf8b30d561801d0964489a979939
andrewcampi/Type-Bot-Project
/birthday_finder.py
1,704
3.84375
4
import wikipedia def birthday_finder(name): try: result = wikipedia.summary(name, sentences = 1) #convert result into a breakable string converted_result = "" for x in range(len(result)): converted_result += result[x] #find birthday and d...
0d6108f2e8e5f8b38fc27ff3781ac2dbbf2290d3
EliotRagueneau/OBIpython
/Theo.py
4,250
3.546875
4
from myProject import get_genetic_code, read_fasta def read_flat_file(filename): """Load a file in memory by returning a string This function is written by Theo Gauvrit. Args: filename: file to open Returns: string of the whole file (with \n) ...
1579656d2f71cd81029d3a755b2e1d385dd466e5
martelosaurus/investments-problems
/forwards.py
2,336
3.578125
4
import random from stocks import Stock class Forward(Stock): """ Forward class """ def __init__(self,ticker,T): super().__init__(ticker) K = self.S[0]*(1.+self.rF)**T K_act = random.uniform(.8*K,1.2*K) self.attr_dict = { 'T' : T, 'tick' : self....