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 |
|---|---|---|---|---|---|---|
f12793c8600f6680c93ed9b0a178990f2785d5e5 | jnovinger/project_euler | /problem_004/problem_4.py | 516 | 3.734375 | 4 | #!/usr/bin/python
'''
Project Euler Problem 4
Answer: 906609
'''
def is_palindrome(x):
z = str(x)
l = len(z) / 2
if z[:l] == z[-l:][::-1]:
return True
return False
upper_limit = 999
lower_limit = 100
found = False
palindrome = 0
for x in xrange(upper_limit, lower_limit - 1, -1):
for ... |
bbcf3f64e16d500f7dd1ba2113d2b76b06827d23 | iCodeIN/algorithms-9 | /solutions/Hashing/ValidSudoku.py | 1,155 | 4.03125 | 4 | ## Website:: Interviewbit
## Link:: https://www.interviewbit.com/problems/valid-sudoku/
## Topic:: Hashing
## Sub-topic:: Search
## Difficulty:: Medium
## Approach:: Just store the numbers seen so far for row, col, and cell
## Time complexity:: O(N)
## Space complexity:: O(N)
## Notes::
import collections
class Solu... |
47be3c2cf7e4a8ea37fdf17625b5aa2512a9b522 | jamiepg1/GameDevelopment | /examples/python/basics/pyguess.py | 650 | 4 | 4 | # Last updated on July 18, 2010
import random
min = 1
max = 100
secret = random.randint(min, max)
print("Welcome!")
guess = 0
numGuesses = 0
while guess != secret:
guess = 0
while guess < min or guess > max:
g = input("Guess the number between " + str(min) + " and " + str(max) + " (inclusive): ")
guess = int(g)
... |
6bc2324f8680a6a3744cc7790e82f1b9c5e834a3 | candyer/leetcode | /2021 January LeetCoding Challenge /15_getMaximumGenerated.py | 1,980 | 3.96875 | 4 | # https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3605/
# Get Maximum in Generated Array
# You are given an integer n. An array nums of length n + 1 is generated in the following way:
# nums[0] = 0
# nums[1] = 1
# nums[2 * i] = nums[i] when 2 <= 2 ... |
9fdea20f3bbd40c24a8c331ee656a0db02c7a60f | mizcarno/Subject-Ai-program2 | /game_tree_node.py | 3,236 | 3.546875 | 4 | from eight_puzzle_game_state import EightPuzzleGameState
"""The adjacent_tiles array holds a mapping of adjacent tiles from a single tile position for the eight puzzle game state.
"""
adjacent_tiles = [(1,3),(0,2,4),(1,5),(0,4,6),(1,3,5,7),(2,4,8),(3,7),(4,6,8),(5,7)]
solution_state_as_array = ['1','2','3','4','5',... |
d8b6677f96a32075ba0fdac98fc1a793463160f4 | Genie1106/TIL | /Quiz/2448.py | 303 | 3.625 | 4 |
N = int(input())
blank = " "
star = "*"
half = int((N-1)/2)
print(half*blank+star)
for i in range(1,half+1):
a = half - i
b = int(N-2-(half/2-1)*2)
print(a*blank + star + blank*b + star)
# print(i*blank+star)
# print((i-1)*blank+star+blank*1+star)
# print((i-2)*blank+star+blank*3+star) |
da4e4f38c56c0383cc38e74ef269a25360c2ee82 | ledbagholberton/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/10-best_score.py | 312 | 3.578125 | 4 | #!/usr/bin/python3
def best_score(a_dictionary):
if a_dictionary is not None:
if len(a_dictionary) is not 0:
mayor = 0
for a, b in a_dictionary.items():
if b > mayor:
mayor = b
key_mayor = a
return key_mayor
|
ae524cc3318b8d8e56a9ad9cc32407ef74d62761 | bethanymbaker/arch | /scripts/demandbase.py | 2,273 | 3.578125 | 4 | #
# /**
# Interview Problem Statement
#
# This challenge is meant to assess the candidates ability to perform operations in the spark framework. You may either use RDDs or DataFrames to complete the challenge.
#
# 1. Start by creating a RDD/DF representing the data below
# 2. Within each group of column A and for each ... |
051d0aa58ff0b5983d547c7e3b91e2c3dbafb4c8 | AthanLapp/scrumbedwordsmultiplayergame | /scrumbling words.py | 1,061 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 28 14:38:08 2021
@author: Athan
@title Scrumble the words
"""
import random
word = input("Give me the word to scrumble")
wordlen=len(word)
for i in range(40):
print("scrumbling...")
wordmn = []
for ln in range(0,wordlen):
wordmn.append(ln)
wordml=[... |
2fa8671a1b0282fa6ca9960ebe7ec19f52b9cd1f | bragon9/leetcode | /1232CheckIfItIsaStraightLine.py | 903 | 3.609375 | 4 | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
# Compare first two points as a baseline.
x1, y1 = coordinates[0][0], coordinates[0][1]
x2, y2 = coordinates[1][0], coordinates[1][1]
# Find slope:
if x1 == x2:
# horizontal line.
... |
7491ed81a17550f957580ce4e4682d132edc8a8d | sarthak13gupta/learning_git | /functions.py | 241 | 3.765625 | 4 | #create function
def sayHello(name = 'sarthak'):
print(f'Hello {name}')
#Return values
def getSum(num1 , num2):
total = num1 + num2
return total
#lambda function
getSum = lambda num1, num2: num1+ num2
print(getSum(10,3))
|
d26742d39e4f2620c4aa03778b048f2d2f1b456b | yatish0492/PythonTutorial | /39_AbstractClass_AbstractMethod.py | 938 | 4.125 | 4 | '''
Abstract Class and Abstract Method
-----------------------------------
Python doesn't have 'abstract' key word like java.
Abstract Class
--------------
we need to import 'ABC" class from 'abc' module. 'ABC' means 'Abstract Base Classes'. if we want to declare
the class as abstract then we need to exte... |
8c73606f3102da55972719fdd02ee9347df39537 | marchuknikolay/bytes_of_py | /byte022/decorators.py | 515 | 3.765625 | 4 | """
Bite 22. Write a decorator with argument
Write a decorator called make_html that wraps text inside one or more html tags.
As shown in the tests decorating get_text with make_html twice should wrap the text in the corresponding html tags, so:
@make_html('p')
@make_html('strong')
def get_text(text='I code with Py... |
f6545b9eef3e122ad310a5e7cfdf7c7da762f9ce | ashishpal07/Python-projects | /Banking/simple Banking system.py | 3,764 | 3.953125 | 4 | class Account :
def createAccount(self):
self.accNo= int(input("Enter the account no : "))
self.name = input("Enter the account holder name : ")
self.type = input("Ente the type of account [C/S] : ")
self.deposit = int(input("Enter The Initial amount(>=500 for Saving and >=1000 for c... |
696b3181af8b64cdb78c10284b0b20e57f3691c9 | bakunobu/exercise | /1400_basic_tasks/chap_5/5_45.py | 232 | 3.65625 | 4 | def fib_seq(n:int) -> list:
a = 1
b = 1
fibbies = [a, b]
for k in range(n-2):
a, b = b, a+b
fibbies.append(b)
return(fibbies)
my_list = fib_seq(10)
for el in my_list[2:]:
print(el, end=', ') |
0c69282ce4e6b9ed4d3b197de74e72240f8a3438 | pani3610/AJGAR | /13payrollt.py | 1,845 | 3.78125 | 4 | class employee:
e_no=0
e_name=''
e_designation=''
e_address=''
e_phno=0
def __init__(self,values=None):
if values==None:
no=int(input("Enter Employee No. > "))
name=(input("Enter Employee Name > "))
desig=(input("Enter Employee Designation > "))
... |
f0e863803b6e71f9f2371a7d97b52fcf8c7a6097 | qwertystop/format_generator | /example.py | 504 | 4.28125 | 4 | """
An example of usage of the format_generator
"""
from format_generator import format_generator
namelist = ['Sarah', 'Ellen', 'Frederick', 'Robert the Seventeenth',
'Mister Plibble', 'Nobody', 'Sparky', 'Bob']
paired = [(n, n[0]) for n in namelist]
template = '{0} is a{2} name, and it starts with {1}.'... |
57394b9e6d57b81920ece92fcf9e992e54e98e53 | eugene-marchenko/pycharm | /coursera_dictionary.py | 549 | 3.59375 | 4 | fname = raw_input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
dic_result = dict()
mail_list = list()
for line in fh:
if not line.startswith('From '):
continue
else:
mail_list.append(line.split()[1])
for email in mail_list:
dic_result[email] = dic_re... |
cd857fa5b1d4d6d3e9712591675417c07e5d56e1 | HunterLarco/Project-Euler | /005.py | 1,286 | 4.15625 | 4 | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
from collections import Counter
from collections import defaultdict
def factorize(N):
if N < 2: return... |
42681ad80429b0c119d6306b821d49825ad3bba7 | dharmit01/competitve_coding | /520A.py | 85 | 3.5625 | 4 | a=input()
if len(set(input().upper()))<26:
print("NO")
else:
print("YES") |
194ca4d37c1ef0c7a23b26846355579e8380e1fc | lnandi1/Python_Solutions_DEC2018 | /Solutions/Modules 31 UP/testmodule.py | 731 | 3.609375 | 4 | import math
def add(a,b):
addition=a+b
print (addition)
return
def sub(a,b):
subtraction=a-b
print (subtraction)
return
def div(a,b):
divide=a/b
return round(divide,2)
def mult(a,b):
multiply=a*b
print (multiply)
return
def expo(a,b):
exponentia... |
91cfa0ccf387afa099c2c9035f1820688f894ee7 | Allan690/Andela_Challenge | /PasswordChecker.py | 1,114 | 3.96875 | 4 | # from unittest import TestCase
def handle_user_input():
passwords = input("Enter your string of passwords: ").split(',')
return passwords
def validate_password(passwords):
special_str = "$#@"
accepted = []
for password in passwords:
lower, upper, digits, special = 0, 0, 0, 0
for char in ... |
531e0afa38d705b1bd5a423e04e3f30a54c9711a | eviluser7/random-pyglet | /basic-examples/control.py | 2,744 | 3.953125 | 4 | # control a shape with the keys
# warning: this code may seem complex, but it's actually fairly simple.
# you'll need some python knowledge for this one, but take this as a template
# for moving a shape on the screen. bigger examples on the minigames/ directory
import pyglet
from pyglet.window import key
from pyglet i... |
a281bb00d282d770daad55db6deca6b10c1a88b7 | saurabh-pandey/AlgoAndDS | /epi/ch01_primitives/parity_is_pow_2_a1.py | 206 | 4.21875 | 4 | '''
Test if x is a power of 2, i.e., evaluates to true for x = 1,2,4,8,... and false for all other values
'''
def is_pow_2(x: int) -> bool:
if x == 0:
return False
return (x & (x - 1)) == 0
|
dba79751ce7d68ce91cc5ce6138c0cf179810d3a | Elvis-Lopes/Curso-em-video-Python | /exercicios/ex039.py | 348 | 4.03125 | 4 | from datetime import date
anoAtual = date.today()
anoNascimento = int(input('Insira o seu ano de nascimento: '))
idade = anoAtual.year - anoNascimento
if idade < 18:
print(f'Falta {18 - idade} anos para se alistar')
elif idade == 18:
print(f'Esta na hora de se alistar ')
else:
print(f'Já passou {idade - 1... |
000668fbaeb828e6e23927a28bc664901d53a803 | ljungmanag42/Project-Euler | /PE-049.py | 1,355 | 3.65625 | 4 | # ProjectEuler 49
''''
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases
by 3330, is unusual in two ways:
(i) each of the three terms are prime, and,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or... |
ee241cb886b43bc621447e8e465023bb4295e8e3 | jiez1812/Python_Crash_Course | /CH3_Introducing_Lists/3-4_Guest_List.py | 398 | 3.921875 | 4 | # Create a guest list who will be invited to dinned
guests = ["Eric", "Alex", "Sandra", "Edward", "Mozilla"]
print("Hi " + guests[0] + ", you are invited to dinner.")
print("Hi " + guests[1] + ", you are invited to dinner.")
print("Hi " + guests[2] + ", you are invited to dinner.")
print("Hi " + guests[3] + ", you are ... |
0bd3a33d5b1be53060efaa01c8ae9b7655357721 | HmirceaD/TermParser | /entrypoint/term.py | 2,549 | 3.6875 | 4 | """Class that creates terms from subexpression int the expression"""
class Term:
def __init__(self, expr, parent, term_type):
"""pointer to the parent term, the contents formed from the subexpression
and a list for the potential children"""
self.parent = parent
self.expr = expr
... |
38654b6a3270c477d60ac503e0e8ba5eec7c4173 | comorina/Ducat_Assignment | /p92.py | 165 | 3.859375 | 4 | def rev(x):
while(x>0):
re=x%10
x=x//10
print(re,end='')
rev(int(input("Enter number : ")))
|
79ea9c572abd8d2664bafe8339d12f2d85a212f1 | xianytt/LeetCode | /数学与数字/整数反转.py | 818 | 3.875 | 4 | # _*_ coding:utf-8 _*_
'''
@author:xianyt
@date:2018/
@func:
整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
'''
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# x是个位数
if (x // 10) == 0:
return x
str_x = ... |
a89f474dda1b9989c2f4a8690cdaa302a41daed8 | NyeongB/Coding_Test_Python | /Stack/Stack_02.py | 313 | 3.53125 | 4 | '''
출제 : 백준
난이도 : 실버 4
문제 : 제로
날짜 : 21.04.11
유형 : 스택
'''
n = int(input())
stack = list()
for _ in range(n):
temp = int(input())
if len(stack) !=0 and temp == 0:
stack.pop()
else:
stack.append(temp)
print(sum(stack))
'''
눈감고 풀었다.
''' |
17a87426a9da8b9a90fd7a40feab0efe3288556a | deepika087/CompetitiveProgramming | /LeetCodePractice/654. Maximum Binary Tree.py | 744 | 3.546875 | 4 | __author__ = 'deepika'
# Definition for a binary tree node.
"""
107 / 107 test cases passed.
Status: Accepted
Runtime: 235 ms
"""
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def constructMaximumBinaryTree(se... |
01dc883e08297d1a2cae0a736a5317c69d1e9e58 | kanwar101/Python_Review | /src/Chapter04/squares.py | 209 | 3.6875 | 4 | squares=[]
for x in list(range(1,5)):
squares.append(x**2)
print (squares)
list_numerics = [1,2,34,565,78,32,5656,89,1212,4]
print (min(list_numerics))
print (max(list_numerics))
print (sum(list_numerics)) |
01f9016a5d16a11c4d94512122758ea969fda280 | Rolya242/python-course | /exo2.py | 142 | 3.578125 | 4 | nom = input("saisir votre nom ")
prenom = input("saisir votre prenom ")
print(" initiaux nom "+nom[0])
print(" initiaux prenom "+prenom[0])
|
79cfc4c27ca109de98853aa7dbcbaaf3380150a1 | babakpst/Learning | /python/106_OOP/4_composition.py | 755 | 3.90625 | 4 |
# babak poursartip
# June 9, 2023
# composition relation: has a
# inheritance relation: is a
class person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def __str__(self):
return f" person: ({self.fname} {self.lname})"
class employee:
def __init__(self, fna... |
c16805df802e78a01e8e34cba013bc09325cc5cb | simonhfisher/passwordgenerator | /pig_latin_maker.py | 622 | 3.875 | 4 | #pig latin maker
def pig_latin_maker(word):
first_letter = (word[0])
rest_of_word = (word[1: ])
pig_word = (rest_of_word) + (first_letter) + "ay"
return pig_word
#print(pig_latin_maker("chicken"))
def pig_latin_sentence_messer(words):
output = " "
list_made_from_input_string = (words.sp... |
0506d6ca0f7e85d4fa14f4ced151460c1eac9e10 | camilahuang/YHuang-cfg-python-project | /hello.py | 432 | 3.5 | 4 | print("i want to create merge conflict!")
print("Hello, world")
print(2*4)
print('Bob'*3)
print('Bob'*3)
print('hello'.upper())
print('GOODBYE'.lower())
print("thelord of therings".title())
age=25
hobby="swimming"
description="Her age is {} and she likes {}".format(age,hobby)
print(description)
exmp="... |
4b7aa8ef8bbf1de574e87b4e536cd491b49e8d15 | Sam-Park/Python | /regex.py | 418 | 3.625 | 4 | import re
#seperate into groups using parens
phoneNumberRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)')
mo = phoneNumberRegex.search('My number is 859-223-2211')
print(mo.group(1)) #accessing groups
print(mo.group(2)) #accessing groups
batRegex = re.compile(r'Bat(wo)?man')
mo = batRegex.search('The adventures of B... |
2a7c125e688e21ede530ac1d2df000c1cf6f1db9 | sidd5sci/game-engin | /obj loader/.last_tmp.py | 2,820 | 3.8125 | 4 | from vector import *
'''
==========================================
physics class
==========================================
'''
class physics(object):
def __init__(self,pos):
# mass
self.mass = 1.0 # kg
# motion physics / newton physics
self.pos = list(pos)
self.veloci... |
9d54da1abc962a894f7bfe7a1d7d6f04624d0784 | adamalston/comp431 | /submissions/hw1/generate_tests.py | 14,321 | 3.984375 | 4 | # 1) Example well-formed sequence (from assignment writeup)
with open("in1.txt", "w") as f:
f.write(
"MAIL FROM: <jasleen@cs.unc.edu>\r\n"
"RCPT TO: <smithfd@cs.unc.edu>\r\n"
"DATA\r\n"
"Hey Don, do you really think we should use SMTP as a class\r\n"
"project in COMP 431 this... |
3fe478bd61b2297e075251633fd0aacff39253c5 | souradeepta/PythonPractice | /code/5-19/stack.py | 782 | 3.640625 | 4 | # Stack
from typing import TypeVar, Generic, List
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
def peek(self) -> T:
... |
2cfbe4ee8f4189e48586b2610851e743710ffd7c | hanss314/TLOW | /S0/R1Revealed/202734950699499522.py | 380 | 4.03125 | 4 | from time import sleep
if str.lower(input("Ugandan Knuckle: Do you know da wae?\nUgandan Knuckle: You must have Ebola to know da wae.\n")) == "yes":
print("Ugandan Knuckle: My brothers, I've found it! They will show us da wae")
else:
print("Ugandan Knuckle: Nonbeliever!\nUgandan Knuckle: My brothers, spit on the nonb... |
2cb543ec0ef477af6f513a792a7575d3fc5ba84f | l225li/hackerrank-interview-preparation-kit | /clickMineSweeper.py | 1,721 | 3.90625 | 4 | # Implement your function below.
def click(field, num_rows, num_cols, given_i, given_j):
if field[given_i][given_j] != 0:
return field
to_check = [(given_i, given_j)]
while to_check:
i, j = to_check.pop()
for x in range(i-1, i+2):
for y in range(j-1, j+2):
... |
8c4af9426745efcfde1fcec9e35650d6c6b8bc3c | FribFrog/Test | /TestBotTextAdventure.py | 879 | 3.875 | 4 | import time
x = input("???: Hi there List your family")
family = x.split()
Ted = False
for x in family:
if (x) == ("testbot") or x == ("TestBot"):
Ted = True
if len(family) >1:
print("???: Oh,That's Nice.")
if Ted == True:
time.sleep(1.5)
print("TestBot: Wait, TestBot is MY name!!!")
else:
... |
c0c0a25167cb0ef33d1edae28452180a5d5fc6c3 | RCNOverwatcher/Python-Challenges | /Sources/Challenges/043.py | 177 | 4.1875 | 4 | upordown=input("Do you want to count up or down?")
if upordown=="up":
upnum1=int(input("Enter the top number"))
for num in range (1,npnum1)
print("I dont know????")
|
5667fb26ea0ed5e008df77f73f48d362ec88a893 | Chaluka/Algorithms | /Sorting/test_quick_sort.py | 2,970 | 4.1875 | 4 | """
Testing file for Question 2 of Interview Prac 2
"""
__author__ = "Chaluka Salgado"
__date__ = "24/03/2021"
import unittest
import random
from quick_sort import partition, quick_sort
class TestQuickSort(unittest.TestCase):
def setUp(self):
""" The 'setUp' method is a frequently used met... |
0b213ff034dc7ee447177cf91e312d3cc2d721ca | da-wad/camelup | /camels.py | 1,946 | 3.5625 | 4 | import random
def get_dice_number():
return random.randint(1,3)
def get_dice_colours():
colours = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"]
return random.sample(colours, len(colours))
def get_dice_with_numbers():
return [(colour, get_dice_number()) for colour in get_dice_colours()]
de... |
079daee4f64218dd72c31d32d0085ce0629471b2 | mauro39ar/prueba | /tp2examen/ejercicio_8.py | 291 | 3.6875 | 4 | #!/usr/bin/python
amy = input ("ingrese numero(del 1 al 7): ")
lita=["domingo", "lumnes", "martes", "miercoles", "jueves", "viernes", "sabado"]
if amy > 0 and amy <=7:
print "el dia de la semana es %s" % (lita[amy-1])
else:
print "el numero ingresado es incorrecto" |
370778dc533a9275d5a73b43567ac7fbcafb61f7 | Tioneb88/TFE_Malware_Visualization_and_Classification | /Plots/activation_plot.py | 950 | 3.703125 | 4 | """
Plot different activation functions.
Author: Benoît Michel
Date : June 2021
"""
import matplotlib.pyplot as plt
import numpy as np
import math
def logistic(x):
a = []
for item in x:
a.append(1/(1+math.exp(-item)))
return a
# x axis
xx1 = np.arange(-3, 3, 0.01)
yy1 = [0]... |
ab73b59c1068cb1d4f2f6cadce9e5503f3acce18 | jcockbain/ctci-solutions | /chapter-16/Q09_operations.py | 1,222 | 3.65625 | 4 | import unittest
def multiply(a, b):
res = 0
for _ in range(abs(b)):
res += abs(a)
negative_count = sum([x < 0 for x in [a, b]])
return negate(res) if negative_count == 1 else res
def divide(a, b):
abs_a, abs_b = abs(a), abs(b)
product, res = 0, 0
negative_count = sum([x < 0 for x... |
fa571b5c37452041db61fe84a5f3d34262e4a17e | rpd54/Python-Deep-learning | /Lab2/Source/lab2/dictio.py | 461 | 3.96875 | 4 | #Umkc-Directory listing its prices for every course
price_book={"python-Deep Learning" : "20", "web Design" : "25",
"machine-Learning" : "40", "network-Architecture" : "50"}
print(price_book)
#For the Range from start to end
x=int(input("Enter the starting number"))
y=int(input("Enter the final number"))
... |
2f63247e658680145003f1e8b04be98aed343d17 | lvonbank/IT210-Python | /Ch.02/P2_14.py | 266 | 4 | 4 | # Levi VonBank
## Reads a number between 1,000 and 999,999 from the user and
# prints it with a comma separating the thousands.
n = int(input("Enter a number between 1000 and 999999: "))
thousands = n / 1000
remainder = n % 1000
print("%d,%d" % (thousands, remainder)) |
a6868094a839b6cb2ff5ce75431bc1097ddb6a32 | NikkieS/Python_studynote_loop | /LeapYear.py | 493 | 3.703125 | 4 | year = int(input('년도를 입력하세요 : '))
'''
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) :
print(str(year) + '년도는 윤년입니다.')
else :
print(str(year) + '년도는 평년입니다.')
'''
if year % 400 == 0 :
print('%d년도는 윤년입니다.'% year)
elif year % 100 == 0 :
print('%d년도는 평년입니다.'% year)
elif year % 4 == 0 :
print... |
30cf48486373269e6b73a11167d3b9f0117eb6e5 | elchuzade/racing-game-ai | /helpers/core.py | 1,479 | 3.671875 | 4 | import constants.constants as vals
class Car:
# Car class is representing common values of all cars in the game
def __init__(self, x, y):
self.x = x
self.y = y
# width is originating from car image width
self.width = vals.CAR_WIDTH
# height is originating from car image... |
d5295b3657c71acc1365d372721c19797500707c | 19179/token_generater-2 | /main.py | 540 | 3.890625 | 4 | import random
# main routine goes here
token = ["unicorn","horse","horse","horse","zebra","zebra","zebra","donkey","donkey","donkey"]
STARTING_BALANCE = 100
balance = STARTING_BALANCE
# Testing loop to generate 20 tokens
for item in range(0,500):
chosen = random.choice(token)
# Adjust balance
if chosen == "uni... |
bbfa2d60c756e93d1f39694a440f8a4c3dae72b3 | SecretAardvark/Python | /pycrashcourse/inputdictionary.py | 383 | 4.125 | 4 | person = {}
person['age'] = input("How old are you? ")
person['hometown'] = input("Where are you from? ")
person['first_name'] = input("What is your first name? ")
person['last_name'] = input("What is your last name? ")
print("Your name is: " + person['first_name'] + person['last_name'] + "Your hometown is: "
+ pers... |
f1c2c2df2c6edd78fb0964f4d7a3bfb4be754ecd | volodiny71299/Right-Angled-Triangle | /03.5_rad_deg.py | 434 | 4.21875 | 4 |
# https://www.geeksforgeeks.org/degrees-and-radians-in-python/
# Python code to demonstrate
# working of radians()
# for radians
import math
# Printing radians equivalents.
print("180 / pi Degrees is equal to Radians : ", end ="")
print (math.radians(180 / math.pi))
print("180 Degrees is equal to Radians : ",... |
2a98de036d5319512879771170b5af00fff62430 | aidardarmesh/leetcode | /Problems/472. Concatenated Words.py | 1,286 | 3.90625 | 4 | from typing import *
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for c in word:
if not c in no... |
0a91c29f254356483e629bdba57231914ba9a8a6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2171/60686/283212.py | 641 | 3.515625 | 4 | nums = int(input())
list_all = []
for i in range(nums):
length = int(input())
str_input = input().split(" ")
for j in range(length):
str_input[j] = int(str_input[j])
list_all.append(str_input)
for i in range(nums):
str_input = list_all[i]
list_dual = []
list_single = []
for j in ... |
1a007229fa6670627e92152b19b2f58b47384b8d | nazaninsbr/Introduction-to-Selection | /Beginner-programs/while_for_loop.py | 164 | 3.609375 | 4 | goal = 100
counter = 0
while counter < goal:
print counter
counter += 1
print "out of the loop"
gl=[1, 2, 3, 5, 6]
for y in gl:
print "number is %d"%y
|
e626e66a032db71a3c7168deebc242bba3211ab1 | saadnasimalgo/PythonTest | /muhammad_osama_python_test.py | 2,855 | 3.65625 | 4 | import json
import random
def open_file():
""" opening file """
with open('data.txt', 'r') as file:
data = json.loads(file.read())
return data
def parse_command():
"""
parse command code first method with list comprehension
"""
parse_commands = []
[parse_commands.append(r... |
0e44455504ce43064929776c77cf9e048ed54e41 | ZwEin27/Coding-Training | /LeetCode/python/lc008.py | 1,202 | 3.578125 | 4 | #!/usr/bin/env python
# Implement atoi to convert a string to an integer.
class Solution:
# @param {string} str
# @return {integer}
def myAtoi(self, str):
result = 0;
strlen = len(str);
if strlen == 0:
return 0;
startIdx = 0;
blankflag = 0;
for ... |
0190d526bc15ddd32f5c307fc49dd97fcee146ac | ryanwilkinss/Python-Crash-Course | /Do it Yourself/Chapter 3/3-5.py | 1,055 | 4.3125 | 4 | # 3-5. Changing Guest List: You just heard that one of your guests can’t make the
# dinner, so you need to send out a new set of invitations. You’ll have to think of
# someone else to invite.
# • Start with your program from Exercise 3-4. Add a print() call at the end
# of your program stating the name of the guest who... |
d4919c9f15307d8a929e5ce787bf202aec064feb | Hellofafar/Leetcode | /Medium/139.py | 1,878 | 3.796875 | 4 | # ------------------------------
# 139. Word Break
#
# Description:
# Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
# Note:
# The same word in the dictionary may be reused multi... |
c452c55d5e8309fc7c7deada38812899f97bbbfb | KroegerP/cs3003 | /scope_lifetime/static_scope.py | 623 | 3.90625 | 4 | import inspect
def function_outer():
outer_variable = "outer variable"
def function_very_inner():
value_of_outer_variable = outer_variable
print(f"outer_variable: {value_of_outer_variable}")
def function_inner_first():
function_very_inner()
def function_inner_second():
out... |
f7794f1f307287cfc574faf05d613d1fc572cbed | thejefftrent/ProjectEuler.py | /2.py | 352 | 3.59375 | 4 | def sumEvenFib(x):
a = 1
b = 1
s = 0
while a < x and b < x:
#print(str(a))
#print(str(b))
a = a + b
b = a + b
if a % 2 == 0:
print(str(a))
s += a
if b % 2 == 0:
print(str(b))
s += b
return s
print("the s... |
5de5eaa8eb9339430c5f5b75de0f859666781667 | pamdesilva/module2 | /ch01 - Introduction to Python/ch1_pam.py | 452 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 28 15:44:52 2018
@author: pamde
"""
###################################
#CHAPTER 01 - INTRODUCTION TO PYTHON
###################################
#---------------------------------------
#Simple calculation operation in Python
#---------------------------------------
p... |
f9c1398fb50ce6705f639044a9d2432861211546 | Chainyinghao/tingyunxuan | /20.py | 1,078 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# date:2018/9/28
# comment:递归二分法查找
#模块bisect提供标准的二分法查找,只是想写写,为啥没有每天写呢,感觉到这后面,需要多思考很多东西
def search(sequance, number, lower = 0, upper = None):
if upper is None:
upper = len(sequance) - 1
if lower == upper:
assert number == sequance[upper]
return upper
... |
55ed8d0b8999e772ccc2a9527d90e6965e5266b7 | nkrot/adventofcode-2015 | /day_14/solution.py | 2,952 | 3.75 | 4 | #!/usr/bin/env python
# # #
#
#
import re
import os
import sys
from typing import List, Dict, Tuple
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from aoc import utils
DEBUG = False
def parse_lines(lines: List[str]) -> Dict[str, Tuple[int, int, int]]:
cars = {}
for line in lines:
... |
4246c916cc6103c476721e374e7e33a384bb5f59 | charishma-kota/Iot | /p16.py | 353 | 3.6875 | 4 | students={'1': {'name': 'Bob', 'grade': 2.5},
'2': {'name': 'Bob', 'grade': 3.5},
'3': {'name': 'Bob', 'grade': 4.8},
'4': {'name': 'Bob', 'grade': 2.2},
'5': {'name': 'Bob', 'grade': 3.5}}
def avgGrade(students):
sum=0.0
for key in students:
sum=sum+students[key]['grade']
a... |
10269ebd72ea6b3b9028c0b86d90ff28105acd2e | haophan1507/phanvanhao_fundamental_c4e30 | /Season3/Vd4.py | 476 | 3.75 | 4 | z = [1,2,3,4,5]
for a in z:
for b in z:
for c in z:
for d in z:
for e in z:
if a in (b,c,d,e):
continue
elif b in (a,c,d,e):
continue
elif c in (a,b,d,e):
... |
d40f7b56bd1e419501dc2ce4b18ffa5728bb7afb | kayyali18/Python | /Python 31 Programs/Ch 1 - 4/Losing Battle.py | 721 | 4.34375 | 4 | ##Losing battle
## This program is intended to demonstrate the infinite loop
## I intend to write this program without an infinite loop
print("Your lone hero is surrounded by a massive army of trolls!")
print("Their decaying green bodies stretch out, melting into the horizon")
print("Your hero unsheathes his swo... |
dc2d95474aad9ba63de12c08c80dcd45f1d094ae | wylaron/hello_python | /pickle.py | 504 | 3.6875 | 4 | #!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
my_file = 'class.data'
# the name of the file where we will store the object
class MyClass(object):
def hello(self):
print 'Hello'
my_class = MyClass()
my_class.hello()
# Write to the file
f = file(my_file, 'w')
p.dump(my_... |
0404e82c8d160eafe603dff5f715daec898280c8 | 17f23206/split-my-bill | /main.py | 564 | 4.25 | 4 | print("---Welcome to Split My Bill---")
print("What is the total bill?")
print("Enter a number")
bill_total = float(input())
print("Enter a number")
print("How many people are sharing?")
people = int(input())
print("What percentage tip would you like to leave?")
tip_percentage = int(input())
percentage_decimal = tip_p... |
8fcb28a8f885b0f3209eb77d70aba8affd9780fb | zerghua/leetcode-python | /sort/N2161_PartitionArrayAccordingtoGivenPivot.py | 2,389 | 3.8125 | 4 | #
# Create by Hua on 7/25/22
#
"""
You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:
Every element less than pivot appears before every element greater than pivot.
Every element equal to pivot appears in between the elements less than a... |
7fe479dbdd4f8d2f5c8f34ebd012444c1783942f | Shadowmistlee/python | /homework/20210523/topic/topic/hw3_database.py | 389 | 3.796875 | 4 | '''
你正在編寫一個Python程式記錄客戶資料並將其儲存在資料庫中。
這個程式處理各種各樣的資料。
以下的變數宣告後他們的資料類別是?請將嘗試碼進行正確的分類。
int:apple、
bool:
str:
float:
example
apple = 1000
'''
age = 12
minor = False
name = "David"
weight = 64.5
zip = "545"
'''
int:age
float:weight
str:name,zip
bool:minor |
7d9642bcc80e207ce57aa9d44dfe6aa2f4c6b5d8 | Candy0701/python | /hw/20210613/topic/hw13.py | 538 | 3.984375 | 4 | '''
你設計了一個Python程式顯示 2到 100中的所有質數,
請將程式碼片段排列到回答區的正確位置。
程式碼片段
(A).
n = 2
is_prime = True
while n <= 100:
(B).
n = 2
while n <= 100:
is_prime = True
(C).
break
(D).
continue
print(name, "是大小寫混合.")
(E).
n += 1
(F).
for i in range(2, n):
if n / i == 0:
is_prime = False
(G).
for i in range(2, n):
... |
872d2d082fe3efdedcb666dde8a457993b0e5d54 | maloneya/osgp | /social_graph.py | 1,173 | 3.78125 | 4 | import networkx as nx
from person import Person
class socialGraph:
def __init__(self,name,age,location):
self.graph = nx.Graph()
self.owner = Person(name,age,location)
self.graph.add_node(self.owner)
def add_friend(self,friend_graph):
self.graph.add_node(friend_graph.owner)
self.graph.add_edge(self.owner,... |
8937f888a9840014a28d6a559bc639eae54f2a64 | wesshih/astr427 | /hw1/interpolate.py | 6,390 | 4.3125 | 4 | import numpy as np
# import matplotlib.pyplot as plt
'''
Wesley Shih
1237017
Astr 427 Homework 1
4/11/17
Problem 3: Interpolation
This problem asks us to implement a program that can read in a data file and interpolate
between the given values. We begin by implementing a linear interpolator, and then move
on to usi... |
93f205d725f9190edc9eee6a279f06d8576f84e6 | SyamsulAlterra/Alta | /Algoritma/linearSearch.py | 113 | 3.578125 | 4 | def linSearch(num,arr):
for number in arr:
if num==number:
return number
return None
|
4c563c0eadda8b1602d244c27f4cf011afb800bf | kongyiji/python-examples-and-exercises | /CorePythonProgramming_Exercises/6/6-2.py | 883 | 4 | 4 | #!/bin/env python
# -*- coding: utf-8 -*-
# platform: python3
import string
import keyword
alphas = string.ascii_letters + '_'
nums = string.digits
print('Welcome to the Identifier Checker v1.0')
# print('Testees must be at least 2 chars long.')
print('Testees must be at least 1 chars long.')
# myInput = raw_input('... |
f88e568ac0c4df9aec10da380f095fd5c9007907 | fffk3045167/ananconda_spyder | /gen_try.py | 685 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 12 19:41:36 2019
@author: Administrator
"""
"""
避免一次性生成整个结果列表的本质是在需要的时候才逐次产生结果,而不是立即产生全部的结果
"""
"""
def gen_squares(num):
for x in range(num):
yield x ** 2
gen1 = gen_squares(4)
print(gen1)
"""
"""
生成器函数
"""
def gen_squares(num):
for x in range(num):
... |
8901dfa5faffa9fb4d40bc63f93e268f49823751 | shouliang/Development | /Python/LeetCode/703_kth_largest_element_in_a_stream.py | 1,114 | 3.859375 | 4 | '''
返回数据流中第K大元素
703. Kth Largest Element in a Stream: https://leetcode.com/problems/kth-largest-element-in-a-stream/
'''
import heapq
class KthLargest:
def __init__(self, k, nums):
self.k = k
self.nums = nums
self.topNums = []
for num in nums:
self.add(num)
def ... |
234776b1697058d87813b34db0690cbdc2588e18 | tanmay-kapoor/Algorithmic-Toolbox-Coursera | /week3_greedy_algorithms/solved codes/different_summands.py | 562 | 3.6875 | 4 | # Uses python3
def optimal_summands(n):
summands = []
sum = 0
#write your code here
i = 1
while sum<n:
if (sum+i) <=n:
sum += i
summands.append(i)
i += 1
else :
i -= 1
last_value = n-sum+i
sum += last_value
... |
ea4572d22c342a0a5700d126f4bf9a9dea7e6b2e | zengm71/Dojo | /Python/Assignments/FunctionsIntermediateI/script.py | 461 | 3.984375 | 4 | import random
def randInt(min = 0, max = 100):
if (min > max or max < 0):
print('Error: min > max or max < 0')
else:
num = round(random.random() * (max - min) + min)
return num
print(randInt())
print(randInt(max=50)) # should print a random integer between 0 to 50
print(randInt(min=5... |
8e1655c260e75fa02307a7d79092e9d1aeed3e60 | greyinghair/kpmg_answers | /lesson_4/questions_b.py | 5,079 | 4.34375 | 4 | # 1 .Loop through the list you created in section A and print each item out
fruit = ["Apples", "Cherries", "Pears", "Pineapple", "Peaches", "Mango"]
for loop_fruit in fruit:
print(loop_fruit)
# 2. Print the numbers 1 to 100 (including the number 100)
print("\n\n## Question 2 ##\n\n")
for one_to_one_hundred in range... |
f1c34c5f5e33f889dc74c663d3b43d76082ce59d | kenzzuli/hm_15 | /05_python高级/19_闭包、装饰器/06_对有参数无返回值的函数进行装饰.py | 464 | 3.796875 | 4 | # 对有参数无返回值的函数进行装饰
def set_func(func):
def call_func(num): # 这里也要加上对应数量的参数
print("权限验证1")
print("权限验证2")
func(num) # 调用原来函数时,也要加上对应数量的参数
return call_func
@set_func
def test(num): # 原来函数有参数
print("在原来函数中 num =", num)
test(3)
# 权限验证1
# 权限验证2
# 在原来函数中 num = 3
|
2ddf423997f9db2da04ef6adb504a48f0cbc48bb | Rajavel485/python | /caculator.py | 923 | 4.03125 | 4 | def add(num1, num2):
return(num1 + num2)
def sub(num1, num2):
return(num1 - num2)
def mul(num1, num2):
return(num1 * num2)
def div(num1, num2):
return(num1 / num2)
print("please select operations -\n"\
"1. add \n" \
"2. sub \n" \
"3. mul \n" \
"4. div \n")
select=i... |
e314423437d2ad66e6cfa5596bf6c23375e5c9f3 | agendaxd276/HackerRank-Solutions | /pairs.py | 190 | 3.578125 | 4 | def pairs(k, arr):
arr = set(arr)
return sum(1 for i in arr if i+k in arr)
n,k = map(int,input().split())
arr = list(map(int,input().split()))
print()
print("Pairs: ",pairs(k, arr))
|
76d513cc555ea6dcd5ce9d20bfe93f4e7e7e23dc | chenbiningbo/programming_learning | /python_learn/small_calculate_v1.0/cube_calculate.py | 572 | 4.09375 | 4 | """
作者:陈思诺
版本:1.0
日期:12/08/2019
功能:计算正方体的各种数值
"""
length = int(input('请输入你要计算的正方体棱长(整数):'))
# 计算油漆面的数量
one_side_num = 6 * (length - 2) ** 2
two_side_num = (length - 2) * 12
three_side_num = 8
none_num = (length - 2) ** 3
print('这个正方体分割后\n一面油漆的数量是:{}\n两面油漆的数量是:{}\n'
'三面油漆的数量是:{}\n没有油漆的数量是:{}\n'... |
8435970e0680d15cfc8944ca83212777b58b866a | nashfleet/codefights | /arcade/intro/level9/longestDigitsPrefix.py | 166 | 3.9375 | 4 | """
Given a string, output its longest prefix which contains
only digits.
"""
def longestDigitsPrefix(inputString):
return re.findall('^\d*', inputString)[0]
|
f9c0897496e3a044d4dd1d8f0222fee262d08502 | eclipse-ib/Software-University-Professional-Advanced-Module | /September 2020/03-Multidimensional-Lists/Exercises/08-Miner.py | 1,654 | 3.65625 | 4 | def s_pos(square):
for row_i, i in enumerate(square):
for col_j, j in enumerate(i):
if j == "s":
return row_i, col_j
size = int(input())
commands = input().split()
square = [
[_ for _ in input().split()]
for i in range(size)
]
start_pos_row, start_pos_col = s_pos(squar... |
0b869f13a115bd3b098ed57f448c8e317bf599d5 | gmotasilva/python_study | /tic_tac_toe.py | 3,517 | 3.875 | 4 |
#Cria um novo jogo
def create_new_game():
print('Um novo jogo se inicia!')
board = [['1a','2a','3a'], ['1b','2b','3b'] , ['1c','2c','3c']]
return board
# atualiza o movimento do brother
def update_board(board, movement, move_count):
for i in board:
for y in range(0, 3):
if i[y] ==... |
fcbf4677829b8c0b151dc88a726fd2fe03aa7d82 | GSantos23/Crash_Course | /Chapter3/Exercises/ex3_7.py | 2,076 | 4.375 | 4 | # Exercise 3.7
# Shrinking Guest List: You just found out that your new dinner table won’t
# arrive in time for the dinner, and you have space for only two guests.
# • Start with your program from Exercise 3-6. Add a new line that prints a
# message saying that you can invite only two people for dinner.
# • Use pop(... |
6fce139fcdc98541358636b4aa801c74ab008457 | lenaireland/Coding-challenges | /linked_list_remove_n_from_end.py | 968 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode':
"""Given a linked list, remove the n-th node from the end of list and
return i... |
d90cdb4d69faf7e54d0b2a8b813cb2ae515d6bb0 | ErenBtrk/PythonOsModuleExercises | /Exercise6.py | 418 | 3.828125 | 4 | '''
6. Write a Python program to create a symbolic link and read it
to decide the original file pointed by the link.
'''
import os
path = '/tmp/' + os.path.basename(__file__)
print('Creating link {} -> {}'.format(path, __file__))
os.symlink(__file__,path)
stat_info = os.lstat(path)
print('\nFile Permissions:', oct(s... |
6a4899eb499c6e1ad1489e02f3421a1f53a6c707 | rhzx3519/leetcode | /python/605. Can Place Flowers.py | 483 | 3.578125 | 4 | class Solution(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
cnt = 0
m = len(flowerbed)
for i in range(m):
if flowerbed[i]==1: continue
l = (i==0) or (flowerbed[i-... |
8fc8a50769c900a8a05212e5f13f486ff7073804 | citizenkey/Tests_py | /guess number.py | 4,647 | 3.90625 | 4 | # Компьютер загадывает случайное число от 1 до 100. Человек угадывает.
# 4 вариант, как только пользователь угадал, объявляем победителя
import random
number = random.randint(1, 100)
print(number)
user_number = None
count = 0 # вводим кол-во попыток
levels = {1: 10, 2: 5, 3: 3} # объявляем уровни сложности на 1 уро... |
82057db1f42321d152502dfdced0ccb422fde218 | mariasilviamorlino/python_practice | /coordinates_handling.py | 10,641 | 3.53125 | 4 | """A set of function definitions that can turn useful when dealing with biological data expressed with
genomic coordinates, such as bed/bedgraph formats"""
import pandas as pd
chromosome_lengths = pd.read_table('/home/mary/internship/hg19.chrom.sizes.txt', header=None)
chr_lengths_dict = dict()
for i in range(len(chro... |
1c3b28018a71021bd51354f5701328b2d433b646 | AhmedAbdelkhalek/HackerRank-Problems | /Algorithms/Implementation/Cats and a Mouse.py | 324 | 3.625 | 4 | #!/bin/python3
# Easy
# https://www.hackerrank.com/challenges/cats-and-a-mouse/problem
for _ in range(int(input())):
d = list(map(int, input().strip().split(' ')))
AtoC = abs(d[0] - d[2])
BtoC = abs(d[1] - d[2])
if AtoC < BtoC: print("Cat A")
elif AtoC > BtoC: print("Cat B")
else: print("Mouse ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.