blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6fa38f935a64815f43b7dfad002a16f4b328f5e3 | durstido/Data-Structures-Practice | /Binary_Search_Tree.py | 4,891 | 4.15625 | 4 | import sys
class Node:
def __init__(self, data): #when you define this, will define value at root
self.left = None
self.right = None
self.parent = None
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)
if self.right:
self.right.PrintTree()
def PrintTre... |
98fab0b1070da55289810b1d5a5c749999eaf049 | durstido/Data-Structures-Practice | /Trie.py | 1,605 | 3.921875 | 4 | class Trie:
def __init__(self, letter):
self.letter = letter
self.children = dict()
self.count = 0 #how many times it's been used
self.Max_letter = None
def insert(self, word):
for letter in word:
if(letter in self.children):
self = self.children[letter]
self.count += 1
else:
temp = Tri... |
3870ff88d2ccf9e93b614019b111298bcf131898 | durstido/Data-Structures-Practice | /mergesort.py | 907 | 4.125 | 4 | def mergesort(arr):
if (len(arr)>1):
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
mergesort(left)
mergesort(right)
#indexes for each array
left_i = 0
right_i = 0
arr_i = 0
while right_i<len(right) and left_i<len(left): #while there is still elements in both lists
if (right[right_i] ... |
c54a3181ace05349b58e8c04615a000d3aa52bc5 | chavitag/DAW_Programacion | /Tema 02/Python/Tarefa20b.py | 518 | 3.859375 | 4 | #/usr/bin/python
# -*- coding: utf-8 -*-
# suma=0
# Pedir num
# num=num-1
# Mentras num>0
# Si num e capicua suma=suma+num
# num=num-1
# FinMentras
#
# Consideramos capicúas os números de 1 díxito
#
def eCapicua(num):
num1=0
bknum=num
while (bknum>0):
num1=(num1*10)+(bknum%10)
bknum=bknum/10
retu... |
a2cbd7b01be6c036f09fa69d978f51a3dcc0f054 | chavitag/DAW_Programacion | /Tema 02/Python/Tarefa19.py | 425 | 3.8125 | 4 | #/usr/bin/python
# -*- coding: utf-8 -*-
#
# Pedir M
# suma=0
# c=1
# Mentras c<=M
# Si (ePrimo(c))
# suma=suma+c;
# FinSi
# c=c+1
# FinMentras
# Visualizar suma
#
def ePrimo(n):
c=2;
primo=True;
while ((c<n) and (n%c!=0)):
c=c+1
if (c<n):
primo=False;
return primo;
M=int(input("Numero Máximo: ")... |
94a42dde49a7edf632372068b72d8f652fbd5ed3 | chavitag/DAW_Programacion | /Tema 02/Clases Presenciais/DiasVida.py | 698 | 3.671875 | 4 | #!/bin/python
# -*- coding: utf-8 -*-
#
# Algoritmo que permita calcular a idade actual de una persona en días,
# solicitando o ano de nacemento e tendo en conta os anos bisiestos (contando dende o 1 de xaneiro).
#
# Pedir ano
# anoactual=2018
# totaldias=0
# Mentras ano < anoactual
# Si ano é bisiesto totaldias=total... |
5bd6f67b35267e18dec253826ac99697ad5921ef | DeepaSunkara/Python | /Q4.py | 4,498 | 3.796875 | 4 | import csv
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
highA_list = [];
lowA_list = [];
precipA_list = [];
fileA = open ("2009-June-Sept.csv") #opening the file 2009-June_Sept.csv
csv_fileA = csv.reader(fileA)
for row in csv_fileA: # here we are adding the high,low temperature values of ... |
214526d95d7a253dd4fe74657bf2d17698cd8edf | sab0946/PR301 | /interpreter v 1.05/unit_test.py | 1,450 | 3.859375 | 4 | import unittest
from class_builder import ClassBuilder, Attribute, Method
class MainTests(unittest.TestCase):
def setUp(self):
#to be executed before each test
x = ClassBuilder("ClassOne", "first_attribute : string", "first_method ()void")
def tearDown(self):
#to be xecuted af... |
a592a2234e5b6947afc1999a5e3b93dc30d13efd | Termich/All | /Ch1/Workshop_1.py | 1,891 | 4.15625 | 4 | #Загадать случайное число
#Ввожу что то, что я изучу через несколько уроков:
import random
start = 1
end = 100
#Указали точку начала и конца откуда можно производить случайный вывод числ. при чем задали их что они переменные.
print('Давайте сыграем в игру: ты загадаешь число, а я попробую его угадать.')
print('Для поп... |
3bf577bf318044b181c5b1fa33167ff62d95fafd | starmap0312/python | /questions/version.py | 618 | 3.5625 | 4 | # Compare two Version numbers (return latest version)
def compare(v1, v2):
arr1 = [int(i) for i in v1.split(".")]
arr2 = [int(i) for i in v2.split(".")]
n1 = len(arr1)
n2 = len(arr2)
if n1 > n2:
for i in range(n2, n1):
arr2.append(0)
elif n2 > n1:
for i in range(n1, n2):... |
7377dab7bacfc1c807b49f473775fea650c305b3 | starmap0312/python | /libraries/enumerate_zip.py | 849 | 4.78125 | 5 | print("1) enumerate():")
# 1) enumerate(iterable):
# return enumerate object that can be used to iterate both the indices and values of passed-in iterable
for index, value in enumerate(["one", "two", "three"]):
print(index, value)
# 2) zip(iterable1, iterable2):
# return an iterator of tuples, where the i-t... |
e8415955f2bc291b9a7334108b868a1c6aeaa8da | starmap0312/python | /libraries/py_parsing.py | 1,017 | 4 | 4 | from pyparsing import Word, Suppress, alphas, nums, alphanums
# example 1:
pattern = Word(alphas) + "," + Word(alphas) + "!" # a tokenized pattern
parsed = pattern.parseString("Hello, World!") # spaces between tokens are skipped by default
print(parsed) # ['Hello', ',', 'World',... |
a2f7b57efb9ddab5def6412fef252a9f3efa5789 | starmap0312/python | /libraries/concurrent_futures.py | 3,922 | 3.84375 | 4 | from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed, wait, FIRST_COMPLETED
import concurrent
import requests
from time import sleep
from random import randint
import math
# concurrent.futures:
# create threads & processes for concurrent execution of a function
# 1) ThreadPoolExecut... |
ad5027473cd9d1ac6cf941e80661c30452dd644e | xploreraj/HelloPython | /basics/print_basics.py | 539 | 4.03125 | 4 | name = "raj"
print(name)
name = 15
print("5 + 2 = ", 5 + 2)
print("5 - 2 = ", 5 - 2)
print("5 * 2 = ", 5 * 2)
print("5 / 2 = ", 5 / 2)
print("3 ** 2 = ", 3 ** 2)
print("5 // 2 = ", 5 // 2) # floors the value
quote = "\'Always remember you are unique"
multi_line_quote = ''' just
like everyone else!\' '''
new_str... |
9dc6900c0eb28775c0e4e8f9fbb353f0a57f6af9 | xploreraj/HelloPython | /algos/programs/ZeckendorfsTheorem.py | 479 | 4.28125 | 4 | '''
Print non-consecutive fibonacci numbers summing up to a given number
'''
# return nearest fibonacci num lesser or equal to argument
def nearest_fibo_num(num):
a, b = 0, 1
while True:
if a + b > num:
break
temp = b
b = a + b
a = temp
return b
if __name__ == ... |
52b299d0b9047ed9c489a3811c6bc089fb26dc52 | putetrekk/aoc-2020 | /day9.py | 1,072 | 3.6875 | 4 | with open("day9input.txt") as f:
my_string = f.read().strip()
numbers = [int(num) for num in my_string.split("\n")]
preamble_len = 25
def find_contiguous_at(index: int, target_sum: int):
for j in range(index, len(numbers)):
cs = numbers[index:j]
if len(cs) > 1 and sum(cs) == target_sum:
... |
2e6729751e4121eb1ced80ac7cc8baaf9fdcee40 | k8k/HBExercise01 | /ex01.py | 3,066 | 4.1875 | 4 | import random #imports random module
name = raw_input("Hi! What's your name?") #ask user for name
print "Hi %s, thanks for playing our guessing game. " % name #greets user by name
def guessGame(): #defines function that will run guessing game
number = random.randrange(1, 101) #generates a random number f... |
856635ac76b513e928fb52aa5ed17875087b4aaa | professor-python/2017-feb-abbblock | /less-5/py_4.py | 1,367 | 3.578125 | 4 |
from threading import ( Lock, RLock, Semaphore,
BoundedSemaphore, Thread )
from time import sleep
Lock # - простой mutex - потокобезопасный объект
# блокировки
# a = 10
# # thread 1:
# a = 20
# # thread 2:
# a = 100
RLock # - рекурсивный mutex, один блогировщик может заблокировать мно... |
55367574b24239fa1eb888ac6680f751d06c8cc8 | ronaldaguerrero/practice | /python2/python/OOP/store_products.py | 1,238 | 3.53125 | 4 | class Store:
def __init__(self, name):
self.name = name
self.list = []
def add_product(self, new_product):
self.list.append(new_product)
return self
def sell_product(self, id):
self.list.pop(id)
return self
def inflation(self,percent_increase):
for i in range(len(self.list)):
eval(self.list[i]).... |
eb828a3c770162eb7a52cd579b3366d838e1894a | ronaldaguerrero/practice | /python2/python/fundamentals/tenary_operator.py | 197 | 3.75 | 4 | stacks = 2
# traditional
# if stacks >= 3:
# print('Coding Dojo')
# else:
# print('You are not Coding Dojo!')
# ternary
print('Coding Dojo' if stacks >= 3 else 'You are not Coding Dojo!')
|
4d8aec916932686fca1970436e87c6149c4a7236 | ronaldaguerrero/practice | /python2/python/OOP/sensai_users_bankaccounts.py | 3,691 | 3.984375 | 4 | # make_withdrawal(self, amount) - have this method decrease the user's balance by the amount specified
# display_user_balance(self) - have this method print the user's name and account balance to the terminal
# eg. "User: Guido van Rossum, Balance: $150
# BONUS: transfer_money(self, other_user, amount) - have this meth... |
2dcff43bb6f73d3b5141178c3374911344e3c4aa | ronaldaguerrero/practice | /python2/python/fundamentals/lambdas.py | 1,291 | 4.6875 | 5 | # # Example 1
# # create a new list, with a lambda as an element
# my_list = ['test_string', 99, lambda x : x ** 2]
# # access the value in the list
# # print(my_list[2]) # will print a lambda object stored in memory
# # invoke the lambda function, passing in 5 as the argument
# print(my_list[2](5))
# # Example 2
# # ... |
3c2672a6b657efc27dd2add7b24d83db0755e87e | kashif-majid/accepts-three-integers-and-returns-True-if-they-are-sorted-and-false-if-they-are-not | /returns true if sorted otherwise false.py | 342 | 4.0625 | 4 | def sort(x):
if x==sorted(x):
return True
else:
print(False)
return sorted(a)
i=1
while i==1:
print("ENTER THREE INTEGERS:")
a=[]
for i in range(0,3):
a.append(int(input()))
print(sort(a))
i = int(input("\nIF U WANT TO CONTINUE PRESS 1 ELSE PR... |
de42c715411fca085cc61c4d6556165e6b6d3da7 | EleComb/IntroductionToAlgorithms | /chapter_2_TheBaseOfAlgo/test_1/test_2_InsertSortByDesc.py | 485 | 4.09375 | 4 |
def insert_sort_by_desc(a):
# loop the array
for i in range(1, len(a)):
key = a[i] # key is the NUM of AFTER
j = i - 1 # j is the index of BEFORE num
# sort by min to max:
while j >= 0 and a[j] < key:
a[j + 1] = a[j]
j = j - 1
a[j + 1] = key
... |
bf34467101325e5de92201ebdef9b014cce56cf2 | EleComb/IntroductionToAlgorithms | /chapter_4_DivideStrategy/C_SquareMatrixMultiplyRecursive.py | 2,944 | 3.75 | 4 | import numpy as np
import math
# Test tools
# A = np.array([[1,2], [2,1]])
# B = np.array([[1,3], [3,5]])
# C = np.zeros((4, 4))
# C[0:2,0:2] = A
# print(C)
# print(A + B)
# we should just use index of A, B, C . without initial more matrix
def square_matrix_multiply_recursive(A, B,
... |
b1ce5e32f46d29a4a33411ed575b7a6a73d4a8b5 | vladislavzik24/python_code | /spiral.py | 355 | 3.96875 | 4 | import turtle as tr
from math import sin, cos, pi
def deg_to_rad(deg, om):
rad = deg * pi / 180
return om * cos(rad), om * sin(rad)
a = int(input('Приращение за 1 круг: '))
n = int(input('Всего кругов спирали: '))
k = a / 360
for deg in range(0, n * 360):
x, y = deg_to_rad(deg, k * deg)
tr.goto(x, y)
print(x, y... |
d8ed1b84a9d47933980b6b7f2ebd4d3e9c7713c7 | zahraaliaghazadeh/python | /HelloWorld/whileloop.py | 213 | 4.03125 | 4 | # for loop
# for i in range(10):
# print("i is not {}".format(i))
# while loop
i = 0
while i < 10:
print("i is now {}".format(i))
i += 1
# i = 0
# while True:
# print("".format(i))
# i += 1
|
d2331f4d0ae550d79cc36677b8d55a4c92153840 | zahraaliaghazadeh/python | /functions_intro/banner.py | 2,242 | 4.15625 | 4 | # def banner_text(text=" ", screen_width=80):
def banner_text(text: str = " ", screen_width: int = 80) -> None:
""" Print a string centred, with ** either side.
:param text: The string to print.
An asterisk (*) will result in a row of asterisks.
The default will print a blank line, with a ** borde... |
5fdfa562e309a1adf91d366bfe03937faa133888 | zahraaliaghazadeh/python | /NU-CS5001/lab02/adder.py | 463 | 4.1875 | 4 | # num1 = float(input("Enter a first value: "))
# num2 = float(input("Enter a second value: "))
# sum = num1 + num2
# print("The sum of {} + {} is {}".format(num1, num2, sum))
# ==================================
# same code with function dedinition
def main():
num1 = float(input("Enter a first value: "))
... |
c6a65a425de28c349410853c79db1c66dab4fd43 | zahraaliaghazadeh/python | /Sequences/outliers.py | 2,412 | 3.953125 | 4 | data = [4, 5, 104, 105, 110, 120, 130, 130, 150,
160, 170, 183, 185, 187, 188, 192, 350, 360]
# TODO: set up test cases
# data = [4, 5, 104, 105, 110, 120, 130, 130, 150,
# 160, 170, 183, 185, 187, 188, 192, 350, 360]
# data = [4, 5, 104, 105, 110, 120, 130, 130, 150,
# 160, 170, 183, 185, 187, ... |
bb0229919c047eb2810ac30364b2b0b6a4eb1fc8 | zahraaliaghazadeh/python | /HelloWorld/operators.py | 533 | 3.828125 | 4 | a = 12
b = 3
print ( a + b) # 15
print ( a - b) # 9
print ( a * b) # 36
print ( a / b) # 4.0 result is float
print ( a // b) # 4 integer division, rounded down towards minus infinity , result is integer
print ( a % b) # 0 modulo: the remainder after integer division
print() # empty line
for i in range(1, ... |
8b4c5a99841830c0bec7f434ff55f51f15e68565 | zahraaliaghazadeh/python | /NU-CS5001/lab03/cap_vowels.py | 820 | 4.03125 | 4 | def cap_vowels(sentence):
answer = ""
for letter in sentence:
# check for vowels and make them uppercase
if letter in "aeiouAEIOU":
answer = answer + letter.upper()
# check for consonants and make them uppercase
else:
answer = answer + letter.lower()
r... |
8961bb70f0eea7a5a4cbeacca34b0a48f9fe42bd | Anutrix/ctfs.me | /PrivateRoom/final.py | 286 | 3.65625 | 4 | res = dict()
key = 0
for num in range(0,255):
key = ( (((num << 5) | (num >> 3)) ^ 111) & 255 )
res.setdefault(key, [])
res[key].append(chr(num))
#print(res)
flag = [233, 129, 9, 5, 130, 194, 195, 39, 75, 229]
for a in flag:
if a in res:
print(a,res[a])
|
112a324baf544eada32616f4de7148786d45e008 | tallyto/Exercicio_Metodologia_EPS | /IdadeEmDias.py | 624 | 3.890625 | 4 | """
5. Um algoritmo que leia a idade de uma pessoa expressa em anos, meses e dias e
mostre-a expressa apenas em dias. Considerar que um ano tenha 365 dias e um
mês tenha 30 dias;
"""
anos = int(input("Digite quantos anos tem: "))
meses = int(input("Digite quantos meses tem: "))
dias = int(input("Digite quantos dias tem... |
181c9171852431ee36304736b097816f6cf423a3 | jenjnif/cassidoo | /parentheses/parentheses.py | 2,217 | 4.28125 | 4 | '''
13 April 2020
This week’s question:
Given a number n, write a function to generate all combinations
of well-formed parentheses.
Example:
generateParens(3)
[“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
'''
# def generate_parentheses(n):
# parentheses_list = []
# if n == 1:
# parentheses_l... |
ac9d5c265190401c2e11d2b144cbf16961da09a2 | snalahi/Python-Basics | /week3_assignment.py | 2,114 | 4.4375 | 4 | # rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches)
# with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of
# rainfall. Store the result in the variable num_rainy_months. In other words, coun... |
f5d0cb627e69e28d7f89e2fdb30453dc9da39baf | kostis706/python-ergasies | /ergasia1.py | 1,525 | 3.9375 | 4 | try:
with open('file1.txt', 'r') as file:
words = words.split()
sorted_list = sorted(words, key=len)
reversed_list = sorted_list[::-1]
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'I', 'E', 'O', 'U')
try:
long_word_0 = reversed_list[0][::-1]
for char in long_word_0: ... |
91ceb0731b036c09dfc46263650e3f30033d9867 | brittanylindberg98/homework3 | /solution-321.py | 292 | 3.796875 | 4 | n=int(input("Enter cost in cents:"))
change=100-n
quarters=int(change//25) # 1 quarters=25 cents
dimes=int((change-25*quarters)//10) # 1 dime=10 cents
pennies=int((change-25*quarters-10*dimes)) # 1 penny=1 cent
print(quarters,"quarters")
print(dimes,"dimes")
print(pennies,"pennies")
|
9958cb6aaee03eb706491788525e3de5f6fb1f11 | qiaochug/TNOSearch | /mergeTriplets/worthadding2 | 1,315 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 3 11:55:38 2017
@author: qiaochug
"""
import numpy as np
import matplotlib.pyplot as plt
def contains(subseq, inseq):
return any(inseq[pos:pos + len(subseq)] == subseq for pos in range(0, len(inseq) - len(subseq) + 1))
#class that stores tri... |
06dbe5531992d6c6df8feb30c6b97b17b113b824 | Daksh-ai/swapcase-of-string | /string swapcase.py | 216 | 4.21875 | 4 | def swapcase(string):
return s.swapcase()
s=input("Enter The String")
sub=swapcase(s)
print(sub)
#example-->input=Daksh output-->dAKSH
#in genrally we say that its used to change the case of string and vice-versa |
69b5f8c8579a03a2d9051e710b9ac49f58556aa5 | VJefimov/rainbow | /12345.py | 464 | 3.6875 | 4 | def sort_values (valjund):
rida=input("Введите цифры и буквы в произвольном порядкеx через запятую:" )
'''fuktsioon mis sorteerib tähed ja numbrid'''
uusrida=rida.replace(",","")
print(uusrida)
uusrida=sorted(uusrida)
i=1
for i in uusrida:
print(i, end="")
return valjund
print(so... |
02db8aabd25e344ffcfda644c102cb95c2066a47 | laoshunya/pythoncode | /day01-04.py | 344 | 4.09375 | 4 | # list和tuple
# list
names = ["Mark","Jack","Bob"]
print(names)
print(names[2])
# 添加元素
names.append("Lucy")
print(names)
names.insert(0,"Noya")
print(names)
# 删除元素
names.pop()
print(names)
names.pop(0)
print(names)
names.remove("Jack")
print(names)
# 替换元素
names[0] = "Noya"
print(names)
# tuplelala撒飞洒发生大
|
460808014d310835d4b74576df32e1b497d2e8fc | kpruehss/LP3THW | /ex33.py | 385 | 3.8125 | 4 | from sys import argv
numbers = []
script, limit, step = argv
def while_loop(limit, step=1):
i = 0
while i < limit:
print(f"At the top i is {i}")
numbers.append(i)
i += step
print("Numbers now: ", numbers)
print(f"At the bottom, i is {i}")
while_loop(int(limit), int(s... |
8e2fe723ed956ade244a08f695f13f41106825a6 | WhatTheMUCK/Lambda | /3.py | 273 | 3.640625 | 4 | m=[]
print('Введите 10 чисел массива')
for i in range(0,10):
a=int(input())
m=m+[a]
print('Для того, чтобы посчитать сумму элементов массива введите: Sum(m)')
def Sum(m):
return sum(m)
|
385d376dffab42f5e3c1955b49f61c9f4501b168 | vanesareyes/HO-python | /ejercicio_01a.py | 174 | 3.78125 | 4 | '''
Ejercicio 1a
'''
x = range (10)
#print (x)
a=range(0,1000,3)
'''print(a)'''
b=range(0,1000,5)
c=(a,b)
'''print(c)'''
d=set(a)|set(b)
'''print d'''
e=sum (d)
print e
|
41f94e2e75ac59020e4867fe822bd8a58e2d7e47 | IslamKyrre/TicTacToe | /main.py | 5,438 | 3.734375 | 4 | import sys
from PIL import Image, ImageDraw
from math import floor
from collections import Counter
def is_black(pixel):
r, g, b, a = pixel
return max(r, g, b) < 10 and not a == 0
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python3 main.py <path_to_input_image> <... |
28438ac3d7eeab73b22fde4b03ce592a548d616f | NisseAnd/P-Info | /library/marked_parking_spots.py | 1,574 | 3.640625 | 4 | import pandas as pd
# import utility.convert_csv as cc
def marked_spots(data):
even_df = data[data['vejside'] == 'Lige husnr.']
uneven_df = data[data['vejside'] == 'Ulige husnr.']
# We sum because there can be more than one parking spot in a place.
even_total = even_df.antal_pladser.sum()
une... |
c3162b99ed727ddf2ac538cceedc6f3781076915 | Tabsdrisbidmamul/PythonMaster | /Section-11-Generators-Yields-Lambda/musicFiles/listfor.py | 252 | 3.90625 | 4 | print(__file__)
numbers = [1, 2, 3, 4, 5, 6]
squares = map(lambda x: x**2, numbers)
for s in squares:
print(s)
squares = []
for number in numbers:
squares.append(number ** 2)
print(squares)
squares = [x ** 2 for x in numbers]
print(squares) |
e8a964b976b529557777850b29d95eb2e876413d | haolloyin/projecteuler | /solutions/prime.py | 448 | 4.0625 | 4 |
import math
def isPrime(num):
if num == 1:
return False
elif num < 4:
return True
elif num % 2 == 0:
return False
elif num < 9:
return True
elif num % 3 == 0:
return False
else:
r = math.floor(math.sqrt(num))
f = 5
while f <= r:
if num % f == 0: return False
if num % (... |
4a5c254c5d241a0c09862ca7995b1652932cd858 | arvagas/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,557 | 4.125 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO
count = 0
while count < elements:
if len(arrA) == 0:
merged_arr[count] = arrB[0]
arrB.pop(0)
e... |
c2e67e22140217bef39c2e7c652e6d8c0557235d | xuzjun/SolutionsForProjectEuler | /p19.py | 1,127 | 3.71875 | 4 | #-*- coding: utf-8 -*-
daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leapYearDays = 366
yearDays = 365
daysBeforeYear = []
def isLeapYear(n):
return (n % 4 == 0 and n % 100 != 0) or (n % 400 == 0)
def fillDaysBeforeYear():
daysBeforeYear.append(0)
daysOfYear = [0 for x in range(101)]
for y in ... |
4d08d877fd3bc6e7aa4d6f1210150fdc45a9ec56 | xuzjun/SolutionsForProjectEuler | /p35.py | 596 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from utils import prime
def isCircularPrimes(n):
if n < 20:
return True
q = n
p = 10
w = 1
while True:
if q / p != 0:
w += 1
else:
break
p *= 10
p = 10 ** (w - 1)
while w > 1:
w -= 1
n = (n ... |
f360e93591777fd257126c370270955994f4e2f9 | xuzjun/SolutionsForProjectEuler | /p28.py | 847 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
#
# 43 44 45 46 47 48 49
# 42 21 22 23 24 25 26
# 41 20 7 8 9 10 27
# 40 19 6 1 2 11 28
# 39 18 5 4 3 12 29
# 38 17 16 15 14 13 30
# 37 36 35 34 33 32 31
#
# It can be... |
27e2826eba12cfd9d7c0016d0400de12e931cea8 | alexandrazelcer/python-challenge | /python-challenge/PyBank/main.py | 2,363 | 3.734375 | 4 | #import modeules
import os
import csv
#define resource file path
csvpath = os.path.join("Resources","budget_data.csv")
#declair variables
total_months = 0
total_net = 0
avg_net = 0.00
greatest_increase_amt = 0
greatest_increase_mo = ""
greatest_decrease_amt = 0
greatest_decrease_mo = ""
#open resourc... |
c93ff1c916b5f758eb8e24dfa8d8b34138149a47 | dominichsiao/CS362_HW4 | /name.py | 186 | 3.640625 | 4 | def name(first, last):
full_name = ""
full_name = first + " " + last
return full_name
def main():
name("Sree", "Gajula")
if __name__ == "__main__":
main()
|
152633ccc8719e7899ade8f95b540e769f7feab0 | brett-dun/games | /tictactoe/intelligentplayer.py | 5,391 | 3.671875 | 4 | #!/usr/bin/env python
__author__ = "Brett Duncan"
__copyright__ = "Copyright 2019"
__credits__ = []
__license__ = ""
__version__ = "0.0.0"
__maintainer__ = "Brett Duncan"
__email__ = "dunca384@umn.edu"
__status__ = "Development"
from typing import Tuple, List
import math
from tictactoe import check_for_winner, tabl... |
a66518fde74ea9cfd3dfc0a4673ffd3c696635c5 | daksh-git/Turtle_Codes | /School/Stamp Spiral.py | 209 | 3.578125 | 4 | import turtle as bob
bob.shape('turtle')
bob.color('blue')
bob.getscreen().bgcolor('#90EE90')
x = 20
for i in range(25):
bob.pu()
bob.circle(x, 30)
bob.pd()
bob.stamp()
x += 5
bob.done()
|
0dfba0726097814301118596ec2b617ee26349d1 | dmiyakawa/python_asyncio_eval_misc | /strange_generator.py | 183 | 3.6875 | 4 | def foo(n):
if n in (0, 1):
return [1]
for item in range(n):
yield item * 2
print(list(foo(0))) # []
print(list(foo(1))) # []
print(list(foo(2))) # [0, 2]
|
525a3604970250f12e90e64e5eab480b2381bdc0 | adamstebbing/mini-projects | /TurtleDraw.py | 1,422 | 4.0625 | 4 | import turtle
def draw_triangle(tim, points):
tim.up() #Nothing is drawn when changing locations
tim.goto(points[0][0],points[0][1]) #Go to bottom left of triangle
tim.down()
tim.goto(points[1][0],points[1][1]) #Draw to top of triangle
tim.goto(points[2][0],points[2][1]) #Draw to bottom right of tr... |
5350e01c730ee8118107c06cc5678d0cd08e50b0 | JoaoHenriqueOliveira/Bioinformatics-1 | /week2/skew.py | 844 | 3.6875 | 4 | def skew(genoma, i = 0):
#Difference between numbers of G and C in genoma (until position i, if i != 0. Otherwise will consider the whole genoma.
c, g = 0, 0
if i == 0:
n = len(genoma)
res = [ 0 for j in range(n+1)]
c, g = 0, 0
for j in range(n):
if genoma[j... |
d5f2922f3230f89a82826b8674cd4218c76f832a | JoaoHenriqueOliveira/Bioinformatics-1 | /week3/MedianString.py | 1,858 | 3.578125 | 4 | from DistanceBetweenPatternAndString import DistanceBetweenPatternAndString
dic = {"A": "0", "C": "1", "G": "2", "T": "3"}
def get_key(val):
for key, value in dic.items():
if val == value:
return key
return "key doesn't exits!"
def base4_to_base10(nbr): #recebe string, retorna int
... |
a19b76dc9a81fc674bdc6d0da3167e202165396f | JoaoHenriqueOliveira/Bioinformatics-1 | /week2/MinimumSkew.py | 599 | 3.6875 | 4 | from skew import skew
def MinimumSkew(genome):
#Find a position in a genome minimizing the skew.
#Output: All integer(s) i minimizing Skewi (Genome) among all values of i (from 0 to |Genome|).
diff = skew(genome)
aux = min(diff)
positions = []
for i in range(len(genome)):
if diff[i+1] ... |
99a7f087b52a151e6f2dc68ed73ffbc83e4ac69c | EnduringBeta/MakeChange | /MakeChange.py | 5,993 | 3.984375 | 4 | # Make Change
# Ross' first significant Python excursion
# 14 April 2014
#
# This program takes in a monetary value and
# calculates the number of ways that value can
# be reached through coinage and paper bills.
#
# The values for denominations can be changed.
# I plan to include a parameter for default currencies.
# ... |
f288475f26f4ab9bb2bdf4d32a3930c020c44646 | yarov475/finder | /finder_store_res_txt.py | 438 | 3.78125 | 4 | import os
def searchfiles(extension='.ttf', folder='H:\\'):
"Create a txt file with all the file of a type"
with open(extension[1:] + "file.txt", "w", encoding="utf-8") as filewrite:
for r, d, f in os.walk(folder):
for file in f:
if file.endswith(extension):
... |
b89bf0e777d458d04f0e3f3612f2b8e6165004a2 | mathias3/tidy-Data-in.py | /.py | 922 | 4.0625 | 4 | # Import pandas as pd
import pandas as pd
# Melt df2 into new dataframe: df2_melted
df2_melted = pd.melt(df2, id_vars = "Country")
# print df2_melted
print(df2_melted)
----
# Rename the columns of df2_melted: df2_tidy
df2_tidy = df2_melted.rename(columns = {'variable':'Year','value':'Income'}, inplace = False)
# Pr... |
c4a8ab2c1c2ea67e030478238ada13aa23add8b8 | wanermiranda/cn2 | /graph.py | 3,713 | 3.5 | 4 | __author__ = 'Waner Miranda'
__email__ = 'waner@dcc.ufmg.br'
DEFAULT_TAU_VALUE = 1
class WeightedGraph(object):
def __init__(self, evaporating_rate=0.0):
""" initializes a graph object """
self._graph_dict = {}
self._graph_dict_weights = {}
self._graph_dict_tau = {}
self._... |
5e96df57c08cd50d1e15c2333358880d06a37321 | layan20-meet/YL1-201718 | /lab1.py | 613 | 3.921875 | 4 | #import turtle
#print("layan")
#for i in range(100):
# print("layan")
#number1=3
#number2=number1/2
#print(number2)
##sum=0
##x=[1,2,3]
##for i in x:
## print("i= ",i)
## print("double i= ",i*2)
## sum=sum+i
##print("total=",sum)
#turtle.goto(100,100)
x=0
y=0
challenge
turtle.pensize(20)
for i in rang... |
adffc060eef44ca730396f705695819ff7f44495 | KevinTorres03/Codigos-fuente-C-y-Python | /Proyectos Python (2)/Aprueba o reprueba materias.py | 599 | 3.90625 | 4 | print ("Vamos a determinar si un estudiante aprobó o reprobó la materia")
ce = int( input ("Ingrese el codigo del estudiante: "))
nm = input ("Ingrese el nombre completo del estudiante: ")
mt = input ("Ingrese la materia: ")
n1 = int( input ("Ingrese la primera nota: "))
n2 = int( input ("Ingrese la segunda nota: ... |
42260365bfcb158f7609e8b8bed7e121b2452db3 | KevinTorres03/Codigos-fuente-C-y-Python | /Proyectos Python (2)/La mitad de un numero.py | 231 | 3.8125 | 4 | print ("Vamos a determinar si la mitad de un numero es mayor o menor a 100")
n1 = int( input ("Ingrese el numero: "))
if n1/2>100:
print("El numero es mayor a 100 es: ")
else:
print("El numero es menor a 100 es: ")
|
24e42531722231e5f75bdebd717573d1666d7e33 | KevinTorres03/Codigos-fuente-C-y-Python | /Proyectos Python (2)/Descuento.py | 541 | 3.875 | 4 | print ("Programa que va a determinar el total a pagar por una compra")
cp = int( input ("Ingrese la cantidad de articulos: "))
vu = int ( input ("Ingrese el valor unitario de los productos: "))
if cp*vu>=20000:
print("El total a a pagar por la compra de los productos es: " ,(cp*vu-cp*vu*35/100)," Ya que se le... |
8c29522db5fcecb06c24725df044fe0aa880c0af | KevinTorres03/Codigos-fuente-C-y-Python | /Proyectos Python (1)/edad.py | 225 | 3.625 | 4 | print ("Vamos a determinar la edad de una persona")
AA = int( input (" Ingrese el ultimo año en el que cumplio años: "))
AN = int( input (" Ingrese el año en el que nacio: "))
print("La edad es: " ,(AA-AN), " años ")
|
ac115c8f83d7894d1c5f4703241e94378a54b033 | aviadnissel/hapython | /pyfiles/conditions.py | 239 | 3.578125 | 4 | גיל = 27.5
שם = "אביעד"
if שם == "אביעד":
print("ברוך הבא אביעד")
elif שם == "נעמה" or (שם == "ענבר" and גיל == 21):
print("שלום נעמה או ענבר")
else:
print("מי זה?") |
654e27532d4de8711c90cdb88e30006c8702751a | srimanikantaarjun/Object_Oriented_Programming_Fundamentals | /08 Constructor in Inheritance.py | 868 | 4.34375 | 4 | class A:
def __init__(self):
print("in A init")
def feature1(self):
print("Feature 1 is working")
def feature2(self):
print("Feature 2 is working")
class B:
def __init__(self):
super().__init__()
print("in B init")
def feature3(self):
... |
b92d3bfe6cf6e25d4b1d68d26da96fe6b74d8eae | orlovD/ResumeParser | /Utils.py | 1,504 | 3.96875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
from string import punctuation
"""
load data from text file into set based on delimiter
if no provided - split by whitespace
"""
def loadFromFile(path, delimiter=None):
words = set()
print "Loading data from " + path + "..."
f = io.ope... |
41cbea77245b88f3d2bdf6a569577ea0cfe99c49 | ConorLongRoad/Communicating-to-files | /Through .txt files/Introduction to .txt Files - Append.py | 294 | 4.09375 | 4 | end = False
with open("/myfile.txt", mode="a",encoding="utf-8") as my_file:
while end == False:
nameToAppend = input("What name would you like to enter? ")
if nameToAppend == "-1":
end = True
my_file.write(nameToAppend)
my_file.close()
|
2d787005363b28c07c13fe69bc091055ee638769 | draetus/python_10apps_course | /app3/birthday_countdown.py | 1,156 | 4.1875 | 4 | import datetime
def print_header():
print('-------------------------------------')
print(' BIRTHDAY APP')
print('-------------------------------------')
print()
def get_birthday_from_user():
print('Tell us when you were born: ')
year = int(input('Year [YYYY]: '))
month = int(input... |
3f4dd4d341047c52bd90fbc671711f41a19fbaa0 | baidw/languages | /python/trainning/train_002_yeild01.py | 420 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__='baidw'
def generator_func():
for i in range(5):
print i
def generator_func2():
for i in range(5):
return i
def generator_func3():
for i in range(5):
yield i
x0=generator_func()
print x0
print '========='
x1=generator_fu... |
8370f0a8de52ec637f66a53f9120a4ce888390b5 | baidw/languages | /python/trainning/train_001_odd.py | 401 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__='baidw'
def find_it(seq):
cnt=0
for s in list(set(seq)):
if s>0:
if s%2 == 0:
pass
else:
cnt+=1
else:
cnt+=1
if seq == None:
return -1
return... |
b67bd069abb5dec0ee4755127b5550463be61035 | baidw/languages | /python/trainning/train_001_input.py | 1,433 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__='baidw'
import sys
#提示信息
banners='''
============================================
|iterm comment |
|1 get all numbers sum |
|2 get all numbers avg |
|3 list all numbers |
|0... |
2d0206f064026d5e94c244b611b7ddfa8bff8431 | baidw/languages | /python/exam/exam_0111_for2range.py | 542 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'baidw'
for iterm in ['hello', 'python', 'world']:
print iterm
for iterm in range(5):
print iterm
for iterm in 'abc':
print iterm
# range()函数经常和 len()函数一起用于字符串索引
strs = 'abc'
for i in range(len(strs)):
print strs[i], '(%d)' % i
# 直接得到索引及其元素
fo... |
6848989eb7ef17bc6f2ebfba88fa5736f212e472 | nazzang49/titanic-survival-prediction | /model/model.py | 3,004 | 3.640625 | 4 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df_train = pd.read_csv("C:/titanic/train.csv")
# check dataset
print(df_train.head())
print(df_train.tail())
print(df_train.info())
# check NaN-included column
print(df_train.Age.isna())
print(df_train.Cabin.isna())
print(df... |
561c132f9c330b6057292f9a89ae38dd787dbaff | nakuls003/dsalgos | /quick_sort.py | 754 | 3.890625 | 4 | import random
def quicksort(A, start, end):
if start < end:
p_index = randomized_partition(A, start, end)
quicksort(A, start, p_index-1)
quicksort(A, p_index+1, end)
def randomized_partition(A, start, end):
p_index = random.randint(start, end)
A[p_index], A[end] = A[end], A[p_index... |
9e7f6fbdfe5c9d34960a222a0663e819a35a2432 | jebuchwald/Automate_The_Boring_Stuff | /chapter9/bulkRename.py | 420 | 3.703125 | 4 | #! python3
# bulkRename.py - Renames file names using regular expressions to find and replace patterns
# in this demo files named capitalsquiz<integer>.txt will be replaced with Capitals_Quiz_<integer>.txt
# refer to regex101.com for help creating regular expressions
import shutil, os, re
# Create a regex that matche... |
3b91a9b67c8a2baed10f2097de88f3f8d5ad681f | chinsun1/Python-LeetCode | /700/657.py | 499 | 3.546875 | 4 | class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
row = col = 0
for s in moves:
if s == 'U':
col += 1
elif s == 'D':
col -= 1
elif s == 'L':
r... |
a5e69bd76f468d3af720595386804cc513e083e8 | subhannita1994/knapsack | /knapsack.py | 4,721 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 14 12:07:33 2018
@author: SUBHANNITA
"""
import random
import numpy
def representation():
"""
generate population of size pop_size, each having n items (either 0 or 1) with
associated cost c[i] (i=0 to n-1)
"""
population=[]
for i ... |
92ad6b2faa2098c63d419ce42e1e425d0644ab7c | RZachLamberty/frenchelection | /representatives.py | 4,166 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module: representatives.py
Author: zlamberty
Created: 2017-04-29
Description:
module for calculating number of representatives based on population
Usage:
<usage>
"""
import os
import pandas as pd
# ----------------------------- #
# Module Constants ... |
5a555ca08a2dfe919ccc11b59fec01f63164564e | ruoduan-hub/algorithm_py | /05_快速排序.py | 935 | 4.03125 | 4 | # coding=UTF-8
def quicksort(arr):
""" 快速排序算法
:param arr:
:return:
"""
if len(arr) < 2:
return arr
else:
pivot = arr[0]
less = [i for i in arr[1:] if i <= pivot]
greater = [i for i in arr[1:] if i > pivot]
print(arr)
return quicksort(less) + [piv... |
5f21c53d581709cebdde5dc6e238182720e41f42 | christianvajgel/AssessmentDesenvolvimentoPythonRedesSistemasOperacionais | /questao_9_multiprocessing.py | 1,560 | 3.546875 | 4 | # ASSESSMENT - Desenvolvimento Python para Redes e Sistemas Operacionais [19E1_4] - Instituto Infnet.
# Christian Vajgel - 04/04/2019 - Thonny IDE - Conceito DML (10/10).
# questao_9_multiprocessing
import multiprocessing, random, time
t0_epoch = float(time.time())
t0 = time.strftime("%S", time.localtime(t0_epoch))
... |
6154996b2d90ec547184c54837d887f043baf163 | CodeWithShamim/python-t-code | /Main/Method overriding.py | 886 | 4.15625 | 4 |
#Method not overriding...........
class google:
def __init__(self):
print("Result 1 : Hello, programmer!!.")
class amazon(google):
#add amazon all method..
pass
val = amazon()
#------------------------------------------------------------------
#Method overriding...........
class google:
... |
2bae843d557c598dec416ddcf140cc4904ddc720 | CodeWithShamim/python-t-code | /Main/List comprehensions.py | 317 | 3.671875 | 4 | #11
num = [5,11,23,30,40,50]
#use list comprehensions....ex>> expresion for num i list:........
result = [x*x for x in num]
print(result)
'''
num = [5,11,23,30,40,50]
result = list(filter(lambda x : x%2==0, num))
print(result)
'''
#22
num = [5,11,23,30,40,50]
result = [x*x for x in num if x%2==0]
print(result) |
4cc66bcd2ff1da3343b6249160e44be1d08c5989 | GladDaniels/PycharmProject | /uno.py | 1,716 | 3.65625 | 4 | import random
from random import randint
colour = ['YELLOW', 'RED', 'BLUE', 'GREEN'] # colour
smallB = ['+ 2 cards', 'skip a move'] # small bonus (+ 2 cards / skip a move)
bigB = ['+ 4 cards and skipping the movE', 'choose the coloR'] # big bonus (+ 4 cards and skipping the move / choose the colour)
big = 0
c... |
d7fee108be2b0c802048a85fab264d797305c96b | GladDaniels/PycharmProject | /antilokh.py | 282 | 3.6875 | 4 | def
f = open("fan.txt")
N = f.readline()
N = int(N)
for i in range(N):
num1, num2, num3 = f.readline().split(" ")
if
num1 = int(num1)
num2 = int(num2)
num3 = int(num3)
else:
print("Числа в этой строке равны")
|
bfd3194a3f57b9e1daf459572d0c3a3c9fd0b24c | LarissaMidori/curso_em_video | /exercicio062.py | 594 | 4.15625 | 4 | ''' Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. '''
print(f'==== Super analisador de P.A. ====')
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
mais = 10
total = 0
cont = 1
while mais !=... |
4e3d6779c54d168fe742e9f30034f8a23ebb8cbb | LarissaMidori/curso_em_video | /exercicio003.py | 473 | 4 | 4 | # Crie um programa que leia 2 números e mostre a soma entre eles
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
s = n1 + n2
print(f'A soma entre {n1} e {n2} é: {s}')
#print(type(n1)) - mostra o tipo do dado recebido
# Crie um programa que leia 2 números e mostre a multiplicação entre el... |
e18f604f43805660026cff8a0ce10d14b0b99ea4 | LarissaMidori/curso_em_video | /exercicio036.py | 703 | 4.1875 | 4 | ''' Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado. '''
casa = float(input('Valor da casa: R$ '))
salario = float(inp... |
8c6fc494dc35319b1b15e1df3de92677d366f2fe | LarissaMidori/curso_em_video | /exercicio014.py | 218 | 4.28125 | 4 | # Escreva um programa que leia uma temperatura digitada em °C e converta para °F
temp = float(input('Digite a temperatura em °C: '))
print(f'A temperatura de {temp:.1f}°C, equivale à {(temp * 1.8 + 32):.1f}°F.') |
9eaed61fd099b5b158f00a720963d79ecacbf770 | LarissaMidori/curso_em_video | /exercicio051.py | 335 | 3.890625 | 4 | ''' Desenvolva um programa que leia o primeiro termo e a razão de uma PA. No final, mostre os 10 primeiros termos dessa progressão. '''
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
decimo = termo + (10 - 1) * razao
for i in range(termo , decimo + razao , razao):
print(i, end = " - ")
print(... |
0e880ba2d2bee9f96c4633b3d97259652973c858 | LarissaMidori/curso_em_video | /exercicio034.py | 548 | 3.875 | 4 | ''' Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$ 1250,00, calcule um aumento de 10%. Para os inferiores ou iguais, o aumento é de 15%. '''
salario = float(input('Qual o valor do salário em R$? '))
if salario > 1250:
aumento = 10
sa... |
6eff7caf05377ff85c98ca69fa42530acb0ae6d2 | Mansurjon1112/WHILE-Shart-sikl-operatorlari-30-ta- | /while01.py | 564 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
While1. A va B butun musbat sonlari berilgan ( A > B). A usunlikdagi kesmada maksimal darajada
B kesma joylashtirilgan. A kesmaning bo’sh qismini aniqlovchi programma tuzilsin. Ko’paytirish va
bo’lish amallarini ishlatmang
Created on Tue Jun 29 05:42:22 2021
@author: Mansurjon Kamo... |
9ac4fb29675c4c5e62d42735f89baabb86edc94d | Mansurjon1112/WHILE-Shart-sikl-operatorlari-30-ta- | /while02.py | 521 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
While2. A va B butun musbat sonlari berilgan ( A > B). A usunlikdagi kesmada B kesmadan nechta
joylashtirish mumkinligini aniqlovchi programma tuzilsin. Ko’paytirish va bo’lish amallarini
ishlatmang.
Created on Tue Jun 29 05:42:08 2021
@author: Mansurjon Kamolov
"""
a=int(input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.