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
e8ef0c0fab744a9dfe4137167f09b2c15c7815aa
AlanMars/python-game4kids
/games/countNumber.py
737
4.125
4
from os import system from random import randint #this say function is the most important part of kids programming #it uses the built in OSX say command to convert text to speech def say(something): system('say "%s"' % something) welcome_input = "Hi, Baby, Please input a number you would like to count." print(wel...
11747cf3f41a1debe2666fc9dcf45749af4b65f5
zanmakes/mooc-progress
/Specializations/Introduction to Python and Java/Introduction to Python Programming/Week 3 and 4/TestCode4/name_slice.py
191
3.859375
4
name = 'Brandon Krakowsky' # get index of single space between first name and last name first_space = name.index(' ') # get substring of name using slice # first_name only print(name[0:first_space])
0711acaa7130a4a2ab6025d3f98cd4619ac29023
jfu-gatech/mbta
/util.py
668
3.78125
4
def breadth_first_search(graph, start, target): # breath first search that outputs the path taken # TODO: expand documentation with parameter details visited = [] queue = [] queue.append([start]) if start == target: return [start] while queue: path = queue.pop(0) la...
57fa954ec9675755975d409af855d8988143f3c2
digipodium/sophomore_python_1230_oct_21
/keep_working.py
332
4.03125
4
# Write your code here :-) question = input('Are you tired? ') if question == 'yes': tired = True else: tired = False q2 = input('Are u sleepy? ') if q2 == 'yes': sleepy = True else: sleepy = False if not tired or not sleepy: print("Keep Working") else: print("Aaj ki din aapki chutti. Jao Ghar...
54e6c4af8b3becbd1818c449e433bca26fe25383
carrda/hero-rpg
/hero_rpg.py
1,891
4.0625
4
#!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def __init__(self, health, power): self.health = health self.power = power sel...
6377dbb805929edaded2f2c414f4d5e8f354ade0
muthuguna/python
/Sample1.py
3,527
3.9375
4
# Find greatest number of 3 given numbers A = 10 B = 11 C = 12 result = A if A >= B and A >= B: result = A elif B >= A and B >= C: result = B else: result = C print(result) # Fibonacci series count = 15 p1=1 p2=0 if count > 0: for i in range(count): p3=p1+p2 p1=p2 p2=p3 ...
6b484119535ee7268a87b2855d876cbedb697662
yw-fang/readingnotes
/machine-learning/Matthes-crash-course/chapt09/scripts/user_03.py
1,243
4
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Yue-Wen FANG' __maintainer__ = "Yue-Wen FANG" __email__ = 'fyuewen@gmail.com' __license__ = 'Apache License 2.0' __creation_date__= 'Dec. 28, 2018' """ 9-3. Users: Make a class called User . Create two attributes called first_name and last_name, and then cre...
20fe4c6b360c3f782dcbbe31fda1f8f4597fce62
ECE492G9W18/ServoControllerV2
/test_servo_controller.py
377
3.515625
4
import unittest import aiming_controller class TestServoController(unittest.TestCase): ''' for block 3 | 5 | 7 1 | 4 | 9 6 | 2 | 8 it should return (4,8,1,5,2,7,3,9,6) ''' def test_map_numbers(self): a = aiming_controller.AimingController() self.assertEqual(a.map_numbers("357149628"), [4,8,1,5,2,7,3...
066c4b4b1b48f337665509d93eab5b887718272e
zenubis/LeetCodeAnswers
/04-Daily/20210126/20210126.py
2,725
4.09375
4
# https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/582/week-4-january-22nd-january-28th/3617/ # You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, # where heights[row][col] represents the height of cell (row, col). You are situated in...
9f12da4ea604994585ece4717b2e406e1c2be2e8
fredtavares2018/ads_ead
/Linguagem - Python/funcoes.py
381
3.578125
4
def precoRoupa(): valor = 3100 if valor <= 1830.29: #comparacao valor -= valor * 0.08 # 1000 - 1000 x 8% = 920 elif valor <= 3050.52: valor -= valor * 0.09 # 2000 - 2000 x 9% = 1820 elif valor <= 6101.06: valor -= valor * 0.11 print(valor) ...
573db08aa7b049616e2bec4785e8fb1f71d5d357
ttnyoung/fastcampus_python_advanced
/myvenv/Chapter02/03.리스트다루기.py
375
3.71875
4
# 리스트 메서드 # 리스트 데이터 삭제 fruits = ['apple', 'orange', 'mango'] del fruits[1] print(fruits) # 리스트 정렬 numbers = [5, 1, 2, 8, 3] numbers.sort() print(numbers) # enumerate titles = ['출석!!', '출석인증합니다!', '출석이요!!'] for index, title in enumerate(titles, 1): print(f'{index} 번째 글입니다. 제목 : {title}')
a649525110a294882c99fa5366d7e196a880904a
aguscoppe/ejercicios-python
/TP_5_Funciones/TP5_EJ5.py
208
3.8125
4
# EJERCICIO 5 def devolverMaximo(a, b): if a > b: return a else: return b a = int(input("Ingrese un número: ")) b = int(input("Ingrese otro número: ")) print(devolverMaximo(a, b))
aabc7012d401bdd7445cf8c83e1f26e4b0a7c901
mazor/Codelity-Exercises
/mininteger.py
1,893
3.640625
4
""" This is a demo task. Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−...
3a26b2fbb9dfaffca1cb71e83476a38eba41dcb8
athenian-programming/thread-examples
/src/main/python/leds/non_threaded.py
671
3.5625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from leds.led import LED def main(): # Setup CLI args parser = argparse.ArgumentParser() parser.add_argument("-p", "--pause", default=0.25, type=float, help="Blink pause (secs) [0.25]") args = vars(parser.parse_args()) # Create LED o...
b6fb6424e22cd457d26dd29238c8e38c1988a3ef
Capybarralt/PyTask
/leap_year.py
571
3.71875
4
year = int(input()) if (year % 4 != 0) or ((year % 100 == 0) and (year % 400 != 0)): print('no') else: print('yes') """ Попросить пользователя ввести с клавиатуры год. Если год високосный - вывести на экран "yes" Если год не високосный - вывести на экран "no" Год не является високосным в двух случаях: ...
60986c5a717f31814eb3b7c5fa83d1cc98e5236d
niayz10/Web-Programming
/week8/Logic-1/5.py
198
3.734375
4
def sorta_sum(a, b): sum = a + b if sum >= 10 and sum <= 19: print("20") else: print(sum) sorta_sum(3, 4) # → 7 sorta_sum(9, 4) # → 20 sorta_sum(10, 11) # → 21
041e6180cf3452d934b22127992d777f7733947f
daniel-reich/ubiquitous-fiesta
/GWBvmSJdciGAksuwS_19.py
87
3.53125
4
def find_letters(word): lst = [l for l in word if word.count(l) <= 1] return lst
ee7ead67f82a2837ce3ac7041bb3942ba1b36380
Hammad-Ishaque/pydata-practise
/turing/problems.py
2,542
3.515625
4
# Find first duplicate from array # First occurence of any element return this element import sys def first_duplicate(arr): duplicate_map = {} for i, v in enumerate(arr): if v in duplicate_map: return v duplicate_map[v] = 1 return -1 def first_duplicate_without_space(arr): ...
4815f53f2e3d2d4fa7d1400e7311115f54260e17
Zylphrex/csc420-project
/geometry/point.py
683
3.8125
4
import math class Point(object): def __init__(self, x, y): self.x = x self.y = y @property def raw(self): return (self.x, self.y) def copy(self): return Point(self.x, self.y) def __mul__(self, n): return Point(self.x * n, self.y * n) def __rmul__(sel...
ba5a62f6f8952adf9d19bf0987f4108faafb8145
Pjamas180/MiscPython
/PA6/vector.py
6,411
4.21875
4
from misc import Failure class Vector(object): """Vector class which creates a vector with a given size or argument list.""" def __init__(self, length): """Constructor for a Vector Object. If the argument is a single int or long, then return a vector with length of argument. if the argument is ...
15b9d1dbcb315512ae64d8dab6aed4ddde750fe1
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/Shweta/Lesson03/list_lab.py
2,384
4.40625
4
#!/usr/bin/env python3 #Series 1 #Create and do modifications on list #including pop, append, +,insert # print("--------Series 1 started--------") fruit_list=["Apples","Pears","Oranges","Peaches"] print("The fruits mentioned in fruit list are:", fruit_list) new_fruit=input("Name the new fruit want to add in list : "...
c7324fa21d37f4a95ce91f3b643d268c0ce9d4d0
ajaysahu3964/pythonasminiprograms
/squareroot.py
159
4.03125
4
def square(num): #num=int(input("enter a number:")) square_root=num**0.5 return"square root of",num,"is",round(square_root) print(square(81))
3a88e5e3c37a9d0728b1627090aabff407409c41
SYN2002/PYTHON-LAB
/d2_Assignment_11_b.py
329
3.625
4
n1=int(input("Enter the lower range(greater than 0): ")) n2=int(input("Enter the upper range: ")) i=n1 if n1>0: print("Perfect numbers are:",end=" ") while i<n2: j,s=1,0 while j<i: if(i%j==0): s=s+j j=j+1 if(s==i): print(i,end=" ") ...
9deca1b67574763d7af287f9975a6a38784714fc
mohira/oop-iroha-python
/class_03.py
857
4.125
4
""" https://qiita.com/nrslib/items/73bf176147192c402049#class 変数で抽象化 """ from typing import List WRITE_TYPE_CONSOLE = "console" WRITE_TYPE_FILE = "file" def write(write_type: str, data: List[str]) -> None: if write_type == WRITE_TYPE_CONSOLE: write_console(data) elif write_type == WRITE_TYPE_FILE: ...
ac39edb41c9687a46b68fd2d07226fe60a18d298
Messi-ops509/mofan_pytorch
/2.py
754
3.5625
4
# 有关variable # 张量与变量,目前版本一致了, import torch from torch.autograd import Variable #定义一个张量数据, 中括号加中括号,外面还有一个大括号 将张量变为变量形式 requires_grad = True与反向传播有关 tensor = torch.FloatTensor([[1,2],[3,4]]) variable = Variable(tensor,requires_grad = True) print(tensor) print(variable) # v=x*x t_out = torch.mean(tensor*t...
f7242d3195488125b68a48c69ef5cb7aad20b1ec
randomman552/Sudoku
/sudoku.py
23,643
3.578125
4
#!/usr/bin/python3.7 import pygame import random import time from tkinter import messagebox as ms_box from tkinter import font as tkFont import tkinter as tk import threading import json import sys import time from solver import Solver import generator from typing import Optional, Tuple, List class DifficultyChooser(o...
dd865aa68e98fcdc3d26330ddf0743bdb5c34899
DmiFomin/HW4
/use_functions.py
1,290
4.15625
4
balance = 0.0 history = [] def incomes(balance_f): add_sum = float(input('Введите сумму для пополнения: ')) return balance_f + add_sum def expenses(balance_f, history_f): price = float(input('Введите сумму покупки: ')) if price > balance_f: print('У вас не хватает средств!') else: ...
5b908e3b54f751a8280305ca7b57b12903cf0f5e
Michael-Naguib/ProjectEuler
/16.py
693
4.125
4
''' Author: Michael Sherif Naguib Date: November 7, 2018 @: University of Tulsa Question #16: What is the sum of the digits of the number 2^1000? Example: 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. ''' if __name__=="__main__": #imports import math from funct...
9b403296e4dfdff4b6ac48def72e2847cf68adf7
natibaggi/faculdade-python
/Aula 25.09/continue.py
777
4.09375
4
executar = input("Você quer calcular? Sim(S) ou Não(N)"); while executar == "S": num1 = int(input("Digite o 1o número: ")); num2 = int(input("Digite o 2o número: ")); operador = input("Digite o operador: "); if operador == "+": resultado = num1 + num2; elif operador == "-": resulta...
47f53d1c6552f9f172a994415bb0a348c098f976
JRVSTechnologies/hackerrank_solutions
/easy/challanges/plusMinus.py
647
3.96875
4
#!/bin/python3 import math import os import random import re import sys # Complete the plusMinus function below. def plusMinus(arr): negative = 0 positive = 0 zero = 0 for i in arr: if(i < 0): negative += 1 elif(i > 0): positive += 1 elif(i == 0): ...
f6476beefdb4a0f875b7f3829188bffb5178f2c5
Maerig/advent_of_code_2017
/day19/main.py
1,667
3.5625
4
from utils.vector import Vector def read_input(): return [ line.rstrip() for line in open('input.txt') ] def get_segment(diagram, x, y): try: segment = diagram[y][x] except IndexError: return None if not segment.strip(): # Empty return None r...
976e0820de9c1efb467fac170274544afe7848a8
ahg2656/KICCampus
/pysou/pro1/pack1/test05.py
1,929
3.9375
4
''' tuple : list 와 유사, 읽기 전용(수정 X), list 보다 검색속도가 빠름 ''' # t = 'a', 'b', 'c', 'd' t = ('a', 'b', 'c', 'd') print(t, len(t), t.count('a'), t.index('b')) print() p = (1,2,3) print(p) # p[0] = 10 # err : 'tuple' object does not support item assignment q = list(p) # 형변환 q[0] = 10 p = tuple(q) print(p) print("\n값...
0cf3456fa826a3a98fa2434766b960518e61e542
sucpandu/CourseRegistration
/src/src/administratorCourseOp.py
8,327
3.53125
4
import sqlite3 import re import sys conn = sqlite3.connect('OpenOnlineCourse.db') curr = conn.cursor() def create_courses_table(): curr.execute( "CREATE TABLE IF NOT EXISTS courses(c_id INTEGER PRIMARY KEY, c_name TEXT, c_duration INTEGER, c_subject TEXT)") def add_course(): c_id = raw_input("...
54066a07f45f51876dc00221eb738b0a469ea63a
prince-prakash/practice_session
/tree.py
276
3.703125
4
hieght = eval(input("Enter the height of tree: ")) row = 0 while row < hieght: count = 0 while count < hieght - row: print(end='') count += 1 count = 0 while count< 2* row + 1: print(end=" ") count += 1 print() row += 1
3c85195049c69a998c673a36bdf33c9392b57d37
imkrislu/Statistical-Machine-Translation
/code/BLEU_score.py
3,786
3.84375
4
import math def BLEU_score(candidate, references, n, brevity=False): """ Calculate the BLEU score given a candidate sentence (string) and a list of reference sentences (list of strings). n specifies the level to calculate. n=1 unigram n=2 bigram ... and so on DO NOT concatenate the mea...
271cee7b28ed2cb30b98cd4b505ecd090b3fe15f
anmolrajputriyal/anmol
/assignment2.py
353
3.5625
4
#Q1 print("hello this is my output") #Q2 print("acad"+"view") #Q3 a=2 b=4 c=7 print(a,b,c) #Q4 print('let\'s get started') #Q5 s="acadview" course="python" fees=5000 print("hello welcome to %s your course name is %s and total amount pending rs %d"%(s,course,fees)) #Q6 name="tony" salary=2000...
29560880561a701e2a371d64ce390e88bccabf91
cainingning/leetcode
/tuter_start/116_tree.py
807
3.796875
4
# Definition for a Node. class Node(object): def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next class Solution(object): def connect(self, root): """ :type root: Node :rtype: Node """ ...
d7751d1873e99be3c5cb074bca409484d968a557
LucasEvo/Estudos-Python
/ex028.py
709
4.15625
4
# Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar # descobrir qual foi o número escolhido pelo computador. # O pragrama deverá escrever na tela se o usuário venceu ou perdeu. import random print('-=' * 30) print('Vou pensar em um número entre 0 e 5...
2913fb266f37073648601daa06bf0f403f6c60e6
Aasthaengg/IBMdataset
/Python_codes/p02812/s612446736.py
232
3.65625
4
n=int(input()) s=input() l=[] count=0 for i in s: if i=='A': l=['A'] elif i=='B' and l==['A']: l.append('B') elif i=='C' and l==['A','B']: l=[] count+=1 else: l=[] print(count)
9d3339091917164e08df0bbdbaff8eec6945d428
StartAmazing/Python
/venv/Include/book/chapter10/remember_me.py
1,317
3.953125
4
import json # 如果以前存储了用户名,就加载它 # 否则就提示用户输入并存储它 def greet_user(): file_name = 'username.json' try: with open(file_name) as username_obj: username = json.load(username_obj) except FileNotFoundError: username = input("What's your name ? ") with open(file_name, 'w') as usernam...
842c229e431eeaf0b254d2e785e5a5c70ae97d94
willwarreniv/resources
/week3/odd_list_test.py
548
4
4
from odd_list import OddList def test_create(): ol = OddList([1, 3]) def test_append_item(): ol = OddList([]) ol.append(7) def test_append_works(): ol = OddList([1]) ol.append(3) assert 3 in ol def test_insert_item(): ol = OddList([1,5]) ol.insert(3,1) assert list(ol) == [1,3,5] ...
e94d3fa4567a072d009caa9dd7560b3e22d6dce8
WaqasAkbarEngr/Python-Tutorials
/Variables.py
1,776
4.46875
4
# variable types are not needed to be declared in python # only value of variable is assigned. # python automatically detects type of entered data # for example numbers = 12345 # CAUTION! variable name is case sensitive # In above statement variable named numbers is declared by giving it numeric value # pytho...
b9161579d77cbc7b7fa4da974faa8e7e4922cdd1
MondayMorningHaskell/Sorting
/src/Quicksort/python/quicksort_inplace.py
1,887
4.34375
4
def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp # Partition the array (between indices 'start' and 'end') # Return the final pivot index. All elements to the left # of that index will be smaller than the element there. # All elements to the right will be greater. def partition(arr, start, end): ...
29415a9120c589cc9219b91223813d4f345135af
vishay28/year-2-project
/plug.py
2,643
3.703125
4
#This program controls the smart plug device #Imports the general file which contains various functions and variables which are used by multiple programs from generalFunctions import * #Importing the GPIO package import RPi.GPIO as GPIO #Setting the server message to blank serverMessage = "" #Creating a func...
6dd2125cb8cdf572b9ad1fd535a275f568321b98
nyowusu/ProgramFlow
/set_challenge.py
665
4.46875
4
# Create a program that takes some text and returns a list of all # the characters in the text that are not vowels, # sorted in alphabetical order. # # You can either enter the text from teh keyboard or # initialise a string variable with the string. vowels = frozenset('aeiou') # frozen set is being used because the ...
65425b08ac4d72da32509e430d5798ee2556f784
fourthtraining/ep35_c_to_f
/ep35_c_to_f.py
213
3.84375
4
c = input('請輸入攝氏溫度: ') c = float(c) #這一行式型別轉換,把c這個變數轉換成浮點數 --- PS:可以用整數(int)或浮點數(float) f = c * 9 / 5 + 32 print('華式溫度為: ', f)
4cd72861ed536f81e34e6b1044dc598af8047dd4
saulhappy/algoPractice
/python/miscPracticeProblems/Graphs/build_graph_from_edges.py
915
3.828125
4
""" Function that takes edges, and makes a graph """ from collections import defaultdict def build_graph(edges): graph = defaultdict(list) for edge in edges: a, b = edge graph[a].append(b) graph[b].append(a) return graph print(build_graph([ ['w', 'x'], ['x', 'y'], ['z', 'y'], ['z', 'v'],...
6eeb86ef6c78405f6a5edc68e748fd825704edd4
27kim/Python_DeepLearning_
/SoftMax_Classification_0.py
1,468
3.515625
4
# tensorflow import import tensorflow as tf import numpy as np xy = np.loadtxt('./data/05train.txt', dtype='float32') print(xy) x_data = xy[:, 0: 3] y_data = xy[:, 3:] print(x_data.shape, y_data.shape) # softmax 는 0으로 넣어도 된다고? W = tf.Variable(tf.zeros([3, 3])) # placeholder 지정 X = tf.placeholder(tf.float32) Y = t...
6be3e42b5a27e49de9e12cd1c03fe37a074d35a9
carolgcastro/Curso_Python
/Mundo 2/ex070.py
706
3.671875
4
total = 0 maior = 0 menor = 0 c = 1 nome_m = '' print('-'*30) print(' LOJA SUPER BARATÃO') print('-'*30) while True: nome = input('Nome do produto: ') preco = float(input('Preço: R$')) if preco > 1000: maior += 1 total += preco #soma preço de todos os produtos if c == 1...
1387b979c73755c838b95d101c7b7f85c182dfd7
dima17502/Python-Programes
/information_security/sieve_of_eratosthenes.py
298
3.578125
4
n = int(input()) sieve = [True] * (n + 1) i = 2 count = 0 while i * i <= n: j = i * i if sieve[j]: while j <= n: sieve[j] = False j += i i += 1 for i in range (2, len(sieve)): if sieve[i]: count += 1 #print(i, end=' ') print(count)
37b87e67a533a1693f99c7837d819d5dc2714306
Python-aryan/Hacktoberfest2020
/Python/Rock PaperScissors.py
2,858
4.15625
4
print("Made by Aayushi") win="You Win" loose="The Computer Wins" drew=0 lives=5 score=0 computer_lives=5 while True: rps=input("Rock, Paper, Scissor? ") import random computer=("rock", "paper", "scissor") computer=random.choice(computer) #rock statements if rps=="rock": if computer=="p...
5d85b75b28ebbfb6f7fabdc2b37602f48db0e427
kocsisttibor/pallida-exam-basics
/uniquechars/unique_chars_test.py
546
3.703125
4
import unittest from unique_chars import unique_characters class UniqueCharsTestCases(unittest.TestCase): def test_empty_string(self): self.assertEqual(unique_characters(""), []) def test_one_letter_string(self): self.assertEqual(unique_characters("a"), ["a"]) def test_duplicated_lette...
6fe7d3fb7f3e3a6aff0af040ac9175503a1a7eb2
T-Nawrocki/Udemy-Python
/Notes06-ProgramFlowControl/05-forloops2.py
505
4.625
5
# lecture 46 # for loops can be used with lists, as lists are another type of sequence for state in ["not pining", "no more", "a stiff", "bereft of life"]: print(f"This parrot is {state}.") # and similarly they work with ranges: for i in range(0, 101, 5): # the third argument is the step value print(i) # em...
cc9a9d497cd4dc6f9812d2d12632fed3296127c0
maxblood/flask-blog
/test.py
7,607
3.609375
4
from flask import Flask ,render_template,request, session ,redirect # flask is a micro frame work for web development from flask_sqlalchemy import SQLAlchemy #sqlalchemy is used for database from datetime import datetime app = Flask(__name__) app.secret_key = 'hello-world' ...
511ed3b5d5d5ae334a83916a138eaff30785bcae
p1pk4/Tasks-from-YNDX-Practicum
/vetv_task_3_4.py
761
4.03125
4
''' #Функция range(24) перебирает все числа от 0 до 24 и по очереди передаёт их в тело цикла в переменной current_hour («текущее время»). #Научите Анфису желать вам доброго утра, если в переменной current_hour записано значение меньше 12. #Расширьте код из прошлой задачи. Если на часах полдень или больше — пусть Анфис...
eeff677f4aaa0e138ca2297914198ac6ab12432d
droudrou/exact_splitting
/shape_split1D.py
18,980
3.6875
4
# coding: utf-8 # In[2]: import numpy as np import matplotlib.pyplot as plt import scipy.integrate as scint import math #get_ipython().magic('matplotlib inline') # In[ ]: # In[3]: def Getx(nx, xmin, xmax): dx = np.abs(xmax - xmin)/float(nx) x = xmin + np.arange(nx+1)*dx return x # In[4]: # re...
82b3a028b794949ff9eebb7f840266b4f4263ece
SyntaxStacks/Dev-test-project
/1-finding-the-source/measurements.py
610
3.703125
4
from reading import Reading class Measurements(): def __init__(self): self.measurements = [] def readMeasurementsFile(self, fileName): try: with open(fileName, 'r') as inputFile: for line in inputFile: x, y, distance = line.split() self.addMeasurement(Reading(x, y, distance)) except Exceptio...
eb7037eca42d1d6e9ff91231fbbd81d67d781aa7
derekhua/Advent-of-Code
/Day23/Solution.py
3,902
3.734375
4
''' --- Day 23: Opening the Turing Lock --- Little Jane Marie just got her very first computer for Christmas from some unknown benefactor. It comes with instructions and an example program, but the computer itself seems to be malfunctioning. She's curious what the program does, and would like you to help her run it. ...
abcb44271f775567bdce6e843debab8828da714d
fulv1o/Python-Basics
/Tipos de Dados/exemplo9.py
300
3.625
4
""" Fúlvio Taroni Monteforte Aluno de engenharia de computação do CEFET-MG. """ """ Exercícios retirados da geek university Leia uma temperatura em graus Celsius e apresente-a convertida em Kelvin. """ c = float(input("Informe a temperatura em graus Celsisu: ")) k = c+273.15 print(f'A temperatura é {k:.2f}K')
3544ebfc62a845356437e2712d8867a3a4983f4a
heathermoses/SI-Sessions
/Week7/kahoot.py
283
3.625
4
""" Questions for Kahoot Quiz Session 7 A """ def foo(start, stop): if start == 0 and stop == 0: print("Invalid start and stop values") if start >= stop: return else: print(start) foo(start + 2, stop) def main(): foo(0, 11) main()
7d45e87a4f29ac2f3cd25a1536cf6c969c5f9cfe
hieugomeister/ASU
/CST100/Chapter_1/Chapter_1/Ch_1_Solutions/Ch_1_Projects/1.1/loops.py
4,453
3.796875
4
""" Author: Hieu Pham ID: 0953-827 Section: 82909 Date: 11/10/2014 Design a function, using 2 loops, to print 10 lines of decimal numbers, from 0 to 9, on each line. Part 1 """ import string #Potential need for string functions import math def printstring(tn,xs): #Printing function """ Use 2 variables to pass...
dffe738b820809fa047f6a8f2f9d50485601798d
chc1129/introducing-python3
/chap04/codeStr.py
3,306
3.71875
4
# 60 sec/min * 60 min/hr * 24 hr/day seconds_per_day = 86400 seconds_per_day = 86400 # 60 sec/min 60 min/hr * 24 hr/day # I can say anything here, even if Python doesn't like it, # because I'm protected by the awesome # octothorpe. print("No comment: quotes make the # harmless.") alphabet = '' print(alphabet) alphabet ...
6b9924405c3393e7d7b4f405651fe5fd4eb6bd03
Kaushal1599/SkitCollege
/Enodes/media/Answer/numberdigit.py
497
3.6875
4
import math n = int(input()) numbers = list(map(int, input().split())) xor = 0 array = [] def printDivisors(n): global array i = 1 while i <= math.sqrt(n): if (n % i == 0): if (n / i == i): array.append(i) else: array.append(i) ...
02bac731615300b70a3c3f68698bddfadd7a3063
callmeislaan/LearnPython
/hello.py
111
3.890625
4
def hello(): name = input("input your name: ") return name name = hello() print("hello " + name + "!")
bfcf74bfa58b26d5f1f7bef719b1e53b5db11797
kenolheiser/try_git
/test_unittest.py
676
3.90625
4
#!/usr/bin/env python ''' Try some unit tests on the sample ''' import unittest from sample_code import is_divisible class TestIsDivisible(unittest.TestCase): def test_divisible_numbers(self): self.assertTrue(is_divisible(10, 2)) self.assertTrue(is_divisible(10, 10)) self.assertTrue(is_divi...
bf9914816fd8c6e989a785dc7b9e6f0edc45aa86
Aathish04/Old-Python-Game-Projects
/PyRPG/PyRPG.py
1,469
3.59375
4
#Code Setting Up Starts # All Modules are imported import time import random hp=30 count=0 peg="false" #All functions are defined def get_input(prompt, accepted): # This function returns an error message if the input doesnt make sense. while True: value=input(prompt).lower() if value in accepted: ...
041a57f8ce0eb5e43f8424bea4d11b8d280043ec
Vipinraj9526/Python
/rect3.py
703
4.03125
4
#create Rectanglr class with atribute lenght and breadth and method to find area and perimeeter. #Compare two Rectangle object by thier area. class Rectangle: def __init__(self,length,breadth): self.length=length self.breadth=breadth def area(self): return (self.length*self.breadth) def per...
7bd182a2987bf222028b22135867160e93eb8381
Selidex/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
526
3.6875
4
#!/usr/bin/python3 """ Test function find_peak """ def find_peak(list_of_integers): """Tests the peak of the list""" loi = list_of_integers if loi is None or len(loi) == 0: return None start = 0 end = len(loi) - 1 while start < end: mid = start + (end - start) // 2 if l...
6c29d66c9c24004a538f0f469c03d557c600e89b
shehryarbajwa/Algorithms--Datastructures
/trees/depth_first_search_pre_order.py
5,990
4.15625
4
# There are a total of 10 functions for the Node class that we rely on # 1-Initializing the Node class with value, left, right # 2-Set value of the Node # 3-Get value of the Node # 4-Set the left child of the Node by passing in a node # 5-Set the right child of the Node by passing in a node # 6-Get the left child of t...
86995c5a47bcda7d24d9355f16071b0e1951ac44
18101555672/LearnPython
/MOOC_Python/week_01/python_01.py
803
3.984375
4
# 实例1:温度转换 def temperatureChang(value,unit='F'): if unit == 'F': return '{}℃ ==> {:.2f}℉'.format(value,value*9/5+32) elif unit == 'C': return '{}℉ ==> {:.2f}℃'.format(value,5/9*(value-32)) else: return 'The second parameter please enter F or C' print(temperatureChang(18,'F')) print(t...
f23e24e975d33c6f288e3789adfb53130fec1098
nickbuker/python_practice
/src/integer_depth.py
471
4.0625
4
""" The depth of an integer n is defined to be how many multiples of n it is necessary to compute before all 10 digits have appeared at least once in some multiple. https://www.codewars.com/kata/integer-depth/python """ def compute_depth(n): bools = 10 * [False] depth = 1 while True: digits = m...
0d2cef3842d47d3d1169707122f7b8b04998d0f9
sivasai2467/siva-sai-kumar-reddy
/largestnum.py
132
3.71875
4
a=int(raw_input()) b=int(raw_input()) c=int(raw_input()) if (a>b) and (a>c): print a elif (b>c) and (b>a): print b else: print c
6a8f19438029dd5c2c820f6facf2eab62fc21986
payneal/price_picker_TDD
/test_price.py
2,558
3.671875
4
# test cases import unittest from price import Price class Test_Price_Case(unittest.TestCase): def setUp(self): self.price = Price(); def tearDown(self): pass def test_the_the_price_is_rounded_down_two_decimal_points(self): product_a = { "original": 2.91, ...
c1d14128f7e029d3b1a95dd3936908c40a0f763b
justinba1010/Pen-Academy-Python
/CoolStuff/RedBlackTree.py
2,655
3.71875
4
class RedBlackTree: class Node: def __init__(self,data, color = False): self.color = color#True for red, false for black self.data = data self.right = None self.left = None def add(self, data): #Is there a root? if self.root == None: ...
78477d2e1f9958a03e9c011146ccd7535afb5954
KaijuVandel/Bioinformatics
/math_functions/variance.py
561
4.28125
4
#!/usr/bin/env python import sys def average(x): tmp=0.0 n=len(x) for number in x: tmp=tmp+float(number) result=tmp/n return result def variance(numbers): '''This function takes in input a list of number and computes the variance''' n=len(numbers) total=0.0 avg=average(numbers) for value in numbers...
558508d95037a7d732fe31327d33d79f8f8c202a
buptconnor/myleet
/solved/P96_numTrees.py
335
3.609375
4
__author__ = 'Connor' class Solution: # @return an integer def numTrees(self, n): if n == 0 or n == 1: return 1 ans = 0 for i in range(n): ans += self.numTrees(i) * self.numTrees(n-1-i) return ans if __name__ == '__main__': so = Solution() print(...
1d2305b0666b9e7a3ecc293ce345c58685f1315f
ahmetoz/algo-assigment
/problem2/inversion.py
1,617
4.3125
4
import random """ Bilmuh 543 => Assigment 3 - Problem 2 ---------------------------------------- The counting inversion algorithm The difference from merge sort algorithm is that we want to do something extra: not only should we produce a single sorted list from A and B, but we should also count the number of "in...
e0286c528496c096d93bbef9f429edd8a0e04598
sandeepshiven/python-practice
/advance python modules/collection modules/counter.py
1,324
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 24 19:04:08 2019 @author: sandeep """ from collections import Counter # counter with list my_list = [1,1,0,0,0,0,1,5,5,5,3,3,2,-2,2,-3,-3,-3,-2,3,8,9,9,-2,4,1,2,8,8,64,66,1,48,88,888,11,1,1,3,6,6,6,4,4,7] print(Counter(my_list)) # prints the e...
a34d4af8152549623f38df6bc63aa246c7740bba
carloshssouza/UniversityStudies
/ProjectsGitHub/Python/Ordering_Methods/InsertionSort.py
338
3.859375
4
def insertionSort(vet): cont = 1 for cont in range(len(vet)): aux = vet[cont] j = cont-1 while j>= 0 and aux < vet[j]: vet[j+1] = vet[j] j -= 1 vet[j+1] = aux n = 5 vet = [] for i in range(n): vet.append(int(input('Type a number: '))) insertionSort(...
3d3ca4bdd5f4452e8f00cf56314f38996ce3edc2
nyucusp/gx5003-fall2013
/kll392/assignment4/problem1.py
3,035
3.578125
4
#Kara Leary #Urban Informatics - Assignment 4 #Problem 1 import MySQLdb import csv db = MySQLdb.connect(host="localhost", user="kll392", passwd="Maywalsh1", db="coursedb") cur = db.cursor() #Create boroughs table: createBoroughs = "create table boroughs (zip int not null, borough varchar(255), primary key(zip))" cur...
00c8035c8e2b386d94f39488f6324e795c34dd7a
matthewharrilal/CS-Questions-GRIND
/Leetcode Problems/majorityElement2.py
1,102
3.6875
4
class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ # We have to find the lower bound for how many times an element should appear lower_bound = math.ceil(len(nums) / 3) # Has to be higher than or equal ...
9447848b21396bae8709996a968b7264ef4a2edb
siddhantprateek/Python-in-Practice
/BFS DFS/bfs2.py
4,739
3.875
4
from collections import deque class TreeNode: def __init__(self, val): self.value = val self.left, self.right = None, None class BST(): def __init__(self): self.root = None def insert(self, val): self.root = self.insertHelper(self.root, val) def insertHe...
4d2b5c5293ba2202d51053f34e115ee21f2430e5
Joseph-Macalinao/Learn
/exceptions.py
426
4.3125
4
#what to do with code so that a single error won't crash program #try: and except: are what you need to use ''' try: code block here except ErrorType: return/result ''' #example try: age = int(input('Age:')) income = 20000 risk = income / age print(age) except ZeroDivisionError: print('Age...
8c0c24baecaf3e9ab064e5f46967b2a0e120304d
PdxCodeGuild/20170626-FullStack
/lab04-rock_paper_scissors.py
1,584
4.53125
5
# lab 4: play rock-paper-scissors with the computer # 1) we get the user's choice # 2) we check to make sure that what the user entered was among the valid possibilities # 3) the computer randomly picks rock, paper, or scissors # 4) depending on the choices, the program declares a winner or a tie # below are the vari...
1018964f92bf3c10f53f5dec7c95650ace729567
amritat123/dictionary-questions
/last_value_in_dict.py
154
3.640625
4
import json my_dict={"key1": "value1", "key2": "value2"} j=0 for i in my_dict.keys(): if j==len(my_dict)-1: print(my_dict[i]) j+=1
78de581f46d7517aea1e943ec522564075b9f5a8
LeJeuxStudio/lejeuxstudiodocs
/price_calculator/user_input.py
3,495
3.65625
4
from tkinter import * from tkinter import ttk from calculator import calculate from shipping import SHIPPING_OPT from plan import PLAN_OPT from taxation import IMPORT_TAX from currency import get_currency TITLE = "Selling Price Calculator" def init(): window = Tk() window.title(TITLE) window.geometry('3...
54ec747106717a3c3c5d4dcec7341bc4afac0e38
antoney1998/Codevita9
/Counting Palindromes/Solution.py
1,891
4.15625
4
from datetime import datetime from datetime import timedelta # code to take input durinng runtime could be added later here n1=1 n2=2 def check_palindrome(string):# returns true if string is palindrome reversed_string = string[::-1] #status=1 if(string==reversed_string): return True else: ...
62ed842e6a4f3e7dfd7ab603c719b3702c1b292c
dikoko/practice
/1 Numerics/1-05_total_num.py
1,284
4.03125
4
# 1-05. Total Number of Digits # Given an integer N, count all non-negative integers equal or less than N in which digit 3 is appearing. # e.g. N = 30 -> 4 (3, 13, 23, 30) # a brute-force solution def total_num_digit_bf(N): if N <= 0: return count = 0 for i in range(3, N+1): if '3' in str(i):...
3189d993628df0b3992446fe09ddfc1614c700bd
ayushgoel/PythonScripts
/HackerCup2017/ProgressPie/ProgressPie.py
1,579
3.640625
4
#!/usr/bin/env python import math def isOnAxis(x, y): return x == 50 or y == 50 def angleWhenOnAxis(x, y): if x == 50: if y >= 50: return 0 else: return 180 if y == 50: if x >= 50: return 90 else: return 270 def angle(x, y):...
c5b6acf4fb3f0d04485b4b2c4db40ba4d610d995
Caleb-Mitchell/code_in_place
/discord_extension/Lecture18/adventure.py
348
3.59375
4
import json ''' Allows the user to navigate around a (text based) world. Data comes from adventure.json ''' START = 'tresidder' def main(): data = json.load(open('adventure.json')) play_game(data) def play_game(data): print('Welcome to the Stanford Adventure Game:\n') # TODO: your code here print(data) if __n...
9ac49d199ec25246a36182cd38446a40ebd47997
Meiselina/Meiselina-
/ex13inputprompt.py
379
3.796875
4
from sys import argv script, first, second, third = argv prompt = '> ' print("The script is called:", script) print("Your first variable is:", first) print("Your second variable is:", second) print("Your third variable is:", third) print("What's your name?") Name = input(prompt) print (""") My english...
20245168da77684b42ece30230ca8f451921cf37
dungpa45/phamanhdung-faudamental-c4e13
/session2/homework/ex4g.py
205
3.859375
4
print("Nhap ma tran n*m voi n cot va m hang") n = int(input("Nhap so cot sao: ")) m = int(input("Nhap so hang sao: ")) for i in range(m): for i in range(1, n+1): print("*", end='') print()
369a3e67e5c9f1754ecfa9882908b1af657e4faa
StefanoBelli/ia1920
/linear_array_queue.py
1,001
3.546875
4
from collections.abc import Collection from ctypes import py_object as PyObject class Queue(Collection): def __init__(self, m): self._array = (PyObject * m)() self._max = m self._write = 0 def enqueue(self, elem): if self._write == self._max: return False s...
0aed344e25fc6d062126af243f698d10d042a4eb
sbordt/markovmixing
/markovmixing/plot_util.py
552
3.890625
4
""" Make good looking plots. """ import numpy def pyplot_bar(y, cmap='Blues'): """ Make a good looking pylot bar plot. Use a colormap to color the bars. y: height of bars cmap: colormap, defaults to 'Blues' """ import matplotlib.pyplot as plt from matplotlib.colors import Normalize from matplotlib.cm impor...
304d3b163ee0b52b2388d2c4c0f98594180252f6
danielv7/Algorithms
/DecodeWaysOfAlphabet.py
735
3.84375
4
#This question I first saw on LeetCode. #Given a non-empty string containing only digits, determine the total number of ways to decode it. #'A' -> 1 #'B' -> 2 #... #'Z' -> 26 #Example: Input "226" #Output 3: #Explanation: "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). #Time: O(n) Space: O(1) def numWaysDecoding(string)...
bdf70280cc4bd78c5b447d450d3186851ec45877
formalabstracts/CNL-CIC
/python-parser/lib.py
1,095
3.703125
4
# from collections.abc import Iterable def iterable(obj): return isinstance(obj, Iterable) def flatten(ls): """flatten a list one level""" return [v for sub in ls for v in sub] #sum([[1,2],[3,4],[5,6]])?? #print(flatten([[1,2],[3,4],[5,6]])) def fflatten(ls): """flatten recursive nested list...
37ed3c281e467ed81428034c82977b163aac44d6
ikekou/python-exercise-100-book
/_answer/PythonExercise/p22.py
250
4.03125
4
word1 = input('1つ目の文字列を入力してください > ') word2 = input('2つ目の文字列を入力してください > ') r = '' for ch in word1: if ch in word2 and not ch in r: r += ch print(f'重複する文字列 : {r}')
155ec9353c051440d8c14d390e9dd68beb6d40ac
nsuvorov17/BPS
/HW3/task1.py
1,052
3.84375
4
# Задание 1. Уровень - уверенный хелловордец. # Условие: Аркадий очень любопытный человек. Он загадал два числа A и B (оба строго больше нуля), # Аркадию всегда было интересно, чему равна сумма всех ЦЕЛЫХ чисел, заключенных между A и B, # включая их самих же. # Входные данные : целые числа A,B >0 # Выходные да...
8dea81a3a9e60daf80426be15e9814edc666bfc9
EitanVilker/CompLingProject
/transliteration.py
5,973
4.15625
4
# Authors: Eitan Vilker and Kai Frey (eitan.e.vilker.21@dartmouth.edu and kai.m.frey.22@dartmouth.edu) # Usage: Simply run with python transliteration.py and enter Romanized Hebrew words when prompted # Machine-transliterated Hebrew to Hebrew rules, for ease of reference # a -> א # b -> ב # g -> ג # d -> ד # h -> ה # ...
fa57723f7a7fba71c4038c6d3e9a73d1f5c68f91
jasonlingo/Machine_Learning-Data_to_Models
/Final_Project/program/src/tripDist.py
3,944
3.59375
4
""" Group the trips into three types: short, median, and long trips. For each trip group, plot every trip's starting point with its color determined by the error ratio: 1. blue color: error distance < trip distance * 0.1 2. green color: trip distance * 0.1 <= error distance < trip distance * 0.5 3. red colo...