blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
50cdc4250da30794c4455260a571b12ae3fde337
ucgmsim/qcore
/qcore/test/tool/utils.py
979
3.515625
4
""" Common functions for the test script """ import numpy as np import os ERROR_LIMIT = 1e-06 def compare_np_array(array1, array2, error_limit=ERROR_LIMIT): """first test if the two numpy arrays are of the same shape if pass, then test if the relative error between the two arrays are <= the preset error lim...
8e300896dfac3055e22b7f4aefb595ee98b1c06a
Navneeth-7/Python-Programs
/test2.py
631
3.765625
4
def square(num): return num*num g=11 def even(num): g=9 return num%2 ==0 a=[1,2,3,4,5,6] '''' print(list(map(square,a))) ''' #print(list(filter(even,a))) #for x in map(square,a): # print(x) #print(g) #print(list(map(lambda num:num**2,a))) #print(list(filter(lambda num:num%2==0,a))) #q=[...
b4e73fce7f10eef87f6d9ccc886e42fa5d8980f3
VeciCZ/ISJ-FIT-VUT
/isj_proj05_xvecer23.py
6,926
4.375
4
#!/usr/bin/env python3 def factorial(num): ''' Return factorial of a number using recursion. ''' if num == 0: return 1 else: return num * factorial(num-1) class Polynomial(): ''' Definition of a class to represent a polynomial and operations with it. ''' def __...
2d7432b6e76b31467b6d2849d57e3259be1521d3
tuanprono1hn/luonganhtuan-fundamentals-c4e16
/Session3/homework/crud.py
1,056
3.9375
4
items = ["T-shirt", "Sweater"] def read(): print("Our items: ", end = "") print(*items, sep=", ") print() def creat(): new = input("Enter new item: ") items.append(new) read() def update(): pos = int(input("Update position: ")) if pos <= len(items): new = input("Enter new item: "...
7e397b5b1085cda65d9851de55fcd5224709ca85
talianassi921/python-practice
/Methods/guessing.py
338
4.0625
4
import random number = random.randint(1,10) print("Guess a number between 1 and 10") guess = int(input()) while guess != number: if guess<number: print("Too low, try again!") guess = int(input()) if guess>number: print("Too high, try again!") guess = int(input()) print("You gues...
2b619f1b8dfacfa74a5a0c264ae9d97fc1255e77
jonsyou/exobrain
/put-data-frames-in-the-list.py
237
3.53125
4
########### # example # ########### import pandas as pd a_list_of_dataframes = [] # for level in range(100): # ## 여러 조건들 추가 # # df = pd.Dataframe(...) # # df = pd.Dataframe() # a_list_of_dataframes.append(df)
aa871e0dd2cec8fab66a5dd8dda712dd3ffa96f3
BenDosch/holbertonschool-higher_level_programming
/0x03-python-data_structures/1-element_at.py
312
3.65625
4
#!/usr/bin/python3 def element_at(my_list, idx): if idx < len(my_list) and idx >= 0: return (my_list[idx]) return (None) def main(): test_list = [1, 2, 3, 4, 5] idx = 3 print("Num at index {:d} is {}".format(idx, element_at(test_list, idx))) if __name__ == "__main__": main()
f7036a4aac608491bf9b67767516faf43a18a523
bhusalashish/DSA-1
/Data/Binary Trees/Height of Tree/Height of Tree.py
628
4.28125
4
''' #### Name: Height of Tree Link: [link]() **TC: O(n)** n is number of node in the tree ''' def height( root ): if root == None: return 0 return max(1+ height(root.left), 1 + height(root.right)) class Node: # A utility function to create a new node def __init__(self ,key): s...
f03ce5ca6d67aa2f8e5d7ec29cfe73640d95cd68
nordmoen/IT3105-quarto
/quarto/quarto.py
1,863
3.5625
4
#!/usr/bin/python from time import time from game import Game def main(player1, player2, num_rounds, simulate=False): game = Game(player1, player2) res = {player1: 0, player2: 0} progress = 0 mod_games = num_rounds / 10.0 for i in range(num_rounds): winner, board, win_pos, last_placed_pos ...
5fb3c5a7aadfa9f4ba4171d9fbab3eefd2fb8224
mfre1re/Diversas-atividades-em-Python
/Atividades - Python/Exerc.027.2 - Super Progressão Aritimática com WHILE Solução mais simples.py
781
3.609375
4
an = 1 count = 1 qntd = 1 b = 0 a1 = int(input('Digite o primeiro termo da PA: ')) r = int(input('Digite qual a razão da PA: ')) print('Os 10 primeiro termos dessa PA com o primeiro termo {} e a razão {} são: '.format(a1, r)) a10 = a1 + (an - 1)*r print(a10, end=', ') an += 1 while an != 0 and qntd != 0: a10 = a1 +...
ba783df233a9e90124cb227ea2d8b2ae8308810f
Jonathan1214/learn-python
/BasicExerciseAndKnowledge/w3cschool/n2_how_much_bonus.py
1,651
3.78125
4
#coding:utf-8 # 题目:企业发放的奖金根据利润提成。 # 利润(I)低于或等于10万元时,奖金可提10%; # 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%; # 20万到40万之间时,高于20万元的部分,可提成5%; # 40万到60万之间时高于40万元的部分,可提成3%; # 60万到100万之间时,高于60万元的部分,可提成1.5%, # 高于100万元时,超过100万元的部分按1%提成, # 从键盘输入当月利润I,求应发放奖金总数? # 一个简单的分段函数问题 # 非常难看的if嵌套...
d7805e6671c7fbe9d1804db907c8348689fbb951
GilbertoAzevedoNeto/AlgoritmosOrdena-oPython
/algoritmos-ordenacao.py
8,264
3.796875
4
from random import randint import datetime #Algoritmo de ordenação insertion sort. def algoritmo_ordenacao_insertion(A): for n in range(1, len(A)): m = n - 1 while A[m] > A[m+1] and m >= 0: A[m],A[m+1] = A[m+1],A[m] m -= 1 return A #Algoritmo de ordenação heap sort. def algoritmo_orden...
1aeb556497ce4b442923ef1c917aa779f16bb670
ryoichi551124/PythonBasic
/q6.py
186
3.90625
4
list = [10, 20, 33, 46, 55] print(f'Given list is {list}') print(f'Divisible of {len(list)} in a list') for list_number in list: if list_number % 5 == 0: print(list_number)
61ba12d58dbf7bfe63ace68dc75beb60b10a8133
maxschommer/business_card
/card_manufacturing/laser_calibration.py
5,521
3.59375
4
import plac import os import drawSvg as draw import numpy as np from mecode import G def draw_digit(num: str, width: float = 1, height: float = 2) -> np.ndarray: """Generates a numpy array of x, y points required to draw a given digit. Assumes that the laser is on the entire time during drawing for each d...
f990eefab6f6a68541adb6a6c684bbf6fa4ffba8
lagcrs/algoritmos
/exercicios/lista1/exercicio11.py
70
3.71875
4
num_real = float(input('Digite um número real: ')) print(num_real/3)
862e4c8023440bb32690acd4b31b11f2c909cbca
zhangkai98/ProgrammingForThePuzzledBook
/Puzzle21/optimal-BST-myexercise3.py
6,535
3.703125
4
#Programming for the Puzzled -- Srini Devadas #Questions Have a Price #An OOP-style BST representation is created. This procedure finds the optimal BST #that minimizes the average (expected) number of guesses to guess a number #given probabilities for each of the numbers. #BST Vertex Class and associated methods clas...
92aa347a9abea53c86498fda828fb3e26d9a5168
officer47p/matplotlib-tutorial
/(Part 1) Creating and Customizing Our First Plots/main.py
1,792
3.640625
4
from matplotlib import pyplot as plt # Link to format string in matplotlib Docs: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html # Printing all the themes print(plt.style.available) # Styling the figure plt.style.use('ggplot') # A cool theme for making our figure more like a hand drawing plt.xkcd() ...
3ce2d35c4823514fc6463cd216345cba76bd85d1
skyfallseven/noface
/core/crypto/core.py
3,937
3.703125
4
''' Skyfall Seven --------------- Introduction to Cryptography Project Assignment --------------- ''' # To seed the lower half of the L1 matrix from random import seed, randint from numpy.linalg import inv # to inverse a from numpy import matmul # for encryption from numpy import array # for NumPy Array to List conve...
4ea423a82ff3b7dba16985df207696739e127494
Achang0121/achangPython
/animal_3.py
775
3.875
4
#!/usr/bin/env python3 class Animal(object): def __init__(self, name, gender): self.name = name self.gender = gender def __getattribute__(self, attr): print('调用了 __getattribute__ 方法, 访问{}属性'.format(attr)) if attr in ('name', 'gender'): return object.__getattribute...
7b055f80ef6655ecceabc26a80561d1cecf4ef1e
dmcdekker/interview-and-coding-problems
/easy-python-problems/add-two/two_sum.py
2,451
4
4
import unittest '''Return true if the sum of any two elements equal the target number''' def two_sum_v1(nums, target): num_dict = {} for idx, num in enumerate(nums): diff = target - num # if the difference has already been recorded return it if diff in num_dict: retu...
2b6e7359e31497ae7fe25a241a2e2737f1436a3b
jmval111/Programming-Foundations-with-Python
/1 - Using Functions/make_program_whait.py
169
3.53125
4
import time #whait in seconds time.sleep(5) print "hola!, You waited 5 seconds before see this message " time.sleep(5) print "\nYou waited 5 more"
309ec2659e2ce55839c95c2a7c67aff0a642b63b
Lusimba/Math_Python
/Working with Numbers/UnitsConversion.py
881
4.40625
4
#Distance #Inches to Metres #1 inch = .0254 meters x = float(input('Enter your number in inches: ')) conv = 0.0254 def distance(x, conv): output = x*conv print('{} inches is equal to {} metres'.format (x, output)) return distance distance(x, conv) #You can use a similar method to convert any other units ...
1b3c5735ed209fdf0c8c22fdd89de0592a27e794
Aasthaengg/IBMdataset
/Python_codes/p03281/s570880490.py
229
3.515625
4
N = int(input()) cnt = 0 for i in range(1,N+1,2): ans=0 for j in range(1,i+1): if i % j == 0: ans += 1 else: pass if ans == 8: cnt += 1 else: pass print(cnt)
dc8ec6c584ad1bd97415ab50d20125cd203e621b
SashoStoichkovArchive/HB_TASKS
/projects/week06/03_04_2019/quadra.py
180
3.65625
4
def quadra(a, b, c): def calc(x): return (a * x ** 2) + (b * x) + c return calc func = quadra(1, 2, 3) # print(func) print(func(1)) print(func(2)) print(func(3))
31469e11c140a71413c1a54eba50e7b2b89b73d3
hungry4therock/my-python
/ch06/chapter06.lecture.step01_class.py
1,408
3.703125
4
#p151 # (1) 함수 정의 def cal_func(a,b): #변수 선언: 자료 저장 x = a y = b def plus(): p = x+y return p def minus(): m = x- y return m return plus, minus # (2) 함수 호출 p,m =cal_func(10,20) print('plus=',p()) print('minus=',m()) # (3) 클래스 정의 class calc_class: # 클래스 변수: 자...
36dd412cf1232ff5572f92f64a619d03dd462969
saumitra1978/pytools
/add2NumberwithLinkList.py
1,261
4.15625
4
import pdb class node(object): ''' Create a empty Node ''' def __init__(self): self.data = None self.next = None class List(object): ''' Below will create the link List and the methods ''' def __init__(self): self.curr_node = None def addNumber(sel...
bcfd71b0af0e0e40ee9dc8640272b40b61cace79
Bertkiing/python_learn
/python_func.py
723
3.90625
4
#无参无返回值 def printHi(): print("Hello,world") #单参无返回值 def printName(name): print(name) # 单参且有返回值 def add(a,b): return a + b #测试用例 print(add(4,4)) print(add("Hello","world")) def intersect(seq1,seq2): res = [] for x in seq1: if(x in seq2): res.append(x) return res #测试用例 prin...
131745887ea8476ec6803af847fe0cb4fc5aecc5
FadiRustom/gitTest1
/amt.py
1,384
3.8125
4
class ATM: def __init__(self, balance, bank_name): self.balance = balance self.bank_name = bank_name self.withdrawals_list = [] def calcul(self,request): self.withdrawals_list.append(request) self.balance -= request notes =[100,50,10,5] for note in notes :...
b33d4cfa3b5a2dff73d32e235b81faf943b9e39c
rsauhta/ProjectEuler
/p523.py
853
3.796875
4
# https://projecteuler.net/problem=523 # ''' Observe that sort proceeds by sorting the first n-1 elements, before tackling the last element. Let X be the last number in list. Sort the first n-1 elements. Now - if X is n, we are already sorted. - if X is 1, we need A(1)=1 steps - if X is 2, we will need A(2)=2 steps ...
9e02202640c324720389e33f9da1954cf20bec56
mbelalsh/Data_Structures_Algorithms_Specialization_Coursera
/3_Algorithms_on_Graphs/Assignments/week2_decomposition2/3_strongly_connected/Submission.py
1,000
3.65625
4
#python3 import sys def number_of_strongly_connected_components(adj): lis = [False]*len(adj) global c c = 0 #write your code here def explore(i,rem, lis): global c lis [i] = True #print(rem) for i in adj[i][:]: #print(i) if lis[i] == False: ...
8dbe7fe9b4e391e03d91c26bb31e4940ed771f25
lucyfayesmith/LucySmithA1
/LucySmithA1.py
3,159
4.09375
4
""" Lucy Smith 22.08.2018 BRIEF PROGRAM DETAILS: Link to program on Github """ MENU = """Menu: L - List all books A - Add new book M - Mark a books as completed Q - Quit""" def main(): print("Reading Tracker 1.0 - by Lucy Smith") book_file = open("books.csv", "r") books = [] '''count...
ff1d471ca8a624584706703d782c28c1743e1323
ramzymohammad/Ramzy_Ujian_Modul1_JCDS_JKT
/Ramzy_Ujian_Modul1_JCDS_JKT/nomer3.py
1,054
3.59375
4
class Statistic: # regular method def mean(self,first): jumlah = 0 for i in first: jumlah += i mean = jumlah/len(first) return mean # regular method def median(self, second): n = len(second) se...
2807b2d2dc28a01f46e39272271d2cb282eb7cc5
aqsc/vizgen
/proj/compiler/transforms.py
27,795
3.515625
4
""" Code transforms. On the Python input source, transform classes can be applied with the syntax (line numbers shown at left): 1 #transform(TypeSpecialize([{"n": "int", "i": "int", "ans": "numpy.ndarray[numpy.float64_t, ndim=1]"}])) 2 def f(n): 3 ans = numpy.zeros(n) 4 for i in range(n): ...
c8a8c34bb16161a4977e0f536c10fbc8aa51dc69
patrickjmartin1/ProjectEuler
/prime_pat.py
3,116
3.796875
4
from math import sqrt from numpy import ones def mrprime(n): d = int(n-1) y = n-1 s = 0 p = 0 z = [2,3,5,7] while d%2 == 0: d = int(d/2) s = s+1 if s == 0: return False for a in z: m = [] for r in range(0,s): m.append...
85f64a449019b66275be064f1b51c976d53f0a97
sabrinaspage/Numerical-Analysis
/solutions/homework_2/scaling.py
4,866
3.890625
4
import scipy import numpy as np import random import operations def main(): """ Using a linear system with randomly chosen matrix A, and right-hand-side vector b chosen so that the solution is known... """ A = np.array([[50, 2, 1], [2, 24, 6], [4, 7, 10]]) ...
2d27d15f5000f361f8dec31b63aa8473da168e93
MrHamdulay/csc3-capstone
/examples/data/Assignment_2/zydemi001/question2.py
2,910
4.40625
4
# A program which asks a series of questions to determine if you should eat food that has fallen onto the ground #Author: Emiel Zyde #Date: 6 March 2014 def intro(): print("Welcome to the 30 Second Rule Expert") print("------------------------------------") print("Answer the following questions by selectin...
f1ffb01db5f046bbded4167bbe0e7949e84cc61c
cgswjs/Leetcode
/prob31_nextPermutation.py
1,017
3.5625
4
class Solution: def nextPermutation(self,nums): i=j=len(nums)-1 #going through every number in this list nums #if left number if greater than current num that means the lexicographical order is right while i>0 and nums[i-1]>=nums[i]: i-=1 #if i==0, this means that all numbers in this list nums are in lexi...
43f0a98385707334faf59e7e0d42f0a08e0830ed
wjohnsson/adventofcode
/2019/03/crossed_wires.py
2,619
3.9375
4
from itertools import repeat # Beware: # Quick and dirty solution, lots of brute force and copy paste ¯\_(ツ)_/¯ input_lines = open("input.txt").readlines() def parse_input(wire_no): """Separate direction from length in each segment of the wire""" return [(segment[0], int(segment[1:])) for segment in ...
177559b26edd9df67f2ddf000e90b8f8b3ccbed2
Eilon17-meet/MEET-YL1
/eilon.py
523
3.921875
4
import turtle import time ''' numbers=[1,2,3] calculate=0 for i in numbers: print i print i*2 calculate+=i print calculate ''' speed=1 turtle.penup() turtle.goto(0,-100) turtle.pendown() turtle.width(5) turtle.ht() colors=['blue','red','green','yellow','pink','brown','purple'] for color in colors: speed+=1 turtle....
e908c0cdb47ec53a584bbb696107ef75881c3153
sumithasundaram/py4e
/range/range.py
115
3.546875
4
__author__ = 'Merlin' namelist = [1,2,3,4,5,'six',7,8,9,'ten'] for number in range(5): print (namelist[number])
c63c415117fa5833c02f4b99e927ef702c5d0216
jiluhu/dirtysalt.github.io
/codes/contest/leetcode/can-place-flowers.py
741
3.8125
4
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt class Solution: def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ ans = 0 for i in range(len(flowerbed)): if flowerbed[i] == 0: ...
f4d87b630a37b7088db1420cea405de95322235f
radmosley/lab_assignments
/lab_assignments/change_return.py
1,505
3.96875
4
# Some supermarkets have automatic change dispensers. # Ask for the amount of change to dispense in cents. # Assume that the amount input will be less than 100 cents. # Calculate the number of quarters necessary first. # Then calculate the number of dimes, nickels, and pennies. # If you do it in that order, you will mi...
800f644963cc8ac007fae43b546014c30e04c444
ahmetkca/trying-data-structures-with-python
/stack.py
1,101
3.84375
4
from main import LinkedList class Stack(LinkedList): def __init__(self, head=None, tail=None): super().__init__(head, tail) def push(self, node): self.insert_first(node) def pop(self): return self.remove_first() def getOpposite(a): if a == ']': return '[' elif a == ')': return '(' elif a == '}': ...
a31be4bc8f28453aac1452a4a95374fe287f5709
ordovicia/ksnctf
/02-Easy_Cipher/solve.py
800
3.734375
4
CODE = 'EBG KVVV vf n fvzcyr yrggre fhofgvghgvba pvcure gung ercynprf n yrggre jvgu gur yrggre KVVV yrggref nsgre vg va gur nycunorg. EBG KVVV vf na rknzcyr bs gur Pnrfne pvcure, qrirybcrq va napvrag Ebzr. Synt vf SYNTFjmtkOWFNZdjkkNH. Vafreg na haqrefpber vzzrqvngryl nsgre SYNT.' ALPHABET_NUM = 26 def rotate(rot, c...
b67deae6a1e2cb6073be36a01574988400e0c352
boshen119/Python-challenge
/PyBank/Bonnie_mainbank.py
2,850
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Dependencies import os import csv # In[ ]: # path to data worksheet # budget_csv = os.path ("..", "PyBank", "budget_data.csv") # In[ ]: # setting variables total_months = 0 total_profit_loss = 0 net_change = [] month_change= [] greatest_increase = 0 greatest_...
824134432f4fbbae673cc9af78912c4b3a28d97a
darkCavalier11/sort-python
/heap_sort.py
847
3.671875
4
def parent(i): return i//2 def left(i): return 2*i + 1 def right(i): return 2*i + 2 # max heapify take a single element and build heap def max_heapify(A, i): l = left(i) r = right(i) if l < len(A) and A[l] > A[i]: largest = l else: largest = i if r < len(A) and A[r] > A...
d6085813aae65d87ff8ae0e33ab801e856a180ba
johnakitto/project_euler
/euler_004.py
287
3.515625
4
import time start_time = time.time() biggest = 0 for n1 in range(100,1000): for n2 in range(n1,1000): x = n1 * n2 if str(x) == str(x)[::-1]: if x > biggest: biggest = x print() print('solution: '+ str(biggest)) print('runtime: %s sec' % (time.time() - start_time)) print()
068198dedcd02f8dd12c4521dc406a54b26d5a98
glebus/LuckyTicket
/luckyticket.py
935
3.859375
4
import sys def lucky(ticket): str_array = [] good_array = [] result = [] main_result = [] i = 0 try: ticket = str(ticket) if (len(ticket) != 6): return "6 digits!!!" except: return "Can't translate to string" for char in ticket: str_array.append(char) good_array.append(str_array[:len(str_array)/2]...
c265df63497279360c8b1e873589583444577333
fatmaoz7/GlobalAIHubPythonCourse
/Final Project/FinalProject.py
1,628
3.75
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 10 20:51:48 2021 @author: fatma oz """ from Question import Question print("Welcome to the Knowledge Competetion program") print("Each question worth 10 points") print("Answers were adjusted according to case sensitivity") print("Please be ready!") questions=...
357185feb859c5a67ae43b8e81c379ddd3a33bbf
ElAwbery/MIT-6.00.1x
/Week 5/cipherDrafts
2,068
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 10 16:49:33 2018 @author: ElAwbery """ import string #first attempt at build_shift_dict(). Got so far, then realized that using a generator might be better. def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to app...
5f2f011308ef491ed8b8ac7ff5d36300a4217c4b
HeadBangZ/PythonExercises
/Python/tkinterProj/Graph.py
343
3.5
4
from tkinter import * import math root = Tk() root.title("Curved Graph") data = [] c = Canvas(width=600, height=300, bg="white") c.pack() axes = c.create_line(50, 150, 550, 150, fill="green") for x in range(550): data.append(50 + x) data.append(150 - math.sin(x/20) * 100) sincurve = c.create_line(data, fi...
44126f49928832af4e3ffa358d3119c2d377f646
bbabaaba/leetcode
/287_Find_the_Duplicate_Number.py
437
3.546875
4
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ res = 0 for i in nums: if nums[abs(i)] > 0: nums[abs(i)] = -nums[abs(i)] else: res = abs(i) break for i in nums: ...
582c29e42d454c58f524fcc2376fe98c637a2393
trunghieu11/PythonAlgorithm
/Contest/Codeforces/Educational Codeforces Round 3/A.py
432
3.625
4
__author__ = 'trunghieu11' def solve(n, fileSize, usb): usb = sorted(usb, reverse = True) i = 0 total = 0 answer = 0 while total < fileSize: total += usb[i] answer += 1 i += 1 return answer if __name__ == '__main__': n = int(raw_input()) fileSize = int(raw_inp...
e9c6e1737bd759dd0b249e154704a0cb1370b001
klingonPiD/Car_detection_and_tracking
/hog_classify.py
990
3.515625
4
from skimage.feature import hog # Define a function to return HOG features and visualization def get_hog_features(img, orient, pix_per_cell, cell_per_block, vis=False, feature_vec=True): """Function to compute and return hog features of a given image""" # Call with two outputs if vis==True if vis =...
170b77de9dbecce887c3baa47fe56b9d5f19bba9
AstridJV/Strings_AV
/main.py
1,628
3.59375
4
# Do not modify these lines __winc_id__ = '71dd124b4a6e4d268f5973db521394ee' __human_name__ = 'strings' # Add your code after this line # First part of the exercise # wie maakte de doelpunten: scorer_1 = 'Ruud Gullit' scorer_2 = 'Marco van Basten' #in welke minuut vielen de doelpunten: goal_0 = 32 goal_...
f575b1a262a344cacbaa4d039e102c1428de7b09
droidy12527/AlgorithmsInPythonandCpp
/mountainclimbingarr.py
448
4.09375
4
def checkMountain(newarr): i = 1 while i < len(newarr) and newarr[i] > newarr[i-1]: i = i + 1 if i == len(newarr): return False while i < len(newarr) and newarr[i] < newarr[i-1]: i = i + 1 if i == len(newarr): return True arr = [1, 2, 3, 4, 2, 1] result = checkMount...
1eb24bb22dd0a40512a28041fe6d0761b9aea731
zhangshv123/superjump
/interview/google/face/exchange.py
679
3.90625
4
# 给两个string a, b,它们的距离定义为对应位置字符不同的个数。现在可以把a任意两个位置的字符交换一次, 问怎么交换使得距离最小。 from collections import defaultdict def exchange(a, b): m = defaultdict(set) for i, (ca, cb) in enumerate(zip(a, b)): if ca != cb: m[ca].add((cb, i)) print m res = (-1, -1) for ca, s in m.items(): ...
b460ebc8d01644e1922a487d227ca2dcc8abbe3b
AdamHussain786/Mathematical-generators-for-kids-in-python
/Algebra/generatorAlgebra.py
1,278
3.921875
4
import random import csv # x + int # x - int # Pick random questions to show the user for this one csv_file = open('algebra.csv', 'a') csv_writer = csv.writer(csv_file) csv_writer.writerow(['Question', 'Answer']) def algebraAdd(): for i in range(1000): y = random.randint(1, 10) x = random...
acaa19f0ad0dbce63bcea623951a94f1ab03d2d6
CodeHiestIndia/HacktoberFest2020
/Python/NewCalc.py
500
3.78125
4
def calc(n):     s=0     p=1     a=int(input("first number"))     b=int(input("second number"))     if n==1:         s=a+b         print("sum",s)     elif n==2:         p=a*b         print("prod",p)     elif n==3:         s=a-b         print("diff",s)     else:         p=a/b         print("divide",p) i...
67d7431cdb61ef938da288f6a798c68245dcdddc
gustavors22/shortest-path
/main.py
427
3.703125
4
from dijkstra.dijkstra import Dijkstra from graph.graph import Graph if __name__ == "__main__": origin = input("Type the origin point: ") destiny = input("Type the destiny point: ") graph = Graph() g = graph.make_dict_graph("grafo.txt") dijkstra = Dijkstra(g, origin, destiny) d, path = ...
65b3905da82fad17ff9ed609e3d15de2f77a6ee0
IsiahB/NameSurfer
/nameSurfer.py
3,000
4.5625
5
#Name: Isiah Behner #Assignment: Programming Assignment 6: Name Surfer #Course/Semester: CS 343 - Fall 2017 #Instructor: Dr. Murphy #Program Description: This program reads in data that contains # name popularity over a certain span of years and allows the user # to search and view the rankings of certain names....
f7f891d0affed22b9ca540559cff4987d517aa1c
PedroGoes16/Estudos
/Exercicios-Python/exercicios-curso-em-video/d102.py
500
3.84375
4
def fatorial(n,show = False): """ -> Calcula o fatorial de um número. :param n: O número a ser calculado. :param show (opcional): mostra ou não o calculo :return: O valor do fatorial de um número n. """ print(30*'-') f = 1 for c in range(n,0, -1): if show: if c > ...
10e015b7755310b7b8a9a89c467a479561be68a6
ys-practice/py_practice
/practice_001.py
1,668
4.03125
4
# 書籍購入ランキング # 社員数取得 input_emp_number = input() if not input_emp_number.isdecimal(): print('エラー:' + input_emp_number + 'は数値ではありません') emp_number = int(input_emp_number) # 社員名を取得してリスト作成 list_emp_name = input().rstrip().split(' ') # 社員数と社員名の件数が一致するかチェック if emp_number != len(list_emp_name): print('社員名の件数が入力値【社員数】...
44509452ba4474ee51660fe0fae37975e892822d
cespardo/grafico-linea-python
/grafica_linea_python.py
439
3.609375
4
#... #César Pardo - 23-marzo-2020 #Código de una gráfica con una línea en Python #... import math import matplotlib.pyplot as plt #Para este caso, importo el módulo numpy pero no lo utilizo, #se puede quitar si se quiere. import numpy as np #Creo una lista de datos. lista1 = [11,2,3,15,8,13,21,34] #Me permite abrir...
54c87d006cc0905a8a3c5f4771b0012e97d82ea9
lord-clam-slayer/python-hafb-main
/Day2/my_iter_part2.py
541
3.78125
4
#!/usr/bin/env python3 """ Author : t21 <me@wsu.com> Date : 8/10/2021 Purpose: """ # -------------------------------------------------- def main(): """Make your noise here""" s = {i for i in range(10)} print(s) d = {i: i*2 for i in range(10)} print(d) g = (i for i in range(10)) print(g) ...
d6608b825195552852b52e2f4e652500f59363d1
mottaquikarim/pydev-psets
/pset_loops/dict_loops/solutions/p1.py
585
3.84375
4
""" Contacts - SOLUTION """ # You went to a conference and got people to sign up for text updates from your startup. Go through this dict to make the phone numbers readable to a computer. # Hint: It can't include any non-numeric # characters. contacts = { 'Jamie': '1.192.168.0143', 'Kartik': '1.837.209.1121', 'G...
f9d7ebb8b47b5ced88529a5e72f2fb8d9c638e39
masonhuh/for_loops_basic1
/for_loops_basics.py
1,277
3.984375
4
# Basic - Print all integers from 0 to 150. for x in range(0,151): print(x) # Multiples of five - Print all the multiples of 5 from 5 to 1,000 num = 5 while num <= 1000: print(num) num = num + 5 # Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by...
a21efb4388c198ba46582b21063b1e1b3c5344f5
hossg/projecteuler
/Problem 41 - Pandigital Prime.py
1,973
4.09375
4
# # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, # 2143 is a 4-digit pandigital and is also prime. # # What is the largest n-digit pandigital prime that exists? # Eratosthenes Primes algorithm import logging def sieve(upperlimit): # mark o...
8e837cd7d02d2e5a0143e194c23f66f4d83b4b0a
obemauricio/Prog_Orientada_Objetos_2021
/main_library.py
1,338
3.578125
4
from library import Biblioteca from libro_library import Libro if __name__ == '__main__': ejecutar = True while(ejecutar): print('-------------BIBLIOTECA----------------') opcion = int(input('¿que vas a hacer?: \n1- Crear Biblioteca\n2- Agregar libro\n3- Ver catalogo\n4- Quitar libro\n5- ...
fd1d56ee7c3c5ea9e38dfa1fcb0003450e3aa076
frumpel/coding-questions
/leetcode/0205-isomorphic-strings.py
1,173
3.53125
4
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ map_f={} map_r={} if len(s) != len(t): return False for ii in range(len(s)): if not s[ii] in map_f: if ...
f7a563fd028e4cbfd739b6b774f3abef2a640bb4
fernandosavio/estudos-phyton
/python-brasil-wiki/1.EstruturaSequencial/exercicio_05.py
655
4.40625
4
#!/usr/bin/env python """ Faça um Programa que converta metros para centímetros. """ def float_or_int(number): return int(number) if number.is_integer() else float(number) def get_number(input_question): numero = None while not numero: try: numero = float(input(input_question)) ...
a271ecdedca0dcea18b26ff13331bb399b3872e2
Computer-Science-Lecture/CSE4020
/labs/lab1/Assignment1.py
1,521
4
4
# ## Loop for Sequence Types # In[16]: animals = ['cat', 'dog', 'monkey'] for animal in animals: print (animal) for idx, animal in enumerate(animals, 1): print ('#%d: %s' % (idx, animal)) # ## Dictionary # In[17]: d = {'cat': 'cute', 'dog': 'furry'} print (d['cat']) print ('cat' in d) d['fish'] = 'wet' ...
863846f1202e5ee2f63fdfff60ef0ac2192fb49f
Vakkruz/PythonExercises
/Example9.py
1,107
4.03125
4
import random usr_input = None while True: result = random.randint(1,9) counter = 0 while usr_input != "exit": usr_input = input("Guess a number between 1 and 9: ") if usr_input.isdigit(): converted_input = int(usr_input) if converted_input > result: ...
44e4caa86cc4a6c55eb3e8d03af39fffac6e694f
faten20/Python-Programming-1
/Week_11/JsonExample-1.py
182
3.640625
4
import json a = '{ "name":"ali", "age":30, "job":"accountant","salary":24000}' # parse x: b = json.loads(a) # the result is a Python dictionary: print(b) print(b["job"])
3baf2974227bbb03bc0b5e831a594bb2495f704b
Abhay-Vashishtha/Python_basics_exercise
/pandas_filling_NULL_with_most_frequent_ones.py
712
3.5
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 24 19:47:33 2020 @author: lic """ import pandas as pd import os #Initialize csv file path CSV_FILE=os.path.join('C:/Users/lic/.spyder-py3','artwork_data.csv') #Read entire dataframe df=pd.read_csv(CSV_FILE, index_col='id') #Filli...
e63438f8d0fb4edfc07e2ca115759d3f1e683380
gabriellaec/desoft-analise-exercicios
/backup/user_267/ch78_2020_06_21_00_43_30_170269.py
492
3.765625
4
def calcula_tempo(dicio): nome_tempo = {} for e,a in dicio.items(): t = (200/a)**(1/2) nome_tempo[e] = t return nome_tempo nome_acel = {} nome = input("Digite o nome: ") while nome != "sair": aceleracao = input("Digite a aceleração: ") nome_acel[nome] = aceleracao nome = input("...
55064b411a1426c6d9279868dd970d38e78152c9
thomurie/python_syntax
/words.py
1,174
4.53125
5
def print_upper_words(words): """Converts strings from array into all uppercase words prints each word on its own line Args: words (Array): accepts array of strings Returns: prints each word from the array in all uppercase """ for word in words: print(word.upper()); m...
af626afce39b0b3a8b04021f8dd1a267e6cb21e9
MaitreWilsen/PythonIntegrationProject
/Project Sprint 2.py
15,389
4.21875
4
# __author__ = Wilsen Maitre # The program will welcome the user and from their choice run a specific code. # Either a space or math related task. # Horoscopes for your Sun and Rising Signs : later(Final Sprint) : Files def main(): import random # Pre built function. Generate random number. continue_pro...
03bf3e70d1ca19edf3b765a789d96dc97dc9e6e4
Sepulta/physics_gifmaker
/3_body/extra_functions_3_body.py
3,229
3.71875
4
import math def check_total_inside_box(positions_list,x_lower_bound,x_upper_bound,y_lower_bound,y_upper_bound): #Loops over a list over positions and tests if any of these is out of bounds. for position in positions_list: val = check_inside_box(position,x_lower_bound,x_upper_bound,y_lower_bound,y_upper_bound) if...
25e235f766aa92213126d7f648e2ef73ba4576d9
TeeOhh/CI_TeachingKiosk
/scraping/courses.py
8,404
3.53125
4
from faculty import scrape_faculty_data import pandas as pd import re import string from nltk import word_tokenize from nltk.corpus import stopwords stops = set(stopwords.words('english')) def fetch_formatted_faculty_data(): """ Fetches and formats data scraped from faculty webpage. """ faculty_data...
c3491247a17bc3b2b0adf2edc0a64439be1f1b4f
mikels111/Practica_Python
/12.modulos/mimodulo.py
530
3.8125
4
def getTipo(var): if type(var) == list: print(f"la variable {var} es de tipo lista") elif type(var) == str: print(f"la variable {var} es de tipo String") elif type(var) == int: print(f"la variable {var} es de tipo entero") elif type(var) == bool: print(f"la variable {var}...
6ac6c9ce472ab18f91467d84bdd79d6a581d2fdf
AdamZhouSE/pythonHomework
/Code/CodeRecords/2451/58758/250498.py
134
3.515625
4
nums = [int(x) for x in input().split(',')] target = int(input()) i = 0 while i < len(nums) and nums[i] < target: i += 1 print(i)
26167441fd68c69ed9015da1ddda713b49550aed
richasharma3101/-100--Days-of-Code
/code/Day-7/firstduplicate.py.py
206
3.78125
4
arr=[int(x) for x in input("Enter the number seperated by space= ").strip().split()] for x in range(len(arr)): if arr[x] in arr[x+1:]: print("First duplicate array ",arr[x]) break
4fa5d162e0ab2ea76079571f6ddd8ca94722c781
JoshPorterDev/codewars
/shortestWord.py
504
4.4375
4
def find_short(s): """ Return the length of the shortest word in the given string """ stringArray = s.split() # Turn the list into an array with each word in the list represented by a different item in the array lenOfWords = [] for word in stringArray: lenOfWords.append(len(word)) lenOfWord...
3f08a352c34e194edb18abec48a17a9eb6a9558c
AndChen153/AP-Stat-scripts
/TwitterFollowerCounter/FollowerCounter.py
3,950
3.75
4
# https://www.geeksforgeeks.org/python-status-object-in-tweepy/ ''' Code to find tweets from memphis area and to count the follower counts for all unique accounts found. ''' import tweepy import time class TwitterClient(object): ''' twitter class for finding tweets from memphis area and counting the follwer c...
2179ac10c99d9fc1af0e79a5d4592c80b1aacfd8
drinaa/Recommendation-system
/intro/from_slides/task4.py
274
3.875
4
print("Введите A и B") a, b = int(input()), int(input()) sum = 0 mult = 1 for i in range (a, b+1): sum += i mult *= i print (f"Сумма чисел от {a} до {b} равна {sum}. Произведение этих чисел равно {mult}")
e4ce13ba196fde2c4aacdf02c39072e0a1b71364
heecer/old
/day7/datetime日期.py
510
3.859375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Haccer import datetime date = datetime.datetime.now() #当前时间 print(date) date = datetime.datetime.now()+datetime.timedelta(3) #当前时间加3天 print(date) date = datetime.datetime.now()+datetime.timedelta(-3) #当前时间减3天 print(date) date = datetime.datetime.now()+datetim...
2458f05bec883585008fecda68c27d45bdb43df6
getsomex/python
/start-basics/tuple.py
486
4.0625
4
# Tuple # tuples are like list we cannot modify them they are immutable my_tuple = (1, 2, 3, 4, 5, 1) # print(my_tuple[1]) # print(5 in my_tuple) user = { 'basket': [1, 2, 3], 'greet': 'hello', 'age': 30, (1, 2): 'tuple' } # print(user[(1, 2)]) # tuple that has single item tends to have a comma in the...
a1c3aff728e375178b6a89b8ed73f2b8b4f78df7
tr1503/LeetCode
/Design/dinnerPlates.py
1,117
3.6875
4
class DinnerPlates: def __init__(self, capacity: int): self.capacity = capacity self.heap = [] self.stacks = [] def push(self, val: int) -> None: while self.heap and self.heap[0] < len(self.stacks) and len(self.stacks[self.heap[0]]) == self.capacity: heapq.heappop(s...
244d7f449d315f1f7bf26062790eee7b9ca96043
kongkongo/LeetCode
/removeDuplicates.py
631
3.6875
4
from typing import List class Solution(object): def removeDuplicates(self, nums:List[int]): """ :type nums: List[int] :rtype: int """ flag=0 #定义一个指针变量 for j in range(1,len(nums)): #遍历数组 if nums[j]!=nums[flag]: # 若指针指向的元素与当前遍历数组的元素不同 ...
44fcdd87f96c9de962adf3a05be7fa2bce3772c1
Ygritte0/blog
/from_introduction_to_practice/10-3.py
168
3.609375
4
#-*-coding:utf-8-*- user_name = input("Please tell me your name:") filename = 'guest.txt' with open(filename,'a') as file_object: file_object.write(user_name+'\n')
5ff9b3aad8a837bbb9081f8e5233ab3f651251b2
JadaShipp/python-exercises
/4.4_control_structures_exercises.py
8,207
4.46875
4
#Conditional Basics --prompt the user for the day of the week, print out whether today is Monday or not In [2]: current_day_of_the_week = input('What is the day of the week? ') if current_day_of_the_week.lower() == 'monday': print('Today is Monday') else: print ('Today is not Monday') What is the day of the w...
dfd6408a3d84846aa37256ddaae8677f72e719f5
gutus/PythonMosh
/3.Control Flow/10_nested_loops.py
221
4.0625
4
# NESTED LOOPS (Loop di dalam Loop) for x in range(5): for y in range(3): print(f"Sample 1 >>> ({x}, {y})") print("\n\n") for x in range(5): for y in range(1, 4): print(f"Sample 2 >>> ({x}, {y})")
c0c7b82f21cf8bedea13b7297793202b4e94d29c
NmBoyd/Mastering-The-Coding-Interview
/Python/number_neg_int.py
771
3.96875
4
# find the number of negative integers in a # row wise / column-wise sorted matrix # [-3 -2 -1 1; -2 2 3 4; 4 5 7 8] --> 4 # the worst case is that you loop through everything # we can abuse the sorted structure!! # row 1: position of the last neg number is 2 -> 3 # row 2: lsat negative number is 0 -> 1 # row 4: non ...
163a9c91ccf471928e550295323e5673f791ce83
limdongjin/ProblemSolving
/Boj/9663.py
553
3.53125
4
from sys import stdin input = stdin.readline def check(cur_row, candidate_col): for r in range(cur_row): if candidate_col == board[r] or (cur_row - r) == abs(candidate_col - board[r]): return False return True def solve(cur_row): if cur_row == N: return 1 ret = 0 fo...
9f36c5270d2ba37c48d3a1c1824297977e94b69e
az-ahmad/python
/projects/BlackJackv2/newblackjack.py
613
3.703125
4
import random playerList = [] def greeting(): print('Welcome to BlackJack 2 player v.02') while True: try: numPlayers = int(input('How many players will there be? ')) except: print('Enter a valid number between 1 and 10') continue if numPlayers>0 and...
cdd6af6c9ea08cea9b96727a0931e3e82a3688df
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
/answers/vjha21/Day26/question2.py
612
4.03125
4
""" To modify the array so that it is non-decreasing. """ def modify_array(array): moves = 0 for i in range(0, len(array) - 1): if array[i] > array[i + 1]: moves += array[i] - array[i + 1] array[i + 1] += array[i] - array[i + 1] return moves, array if __name__ == "__main_...
2720eb990e5cc532b1d4ef6a8307860540913ee2
siryang/leetcode
/src2/3Sum/3Sum.py
1,519
3.734375
4
''' Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a <= b <= c) The solution set must not contain duplicate triplets. For example...
d13f15855311db18e7b85ca4e19979c59c2cfd8a
erinleeryan/2020adventofcode
/code/2020advent_day1.py
1,005
4
4
import itertools f = open("../data/advent_of_code_input_day_one.txt", "r") inputlist = list([(int(x.strip())) for x in f.readlines()]) def make_combos(listofvalues, combolength): combo = list(itertools.combinations(listofvalues,combolength)) return combo def add_elements_makes_2020(pair): retur...
ad50ce8a1afc59627c98457a9ff959e8688cbac7
booooster/Learning
/basic_day4 Quiz.py
1,185
3.71875
4
# Quiz) 당신의 학교에서는 파이썬 코딩 대회를 주최합니다. # 참석률을 높이기 위해 댓글 이벤트를 진행하기로 하였습니다. # 댓글 작성자들 중에 추첨을 통해 1명은 치킨, 3명은 커피 쿠폰을 받게 됩니다. # 추첨 프로그램을 작성하시오. # 조건1 : 편의상 댓글은 20명이 작성하였고 아이디는 1~20 이라고 가정 # 조건2 : 댓글 내용과 상관 없이 무작위로 추첨하되 중복 불가 # 조건3 : random 모듈의 shuffle과 sample을 활용 # (출력 예제) # -- 당첨자 발표 -- # 치킨 당첨자 : 1 # 커피 당첨자 : [...