blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
89debeff8132ce784e860fb26142b91494ecfd93
mtz99/SMC-CS21
/zhang_sine_plot.py
3,931
4.3125
4
# Matthew Zhang # CS 21, Fall 2018 # Program: sine plot """ Module description: This program allows the user to select how they would like to have the sine wave graphed. Either as a vertical or horizontal axis and also either between 0 and pi or 0 and 2pi. """ # Bring in libraries to get access t...
8fef4dc4fa7417584278ee310ef543b15cf15cf4
isakss/Scrabble
/main.py
7,508
4.15625
4
from operations import Operations def choose_letters(player_instance): """Function that allows the player to choose which letters he/she wants to use just needs to press 1 to stop selecting""" letter_input = "" returning_list = [] while letter_input != "1": letter_input = input("Choose a lette...
5eafd2bc7822e5e7f67a5e46acebe4eb3dbc7761
UWPCE-PythonCert-ClassRepos/Self_Paced-Online
/students/Sahlberg/Lesson8/circle_test.py
1,439
3.96875
4
import unittest as u from Circle import * class test_circle(u.TestCase): """For testing Circle module""" def test_radius(self): c = Circle(4) self.assertEqual(4,c.radius) def test_diam(self): c = Circle(4) self.assertEqual(8,c.diameter) def test_area(self): c ...
c57b44eb8875d930743e23a4f7412d9b63dfcb83
HopeMeNow/MDS
/python_basic/week2/task_9/solution.py
131
3.5625
4
n = int(input()) i = 2 Fn1 = 0 Fn2 = 1 Fn = 1 while i <= n: Fn = Fn1 + Fn2 Fn1 = Fn2 Fn2 = Fn i += 1 print(Fn)
64fc5ad9963d54ef65aa7e79e9c6eb09e2eb36c9
caiqinxiong/python
/day07/day7/12.组合练习.py
1,609
4.1875
4
# 学生 : 姓名 性别 年龄 所学习的课程 # class Student: # def __init__(self,name,sex,age,course): # self.name = name # self.sex = sex # self.age = age # self.course = course # class Course: # def __init__(self,cname,period,price): # self.name = cname # self.period = period # ...
2788974828e4416fa9054217885ab3a3a8f16195
Jhy1993/Data-Structure
/bishiti/juzi_fanxiang.py
537
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 23 15:38:19 2016 @author: Jhy1993 """ n = raw_input() nums = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"] nn = list() for i in range(int(n)): fenshen = raw_input() num = [] for shuzi in nums: # print shuzi if...
2fba683578ccc9667fee55c7f18a2ab28f9b34e5
lauren-juskelis/automate-the-boring-stuff
/mad_libs_1.py
754
3.875
4
# This program lets the user play Mad Libs, using a .txt file as the # source data. import re, os, pathlib # Create a function to replace buzz words: def mad_libs_function(our_file): tester = 1 mad_libs_re = re.compile(r'ADJECTIVE|NOUN|ADVERB|VERB') while tester == 1: try: ...
466471102d59a9320f1721fab03c2992bd0d0a21
IOntUMAtIp/introducao-a-ciencia-da-computacao-com-python-parte-01
/semana 07 exercicio complementar 01.py
132
3.671875
4
def maior_elemento(lista): maior = 0 for i in range(len(lista)): if lista[i] >= lista[i - 1]: maior = lista[i] return maior
4b8b153414cff8af6ce3a0d7e723bfd0e54b5088
memiles47/UdemyPythonProgrammingMasterClass
/Section4/Searching.py
525
3.640625
4
__author__ = "Michael E Miles" shoppingList = ["milk", "pasta", "eggs", "spam", "bread", "rice"] itemToFind = "spam" # itemToFind = "albatross" foundAt = None # for index in range(6) # for index in range(len(shoppingList)): # if shoppingList[index] == itemToFind: # foundAt = index # break if itemT...
3469e2477676c7ea2613d0316a1e6ae9e0d7bf97
purringpower/Homework_Lesson_10
/task2.py
265
3.859375
4
import os import datetime # 1 print(os.path.abspath(os.curdir)) # 2 my_date =input("Your date:") day, month, year = (int(x) for x in my_date.split('.')) ans = datetime.date(year, month, day) print(ans.strftime("%A")) print(ans.isocalendar()[1])
02dd70396dbd26e71684586fc6e3995a155c72e0
ShivaniTamilselvam/Python
/not is.py
212
4.0625
4
def is_group_member(group_data,n): for value in group_data: if n== value: return True return False a=input("enter the group") b=input("enter the group_member") print (is_group_member(a,b))
abb33f34e13ab60f3fed7565061bf5f61fb09170
kurtrm/data_structures_rev
/tests/test_merge.py
1,217
3.53125
4
"""Test merge sort.""" import pytest from random import randint to_sort = [ ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), ([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), ([10, 9, 8, 17, 6, 300, 4, 3, 2, 11], [2, 3, 4, 6, 8, 9, 10, 11, 17, 300]) ] def test_merg...
7861bc48fb8b4d373f9df89435feb57a31435ef1
vinchuco/tutorials
/python/fundamentals/17_functions.py
214
4.125
4
def add(x, y): # Add the contents of two variables x and y return x + y # No longer in the function z = add(1, 2) # Call the function and store its result in the variable z print "Return value of add:", z
912033912c9a33bfe5ca97f337528502015a3eeb
xiaoqieee/firstpython
/test1/iterater/FibIterator.py
489
3.53125
4
class FibIterator(object): def __init__(self, all_num): self.all_num = all_num self.a = 0 self.b = 1 self.idx = 0 def __iter__(self): return self def __next__(self): if self.idx < self.all_num: ret = self.a self.a, self.b = self.b, se...
daf0806cbb24474f7d5b23b7441bca69e575f80c
AfonsohsS/DataScienceCurso2_Pandas
/R7 Criando Agrupamentos.py
3,087
3.8125
4
# Criando Agrupamentos import pandas as pd dados = pd.read_csv('aluguel_residencial.csv', sep = ';') dados.head(10) dados.Valor.mean() ## Link para cheatSheet de funções estatísticas do panda ## https://pandas.pydata.org/pandas-docs/stable/reference/frame.html#computations-descriptive-stats # Buscando o valor méd...
03af04dc18cc77b611d748331e67226bb92f1776
minhd2/time2code
/sort_by_date/sort_by_date.py
592
3.796875
4
import re from datetime import datetime def sort_by_date(file): file_date_dict = {} pattern = r"\w* \d+, \d{4}" with open(file, 'r') as file: for line in file: columns = line.split() date = re.search(pattern, line) print(line) file_date_dict[columns[-1]] = file_date_dict.get(columns[3], date.group(0)...
4803317e3aa0b21f16960b54afed325ae4c0c16b
IfDougelseSa/cursoPython
/exercicios_secao5/4.py
184
4.1875
4
# Número positivo ao quadrado e sua raiz import math x = float(input("Digite o numero: ")) if x >= 0: print(f'{x ** 2},{math.sqrt(x)}') else: print("Número inválido!!")
71241a7093805ed0b109d09c17ee4a30c0f26522
xizhang77/LeetCode
/Previous/maxSubArray.py
759
4.0625
4
# -*- coding: utf-8 -*- ''' Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution...
45cd27a009bdb7a556aec259ffa62c4839826181
valerykurak/Tasks
/task1/python.py
75
3.5625
4
n = int(input()) text = raw_input() for i in range(n): print(text * n)
d746915d5c4c52c0bc5397dcaea4f44252568a36
SoumyajitBasu28/Python-Lab-Assignments
/Assignment3/Prog 6.py
353
4.21875
4
#6. Find the second maximum from a list of integers. #Input/output: #User will give a list of integers #the program will print the second maximum of the list. #In case of multiple occurrence of maximum value or a single number in the list, the #second maximum will be also the maximum number. l = list(map(int, input()....
3f564cd5c54341f713106ee59c877354aefbd723
SkaTommy/Pythongeek
/Lesson6/Example1.py
1,344
3.65625
4
# 1. Создать класс TrafficLight (светофор) # и определить у него один атрибут color (цвет) и метод running (запуск). # Атрибут реализовать как приватный. # В рамках метода реализовать переключение светофора в режимы: красный, желтый, зеленый. # Продолжительность первого состояния (красный) составляет 7 секунд, # второг...
1dae639bbc79306f9442fe93de94e29f00eaa683
biancaleeyx/projectEuler
/022_names_scores.py
1,179
3.890625
4
""" Project Euler Problem 22: Names scores Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the l...
145fa2b0bf566569b17c387d06783c9f17abcd2b
Yairo/Python-for-Everybody-Specialization
/10.2 v1.py
1,490
4.09375
4
""" Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Onc...
f127e50f55953403bc994c2013c465ecce4b713e
GDashBoss/python-1
/review/hi
249
4
4
#!/usr/bin/env python3 import colors as c print(c.red + "OMG " + c.blue + "HI! " + c.yellow + "I need your " + c.red + "name " + c.yellow + "so I can hack you!") name = input (c.red + '>' + c.blue) print(c.yellow + "Prepare to be hacked sucker!)
22fbda36896c0e0d0b7f69a5c44cc572c6ee0d46
Gorpo11/supreme-guacamole
/Learn.py
616
4
4
age = 24 name = 'Gogol' print('Привет {0}, тебе уже {1}'.format(name, age)) i = 5 print(i) i = i + 1 print(i) s = '''Это много сторчная строка Это вторая ее строчка а это третья''' print('Привет вот пример для обучния многострочной строки {};\r\nВот это все!'.format(s)) lenght = 5 height = 3 print('Длина {} а ширин...
efc58c2209f2273c5790372d013bbd9e3f466777
r4rathore/CodeChef
/PrimeNumber.py
526
4
4
import math import time # 1st solution Time Complexity O(n) def isPrime1(n): for x in range(2, n): if(n % x == 0): return False return True def isPrime2(n): limitRange = math.floor(math.sqrt(n)) for x in range(2, limitRange): if(n % 2 == 0): return F...
e0a675a602dad3745ba602e99ef1dcb5f563a7e1
lopz82/exercism-python
/twelve-days/twelve_days.py
754
3.609375
4
from typing import List GIFTS = """twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree""".replace( "\n"...
2445650c6d358e71cd866a0ad1e818479cf61795
zzz686970/leetcode-2018
/594_findLHS.py
439
3.59375
4
# -*- coding: utf-8 -*- # @Author: zzz686970 # @Date: 2018-12-14 00:11:40 # @Last Modified by: zzz686970 # @Last Modified time: 2019-01-18 12:36:05 def findLHS(nums): ## get num:freq for nums, if key+1 also in dict then concatenate them ## calculte the sum of freq for this sequence import collections d = colle...
253e1d110af62974203314464123da0980c4c3d7
vm7151810/BoT
/whatsapp_bot.py
1,168
3.609375
4
from selenium import webdriver driver = webdriver.Chrome()#install the chrome divers for this code to work(accordance to your chrome version) driver.get('https://web.whatsapp.com/') name = input('Enter the name of user or group : ')#whom you wanna sent msg = input('Enter your message : ')#what you wanna sent input('Ent...
ee7e286e1807474028ed89639a1fb4da1e746088
MaryferMejiaChavez/IA_MejiaChavezMariaFernanda_GomarSalvadorJuanManual
/Reinas_GomarSalvadorMejiaChavez/Reinas.py
3,273
3.5
4
############################################# # Gomar Salvador Juan Manuel # # Mejía Chávez María Fernanda # ############################################# print('#----- R E I N A S-------#') print() matriz =[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] #guarda posicion posAct=[] l...
4702391e7097acfbca41cf545e8cbdbe37ab2962
rupaku/Leetcode-solutions
/May/23CountingBits.py
495
3.84375
4
''' Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2 Output: [0,1,1] Example 2: Input: 5 Output: [0,1,1,2,1,2] ''' # Solution:::::::::::::::::::::: class Solution: def...
f803b3abba1bbe30f870244d921a77d120a39c1d
nthomps49/firstlocalrepos
/PythonLearning/chinaindia.py
535
3.6875
4
from __future__ import print_function import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib as mpl years = map(str, range(1980, 1984)) df_chinaindia=pd.read_excel(r"C:\Users\natha\Documents\GitHub\firstlocalrepos\PythonLearning\chinaindia.xls") print(df_chinaindia.head()) #this kind...
1a49df2a0943e41e85389646e9a721acd1b90881
satuhyva/100daysOfPython
/Day 024/practicing/snake.py
1,886
3.625
4
from turtle import Turtle DISTANCE = 20 START_POSITIONS = [(0, 0), (-DISTANCE, 0), (-DISTANCE * 2, 0), # (-DISTANCE * 3, 0), (-DISTANCE * 4, 0), (-DISTANCE * 5, 0), (-DISTANCE * 6, 0) ] class Snake: def __init__(self): self.snake_bits = [] self.create_sna...
62a65522e86a6a53f814ba4a03d05e9d834a1cbb
ruifan831/leetCodeRecord
/109_Convert_Sorted_List_to_Binary_Search_Tree.py
1,930
4.1875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # ...
52d64870906d658e5abb5547274cef4bba2ca7a3
himanjal/FI_Simulator
/mask.py
1,215
3.6875
4
import sys ''' Recieves integer value of a register The values are changed by the algorithm in the mask function and returned to the backend.py to set new register value ''' def mask(operation, registerValue, opValue = None): resultVal = None flag = False val = None if registerValue[0:2] == "0x": va...
7c8dcb3a96ceb6fb8bde2c0f68159c322b04c0ce
0421cjy/pygames
/04_columns/columns.py
3,888
3.578125
4
# 가로, 세로, 대각선으로 3개의 블록이 같으면 깨진다. # 빨, 주, 노, 초, 파, 보 # 변경을 누르면 아래꺼 빼서 맨 위로 보냄 # 3 -> 1 # 2 -> 3 # 1 -> 2 # 가로 6칸 # 세로 13칸 # 블록 하나 3칸 import sys, pygame import random import time TARGET_FPS = 3 # colors white = (255, 255, 255) color_list = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] bloc...
edd271129172b0f8b6e8d41ddf6304e08b95734e
SuMarsss/exam
/leetcode/1217.py
450
3.546875
4
class Solution(object): def minCostToMoveChips(self, chips): """ :type chips: List[int] :rtype: int """ size = len(chips) odd_cnt = 0 even_cnt =0 for i in range(size): if chips[i] % 2 == 0: even_cnt += 1 else: ...
f9ab9e3959f9f9ac4e4eed56dc38b17e13d2d6c0
send2manoo/All-Repo
/myDocs/pgm/c/Exercise/dictionary.py
145
3.953125
4
print "dictionary" dic={ "name":"manohar", "age":23, "color":"black" } inp = raw_input("Enter the key..") print "value is=",dic.get(inp,-1)
057ace520eb0291a89c2dfc970385f2d7700c913
MugPand/2D-Ray-Casting
/light.py
1,187
3.671875
4
import pygame import math from ray import Ray # define light class class Light: # constructor for new light object def __init__(self, x1, y1, n): self.x1 = x1 self.y1 = y1 self.rays = [] self.n = n for i in range(0, 360, int(360 / n)): self.ray...
9e59d0a1cfd89f09a76649c7bd602f5b208b6e97
MycroftAI/lingua-franca
/lingua_franca/lang/format_nl.py
11,427
3.765625
4
# # Copyright 2017 Mycroft AI Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
17d143dfd6c392f22fe76d57fa3401de0670bec4
kruglov-dmitry/algos_playground
/rle.py
1,588
3.75
4
""" https://leetcode.com/problems/string-compression Given string, possible empty: AAAABBBCCXYZDDDDEEEFFFAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB we need to implement RLE (run length encoding) which produce following result: A4B3C2XYZD4E3F3A6B28 Notes: If symbol appears only once it doesn't changed If symbol appea...
49b7d4152e369787ba650796d637ed5e374e5f98
unexpectedCoder/simpy_Carwash
/src/main.py
2,573
3.875
4
from typing import Generator import random import simpy class Carwash: """A carwash has a limited number of machines to clean cars in parallel. Cars have to request one of the machines. When they got one, they can start the washing processes and wait for it to finish (which takes ``washtime`` minutes). ...
1b47731129211cac01ad863913268c4c09873242
python-advance/sem5-t2-TsirulikIvan
/var1.py
174
3.546875
4
import itertools def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b num = 10 print(', '.join(str(i) for i in itertools.islice(fib(), num)))
f1c20a5c796278656bd1e7c9694de69f672db39f
sachinlokesh05/Python-progrmas
/stopwatch/stop_watch.py
310
3.984375
4
import time as t class stopwatch: x=int(input("enter 1 to start")) start=t.time() y=int(input("enter 0 to stop")) stop=t.time() eclapsed_time=stop-start print("starting time is:",start) print("ending time is :",stop) print("total time taken is:",eclapsed_time) t=stopwatch()
01468e0cdd0b7e63e366176b0d1474660ab8609d
WongWai95/LeetCodeSolution
/36. 有效的数独/Solution.py
1,265
3.65625
4
class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: '''check for row valid''' for i in range(len(board)): hash_set = set() for e in board[i]: if not e == '.': if e in hash_set: return False ...
df8d9e313df21ea1d1be472d6885ed77f28a5309
punithakur/tea-and-coffee-machine
/tcvm.py
3,028
3.921875
4
from model import * class app: tea=2000 coffee=2000 sugar=8000 water=15000 milk=10000 choise=0 teacount=0 blkteacount=0 coffcount=0 blkcoffcount=0 def start(self): while True: self.printoption() if app.choise==1: ...
42fe81bb4711a1cc9f4106876707a85e78b937df
anmutu/arithmetic
/leetcode/01array/05single-number.py
1,666
3.921875
4
# _*_ coding :utf-8 _*_ __author__ = 'du' __github__ = 'www.github.com/anmutu;' __date__ = '2020/5/18 20:03' # https://leetcode-cn.com/problems/single-number/ # 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 # 说明: # 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? # example # 输入: [4,1,2,1,2] # 输出: 4 def single_number(nums): ...
e59bfc233bf6319617f6a08aebd3ece92b9db158
Smurfs-LYQ/Python
/day2/1.py
486
4.09375
4
#!/usr/bin/python3 # 格式化输出 ''' ---%:占位符--- %s:占位字符串 %d:占位数字 注意: 1. 如果在格式化输出中要输出%符号,那么需要再加一个%用来转义一下 %% ''' name = input('请输入你的名字:') sex = input('请输入你的性别:') age = input('请输入你的年龄:') res = ''' -----------%s的信息------------ 姓名:%s 性别:%s 年龄:%d -----------end------------ '''%(name,name,sex,int(age)) print(res)
df39013a7f17d02b2a97bdebc36104ad5eebd632
Jochs1989/CSC-121
/M1HW1_Debugging_JeffreyOchs.py
664
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 13:05:48 2020 This will create a table of squares and cubed numbers 01/27/2020 CSC121M1HW1-Degbugging Jeffrey Ochs """ # Asks the user how many times they would like to the program to loop loopAmount = int(input("How many times would you like to Square/Cube...
20cc97397e537b88d2492970589e6c168df8f2e3
deepanshululla/DataStructuresAndAlgo
/python/graphs/reachability.py
1,568
3.5625
4
''' Given a directed graph, a source vertex ‘s’ and a destination vertex ‘d’, print if 'd' is reachable from ‘s’. ''' from pythonds.graphs import Vertex,Graph; from pythonds.basic import Queue; import unittest; class ReachGraph(Graph): def __init__(self): super().__init__() def isReachable(self,u,v):...
3708a6ba5951e7ccc30b7bc7ba2de015f59e353f
GlennNicholas/CP1404practicals
/Prac_01/shop_calculator.py
582
3.984375
4
def main(): total_price = 0 number_item = int(input("Enter No. of items: ")) while number_item <= 0: print("Invalid Input") number_item = int(input("Enter No. of items: ")) for i in range(number_item): item_price = float(input("Price of item: ")) ...
535ef1555f7340cf22ce405c374392fb709d646d
connielei-stuy/old-public-html
/hw/55/triCGI.py
885
3.828125
4
#!/usr/bin/python print "Content-type: text/html\n" print "" import cgi import cgitb from math import sqrt def FStoD(): ''' Converts cgi.FieldStorage() return value into a standard dictionary ''' d = {} formData = cgi.FieldStorage() for k in formData.keys(): d[k] = formData[k].value ...
608c135ebd1640690a98dc8bc1246a846846c349
okliou/lcode
/String/two.py
1,270
4.03125
4
class Solution: """ 给定一个 32 位有符号整数,将整数中的数字进行反转。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。根据这个假设,如果反转后的整数溢出,则返回 0。 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 """ def reverse(self, x): """ :type x: int :rtype: int """ if -2**31 ...
d83c3bf61e00c9c6f6d144c8e5886dd02642ac7d
Swift-2016/Python
/Python35-IDEL/demo2.py
125
3.765625
4
n = input(" 请输入整数 N: ") Sum = 0 for i in range(int(n)): Sum += i + 1 print("1 到 到 N 求和结果: ", Sum)
cb43ea95276a97f5154119b60951f5855e826864
VinayMV/Python-Django
/per.py
609
3.984375
4
def percentage(total_amount,discount_amount): if not(type(discount_amount)==float and type(total_amount)==float): return ("Invalid arguments") if total_amount <= 0: return ("Invalid Case.Division by Zero is not possible!") return (discount_amount/total_amount)*100 def main(): to...
4ae87f453613fc87a2a886875e066879097bd3d4
j-chandler/Web-Portal
/server/Apps/utility/output_write.py
1,818
3.859375
4
import csv import codecs def write_dictionary_list(dictionary_list, file_path, encoding = 'utf-8-sig', appending = False): """Writes a csv of a dictionary list to the chosen file path""" if not appending: style = "w" else: style = "a" with codecs.open(file_path, style, encoding = encod...
00f11776005b025b6ba870c017ca5fc993415c11
pinple/leetcode
/mathematics/pascals-triangle.py
611
3.75
4
""" 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 在杨辉三角中,每个数是它左上方和右上方的数的和。 示例: 输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ ans = [[1] * n for n ...
d50d663e07201d214d1483237764a5fda021d21b
ftrijillo/PythonFiles
/gameclasses.py
3,847
3.796875
4
#!/usr/bin/env python3 class Game: def __init__(self, noOfQuestions=0): self._noOfQuestions = noOfQuestions @property def noOfQuestions(self): return self._noOfQuestions @noOfQuestions.setter def noOfQuestions(self, value): if value < 1: print("Minimum questi...
0e6e4ffeb673e41d6a8293dc1f2502fe493bf352
chang-jing0/ycsh_python_course
/期末考/season.py
260
4.0625
4
x = int(input("請輸入一個整數 : ")) if x==2 or x==3 or x==4 : print('春天') elif x==5 or x==6 or x==7 : print('夏天') elif x==8 or x==9 or x==10 : print('秋天') elif x==11 or x==12 or x==1 : print('冬天') else : print('輸入錯誤')
fb39e65c12a754edc8e557b2343efb1c61cd48df
frankwwu/machine-learning-exercise
/coursera-machine-learning-python/ex8/cofi_cost_func.py
1,599
3.84375
4
import numpy as np def cofi_cost_func(params, Y, R, num_users, num_movies, num_features, l): """ Returns the cost and gradient for the collaborative filtering problem. Parameters ---------- params : ndarray, shape ((num_users + num_movies) * num_features,) Parameters for collaborative fil...
bc34b1a053d35f2538daa08bba43fd422b8641bd
kknet/AlgorithmicTrading
/portifolioEvaluator.py
6,330
3.515625
4
__author__ = 'kmanda1' import numpy as np import predictorGenerator as helper import pandas as pd def compute_portvals(start_date, end_date, orders_file, start_val): """Compute daily portfolio value given a sequence of orders in a CSV file. File contains - list orders Load historical data Execute th...
900a508e93849cc805aeec2f98b3acd1ec528169
orchsik/jhpar
/python/BFS/basic/ex1.py
601
3.671875
4
# s에서 f로 가는 최단 경로를 구하세요 graph = {} graph['s'] = ['a','b'] graph['a'] = ['c', 'f'] graph['b'] = ['c', 'd'] graph['c'] = [] graph['d'] = ['f'] graph['f'] = [] from collections import deque def search(name): search_queue = deque() search_queue += graph[name] searched = [] while search_queue: site = search_...
99fdd85c63de8eed27f59f9b7c9deafdd5e90fbc
shen-huang/selfteaching-python-camp
/19100104/fan101105/d6_exercise_stats_word.py
5,277
3.703125
4
text = ''' The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although pr...
cb4b2e7eb07911747f06fba184d7358dda116ce5
Aaxom/geek-camp
/week03/课后作业/前序遍历与中序遍历构造二叉树.py
2,137
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: # 终止条件 if not preo...
b21e4633ffe4be8c39cd0bf65225c27ba13e4e06
mxrxtx/pykeymopad
/pykeymopad.py
5,797
3.546875
4
from time import sleep import pygame import win32api import win32con # We start the necessary modules pygame.joystick.init() pygame.display.init() # checks if the modules are started print("Joystick Module Status ==> ", pygame.joystick.get_init(),"\nDisplay Module Status ==> ", pygame.display.get_init()) # Freezes ...
2149337077daa9565cb97f4d6a56104860740a50
HawkinYap/Leetcode
/jz_25.py
720
3.703125
4
# -*- coding:utf-8 -*- class RandomListNode: def __init__(self, x): self.label = x self.next = None self.random = None class Solution: # 返回 RandomListNode def Clone(self, pHead): # write code here if not pHead: return None newhead = RandomListNod...
64d096d657f69f30c866c3198be7e457cd7c8c37
BauerJustin/Elements-of-Programming-Interviews-in-Python
/Ch.5 Arrays/5.13 Random sampling 2/random_sampling_2.py
331
3.75
4
import random import itertools # code def random_sampling(size, A): current = list(itertools.islice(A,size)) num = size for item in A: num += 1 index = random.randrange(num) if index < size: current[index] = item return current print(random_sampling(5, [1,2,3,4,5,6,...
16147e48b121742e97c7449f51094e7b8f1b4e0a
jiwxyzonlee/deepLearning
/20200316/2020_03_16/scatter_graph01.py
401
3.71875
4
# scatter_graph01.py # 산점도 함수 scatter() # 배열 생성 패키지 #import numpy as np import matplotlib.pyplot as plt #x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) #y = np.array([9, 8, 7, 9, 8, 3, 2, 4, 3, 4]) x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [9, 8, 7, 9, 8, 3, 2, 4, 3, 4] plt.figure(figsize=(10, 6)) plt.scatter(x, y ...
82a88a1b072b0ff09662778b7064f064cd22a882
AntonSergeqich/GeekHttps
/Less6/ls6_dz1.py
1,611
3.578125
4
# Создать класс TrafficLight (светофор) и определить у него один атрибут color (цвет) и метод running (запуск). # Атрибут реализовать как приватный. В рамках метода реализовать переключение светофора в режимы: красный, желтый, # зеленый.Продолжительность первого состояния (красный) составляет 7 секунд, второго (желтый)...
71ea8d2734a4ea61d3fcdd5056c9296bca9452cd
davepierre23/financeParser
/animeDb.py
4,451
4
4
import sqlite3 #https://likegeeks.com/python-sqlite3-tutorial/ nameOfDatabase = "animeTracker.sqlite" db = sqlite3.connect(nameOfDatabase) def create_table(): db=create_connection(db_name).cursor() db.execute("CREATE TABLE IF NOT EXISTS user(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") db.execute("CREATE...
d533a211d66905e93ba1a9c37bd4f9b00aff2e49
Vania03/Curso-Python-Intersemestral
/CursoPythonBásico/Clase3/Diccionario.py
590
3.96875
4
diccionario={1:"Opcion 1", 2:"Opcion 2", 3:"Opcion 3"} #list casteamos a una lista #keys nos lleva a las llaves lista=list(diccionario.keys()) #pero esta en desorden, entonces hay que ordenarlos lista.sort() print(lista) while True: for llave in lista: print("\t%s. %s"%(llave,diccionario[llave])) seleccion=int(...
58e843528de9b23090928a8afd278971704b33c9
1sucong/NewSalesPrediction
/quick_sort.py
653
4.0625
4
def quick_sort(lists,i,j): if i >= j: return pivot = lists[i] low = i high = j while i < j: while i < j and lists[j] >= pivot: j -= 1 lists[i]=lists[j] while i < j and lists[i] <=pivot: i += 1 lists[j]=lists[i] lists[j] = pivot ...
f59bb1fbf9ee4904cf56e0fbec0d3d4f5c8b4d9a
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_84/172.py
1,179
3.765625
4
import sys def read_string(): return sys.stdin.readline().strip() def read_strings(): return read_string().split() def read_integer(): return int( read_string() ) def read_integers(): return [ int( x ) for x in read_strings() ] T = read_integer() for t in range( T ): print 'Case...
c7f1db6a386c1f0586451bcfeb7acb2476b80866
ErickMwazonga/learn_python
/logic/check_freq2.py
186
3.6875
4
def check_freg(str): freq = {} for c in str: freq[c] = str.count(c) return freq print(check_freg("abbabcbdbabdbdbabababcbcbab")) # {'a': 7, 'b': 14, 'c': 3, 'd': 3}
5d56effd744d4f6fc218ea540e7d5b6bf287cb83
javiermms/cs1.3
/set_operations.py
2,289
4.1875
4
class Set(object): def __init__(self, elements=None): """Initialize set with the given data.""" self.elements = [] self.size = 0 if elements is not None: for item in elements: self.add(item) def __repr__(self): """Return a string representation of this node.""" return 'Set: {!r} Size: {!r}'.form...
0edc5a15bb41e587e3c47d0d986eea4c2023cf10
himu999/Python_Basic
/C.condition/leapyear.py
299
4.28125
4
# Remember year must be greater than 1581 year = int(input("Select a random year : ")) if year <= 1581: print("Year must be greater than : 1581") elif (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0): print(year, " : is a leap year") else: print(year, " : is not a leap year")
0cde47a642a73ac5df571dde8867a4ef07a17309
larajorge11/python-davor-training
/classes/cubo.py
555
3.640625
4
class Cubo: def __init__(self, ancho, alto, profundidad, *valores, **terminos): self.ancho = ancho self.alto = alto self.profundidad = profundidad self.valores = valores self.terminos = terminos def calcular_volumen(self): return self.ancho * self.alto * self.pro...
0d99ad5ff6bf3d840d69115cbdba71c9d8382cfe
Aasthaengg/IBMdataset
/Python_codes/p04019/s460147194.py
191
3.96875
4
from collections import defaultdict S = input() dic = defaultdict(bool) for s in S: dic[s] = True if dic["N"] != dic["S"] or dic["W"] != dic["E"]: print("No") else: print("Yes")
f384e093559572a01caaa9d64b103ee2e45e0409
GaoFan98/algorithms_and_ds
/Coursera/11_fractional_knapsack.py
1,611
4.0625
4
# Uses python3 import sys def get_optimal_value(capacity, weights, values): """ Input: 3 50 => number of items/ capacity of bag 60 20 => value/weight of item 100 50 => value/weight of item 120 30 => value/weight of item Output: 180.0000 max number of fractions in bag in thi...
96ded26464987c898cee1177234b31353d4c995a
muziqianjunxiu/DataStructureInPython
/Queue/CircularSequenceQueueDefine.py
2,975
4.125
4
class CircularSequenceQueue: ''' 元素个数:(rear-front+MaxQueueSize) % MaxQueueSize 队空条件:front==rear 队满条件:front==(rear+1) % MaxQueueSize 顺序存储即采用数组存储元素,以下标值 为依据 访问操作 ''' #初始化循环顺序队列 def __init__(self,MaxSize): self.MaxQueueSize=MaxSize+1 self.s=[None for x in range(0,self.MaxQueueSi...
a18679698c22ea8f25793266beb0f5d30622aca8
rendersonjunior/UriOnlineJudge-Python
/1016_Distance.py
80
3.609375
4
#cars x and y km = int(input()) time = km*2 print(str(time)+" minutos")
0880b516ed4597aa55028ba63c25c0da37ed0f76
JulioBatista95/Cursos-de-Python
/Curso em Vídeo/Mundo 1/Pycharm Aula 5 em diante/Exercícios/ex017.py
522
4.03125
4
#import math #b = float(input('Digite o valor do cateto oposto ')) #c = float(input('Digite o valor do cateto adjacente ')) #a = b**2+c**2 #h = math.sqrt(a) #print('Com o cateto oposto de {}, e com o cateto adjacente de {},\na hipotenusa é {:.2f}'.format(b, c, h)) from math import hypot b = float(input('Digite o valor ...
e2d19d1f515c6c5a2b1110fc1a8a1055eacbb64d
ChristopherMorrison/advent-of-code-2018
/5/1sol.py
831
3.734375
4
# input data data = open("input.txt").read() data.strip() alphabet = "abcdefghijklmnopqrstuvwxyz" def react(data): # iterate until no changes are made on the condensing process changes_made = True while changes_made: changes_made = False data_size = len(data) for character in alpha...
f5fea35a1e464dc9c049a0fb0756fef861d5f07d
atikurrahmanm3/python_programming
/test/p6-pr-06.py
112
3.9375
4
name = input("Enter your name:" ) date = input("Enter a date:" ) print(f"Dear, {name} you are selected {date}")
b14907961a9308909fe5c1a9eeb5774973853fa6
rustylife42/Russ-pository
/dateTime.py
313
3.5625
4
# Program Name: dateTime.py # Program Author: Russell Holmes # Last Edit Date: 10/19/2020 from datetime import datetime, timedelta def half_birthday(year, month, day): birthday = datetime(year, month, day) return birthday + timedelta(weeks=24) if __name__ == '__main__': print(half_birthday(2000, 1, 1))...
16ba5e6ae3a0ae742c81a7005655f7daef4d3b55
davidgascon/qr_reader-scanner
/misc/last_name_cleanser.py
1,599
4.375
4
#used to clean the data from the original last names csv. #initially I used pandas, but I quickly learned it would be easy to work with the csv file rather than the data type that pandas imported it as. I realized this when I tried to clean each name. #The main difference between this and first name cleanser is how the...
f44b773839c28a44a34f61d1792a4abaa3cc38ce
KrishothKumar/Python_Practice
/birthday.py
1,164
4.34375
4
# This program is used to view birthday date based on name def birthday_date(user_name,birthday_dictionary):# Input as Name and Dictionary dummy_list = [] for new_data in birthday_dictionary["birthday"]: # It take each data and validate the name in Dictionary if new_data["Name"] == user_name: ...
7bb9a4884a4d070acf10d07ec20b56dd17970a97
jrahlf/3D-Non-Contact-Laser-Profilometer
/xpcc/tools/system_design/xmlparser/utils.py
1,928
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import copy from parser_exception import ParserException def check_name(name): """ Checks if a string comply with some rules for the notation of a name. """ if not re.match("^([A-Z]?[a-z0-9]* )*([A-Z]?[a-z0-9]*)$", name): raise ParserException("Error in...
a0ea05111ec611353a6e19ad956ecca07628a67e
aungsettpaing/Code-Uva
/10773 Back to Intermediate Math.py
464
3.703125
4
import math testcase = int(input()) for i in range(testcase): lst = list(input().split(" ")) d = float(lst[0]) v = float(lst[1]) u = float(lst[2]) if u == 0 or v == 0 or u <= v: print("Case %d: can\'t determine"% (i+1)) else: # fastest path t1 = float(d/u) ...
063be4144f6816cac15038fb4d3f7b9d2df98614
den01-python-programming-exercises/exercise-2-24-from-parameter-to-one-jakeleesh
/src/exercise.py
238
3.890625
4
def main(): #write your code below this line num = int(input()) print_from_number_to_one(num) def print_from_number_to_one(num): while (num > 0): print(num) num -= 1 if __name__ == '__main__': main()
39618179ca7a960382e4256567c50824437eb5d4
thelsandroantunes/EST-UEA
/LPI/Listas/L2_LPI - repetição e condicionais/exe02l2.py
422
3.828125
4
# Autor: Thelsandro Antunes # Data: 31/03/2017 # EST-UEA # Disciplina: LP1 # Professora: Elloa B. Guedes # 2 Lista de Exercicios (06/04/2015) # Questao 02: Escreva um programa para ler cinco valores inteiros aleatorios, imprimir # os valores lidos e determinar o maior dos valores lidos. from random import...
a646b2551cc7c7851be11a91685bc2deca78d001
vincentknguyen/Leetcode
/Week 2 - Strings, Hash Tables/LC_#0387_FirstUniqueChar.py
1,245
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 26 13:33:36 2021 @author: vincentnguyen Time: O(n*2) = O(n), due to the for and while loops going through the string s Space: O(n). String is O(n) https://leetcode.com/problems/first-unique-character-in-a-string/ """ #O(n) runtime #O(1) space c...
5ba3eb7393c317878389f6de841e03e0570bdc09
d4ngermana/python
/rotation.py
199
3.5625
4
ar = [1,2,3,4,5,6,7] rotate = int(input("How many rotation?")) n = len(ar) while rotate: temp = ar[0] for i in range(n-1): ar[i] = ar[i+1] ar[n-1] = temp rotate-=1 print(ar)
2289083dec9811b22fafad160f2e03e8c1716618
alyhemani/DojoAssignments
/Python/Python/fun.py
239
4.03125
4
for count in range (1, 2001): if count%2 == 1: print 'Number is {}'.format(count) +'. This is an odd number.' else: print 'Number is {}'.format(count) +'.This is an even number' a = [2,4,10,16] b = 5 a = [x * b for x in a] print a
5bbe7d03935ba6733050ca56a9ca872e15944182
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/2_input_print/2.5.more_arifmetic/11.py
327
3.953125
4
""" Напишите программу для пересчёта величины временного интервала, заданного в минутах, в величину, выраженную в часах и минутах. """ x = int(input()) print(f'{x} мин - это {x // 60} час {x % 60} минут.')
adbfecf37f05e772bd6fe38180f75887e500d9de
Katarzyna-Bak/Coding-exercises
/Easy unpack.py
949
4.625
5
# Create a function that gets a tuple and returns a # tuple with 3 elements - the first, third and second # element from the last for the given array. # One important thing worth pointing out is that # you need to use index in order to extract elements # from the array. Pay attention, index counting starts # from...
0eb0a0c67c913b3a6f94c19a4fdfa071e024d9ae
4925k/cs50_2021
/pset6/mario/more/mario.py
501
4.03125
4
while True: try: height = int(input("Height: ")) if (height > 0 and height < 9): break except ValueError: print("Input integer value") for i in range(height): # print blank spaces for j in range(height - i - 1): print(" ", end="") # print left bricks ...
8e38fa0efe5d96fd446fd602a1231a66db69f4ee
tillyoswellwheeler/algorithms
/hash_tables.py
1,002
3.546875
4
# ------------------------------------------ # Grokking Algorithms -- Hash Tables # ------------------------------------------ #---------------------------------------- # Phonebook System # Creating the phone_book dictionary/hash table phone_book = dict() # same as phone_book = {} # Adding phone numbers to the phon...
65b61f28947d3b4747b736a9c9756bb0c6e8709c
wyaadarsh/LeetCode-Solutions
/Python3/0023-Merge-K-Sorted-Lists/soln-2.py
702
3.90625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from queue import PriorityQueue class Solution: def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ dummy = Lis...
aae651f1ba210d9b73a1dd8fc6cd75a7f5111c2b
DavidAndrade27/DataScienceAndMLBassics
/IA_dovo_r/5_Association Rule Learning/Apriori/Apriori.py
1,659
3.8125
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 20 16:29:02 2020 Apriori / Assosiation Rules Learning Apriori is an algorithm for frequent item set mining and association rule learning over relational databases. It proceeds by identifying the frequent individual items in the database and extending them to larger ...