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 |
|---|---|---|---|---|---|---|
43c9ff8d595097a1efa90f5e7d8b748ebc88c8ad | fatezy/Algorithm | /leetCode/easyCollection/array/moveZero.py | 726 | 3.875 | 4 | # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
#
# 示例:
#
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# for i in range(len(nums)):
... |
9730c6b61c671eeedf11eba9610e94b34f36ab0b | monkeylyf/interviewjam | /hackerrank/pythonista/hackerrank_xml2_find_the_maximum_depth.py | 758 | 3.5625 | 4 | """hackerrank_xml2_find_the_maximum_depth
https://www.hackerrank.com/contests/pythonista-practice-session/challenges/xml2-find-the-maximum-depth
"""
try:
from lxml import etree as ET
except ImportError:
import xml.etree.ElementTree as ET
def main():
n = int(raw_input())
xml = []
for _ in xrange... |
156ecc3d784f176ea8eb532e6fdcaa49d1ee4da6 | jsochacki/Google_Foo_Bar_Solutions | /Paying_Henchman.py | 1,126 | 3.53125 | 4 | def answer(total_lambs):
try:
assert isinstance(total_lambs, int)
except AssertionError as e:
raise SystemExit('You need to enter and integer'
'for this function to work')
else:
try:
assert ( 10 <= total_lambs <= 1000000000 )
except Assert... |
169748ba736b19cd845ad854441f91fcb8300177 | Lojdquist/Problem14ProjectEuler | /algorithm/collatz.py | 1,056 | 3.6875 | 4 | #problem 14 project euler
import time
from collatzSeqString import genCollatzString
hasDict={}
def collatz(current, steps, seq):
current = int(current)
seq.append(current)
if current == 1 or current in hasDict:
if current in hasDict:
addSequence(seq, hasDict[current])
return... |
93b2c6fb2d3388edf782c02c05c6a36127d05ec2 | Pavanyeluri11/LeetCode-Problems-Python | /defanging_ip_address.py | 229 | 3.71875 | 4 | def defanging(address):
s=''
for i in range(len(address)):
if address[i] == '.':
s+='[.]'
else:
s+=address[i]
del address
return s
print(defanging('1.1.1.1'))
|
86c4748c79e07c1aa9ded7e8edd6b5a62b70f0c7 | anjaligr05/TechInterviews | /grokking_algorithms/recursiveSumArr.py | 118 | 3.75 | 4 | def sum(arr):
if len(arr) == 0:
return 0
else:
return arr[0] + sum(arr[1:])
print sum([1,2,4,3])
print sum([])
|
b95188798aaf2ff1918e319d9abdded2a5cf1269 | dtekluva/cohort7 | /CLASS-ATHA/datastructures/ds2.py | 3,243 | 3.953125 | 4 | # file = open("datastructures/financials.csv", "r")
# # print(file.readline()[12:20]) # GET TAX TYPE VIA SLICING
# # heading_list = file.readline().split(",")
# # print(heading_list)
# # print(heading_list[5])
# cash_transactions = []
# for line in file.readlines():
# transaction_type = line.split(",")[7]
# ... |
dcf7d32f100886c7930668cba5fc76b5309eb86e | hoginogithub/python_kiso_dorill | /q05_06.py | 723 | 3.71875 | 4 | import re
def print_double_words(file_content):
doubled = re.compile(r'\b(\w+) (\1\b)+', re.IGNORECASE)
for result in doubled.findall(file_content[0]):
print(f'{result} on line {1}')
for i in range(1, len(file_content)):
for result in doubled.findall(file_content[i]):
print(f'... |
79f879674530c603faa710400bc96efaf35ff29a | javacode123/oj | /leetcode/middle/backTrack/subsets.py | 762 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-08-25 15:29
# @Author : Zhangjialuo
# @mail : zhang_jia_luo@foxmail.com
# @File : subsets.py
# @Software: PyCharm
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def back... |
d445120d70d91a4dc3c8dbfb7cd1767d30783d3a | Naisargee/hackerrank-challenges | /largest_permutation.py | 502 | 3.53125 | 4 | N,K = map(int,input().split())
nums=list(map(int,input().split()))
dic={}
for i in range(0,N): dic[nums[i]]=i
def exchange(num1,num2):
num1_pos=dic[num1]
num2_pos=dic[num2]
nums[num1_pos]=num2
nums[num2_pos]=num1
dic[num1]=num2_pos
dic[num2]=num1_pos
k=0
n=0
num=N
while k<K and n<N:
if ... |
41e323d976684dd6fabfe7952256249d776d9515 | BYRans/LeetCode | /Python/ZigZagConversion.py | 869 | 4.28125 | 4 | #ZigZag Conversion
#The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#And then read line by line: "PAHNAPLSIIGYIR"
#Write the code that will take a string and make this conversion given a number ... |
6b2ea075b60dfc4ee00e21d5d7b0682f0ee766d3 | renmengye/tfplus | /tfplus/utils/progress_bar.py | 2,072 | 4.09375 | 4 | """
A python progress bar.
Example 1:
N = 1000
pb = progress_bar.get(N)
for i in xrange(N):
do_something(i)
pb.increment()
Example 2:
N = 1000
for i in progress_bar.get(N):
do_something(i)
Example 3:
l = ['a', 'b', 'c']
for c in progress_bar.get_iter(l):
... |
3b5cb96198dd24ebd64dfc6db2dc6ac14a681f4e | dataaroom/Lulus | /uc.py | 8,040 | 4.09375 | 4 | #! python3
"""
Create a data structure for all units.
build a class "Units" to convert unit as required.
"""
class Units:
'''
类属性保存所有单位,和单位间的转换系数。megic method 用来定义 +-*/, 建立函数进行相应的单位转换计算。
'''
def __init__(self, value = 0.0, unit = 'm', type = 'L'): # 默认格式:(0.0, 'm', 'L') 参数均可选。 TODO: 考虑是否将... |
f409f261135059eb14d3003db0b4408b4bae6cf8 | Caiocolas/-Exercicios-Python- | /PycharmProjects/pythonProject/venv/ex013.py | 256 | 3.65625 | 4 | salario = float(input("Qual é o salário de um funcionário:"))
novo = (salario * 15 / 100)
a = salario + novo
print ('o novo salário de um funcionário com 15% de aumento sai de {} reais para {} reais com um aumento de {} reais'.format(salario,a,novo)) |
4abed32d81a745d2ec69f513a7d6ef535a5e184a | SudhaDevi17/PythonCodingPractice | /Beatiful Arrangement.py | 258 | 3.78125 | 4 |
n = 3
arr = [i for i in range(1, n+1)]
visited = []
def dfs(num , arr , temp: list):
for n in arr:
if n!=num:
temp.append(n)
visited.append(temp)
print(temp, visited)
return temp
for i in arr :
dfs(i , arr , [i])
|
c5137068d805ccc487569d6d199871a1d0db5be6 | ronald0807/Running-python | /python_list_practice1/문제2.py | 344 | 4.03125 | 4 |
# 문제 2.
# 10개의 문자를 입력받아서 첫 번째 네 번째 일곱 번째 입력받은 문자를 차례로 출력하는 프로그램을 작성하시오.
# 입력 예: A B C D E F G H I J
# 출력 예: A D G
list = []
for i in range(10) :
list.append(input("문자 10개를 입력하시오."))
print(list[0], list[3], list[6])
|
90ba32800ecf8a48c25bcda732642af228230c57 | kpurdom/space-invaders | /main.py | 2,444 | 3.859375 | 4 | from turtle import Screen
from border import Border
from player import Player
from shoot import Shoot
from enemy import Enemy
from scoreboard import Scoreboard
FIRE_STATE = "ready"
# set up screen
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=800)
screen.title("Space Invaders")
screen.trace... |
3bfc2670a52bab2e7220abf8f282d17d2c300551 | tomasbm07/IPRP---FCTUC | /4/4_12.py | 166 | 3.828125 | 4 | linhas = int(input('Digite o nº de linhas da tabela: '))
print('Numero | Quadrado')
for i in range(linhas):
x = (i+1)**2
print('{0:6} {1:6}'.format(i+1, x)) |
e443811197bfe77a7ebabbf737c389df6ba5af3b | JerinPaulS/Python-Programs | /CountTriplets.py | 1,939 | 4.03125 | 4 | '''
You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and .
Example
There are and at indices and . Return .
Function Description
Complete the countTriplets function in the editor below.
count... |
243e795217a21c79e3be76fc2784a047e3f8ec6d | lw2533315/leetcode | /setMatrixZeroes.py | 756 | 3.890625 | 4 | # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row = set();
... |
b0c67bb2da86ae946764d066deaf3f091ad92eca | Niemaly/python_tutorial_java_academy_and_w3 | /zad_1-10/zad10.py | 173 | 3.796875 | 4 | number = int(input("podaj liczbę"))
divisor = 8
if number % divisor == 0:
print("liczba podzielna przez", divisor)
else:
print("liczba niepodzielna przez", divisor) |
4eb5e6849965f47321b9a80df68f959c5d3e0dc7 | ankitagupta820/LeetCode | /Count_univalue_subtrees.py | 681 | 3.546875 | 4 | class Solution:
def countUnivalSubtrees(self, root):
if root is None:
return 0
self.count = 0
self.is_uni(root)
return self.count
def is_uni(self, node):
if node.left is None and node.right is None:
self.c... |
91bfcb3a2b44260b42c06c05987a6e3d6a1030e3 | labarreto/Python | /ex9.py | 357 | 3.84375 | 4 | #Jan 13, 2016
#Learning Python the Hard Way Exercise 9
days = "Mon Tue Wed Thurs Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSept\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
print """
there is something going on here, typing as
many lines as we want
type... |
ba48bb1b264255b7005b3714d57097dcae8c59af | Repicmi/201801643_TareasLFP | /Tarea5/main.py | 1,003 | 3.5 | 4 | prueba1 = "_servidor1"
prueba2 = "3servidor"
abecedario = ["a", "b" ,"c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "ñ", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
digitos = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
def afd(entrada):
letrasAFD = []
contador_fase = 0
c... |
b27adcc7c73c63812130f8510c4d61241e6eca7a | sinasab/cse5914 | /src/brutus-module-weather/brutus_module_weather/tests/windQuestion_test.py | 927 | 3.515625 | 4 | import unittest
from flask import json
from .common import BrutusTestCase
class WindTestCase(BrutusTestCase):
"""
Simple tests for the weather module
Check that questions about wind returns the correct answers
"""
windQuestions = ['Is it windy',
'is it WINDY',
... |
7a8b3cdea6954bc8d45c0ab4af0394f8f2d26958 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 3.13 - Boucle While.py | 1,321 | 4.34375 | 4 | """ Auteur: Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire un programme qui additionne des valeurs naturelles lues sur entrée et affiche le résultat.
La première donnée lue ne fait pas partie des valeurs à sommer.
Elle détermine si la liste c... |
a68829830647834c0372ce8f7ff76219e715c874 | gimquokka/problem-solving | /CodeUp/Basic_100 (기초100제)/cu_1064.py | 158 | 3.640625 | 4 | # Find a minimum value using ternery operation
a, b, c = input().split()
a = int(a)
b = int(b)
a1 = (a if a>b else b)
a2 = (a1 if a1 > c else c)
print(a2)
|
38610fd136b53199debfe2f8f35ab69361b21145 | charleslee94/CardGames | /Deck/Deck.py | 1,786 | 3.859375 | 4 | from collections import OrderedDict
from Card import Card
import pprint
from random import shuffle
class Deck():
"""
This is the deck class
can have as many cards as you want, but the default will be 52 of 4 suits
"""
def __init__(self, ruleset=None):
self.drawCount = 0
self.cards... |
b10d66afe764ce59198c71e999f141250c6ccefb | TeddyFirman/lenDen | /leapyear.py | 213 | 4.21875 | 4 | def leapyear():
year = int(input("Insert Year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("This year is leap")
else:
print("This year is not leap")
leapyear()
|
58d943c7b96846e6eac58a3f010d31572d4c331b | LYASDF/NTNU_TextProcessing_2021 | /week02/week02_40992022m.py | 478 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
def main(inputSTR):
myNameSTR = inputSTR[0:7]
myIdSTR = inputSTR[8:17]
myInfoSTR = myNameSTR + " " + myIdSTR
print(myInfoSTR)
inputLIST = inputSTR.split(" ")
print(inputLIST)
print("私の名前:{}".format(inputLIST[0]))
print("... |
a87d952e69c91c14f1762a75260c7ac4a5d49049 | Shanyao-HEU/PTA-PAT | /pat-b/1079.py | 431 | 3.9375 | 4 | num = input()
step = 0
def is_palin(number):
n = str(number)
m = n[::-1]
return m == n
while step < 10:
num_rev = num[::-1]
temp = str(int(num)+int(num_rev))
print("{} + {} = {}".format(num, num_rev, temp))
if is_palin(temp):
print("{} is a palindromic number.".format(temp))
... |
c5abb65f3bc95e52054df6819df26fe505efc35c | cdallasanta/Python-projects | /coin estimator.py | 615 | 3.640625 | 4 | import pandas as pd
#print('Please select "g" or "oz"')
metric = input()
dict = {'Coin':['pennies', 'nickles', 'dimes', 'quarters'],
'Grams':[2.5, 5, 2.268, 5.67],
'Ounces':[0,0,0,0],
'Number':[0,0,0,0],
'In Each Wrapper':[50,40,50,40],
'Wrapp... |
021d3aef7f6783f230bbd5d0671fc015ebb5fe11 | shishir-umesh/TSP-SimulatedAnnealing | /main.py | 889 | 3.5625 | 4 | import pandas
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from data import *
from simulatedAnnealing import *
from helperFunctions import *
def randomTour(df):
dfNew = df.copy()
arr = np.random.permutation(len(df))
print(arr)
j=0
for i in range(2,len(df)-1):
... |
be773d01a8c55aaf620db11271afc67f8ec0af2b | GaureeshAnvekar/ProblemSolving | /UCSDProblems/week3/money_change_dp.py | 1,039 | 3.953125 | 4 | #Uses python3
'''
The money change problem has the property of optimal substructure i.e. least no.of
coins required for an input 'm' can be the sum of least coins for subproblem of 'm' +
least coins for another subproblem of 'm'.
The following uses it and is done using dynamic programming through memoization.
'''
impo... |
e6ac57a3687086bdf6b362d739ef7919f1faf425 | DilipBDabahde/PythonExample | /Assignment_4/Square_find_using_F_M_R.py | 1,326 | 4.09375 | 4 | '''
4.Write a program which contains filter(), map() and reduce() in it. Python application whichontains one list of
numbers. List contains the numbers which are accepted from user. Filter should filter out all such numbers which are
even. Map function will calculate its square. Reduce will return addition of all that... |
a16adf8ea349a6593bf9d251a3331ea3d106fe79 | Daniel-VDM/Intro-CS-projects | /Program_Structure_and_Interpretation/Labs_and_Hwks/hw/hw04/hw04.py | 5,316 | 4 | 4 | HW_SOURCE_FILE = 'hw04.py'
###############
# Questions #
###############
def intersection(st, ave):
"""Represent an intersection using the Cantor pairing function."""
return (st+ave)*(st+ave+1)//2 + ave
def street(inter):
return w(inter) - avenue(inter)
def avenue(inter):
return inter - (w(inter) ... |
b1de2e26abff0a05f163e21c9c2de4edd9d4eaaf | pahisan/python-exp | /main.py | 194 | 3.765625 | 4 | import datetime
def timeofCity ():
return datetime.datetime.now()
print(timeofCity())
a = 1
b = 1
print(a + b)
w = 1
x = 2
print(w * x)
c = 3
g = 3
print(c/g)
y = 5
z = 5
print(y - z) |
fa1f110dec8610c2df834ed2ef10c48405833133 | js-yoo/CheckiO | /Home/sun-angle.py | 341 | 3.609375 | 4 | # https://py.checkio.org/en/mission/sun-angle/
# Difficulty : Elementary
def sun_angle(time):
h,m=map(int,time.split(':'))
dtime=60*h+m-360
if -1<dtime<721:
return dtime/4
else:
return "I don't see the sun!"
# Example)
# sun_angle("07:00") == 15
# sun_angle("12:15"] == 93.75
# sun_angle("01:23") == "I... |
879f90a2549d165c36bcf4e124ffed3498fc882f | diegocolombo1989/Exercicios_templo | /elevador-mais-proximo/start.py | 537 | 3.890625 | 4 |
def elevador(left,right,call) -> int:
call_1 = 'Elevador da esquerda esta vindo'
call_2 = 'Elevador da direita esta vindo'
if left == call: return print(call_1)
elif right == call: return print(call_2)
elif left == right: return print(call_2)
elif left > right: return print(cal... |
74ceea22f8b70fa774cf396a3f882b36483b4f05 | bhuvanakundumani/Python | /Src/decimaltobinary.py | 185 | 4.15625 | 4 |
def decimal_to_binary(num):
""" This function converts a decimal number (num ) to a binary number"""
if (num > 1):
decimal_to_binary(num // 2)
print(num % 2, end ='') |
1409167f2f04d8b3e080034abea8b40b22a68ef8 | hwang033/job_algorithm | /py/reverse_linked_list_ii.py | 1,481 | 4 | 4 | import pdb
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverseBetween(self, head, m, n):
if m ==... |
e2a20e955edaccd9d89b14593257aa24877d3e33 | Sheyin/advent-of-code-2020 | /day5.py | 2,719 | 3.8125 | 4 | F = "F"
R = "R"
L = "L"
B = "B"
def main():
# Get file input
filename = "./data/day5input.txt"
input = open(filename, "r")
boarding_passes = []
for _ in input:
line = _.rstrip()
boarding_passes.append(line)
# boarding_passes should now be a tidy array of data
highest_seat... |
87b65c36f0123150f5f867e648f2be76f8694b4c | LukeHufnagle/BankAccount_Assignment | /BankAccount.py | 977 | 3.859375 | 4 | class BankAccount:
balance = 0
def __init__(self, interest_rate, balance):
self.interest_rate = interest_rate
self.balance = balance
def makeDeposit(self, amount):
self.balance += amount
return self
def makeWithdrawal(self, amount):
self.balance -= amoun... |
eb83856e0974a5ad63e58c0e54ae97e83dc04733 | zuchunlei/leamon | /patteraless/src/thread/main.py | 706 | 3.546875 | 4 | #-*- encoding: utf-8 -*-
"""
多单线程运行一段程序
"""
import time
import thread
def loop0():
"""
睡上几秒
"""
print 'start loop 0 at: ', time.ctime()
time.sleep(4)
print 'loop 0 done at: ', time.ctime()
def loop1():
"""
再睡上几秒
"""
print 'start loop 1 at: ', time.cti... |
a949cab73eed36616eed9f8b873df4c54fcf74e0 | laurenchow/algorithms | /reverse_linked_list.py | 659 | 4.3125 | 4 | #reverse linked list
class Node:
def __init__(self, data):
self.data = None
self.next = None
# class LinkedList:
#step through or traverse the linked list
#for each node, create a new pointer going backwards pointing to previous node .last
#return a linked list such that node.next is node.last
def reverse(node... |
545485f0e95ba066dbd05f522d0539bbdf2f3020 | patrykpalej/weather-forecast-accuracy-assessment | /functions/convertTimestampFormat.py | 1,264 | 3.625 | 4 | from dateutil import parser
from datetime import datetime
def convert_from_str_timestamps(original_timestamps, target_format):
"""
Converts list of timestapms from string format to datetime or unix
"""
if target_format == "datetime":
output_timestamps = [parser.parse(elem)
... |
b15da86a9da1f20dfcd6c304e578ae1e9c838a30 | claudiodornelles/CursoEmVideo-Python | /Exercicios/ex087 - Mais sobre Matriz em Python.py | 1,306 | 4 | 4 | """
Aprimorar o desafio anterior, mostrando no final:
1 - A soma de todos os valores pares digitados.
2 - A soma dos valores da terceira coluna.
3 - O maior valor da segunda linha.
"""
matriz = [[],[],[]]
soma_pares = soma_terceira_coluna = maior_valor_segunda_linha = 0
for i in range(0,3):
for j in range(0,3):
... |
4f5704da66b3fa0bd12023eabc466e361ab74170 | guoguanglu/leetcode | /mycode/array/Search Insert Position.py | 320 | 3.53125 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i,each in enumerate(nums+[0]):
if each < target:
continue
else:
break
return i |
41687f34ba6cc949848f6ce1f0f3260ec76d4a64 | myleslangston/Data22 | /Inheritance/main.py | 540 | 3.78125 | 4 | class Car: #parent class
def __init__(self, name, mileage):
self.name = name
self.mileage = mileage
def description(self):
return f"The {self.name} car gives the mileage of {self.mileage}km/l"
class BMW(Car): #child class
pass
class Audi(Car): #child class
de... |
a603277baf1581b2d35552e7df0c17378131195d | RodrigoMSCruz/CursoEmVideo.com-Python | /Desafios/desafio095.py | 1,599 | 4 | 4 | # Aprimoramento do desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de
# visualização de detalhes do aproveitamento de cada jogador.
time = []
jogador = {}
partidas = []
while True:
jogador.clear()
jogador['nome'] = str(input('Nome do Jogador: '))
njogos = int(input(f'Quantas pa... |
1a4214c24781eeb7de1267d6dd841328272ff56e | twardoch/robofab | /Docs/Examples/talks/interpol_07.py | 788 | 3.640625 | 4 | # glyphmath example, using glyphs in math
# in the test font: two interpolatable, different glyphs
# on positions A and B.
from robofab.world import CurrentFont
f = CurrentFont()
# glyphmath
a = f["A"]
b = f["B"]
# multiply works as scaling up
d = a * 2
# or
d = 2 * a
# note: as of robofab svn version 200,
# th... |
c329a6e1edab4825a52dd5576bdfbc119bb6badf | Jayvee1413/AOC2020 | /aoc2020/day2/main.py | 2,050 | 3.5625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import re
def read_file(file_name):
with open(file_name, "r") as f:
input = [x.strip() for x in f.readlines()]... |
e6cfb66c9758874eec602e7a5d76e4c4c87784dd | fuyangchang/Practice_Programming | /IntroToComputerScience/PS2_payingdebtoffinayear.py | 857 | 4.1875 | 4 | #2-2. Paying Debt off in a Year
#Write a program calculating the minimum fixed monthly payment needed
#in order to pay off a credit card balance in 12 months.
#balance & annualInterestRate will be handled by the instructor.
balance = float(raw_input('balance = '))
annualInterestRate = float(raw_input('annual interest ... |
996eedaa0cb4fab26949f5c001de626856d1d2a2 | CauchyPolymer/teaching_python | /python_intro/p3_hanoi.py | 1,639 | 3.671875 | 4 | disknum = input('Enter the number of disks : ')
def hanoi(n,start,to,other):
n == disknum
if n == 0:
return
hanoi(n - 1, start, other, to)
print('Disk Move {} => {}'.format(start, to))
hanoi(n - 1, other, to, start)
hanoi(4,'A','C','B')
# H(1,A,C) 1개의 디스크를 A B C에 해당하는 Pole A에서 C로 옮긴다. 재귀함... |
f15aed5f9393d5c73fe1cc1bd2936513c77e287e | Alejandro-15/python | /python/python programa 1.py | 120 | 3.734375 | 4 | def fib_r(n):
if n < 2:
return n
return fib_r(n-1)+ fib_r(n-2)
for x in range(20):
print(fib_r(x))
|
f6379ef74da0697f46deec07a40ef04f14d57961 | Henok-Matheas/RSA-Encryption | /RSA4.py | 2,251 | 3.8125 | 4 | """Group Members
1. Henok Matheas UGR/2553/12
2. Kaleab Taye UGR/0490/12
3. Kaleab Tekalign UGR/3664/12
4. Betel Tagesse UGR/5409/12
5. Beka Dessalegn UGR/4605/12
6. Bethlehem Alula UGR/0462/12
7. Tsega Yakob UGR/8465/12 """
p=72196062906190411075697304789682052965064662691398791419305808194686... |
c1df45fe33a8c149919019aa5caf3fa3980f8c81 | WuLC/LeetCode | /Algorithm/Python/133. Clone Graph.py | 1,354 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2016-08-21 10:25:30
# @Last modified by: WuLC
# @Last Modified time: 2016-08-21 10:26:16
# @Email: liangchaowu5@gmail.com
# Definition for a undirected graph node
# class UndirectedGraphNode(object):
# def __init__(self, x):
# self.label = x
# se... |
122b34553c558107a37ab33bbd3134102f1dcaef | AaronVelasco93/Prueba_Python | /Clase 1404218/prueba2.py | 235 | 3.90625 | 4 | print("Suma de numeros")
num1=int (input("Dame un numero: "))
num2=int (input("Dame otro nummero"))
resultado=num1+num2
print("El resultado de la suma es",resultado)
input("Preciona cualquier tecla para continuar...")
|
629aa48734f202872ff8d6488f9e72e7aa18ae62 | 0ashu0/Python-Tutorial | /Lynda Course/0406_using functions.py | 810 | 4.3125 | 4 | def main():
print("this is main function")
fu()
func(-5)
func(3)
func(5)
funck(1)
funck(3)
funckers()
def fu():
for i in range(13):
print(i, end=' ')
print()
def func(a):
for i in range(a, 10):
print(i, end=' ')
print()
def funck(b):
for i in range(b, 10 ,2):
print(i, end=' ')
print()
def funcke... |
385479a3a0803c6ff64acb3152dbd2197c343d56 | hemanth-007/Path-Finding-Visualizer | /buttons_class.py | 1,009 | 3.5625 | 4 | import pygame
from settings import *
class Buttons:
def __init__(self, app, color, x, y, width, height, text=""):
self.app = app
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw_button(self):
... |
b0008ad66262e873f0ca20c0b04bb10ce8086e14 | Lilwash333/APCS | /GuessingGame.py | 333 | 3.953125 | 4 | #Julius Washington
import random
rand = random.randint(1,10)
give = 0
print("Give me a number from 1 - 10")
while(give != rand):
give = int(input())
if(give > rand):
print("Your number is too high!\n Try again!")
elif(give < rand):
print("Your number is too low!\n Try again!")
else:
... |
37525d690fffd2812e06a76dacfc223f1038fbfd | stnorling/Rice-Programming | /iipp/Week 3/Mini_Project_2_Guess_The_Number.py | 2,468 | 4.375 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
guesses = 7
count = 0
rg1000 = False
secret_number = 0
numrange = 100
# helper function to start and restart the game
def remaining... |
cdb63d9a8fab0f37095981716f1997c412808b33 | SirCipher/EvolutionaryComputation | /Assignment/snakePlay.py | 4,876 | 3.8125 | 4 | # This version of the snake game allows you to play the same yourself using the arrow keys.
# Be sure to run the game from a terminal, and not within a text editor!
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
import random
import math
curses.initscr()
XSIZE, YSIZE = 18, 18
NFOOD = 1
win = ... |
966ca259273bd40eafea65463d32bdc36d4d0c99 | pragatirahul123/list | /Harshad_Number.py | 232 | 3.703125 | 4 | user=int(input("enter a number"))
sum=0
var=user
while var>0:
rem=var%10
sum=sum+rem
var=var//10
print(sum)
if(user%sum==0):
print("Harshad number")
else:
print("Not harshad number")
|
01484ceaa23e2c4fd650212ccb528210598c6c2d | Devansh-ops/HashCode2021 | /stupidV2.py | 1,841 | 3.859375 | 4 | # Hashcode 2021
# Team Depresso
# Problem - Traffic Signaling
## Data Containers
class Street:
def __init__(self,start,end,name,L):
self.start = start
self.end = end
self.name = name
self.time = L
def show(self):
print(self.start,self.end,self.name,self.time)
class Car:
def __init__(sel... |
ec0edfd7914077fc213524fe65fae3df4740008c | jesuprofun/python_problems | /functions/ex8.py | 199 | 4.25 | 4 |
def fact(num):
if num == 0:
return 1
else:
return num * fact(num - 1)
number = int(input("Enter the number to find factorial: "))
factorial = fact(number)
print(factorial)
|
6b2a4eff39228deffe0b7bc8217c5b7c8cd57a4a | yarik335/GeekPy | /HT_2/task3.py | 1,350 | 3.8125 | 4 | '''
Створіть 3 різних функції(на ваш вибір), кожна з цих функцій повинна повертати
якийсь результат. Також створіть четверу ф-цію, яка в тілі викликає 3
попередніб обробляє повернутий ними результат та також повертає результат.
Таким чином ми будемо викликати 1 функцію, а вона в своєму тілі ще 3
'''
def func1(n, x =... |
2f11e7bd7981e67437e4dd30b4882e78e84de586 | Ellieli78/LearnMorePython3theHardWay | /Ex5/Ex5cat.py | 608 | 3.6875 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", metavar = 'E',type = str,nargs = '+',
help = "display a square of a given number")
parser.add_argument("-n", '--numbers', action='store_true',
help = 'Print line numbers')
args = parser.parse_args()
print(">>>"... |
dc97b6dd04d6b8e0daf57bdacab3fb883427beff | Gunny-Lee/chatbot | /lotto.py | 831 | 3.5 | 4 | """
requests를 통해 동행복권 API 요청을 보내어, 1등 번호를 가져와 python list로 만듬
"""
import requests
# 1. requests 통해 요청 보내기
url = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=873"
response = requests.get(url)
# print(response) # 200뜨면 됩니다
# 콘솔에서 python lotto.py 입력해서 확인
# print(response.text) # 내용이 나옴
res_dict = r... |
158c2c9c4439634f5dda7358bf9816a7462b26df | huiup/python_notes | /function/装饰器/c1.py | 383 | 3.515625 | 4 | import time
# 不使用装饰器时
# 开闭原则:对修改是封闭的,对扩展是开放的
# 新加业务逻辑:添加运行函数时打印运行时间的功能
# 允许向一个现有的对象添加新的功能,同时又不改变其结构。
def print_time(func):
print(time.time())
func()
def f1():
print('this is a function')
print_time(f1)
|
4d5ed3f3a9dc5d90419621a90d9ff8a9c48afaa9 | gabrielnhn/snake | /snake.py | 979 | 4.09375 | 4 | """Snake class and methods implementation:"""
class Snake:
def __init__(self, size, lines, columns, char, color):
"""
Initializes the snake in the center of the board,
With an initial 'size'
"""
if size > columns:
raise ValueError("Snake's size is too large")
... |
ebd71f19b842cade340b112aff24f95838499d90 | cnsapril/JZAlgo | /Ch 1 - Introduction & Subsets/permutations.py | 597 | 3.859375 | 4 | """
Given a list of numbers, return all possible permutations.
You can assume that there is no duplicate numbers in the list.
"""
class Solution(object):
def permute(self, nums):
def _permute(result, temp, nums):
if not nums:
result += [temp]
else:
f... |
3ba96b004e67087b033f0f075c98630ffb891892 | miriamlam1/csc349 | /asgn3-miriamlam1/two_colorable.py | 1,895 | 4.03125 | 4 | # two colorable / bipartite / no odd cycles
# input: a graph given in a list of edges connecting vertices
# output: lists of each color if 2-colorable, else false
from collections import *
import sys
class Graph():
def __init__(self):
self.graph = defaultdict(list)
def add_edge(sel... |
86dc179c42dd6c4e3ab083e17062b149b4ec8202 | JBPelzner/Termite | /webscrapers/web_scraper_v1.py | 962 | 3.640625 | 4 | ## Source: https://pythonspot.com/extract-links-from-webpage-beautifulsoup/
### THE PACKAGES IN THIS LINK ARE OUTDATED
"""Note: this version is somewhat functional, although it does not return even the relative links
from the footer of the HTML page that are returned in the v2 scraper
"""
from bs4 import BeautifulSo... |
ee18a8ed6c732aa87c2527e449587aea26b38252 | ZhaoYun17/sql | /car_sql3.py | 472 | 3.9375 | 4 | # use COUNT() calculate total number of orders for each make and model
# Output car's make and model
# output quantity
# output order count
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("SELECT * FROM inventory")
rows = c.fetchall()
for r in rows:
print r[0]... |
868345620ebf25c4a37043e0a31579dac1e0fea7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/hlncec001/question3.py | 956 | 4.15625 | 4 | #HLNCEC001
#Question3
#Assignment8
#program that uses a recursive function to encrypt a message
l = []
def encrypt(s):
global l
if s == s.lower():
if ord(s[0]) == 122:
a = 122 - 26
s =chr(a)+s[1:]
return encrypt(s)
elif s[0] != ' ' and ... |
ad10751cb94853670a2a77e0a44027bcea3f5bfd | Dissssy/AdventOfCode2020 | /03/2/code.py | 1,180 | 3.703125 | 4 | import time
start_time = time.time()
#open the file and parse it into a list of strings on newlines
text_file = open("input.txt", "r")
lines = text_file.read().split('\n')
#every input text file has an empty newline at the end, delete it
lines.pop(-1)
#define the checkslope function that i will be using to check each... |
5ea4bf263ae6550766a96ff1b86af63d67ed4b0f | posuna19/pythonBasicCourse | /course2/week3/03_regex_wildcards.py | 2,612 | 4.15625 | 4 | import re
regex = r"[Pp]"
text = "Python, python, ruby, Xython, papa"
result = re.search(regex, text)
print("Result: ", result)
result = re.match(regex, text)
print("Result: ", result)
result = re.findall(regex, text)
print("Result: ", result)
regex = r'[a-z]way'
text = 'The end of the highway'
result = re.search... |
75696936ead8d45fc5351e28466946047b4b8959 | MariaSun/Algebraic-Montgomery-multiplication | /montgomery_multiplication.py | 1,312 | 3.796875 | 4 | ##########################################################
#08/12/2021 -- Maria Solyanik-Gorgone #
#Exact algebraic algorithm for Montgomery multiplication.#
##########################################################
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import cmath
... |
a51d19421472e22969ea8e086131ff3fff0b72c7 | Anton-L-GitHub/Learning | /Python/1_PROJECTS/Python_bok/Uppgifter/Kap8/uppg8-5.py | 244 | 3.65625 | 4 | def är_perfekt(n):
sum = 0
for k in range(1, n):
if n % k == 0:
sum = sum + k
return sum == n
tal = int(input('Skriv ett tal: '))
if är_perfekt(tal):
print('Talet är perfekt')
else:
print('Talet är inte perfekt') |
82f3c685b4137be5f99fd411a09869e36702ba1e | vivianvivi1993/X-Village-2018-Exercise | /周蔚Analysis/30.py | 2,593 | 3.546875 | 4 | # data visualization
# 關於API獲得json檔案的資料
# 選擇豆瓣圖書
import json
import pandas as pd
import requests
import matplotlib.pyplot as plt
plt.rcdefaults()
from requests_html import HTMLSession
import re
url = 'https://api.douban.com/v2/book/4238362'
r = requests.get(url)
r.encoding = "utf-8"
r=r.json()
count=[]
name=[]
for ... |
a8564ed0c6650c793ce40329bc378c7982ee47fa | deepikanagalakshmi/python | /4for_loop.py | 258 | 3.859375 | 4 | import turtle
my_turtle = turtle.Turtle()
my_turtle.speed(1)
#triangle
def triangle():
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.left(135)
my_turtle.forward(142)
for count in range(3):
triangle()
|
5a5083d54ea68e863e32c90678cc8f42982ee73f | Vanyali/100-Python-challenging-programming-exercises | /Question24.py | 773 | 4.125 | 4 | '''
Question:
Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books.
But Python has a built-in document function for every built-in functions.
Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
A... |
613132ab909da8cc94e52454695070735e3fc59c | zhangwang0537/LeetCode-Notebook | /source/Clarification/Array/44.通配符匹配.py | 1,166 | 3.84375 | 4 | # 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
#
# '?' 可以匹配任何单个字符。
# '*' 可以匹配任意字符串(包括空字符串)。
# 两个字符串完全匹配才算匹配成功。
#
# 说明:
#
# s 可能为空,且只包含从 a-z 的小写字母。
# p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
# 示例 1:
#
# 输入:
# s = "aa"
# p = "a"
# 输出: false
# 解释: "a" 无法匹配 "aa" 整个字符串。
class Solution:
def isMatch(sel... |
d2dbf5e8ecd342cd1ee46aa4e79da37505c64b7d | weipanchang/FUHSD | /list-swap-element.py | 233 | 3.96875 | 4 | #!/usr/bin/env python
def swap(l,i,j):
l[i], l[j] = l[j], l[i]
bag=[]
for i in range(10):
item=int(input("Enter the next item: "))
bag.append(item)
print bag
print""
print "after swap:"
swap(bag,2,8)
print ""
print bag
|
d956a3f65838eec912867ebe5325d60e89957d8f | sudhasr/DS-and-Algorithms-Practice | /CheckStraigntLine.py | 1,115 | 4.03125 | 4 | # 1232. Check If It Is a Straight Line
"""
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example ... |
5c6397795cdec74db136bee2f236e15297051085 | AChen24562/Python-QCC | /Week-3-Lists/ListsExamples_I/5_list_modify.py | 237 | 4.125 | 4 | # s. trowbridge 2020
vehicles = ['car', 'truck', 'motorcycle', 'plane', 'boat']
# modify the first list element
vehicles[0] = 'bike'
print(vehicles)
print("")
# modify the third list element
vehicles[2] = 'scooter'
print(vehicles)
print("")
|
fc1c43e065320e5f1701c57e07c2878370ed9712 | amirmojarad/maze | /models/main.py | 1,053 | 3.609375 | 4 | import map_generator
import astar
import path_drawer
import time
def main():
# Reading maze from file
print('Loading file...')
with open('examples/normal.txt') as file:
text_maze = file.read()
print('File loaded')
# Generate graph from raw text in file
print('Creating maze graph')
... |
825560c8d4e9ac7d00e089242565494656aea8d9 | GabrielTrentino/Python_Basico | /02 - Curso Em Video/Aula 16/E - 077.py | 291 | 3.703125 | 4 | palavras = ('AVIÃO', 'CARRO' , 'FUTEBOL', 'SKATE','PYTHON','JAVA','CHUVA','ARVORE','NATUREZA')
for i in palavras:
print("Na palavra {}, temos: ".format(i), end = '')
for letra in i:
if letra.lower() in 'aeiou':
print(letra.lower(), end = ' ')
print('') |
bf1fa8daebe674fae8c5e879bd04e9e303ef4289 | moaoh/algorithm | /baekjoon/1673번 - 치킨 쿠폰/main.py | 285 | 3.59375 | 4 | def count(chicken, n, k):
if n >= k:
coupon = n // k
chicken += n // k
n = n % k
n += coupon
return count(chicken, n, k)
return chicken
while True:
try:
n, k = map(int, input().split())
chicken = n
chicken = count(chicken, n, k)
print(chicken)
except:
break
|
a25f2328c4bdf587a5f2a08201d4c5e9550bd057 | sainad2222/my_cp_codes | /codeforces/1038/B.py | 292 | 3.5 | 4 | n = int(input())
if n<=2:
print("No")
exit()
print("Yes")
print(n//2,end=" ")
lis = [x for x in range(2,n+1,2)]
print(' '.join(map(str,lis)))
if n&1:
print((n//2)+1,end=" ")
else:
print(n//2,end=" ")
lis = [x for x in range(1,n+1,2)]
print(' '.join(map(str,lis))) |
eb0a9974c5d3c105b44026c5f96c14be4168cbb6 | Lyuflora/test | /classed.py | 505 | 3.703125 | 4 | # 类和对象
class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def print_score(self):
print('%s, %s' % (self.name, self.__score))
def get_score(self):
return self.__score
def set_score(self, mark):
self.__score = mark
#... |
0b2ad8323ac3e5958812becab7af0dc7643a6b64 | JeonghoonWon/Eclipse_Pydev | /HELLOPYTHON/day01/myholl.py | 291 | 3.578125 | 4 | import random
com = ""
mine = input("홀/짝을 선택하세요.")
result = ""
rnd = random.random()
if rnd > 0.5:
com = "홀"
else:
com = "짝"
if com == mine :
result = "승리"
else :
result = "패배"
print("컴 : ", com)
print("나 : ",mine)
print("결과 :",result) |
86757049b020781019b68e36e007c89c3d4e49ef | Barshon-git/Test | /Try Except.py | 183 | 3.953125 | 4 | try:
value=10/0
number= int(input("Enter a number: "))
print(number)
except ZeroDivisionError :
print("Division by zero")
except ValueError:
print("Invalid input") |
784d053765e5e95f93c307b671df8e515d42e758 | Taeg92/Problem_solving | /SWEA/D2/SWEA_1948.py | 879 | 3.5625 | 4 | # Problem [1948] : 날짜 계산기
# 입력 : 월 일로 이루어진 날짜 2개
# 두 번째 날짜가 첫 번째 날짜의 몇칠째 인지 출력
# 두 번째 날짜 > 첫 번쨰 날짜
calendar = {1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}
test_cnt = int(input())
for test in range(1,test_cnt+1) :
result = 0
calc_date = list(map(int,input... |
1220a27f56bbc2f55e28e17f3c6b435a7df827b0 | EmersonDantas/SI-UFPB-IP-P1 | /Python Brasil - Exercícios/Estrutura Sequencial/Q15ES-Salário-Horas-Impostos.py | 419 | 3.75 | 4 | gh = float(input('Quanto você ganha por hora: '))
nhtm= float(input('Número de horas trabalhadas no mês: '))
salarioTotal = gh * nhtm
ir = salarioTotal * 0.11
inss = salarioTotal * 0.08
sindi = salarioTotal * 0.05
salarioLiquido = salarioTotal - (inss + sindi + ir)
print('Salário bruto: R${0}\nINSS: R${1}\nSindi... |
cf82bb27c03d521111e449f589064441a9ec3583 | massadraza/Python-Learning | /dictionary_calculations.py | 422 | 3.953125 | 4 | Stock = {
'NASDAQ': 10680.36,
'NYSE': 12508.68,
'Dow Jones': 26840.40,
'APPL': 388.00,
'SBUX': 75.44,
'NKE': 98.36,
'TMUS': 105.58,
'AMZN': 3138.29,
}
min_price = min(zip(Stock.values(), Stock.keys()))
max_price = max(zip(Stock.values(), Stock.ke... |
31444eab42be319c3d709b195fe86028b477f38d | Behzodbek777/Python_darslari | /02.07.2021/massivlar(ro'yxat).py | 472 | 3.671875 | 4 | oquchilar = ["Abduvaliyeva", "Abdusalomova", "Aliqulova", "Jabborov", "Sattorov", "Xudoyorov" ]
print(oquchilar)
oquchilar.append("Xudoyberdiyev")
print(oquchilar)
oquchilar.insert(3,"Bo'ribekova")
print(oquchilar)
print(len(oquchilar))
oquchilar.append("Aliqulova")
print(oquchilar.count("Aliqulova"))
oquchilar1 = ["Bo... |
f00d8d0bd44dc8f52538f79c8955398d60ce6f9b | Near-River/leet_code | /181_190/190_reverse_bits.py | 933 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many ... |
634fcca82968a83826828abb30f19dffcd1bf285 | Christy538/Hacktoberfest-2021 | /PYTHON/Gui calculator.py | 6,784 | 3.90625 | 4 | from tkinter import *
root = Tk()
#button_9 = Button(label_key,text='9',height=3,width=5,font=('Helvetica','12'))
#button_9.grid(row=0,column=0)
class Calculator:
def click_button(self,numbers):
global operator
global var
self.operator = self.operator + str(numbers)
self.var.set(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.