blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0610dba326987595a13091d1f15fd3029ac45e6d
YohanKulasinghe/pythonSamples
/Index_LastDigit_Issue/index.py
635
3.625
4
import numpy as np import matplotlib.pyplot as plt import numpy as np import pandas as pd import math import xlrd loc = ("FIT16.xlsx") indexes = [] names = [] checkDigit = input("Please enter the last digit: ") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) for i in range(sheet.nrow...
ac7dc81db9fb7b26506714d40177935d0059bb32
brosenberg/limbo
/limbo/plugins/roll.py
1,337
3.671875
4
"""!roll [diceroll] returns the result of a given dice roll""" import random import re USAGE = """```Usage: !roll [diceroll] ex: !roll 3d6 !roll 2d4-2 !roll 10d4+10```""" def roll(input_dice): r = re.match('^([0-9]+)\s*d\s*([0-9]+)\s*([-+\/*x])?\s*([0-9]+)?\s*$', input_dice) result = 0 rolls = []...
6f35b2866b48b930a1ff084ee444ea04c7abece1
fixitsammie/cookiegame
/cookie.py
669
3.71875
4
"""program that solves the cookie game and gives a list of words""" import itertools import json import os, sys def load_words(): try: filename ="words_dictionary.json" with open(filename,"r") as english_dictionary: valid_words = json.load(english_dictionary) return valid_wo...
458b1e6f951f4f53aaa625b3d8c09e7a69703257
aechen10/redtrackedit
/Test/Pandas+NumPy/pandasTest.py
2,017
3.546875
4
import numpy import pandas import random #Creating series (similar to arrays?) s = pandas.Series([1, 3, 5, numpy.nan, 6, 8]) print(s) #Creating Date Range dates = pandas.date_range('20190602', '20190604',3) print(dates) numpyData = numpy.random.randn(3, 4) for i in range(0, len(numpyData)): for j in range(0, len(num...
0c11d4d48b9677c78bcd9a2c70bdeac101741815
legolas-zeng/scripts
/leetcode/初级算法/数组/移动零.py
665
3.640625
4
# coding=utf-8 # @author: zenganiu # @time: 2019/2/16 17:45 ''' 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原数组上操作,不能拷贝额外的数组。 尽量减少操作次数。 ''' nums = [0,1,0,3,12] # for index,values in enumerate(nums): # if values == 0: # nums.pop(index) # nums.append(0)...
0d4a994194171c1547bb22889058167de0b35cc5
ITInfra-101/Python_practice_public_repo
/exercise_5_list_intersection_pub.py
1,242
4.25
4
#Take two lists and write a program that returns a list that contains only #the elements that are common between the lists(without duplicates). #Make sure your program works on two lists of different sizes. # Extras: #Randomly generate two lists to test this #Write this in one line of Python (don’t worry if you can...
8549d5e7ffb3ff3794ca16af85923aa182362418
wkeilsohn/Python-Interview-Problems
/Fib_seq.py
629
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 31 11:32:05 2018 @author: William Keilsohn """ ''' Find the Nth fibinachi number iterativly and recursivly. ''' inNum = int(input('Please enter a number: ')) # Iterativly def itFibFinder(num): i, j = 0, 1 for x in range(0, num): i, j = ...
fd53299db8177fc9527a3e7ef1118ecd25ae6f15
petreflorina/Python
/Exercitii Curs/1/1-3.py
254
3.71875
4
a = [1, 3, 20, 1024, 53, 12, 102, 1, 4, 43, 32] ok = True l = len(a) for elem in range(l): if a[elem] % 3 != 0: ok = False break if ok ==False: print 'nu toate numerele sunt divizibile cu 3' else: print 'toate numerele sunt divizibile cu 3'
ab1975e2b2f00bf2a8b7257f486cdb4d6066afe7
joacosGoat/JoacosGoat
/general_lib.py
463
4.375
4
# Function: limited entries per user # What this function does is limit the variable entered by the user # In info you should put the requeriments you want the user to follow (string type) # In num_char you define the maximum length of the variable to assign def keyboard_input(info, num_char): screen = input(f'{in...
a9b659556690be1155284d3804c648dac4afca48
VesnaBrucoms/advent-of-code-2019
/advent/__main__.py
2,588
3.578125
4
from .day_one import calculate_fuel_for_mass, calculate_fuel_for_fuel from .intcode.core import run_program def day_1(): masses = _read_puzzle_file('day_1.txt') fuel_total = 0 for mass in masses: calculated_fuel = calculate_fuel_for_mass(mass) calculated_fuel += calculate_fuel_for_fuel(cal...
f4eb168db2c758ca4f12e7dc6f7a2e2cbcf0583a
roohom/demo
/daffodil_numbers.py
1,177
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : daffodil_numbers.py # Author: roohom # Date : 2018/10/15 0015 #!/usr/bin/env python # -*- coding: utf-8 -*- # File : practice.py # Author: roohom # Date : 2018/9/28 0028 # 找出所有的水仙花数 例如:153 = 1^3+3^3+5^3 # 一个寻找水仙花数的处理方法,通过字符串追加将数字拆分,并将每一位数字的立方相加最终与原数字比较,相等即为水仙...
b84c78a6c52921476ef6274e2b07d331f6ecf76a
daniel-reich/ubiquitous-fiesta
/zRm6YDfQHoesdc3rb_9.py
152
3.828125
4
def rectangles(step): if step == 1: return 1 else: counter = 0 for i in range(1,step+1): counter += i**3 ​ return counter
24e64a1717e3714c986de7d2cdc7cda8ee7c8c05
same1009/dsp
/python/q6_strings.py
6,249
4.28125
4
# Based on materials copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 def donuts(count): """ Given an int count of a number of donuts, return a string of the form 'Number of donuts: <count>', where <count> is the number passed in. However, if the count is 10 or more, then us...
58eed55eafff69ed769ea07c8ed251efe0727ba6
leenatomar123/if_else
/calculator.py
303
4.21875
4
num=int(input("enter the num1")) opertor=input("enter the operator") num2=int(input("enter the num2")) if operator=="+": print(num1+num2) elif operator=="-": print(num1-num2) elif operator=="*" : print(num1*num2) elif operator=="%": print(num1%num2) else: print("invalid")
689b70c57b0f3a5b04ad49d50fa6799578c99c64
Pinin25/ConnectFour
/ConnectFour.py
5,887
3.5625
4
from tkinter import * import random #Blue background #1F5FD5 #Yellow player #F4E332 #Red player #C0222A YELLOW = "#F4E332" RED = "#9E050E" NAVY = "#3483F0" WHITE = "white" PLAYER_COLOR = RED ROW = 7 COLUMN = 7 SIZE = 40 WIDTH = COLUMN * SIZE + 10 HEIGHT = ROW * SIZE + 10 MAX_TURNS = (ROW - 1) * COLUMN NUMBER_TO_WI...
f7dd6d2edcd435e0f1fdfaf76458b42821c2f478
t1b3r1us/AoC
/2020/Day_02/script1.py
794
3.65625
4
filepath = '/Users/thomasmkirk/Python_Apps/2020_Advent/Day_02/input.txt' f = open(filepath,"r") lines = f.readlines() f.close() valid_count = 0 for x_line in range(0,len(lines)): string_l = lines[x_line] dash_pos = string_l.find("-") space_pos = string_l.find(" ") length = len(string_l) min = in...
588ae78d535d937e0fd8b07eb3a144cab1b84538
smart-cau/Python-Algorithm-TeamNote
/test-book-practice/code-up-basic-100/6092-attendence-check.py
456
3.5625
4
# 문제 링크: https://codeup.kr/problem.php?id=6092 if __name__ == '__main__': repeat = int(input()) input_arr = list(map(int, input().split())) attendance_check_arr = [0 for _ in range(24)] # 파이썬은 for in으로 배열을 사용하면 index가 아니라, 배열 값 자체에 접근한다 for i in input_arr: attendance_check_arr[i] += 1 ...
21fae361a56d3b9e2bfe9ddf12a1da8ba3f45c7d
UnderXirox/Pi-Power-Supply-Isolated-GPIO-Board
/reboot.py
1,063
3.5625
4
from time import sleep import RPi.GPIO as GPIO # added on 09/01/2018 by Naren import os # added on 09/01/2018 by Naren ######For reboot button input ######## gpio_pin_number_for_pi_reboot_input =37 #37 is pin number and 26 is gpio GPIO.setmode(GPIO.BOARD) gpio_pin_number_for_pi_reboot_output =13 #13 id pin number and ...
11a8ec095bba75ad4ae59a491dbc26a408169a30
avadai/hello-world
/Week8Project3.py
416
4
4
def newton(x, estimate=1.0): if abs(x - estimate ** 2) <= 0.000001: return estimate else: return newton(x, (estimate + x / estimate) / 2) def main(): while True: x = float(input("Enter a number to be squared, or press 'Enter' to quit: ")) if x == " ": ...
8794bdd42ba06bbf3554dca6fa3302f534a1fac5
Spraynard/the_scraper
/web_scraper_ui.py
2,417
3.515625
4
import sys import os import requests import lxml from bs4 import BeautifulSoup from mechanize import Browser from classes.UI import UI class Web_Scraper: print os.environ def __init__(self, website): # Website the scraper will be on self.website = website # Browser initialization self.browser = Browse...
eb7219e415d5b5494734580e9b53e8af8d565f77
qwaneu/vendingrefact_python
/lib/vending_machine.py
2,756
3.625
4
# # (c) 2019 Quality Without a Name # www.qwan.eu # Refactoring Course material # from .enums import * from .can_container import * class VendingMachine: def __init__(self): self.cans = {} self.payment_method = None def set_value(self, v): self.payment_method = 1 if hasattr(sel...
a81a6d31e6c5bdb48cbe2e07199fd64243b77501
figueroaluis/cv-utils
/python/util.py
342
3.5625
4
#!/usr/bin/env python # coding: utf-8 import numpy as np def get_bbox_center(box): ''' Naive implementation, returns center with floating numbers Bounding box has format: x1, y1, x2, y2 ''' box_w = box[2] - box[0] box_h = box[3] - box[1] center = ((box[0] + box[2])/2, (box[1] + box[3])/2) ...
3cf9b033d7e08ded108617889d7c413604131284
thinhld80/python3
/python3-37/python3-37.py
2,026
4.125
4
#Exceptions #Bad thing happen, we need to know how to handle them """ Errors mostly occur at runtime that's they belong to an unchecked type. Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers. Exceptions are divided into two categories su...
d84eb66cefcd965978d42bcc2ed299cdad1239c9
kapil1430/pythonsubmitedass
/PythonSubmition/module2/discount_demo.py
325
3.640625
4
pk=int(input("Enter The Packae Qty")) t=99*pk dis=0 if pk>=10: dis=10 elif pk>=20: dis=20 elif pk>=50: dis=30 elif pk>=100: dis=40 else: print("NO Discount Amount") print("Total Amount OF Purchased",t) totd=(dis/100)*t print("Discount",totd) print('Total Amount OF purchased',t-to...
c5f914d634caf492e38fa21d122c025eb0163ff7
billaanil3/PRACTICE
/2ndLargeList.py
202
4.15625
4
n=int(input("Enter the no.of elements:")) a=[] #for i in range(0,n): for i in range(1,n+1): elem=int(input("Enter a number:")) a.append(elem) a.sort() print ("The second largest number is :",a[n-2])
a5e7a0ca5c2d033cd59f0bfcb47aa04ebde4f972
SD-CEO/games_cards_beta
/gamescards/Cards.py
625
3.71875
4
class Cards: def __init__(self, value, suit, volume): self.value = value self.suit = suit self.volume = volume def __repr__(self): return f"{self.value} {self.suit}" def __str__(self): return f"{self.value} {self.suit}" def __gt__(self, other): #מלחמה ...
6525b6518a7edecf03ce3d2e4980269a3791eb08
brandontarney/all_machine_learning
/algorithms/kmeans_short3.py
1,583
3.6875
4
'''Implementation and of K Means Clustering - adapted from https://jonchar.net/notebooks/k-means/ ''' import numpy as np from sklearn.metrics import pairwise_distances_argmin def find_clusters(X, n_clusters, rseed=2): # 1. Randomly choose clusters rng = np.random.RandomState(rseed) i = rng.permutation(X.s...
e6c1aa563f31ae329a41ced9f0c3f4d93b80cec7
emanueel-c/CODES.py
/12. def_funcoes/exercicio_4.py
1,043
4.0625
4
""" 4 - Fizz Buzz - Se o parâmetro da função for divisível por 2, retorne fizz, se o parâmetro da função for divisível por 5, retorne buzz. Se o parâmetro da função for divisível por 5 e por 3, retorne FizzBuzz, caso contrário, retorne o número enviado. """ def value(n1): if n1 % 2 == 0: print("fizz") ...
c1024971dcf406237537c44abfdbb1eedde763ca
NathanaelV/CeV-Python
/Exercicios Mundo 2/ex044_gerenciador_de_pagamentos.py
1,353
4.125
4
# Class Challenge 12 # Entrar com o valor do produto e com a forma de pagamento # À vista no dinheiro/cheque: 10% de desconto # À vista no cartão débito: 5% de desconto # Até 2x no cartão de crédito: preço normal # 3x ou mais no cartão de crédito: 20% de juros no total print('{:=^40}'.format(' LOJAS GUANABARAS ')) pri...
dbed58a6efbad0c1e0dc9962cfebf865012fa0b5
apassan23/Python
/laptop.py
2,850
3.9375
4
class Laptop: # class constructor to initialise data members # @param self: object -> reference to the object # @param brand: str -> brand of the laptop # @param ram: int -> Amount of memory installed in GB # @param color: str -> color of the laptop # OUTPUT: None def __init__(self, brand, p...
b50b7a5fd782136452058c64cf8d6d493c26ef6a
AndreaxMoore/Moore_Andrea
/PyLesson_07/AverageDigits(7.0).py
322
4.125
4
number = int(input("Please enter a number: ")) digits = 0 average = 0 def avDigits(): global average,digits,num num = number while num > 0: digits += 1 average = average + (num%10) num = int(num/10) avDigits() print("The average of the digits in", number,"is",average/digits) ...
fbe9bde585672e8e584e4b4605825a3c380d544f
Mannymunjuri/Project
/class.py
958
3.796875
4
class Animal: def __init__(self,species,kingdom,phylum,subphylum,order,family): self.species = species self.kingdom = kingdom self.phylum = phylum self.subphylum = subphylum self.order = order self.family = family def getSpecies(self): return self.speci...
6c0ff5c68148923b1b20219b373ffcaba88694d2
chuzasjota/average
/avg.py
1,208
4.3125
4
# Initialize the matrix to save each student's name and notes M = [] estudiantes = 2 notas = 6 for i in range(estudiantes): nombre = input('Nombre del estudiante: ') notas_estudiante = [nombre] for j in range(notas): nota = input('Ingrese la nota #%d: '%(j+1)) notas_estudiante.append(float(...
a8640e8bed47670ac7a653c77473480ae08d9cb9
CrytonAndrew/Pomodoro-Clock
/main.py
2,513
3.609375
4
from tkinter import * import time as t import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 1 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 reps = 0 # ---------------------------- TIMER R...
f9099e1f5328a3902cf536276eb36619067ed298
rsalesfreitas/python520
/users.py
899
3.703125
4
#!/usr/bin/python3 def hprint(): print('{0:.<4} {1:.<20} {2:.<40}'.format('ID', 'NOME', 'EMAIL')) def fprint(i, u): print('{0:.<4} {1:.<20} {2:.<40}'.format(i, u['nome'], u['email'])) usuarios = [] for l in open('usuarios.csv'): nome, idade, email = l.split(',') usuarios.append({"nome" : nome.strip()...
169706151814aa159d4a25018e47f90fc0446991
caseymm/python_class_materials
/assorted/caseymm_ex7.py
3,271
3.796875
4
import random class Card(object): suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] def __init__(self, suit=0, rank=2): self.suit = suit self.rank = rank def __str__(self): ...
88d2262e0ac06ba2a12e27534ea661d5fb28066a
kanwalk1115/DigitalCraftAssignments
/python assignments/Algorithms_duplicates.py
244
4.03125
4
names= ["Alex", "John", "Mary", "Steve", "John", "Steve"] def remove_duplicates(list): newlist= [] for name in list: if name not in newlist: newlist.append(name) return newlist print(remove_duplicates(names))
a73deabc404f25e1a1c2539e8613d9440fba81a7
FinnLandLab/Psychopy-Templates
/reading_csv_multiple_stim/reading_CSV_files.py
830
3.71875
4
from psychopy import data # TEMPLATE: READING CSV FILES # Demonstrates how to read CSV files that has multiple columns. # CSV file that gets read FILE_NAME = 'sample_csv.csv' # Class to handle trial sequencing and data storage. # Gets passed in the CSV file name trial_handler = data.TrialHandler(nReps=1, method='seq...
6bec2e166f630378872b9a1d87c0e14855c31184
pomonykr/DataScience
/Python,Pandas,Mysql/Python_5일차/Python05_08_CollectionList05_김병수~.py
201
3.625
4
#리스트의 수정과 삭제 #리스트에서 값 수정하기 a=[1,2,3] a[2] = 4 print(a) print("-"*15) a=[1,2,3] del a[1] print(a) print("-"*15) a = [1,2,3,4,5] del a[2:] print(a) print("-"*15)
e4ac59925f52fb960da1cb34e1488cfc1f1786c2
compjour/compjour-class-site
/source/files/code/viz/stanford_tuition.py
1,549
3.609375
4
######################## # Set up inflation calculator import csv import requests url = 'https://raw.githubusercontent.com/datasets/cpi-us/master/data/cpiai.csv' cpidata = list(csv.reader(requests.get(url).text.splitlines())) cpidf = pd.DataFrame(cpidata[1:], columns = cpidata[0]) cpidf = pd.DataFrame.convert_objects...
118d18c9846b33c5ae229f4b5cdf45a0b7628e32
eshaan2411/python
/Spotify API/main.py
1,958
3.5
4
from bs4 import BeautifulSoup import requests import spotipy from spotipy.oauth2 import SpotifyOAuth import pprint # Songs scraping from the BillBoard. choice = input("Which year you would like to travel to? (YYYY-MM-DD) : ") response = requests.get(url=f"https://www.billboard.com/charts/hot-100/{choice}") ...
aaef36a05dc97b842af01c5a8443700016bd172e
rahulcode22/Data-structures
/Math/Grid-unique-paths.py
435
3.953125
4
'''A robot is located at the top-left corner of an A x B grid The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below). How many possible unique paths are there? ''' def uniquePaths(a,b): if a ==1 or...
c05f82fdded1de36831260678c2433a7b5d776c8
dhlife09/pyschool
/20201103_forinrange*.py
635
3.890625
4
for i in range(10, 0, -1): # 역순으로 ( 10부터 0까지 (10, 9, 8, 7, 6, 5, 4, 3, 2, 1) -1씩 증가) print(i) for i in range(200, 9 , -5): # 200부터 10까지 -5씩 증가 print(i) sum = 0 for i in range(1, 101, 1): # 1부터 100까지 1씩 증가 print(i) sum = sum + i print('합계: ', sum) ''' sum = 0 for i in range(...
a4486acd08f460b00bce889fa277ef520e24e264
jiangxinyang227/leetcode
/剑指offer/4,重建二叉树.py
5,021
4.125
4
""" 根据树的前序遍历和中序遍历构建二叉树 """ class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Tree(object): def __init__(self, node=None): self.root = node def add(self, val): """ 用层序遍历实现二叉树的加法 :param val: ...
b1508e513a115b57381572cdf229b37fe4f64aab
sakurasakura1996/Leetcode
/二分查找/problem852_山脉数组的峰顶索引.py
851
3.5
4
from typing import List class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: n = len(arr) for i in range(1, n-1): if arr[i-1] < arr[i] and arr[i] > arr[i+1]: return i def peakIndexInMountainArray2(self, arr: List[int]) -> int: # 二分法 ...
28e54aa554f9d453e446e8b54f7131bdb79bc392
roger6blog/LeetCode
/FamousAlgorithm/TreeOrder.py
2,314
3.890625
4
class Node: def __init__(self, data): self.val = data self.left = None self.right = None def add(self, data): if self.val: if self.left is None: self.left = Node(data) else: if self.right is None: sel...
df541fb7f336ba310714727d0aba45a290e50834
y0umu/monty-hall-problem
/monty_hall.py
2,812
4.03125
4
# reinvent the wheel simulating the monty hall problem # https://en.wikipedia.org/wiki/Monty_Hall_problem # using python3 from secrets import randbelow # def isHit(p): # '''Generate a float in range [0,1] and say if is lower than p''' # assert p >=0 and p <=1 # if np.random.rand() < p: # return T...
8738ee8d6747b5dcab35ad6ed5d8e583780cc40e
ZDietz28/bradleycodeu.github.io
/_apcsp/textgames/castlesAndCreaturesTemplate.py
7,356
3.71875
4
# Castles and Creatures by Justin Riley # from random import everything # from time import everything # create a function called askPlayer that will return the number that the player selects # No arguments needed... so it'll look like this: askPlayer() # Ask the player if they want to try to steal or use one of their...
bccf01e1a46a6157ace202e300819d7312df8277
Sidhikesh/PYTHON
/12th july 6th lec/factorial of a no.py
112
3.609375
4
x=int(input('enter the no')) sum=1 for i in range (1,x+1): sum=sum*i x=x-1 print(sum)
f19a60a96a46adb39538953fd42f5c02c63198a0
BelindaRobinson/year3
/savings-calculation.py
1,042
4.125
4
item = input("What is the name of the item?") itemPriceText = input("What is the price of that item?") numberOfItemsText = input("HOw many would you like to purchase?") itemPrice = float(itemPriceText) nonMemberSavingPrice = itemPrice - (itemPrice * 0.2) print("The Non Member Saving price =", nonMemberSavingPrice) nu...
64ecb5dcf65e363d8a38226a994269f57692b080
akksa/examples
/algorithms/merge_sort.py
1,072
4.1875
4
#Akksa #Pseudo code available in http://en.wikipedia.org/wiki/Merge_sort def merge(left, right): result = [] while left or right: if left and right: if left[0] >= right[0]: result.append(left[0]) left = left[1:] else: result.appen...
2a2a3c0054b0e61959abb55296f5dc838eb44a1c
yhs3434/Algorithms
/baekjun/exercise/2020Jan/5354.py
369
3.640625
4
# J박스 # https://www.acmicpc.net/problem/5354 # https://github.com/yhs3434/Algorithms t = int(input()) for _ in range(t): n = int(input()) for i in range(n): for j in range(n): if i==0 or i==(n-1) or j==0 or j==(n-1): print('#', end='') else: print...
64d033ee383be45086397e29067b8ab98f8f1c51
KristoferGauti/Forritun-1-HR
/projects/population1.py
529
3.640625
4
#Eg vann þetta verkefni með Johanni Inga i hop 2 population = 307357870 #folksfjöldinn i Bandarikjunum year = int(31536000) #sekundur a ari (365) birth = year / 7 #fæðing a ari death = year / 13 #dauðsfall a ari new = year / 35 #nyr innflytjandi a ari #breyting a folksfjölda ar hvert new_population = birth - death...
878d34c0a67bdfd78f70b250a45fd36487181366
seyoungnam/Udacity-Data-Structures-Algorithms
/Project3/problem_6.py
851
3.828125
4
def get_min_max(ints): if len(ints) == 0: return (-1, -1) minInt, maxInt = float('inf'), float('-inf') for num in ints: if num < minInt: minInt = num if num > maxInt: maxInt = num return (minInt, maxInt) ## Example Test Case of Ten Integers import random...
7b2aeb565f4628411207c35e12c4544b79c28bdf
taehoon95/python-study
/enumerate와리스트내포/enumerate와리스트내포.py
882
3.765625
4
#리스트 를 enumerate 이용하면 index를 키로 사용 example_list = ["요소A", "요소B", "요소C"] for i, value in enumerate(example_list): print("{}번째 요소는 {}입니다.".format(i,value)) #딕셔너리 아이템 example_dictionary = { "키A" : "값A", "키B" : "값B", "키C" : "값C" } print() print("items() : ", example_dictionary.items()) for key, element ...
b6bd5893963a88bb7a9aec2bc452dd71e83916c8
laomu/py_1709
/python-base/days09_code/demo01_os.py
765
3.546875
4
# 程序用来列出给定路径下所有的文件夹和文件信息 # 通过import引入os模块 import os # 定义一个函数,用于罗列所有的文件夹和文件 def scan_dir(path):#d:/resp_work/ # 获取当前文件夹下所有的文件【文件夹/文件】 file_list = os.listdir(path)#['py_1709'] # 遍历循环 for file in file_list: file = path + os.sep + file # 如果是文件,直接打印文件名称 if os.path.isfile(file): print(">>>>>>>>这是一个文件:%s" % f...
81a95723b91d8ceafb2b5b8710fb39bb67d6cac3
xiaohai0520/Algorithm
/algorithms/1023. Camelcase Matching.py
1,294
3.84375
4
This is a match problem. It means that the pattern can add any char to match the query So we need to think that the query need to have the same Captical of the pattern and the lowercase can not include the query not have. We iterite the query and if we find the match char in both word, the index of pattern plus 1. ...
2017656fc90e188f6ecb0247665af40217143d4d
galaxo420/loop-engine
/textMap.py
3,221
4.03125
4
''' this class loads files that are like this: "map.txt" : 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 the class then calculates n and m and stores the data in a o...
6c35118b21f82774d88602799a599812a85bc924
altarac/intro-2-python-3
/lesson 1 challenge 1.py
372
3.953125
4
initial_amount = float(input('How much money are you initially putting in the account? ')) interest_rate = float(input('What is the percent interest rate? ')) year = int(input('How many years? ')) total = round(initial_amount*(1+(interest_rate/100))**year,2) #round to the second decimal place print('After ' + str(yea...
a46c0ea2defe1e1d9331a26d8814520b73c8d27b
daniel-reich/ubiquitous-fiesta
/8vBvgJMc2uQJpD6d7_20.py
323
3.6875
4
def factorization(x): for i in range (2, int(x) + 1, 1): if x % i == 0: return i return 1 ​ def prime_factors(x): factors = [] factor = factorization(x) while factor != 1: factors.append(factor) x = x / factor factor = factorization(x) return factors ...
cce70407f575eb091cf9abd24f2025b3e4c105fe
zion-ai/PythonLearn
/with mosh everybody python/gettingInput.py
244
3.953125
4
# kullanıcıdan bilgi almak için input fonkiyonunu kullanırız name = input('What is your name? ') print('Hi',name) userName = input('What is your name? ') userColor = input('What is your favorite color? ') print(userName,'likes',userColor)
aebd9e2496cc219d088e6c84e181ea8037ed7d0f
shrirangmhalgi/Python-Bootcamp
/30. File Handling/writing_file.py
456
3.765625
4
# you need to add some backslash characters if you want a newline # with open("abc.txt", mode="w") as file: # file.write("Hey bud how are you..?\n") # file.write("Hey bud how are you..?") # with open("abc.txt", mode="a") as file: # file.write("Hey bud how are you..?\n") # file.write("Hey bud how are yo...
ed392957aca12ab7c55f46104db98b210e8d2cb0
Qamra/python
/-Study-from-ChildrenBook/import.py
404
4
4
from study3 import a print(a) while True: #程序的异常处理,异常处理的程序需要包裹在try结构中,except说明当特定错误发生时,程序应该如何应对。 inputStr = input("Please input a number:") try: num = float(inputStr) print("Input number:",num) print("result:",10/num) except: print("Please try again.") import this
bd7be6ed3bebd625ce35c616f125406ec3f128a2
Ell-91/Leetcode-Questions
/Array/mergeOverlappingIntervals.py
735
3.71875
4
def mergeOverlappingIntervals(intervals): #check if the list is empty #sort the intervals intervals.sort() #Initialize a variable to hold the merged intervals merged_intervals = [] #print(merged_intervals[-1][1]) #start times are indexed at 0 // end times are indexed at 1 for int...
94544e075e94c36f59a9938ea8cc440c10f2e081
yukiko1929/python_scripts
/evening_review.py
1,490
3.53125
4
# from random import randint, choice # ops = '+-' # def calculation(): # nums = [randint(1,1000) for i in range(2)] # nums.sort(reverse=True) # ope = choice(ops) # if ope == '+': # result = sum(nums) # else: # result = nums[0] - nums[1] # while True: # greet = int(input('...
b2108a9b6a207399d5eb89b19acad0e23663a92f
betty29/code-1
/recipes/Python/577329_Some_prime_generation_algorithms/recipe-577329.py
7,566
3.765625
4
""" Topic: prime algorithms. Here is an example output of this script: Totally free. No warranty. Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] [calc_slower] seeking primes between (0..100000) ... ...profiling of 'create_primes_1': tooks 6.974707 seconds ...profiling of 'create_...
3fbef16c021d870a152e1dd9dcc4de4e33a4e82a
3keepmovingforward3/ENGR1102
/python/hackerrank/console input and output/middle ground/task.py
202
3.6875
4
# Function takes three integers as input, sums them, and returns the answer # Sample input: 5 16 57 Output: 78 def m_g(): # Start your code below (tip: Make sure to indent your code) return()
6952dde981a6260bc9afef68a8bfce4f3aecde35
PerlaOvalle/Learning-Python
/listas.py
244
4.09375
4
lista = [9 , 5,11, 8] print(sorted(lista, reverse = True)) print(lista[0]) lista.remove(11) print(lista) print(range(1, 10)) lista =list(range(1,13, 3)) print(lista) for valor in lista: print(valor) lista.append(5) print(lista)
c8fb62a93788e6c0be180220fc621d5aee4cdbc3
devinpowers/algorithms
/Projects/Algorithms.py
1,058
3.59375
4
class Algorithm: def __init__(self, name): self.array = random.sample(range(512), 512) # Random array of size 512 self.name = name # Get name of the variable def update_display(self, swap1=None, swap2=None): import visualizer visualizer.update(self, swap1, swap2) # pass the i...
a6fd4d1ef7748ce9820f0802b4c3780f78700dd3
Jackywathy/past-work
/Progcomp/rats.py
1,095
3.53125
4
def revFunc(i): return int("".join(reversed((str(i))))) def rev_sort(i, check, count): if i > 10**12: return [] # i is int of number, rev = revFunc(i) # sorts and reerses string sort = int("".join(sorted(str(i+rev)))) if sort in check: return check[check.index(sort):] ...
9053b34139bb47b72ef15efc7adf4d9a3d0fa8e7
mikola-s/lesson_29_OOP_05_inner_decorator
/task_02_how_old.py
1,007
3.796875
4
from datetime import datetime, date class InvalidBirthday(Exception): pass class UserAge: def __init__(self, user_input, *args, **kwargs): self.now = date.today() self.birthday = self.check_date(user_input) self.age = self.get_age(self.birthday) def check_date(self, checked_str)...
d120b4ec46f7060bd120b77066f8d492f30a37a0
siva6160/helloworld
/becomde9-2.py
136
4.21875
4
def pow(num,p): res=num**p return res num=int(input("enter a number")) p=int(input("enter a num")) s=pow(num,p) print(s)
770c7a284ab0f5d5581751258eb9595f22474f09
KevinMichaelCamp/Python-HardWay
/Algorithms/Chapter4_Strings/04_Count_Non_Spaces.py
371
4.40625
4
# Accept a string and return the number of non-space characters found in the string. For example, given, "Honey pie, you are driving me crazy" return 29 (not 35). def countNonSpaces(string): count = 0 for char in string: if char != " ": count += 1 return count # Test Cases print(coun...
5400db8a5668279abf9ed0d2cc94beef0302af12
basu0001/first-pr-Hacktoberfest--2019
/codes/data_structures/queue/python/queue_two_stacks.py
1,462
3.53125
4
def get_command(): parts = input().strip().split(' ') command = int(parts[0]) if len(parts) == 1: return (command, None) try: arg = int(parts[1]) except ValueError: arg = parts[1] return command, arg class Stack: def __init__(self): self._l = [] def _...
3fa1513409b28c6cbafc3156a2b4e520beb1ab08
bmihovski/funct_prog_with_python_pluralsight
/order_item.py
432
3.53125
4
class OrderItem: name = '' item_number = '' quantity = 0 price = 0 back_ordered = False def __init__(self, name, item_number, quantity, price, back_ordered): self.name = name self.item_number = item_number self.quantity = quantity self.price = price self....
48ec1ddaf15841ed939498c54112d0baa9a14d5a
s-londono/python-cheatsheets
/data_science/lessons/etl/transform_parse_dates.py
2,236
3.5625
4
import os import pandas as pd if not os.getcwd().endswith("etl"): os.chdir("./data_science/lessons/etl") # Parse a date literal parsed_date = pd.to_datetime('January 1st, 2017') print(f"A {type(parsed_date)}: {parsed_date.year} {parsed_date.month} {parsed_date.second}") # Formats: follow the Python standard dat...
c993aae2a737628696112b179df7a083da1ac932
AliM3/Net-Centric
/PalindromeSub.py
1,933
3.96875
4
# Longest Palindrome Subsequence import sys # A utility function to print a # substring str[low..high] def printSubStr(st, low, high): sys.stdout.write(st[low: high + 1]) # Clear out output buffer sys.stdout.flush() return '' # This function prints the longest palindrome # substring of s...
86a906b092a3ac7d277b4c9496e2e0911ae47cf4
dkp-1024/face_counter
/my_work/pro1.py
451
3.609375
4
#img = Image.open(path) # On successful execution of this statement, # an object of Image type is returned and stored in img variable) from PIL import Image try: img = "zzz.jpg" with Image.open(img) as image: width, height = image.size print "successfully read" except IOError: print "something went wrong"...
995eef597ca24519f80f28ddb81bd941c07df461
JaiAravindh-git/HactoberFest21
/Python/Number_of_sub-arrays_with_an_odd_sum.py
348
3.65625
4
#Number of sub-arrays with an odd sum def countOddSum(ar,n): result = 0 for i in range(n): val = 0 for j in range(i, n): val = val + ar[j] if (val % 2 != 0): result +=1 return (result) n= int(input()) ar = list(map(int,input().split())) p...
672f5f727e7c889da06891a92bacf67953e8b675
Jollyhrothgar/learning
/programming_languages/python/basics/module_vs_class/FunTime_class.py
1,476
3.96875
4
import sys class FunTime: # no such thing as private variable, but convention is to # prepend '_' to something that is private. # Note too that variables do not need to be explicitly called, # they are available as soon as we define them, within the scope # of the class. # or: _concat = '' ...
00efb2bbd4dfa3f86e604cac6d8e7d41d5631b3c
RickyLiTHU/codePractice
/606.py
928
3.8125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ def construct(node):...
9895f8277e5ed6a17f7ab9a392edfebf177d349d
avallbona/python-crash-course
/files_csv.py
671
3.65625
4
import csv elems = [ {"first_name": "Baked", "last_name": "Beans"}, {"first_name": "Lovely", "last_name": "Spam"}, {"first_name": "Wonderful", "last_name": "Spam"}, ] # write print("==Write file==") with open("names_iter_2.csv", "w", newline="") as csvfile: fieldnames = ["first_name", "last_name"] ...
87d708466b45bce29c758e2102f5dd467f0f56cb
KFOAS/automate-the-boring-stuff
/table_printer/table_printer.py
1,114
4.34375
4
#! /usr/bin/env python3 # table_printer.py - formats lists of string into a tabular format def build_table(data): """ Formats and builds a table from a nested list of strings. Each individual element of the list represents a column :param list data: list of strings :return: str formatted for tabu...
cc9b5d79e1a95670ee79985c8b99ab74033eb139
DaHuO/Supergraph
/codes/BuildLinks1.10/test_input/CJ_16_2/16_2_1_ShiZo_solution.py
1,982
3.53125
4
import sys numberWords = [ 'ZERO', 'TWO', 'FOUR', 'THREE', 'ONE', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE' ] wordNumbers = [ 0, 2, 4, 3, 1, 5, 6, 7, 8, 9 ] def testWord(word, string): for char in word: if char not in string: ...
7cfa700cb5a54506bc338b99b93d6a6c228c99c9
SakuraGo/leetcodepython3
/P3/Solu5176.py
4,739
3.765625
4
# 5176. 猜字谜 # 外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。 # # 字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底: # # 单词 word 中包含谜面 puzzle 的第一个字母。 # 单词 word 中的每一个字母都可以在谜面 puzzle 中找到。 # 例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及 "based"(其中的 "s" 没有出现在谜面中)。 # 返回一个答案数组 answer,数组中的每个元...
ce024cefc7550a1f19c444167c490a6b3f868c37
hajdaini/Games
/Python/games/Plus-ou-moins/plusoumoins.py
2,633
3.953125
4
""" @Author : AJDAINI Hatim @Github : https://github.com/Hajdaini """ TRY = 5 DEFAUT_MONEY = 200 class PlusouMoins: def __init__(self, hidden_number): with open('money.txt', 'r') as file: self.money = int(file.readline()) self.current_try = TRY self.hidden_number =...
bcf946c29bd5a5e460d17a459d396999a1b5fa8a
milson389/python-project
/Fundamental/src/Basics/InputOutput.py
685
4.125
4
# Python Input Output # Output # Combine directly variable with String a = 5 print('The value of A is ', a) # Using String Format Mechanism print('Hello {}'.format('brother')) # Using % operator and argument specifiers name = "John" age = 15 print("Hello, %s!" % name) print("%s is %d years old." % (name, age)) myL...
a8d5321a55ab4edf83e58caa8af28e2431dd6ea3
LauraHoffmann-DataScience/DSC510
/GuessaNumber.py
1,843
4.09375
4
correct_number = 7 Guess = input("Guess a number between 1 and 10: \n") if int(Guess) == int(correct_number): print("You are correct!") elif int(Guess) > int(correct_number): print("That is too high.") Guess = input("Guess another number: \n") if int(Guess) == int(correct_number): print(...
c38aeeaf18e7ed9ac04fb3c5acfdf3785284d992
matyasalfoldi/codingame
/easy/descent.py
206
4.09375
4
while True: tallest = -1 index = -1 for i in range(8): mountain_h = int(input()) if mountain_h > tallest: tallest = mountain_h index = i print(index)
5d05dcde1ef0a9044e3b5cdd269d577c86ea7fb9
AUNG-MIN-OO/python_from_scratch
/lambda.py
88
3.546875
4
# def add(num1,num2): # return num1+num2 add = lambda n1,n2 :n1+n2 print(add(1,2))
01a27f980a63ecc5d633efa46aa61e18cae12ac2
SpideyUU/21SummerPC_COMP2021_Assignments_Solutions
/Assignment_2/p123_4.15.py
1,500
3.9375
4
import math import random lottery = int(random.randrange(100, 1000)) guess = eval(input("Please enter your lottery pick. Three Digits Only: \n")) lotteryDigit_1 = str(lottery % 100 % 10) lotteryDigit_2 = str((lottery % 100) // 10) lotteryDigit_3 = str(lottery // 100) guessDigit_1 = str(guess % 100 % 10) guessDigit_2...
032aceac674f677e8851387eef2a3a3d193be3eb
vuyani/repo
/Assignment1/excercise_4.py
188
3.71875
4
def y(m,x,b): y= m * x + b return y print "The results for the linear equation Y=mX+b with m=1 and b=0 are:","\n" "X","\t","Y" for i in range(1,11): yint=y(1,i,0) print i,"\t",yint
9a649e8aa1141b44f7fb37f43e8412ddeacde1c1
Kattusite/linguistics-db
/phonemes/ipa_json.py
1,019
3.546875
4
"""A collection of tools to help consonants.py and vowels.py read in their input data from .json files""" import json def isEnabled(p): """Given a dict p representing the properties of a phoneme, return true if the phoneme either has no "disabled" field, or if it has "disabled": False""" if "disabled" not...
1e7b53652317c3d1313cb898ed2f414ee2bac7b7
oliver-johnston/advent-of-code-2020
/18.2.py
1,072
3.765625
4
from pyparsing import nestedExpr def solve_nested(parts): if type(parts) is str: return int(parts) if len(parts) == 1: if type(parts[0]) is list: return solve_nested(parts[0]) else: return int(parts[0]) if "+" in parts: index = parts.index("+") ...
fd959a547ba12072acf1a36c7a26512c0d7982fc
nataliakusmirek/CS50x---Portfolio
/pset6/dna/dna.py
1,524
3.890625
4
import csv from sys import argv, exit def main(): # Ensure correct usage if len(argv) != 3: print("Usage: python dna.py data.csv sequence.txt") exit(1) start = argv[1] with open(argv[1]) as file: files = csv.DictReader(file) dic_list = list(files) # open csv file a...
57aefec41502f43d166b5a1363fb8497fef78532
JoLeungGitHub/AdventOfCode2017
/Day12.py
3,730
4
4
''' --- Day 12: Digital Plumber --- Walking along the memory banks of the stream, you find a small village that is experiencing a little confusion: some programs can't communicate with each other. Programs in this village communicate using a fixed system of pipes. Messages are passed between programs using these pipe...
150253dc1ef468a06ad634eeb3ba1eebce22d724
aberenjian89/Challange
/Python/split.py
389
3.6875
4
def split(s, delimiter): result = [] str = "" length = len(delimiter) i = 0 while i < len(s): if s[i:i+length] == delimiter: result.append(str) i = i + length str = '' else: str += s[i] i += 1 if str != '': resu...
e62c53f4b27168453c08c13325167744da42e0d4
ed1rac/Estrutura-de-Dados-com-Massanori
/Função para inverter um entrada String recursivamente.py
170
3.6875
4
def inv(s): '''Função para inverter um entrada String recursivamente''' if len(s) == 1: return s return inv(s[1:]) + s[0] print(inv("abc"))
5137c6c665c1c43da5c5d83c61c02d82de07ab57
wesleyhedrick/Digital-Crafts-Classes
/Programming-101/userPromptName.py
176
3.953125
4
name = input('What is your name?: ') print(f'Hi {name}! You\'re mom says you\'re a loser!') print('Hi!' + input('What is your name: ?')) input('What is your favorite cat?')
11f8e345afff481622902e025fbbc3269ece04a2
yangyue-king/alien-test
/alien_invasion/bullet.py
1,170
3.765625
4
import pygame from pygame.sprite import Sprite # 从精灵模块中导入精灵类,精灵类可以将游戏中的相关元素编组 class Bullet(Sprite): # 子弹类继承自精灵类 def __init__(self, ai_settings, screen, ship): super().__init__() self.screen = screen self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_hei...