blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
dbebf120192e1389d8f9abb7a925d7825a0bc255 | hn0872887/608-mod3 | /custom-object.py | 1,415 | 3.890625 | 4 | import math
class Purchase(object):
def __init__(self, amount):
self.amount = amount
def calculateTax(self, taxPercent):
return self.amount * taxPercent/100.0
def calculateTip(self, tipPercent):
return self.amount * tipPercent/100.0
def calculateTipInWholeDollarsOver20Percent... |
1eba40c0caa67608204068f0158d46d964e3a0f1 | ThallesTorres/Curso_Em_Video_Python | /Curso_Em_Video_Python/Como_Usar_For.py | 884 | 3.96875 | 4 | # Aula 13
# Exemplo 01
for c in range(0, 6):
print('Oi')
print('Fim!!')
# Exemplo 02
for c in range(0, 6):
print(c)
print('Fim!!')
# Exemplo 03
for c in range(1, 7):
print(c)
print('Fim!!')
# Exemplo 04
for c in range(6, 0, -1):
print(c)
print('Fim!!')
# Exemplo 05
for c in ran... |
3fcd154336f6be3d3a7e4f9bd25d24b19cb1e85c | dabaicai233/Base-Prooject | /生成数与输入数比误差.py | 1,103 | 3.9375 | 4 | # 需求:随机生成一个1到100之间的数,从控制台输入一个数与之比较误差:
"""
import random
while True:
m = random.randint(1,100)#randint的使用,randint的后面必须跟范围(包头包尾 )
print(m)
n = int(input("请输入一个数:"))
if m >= n :
if m-n <10:
print("aaaa")
elif m-n < 30:
print("bbbb")
elif m-n <50:
... |
6cb4ae0f4eb5a3fe723a8790ef347fb36c7fefed | TimiLikesJava/Cousera-AlgorthmicToolBox | /fibonacci_huge.py | 456 | 3.515625 | 4 | def pisano(m):
prev , curr = 0 , 1
for i in range(0 , m*m):
prev , curr = curr , (prev+curr) % m
if(prev == 0 and curr == 1):
return i + 1
def fib(n, m):
array = [0,1]
n = n % pisano(m)
for i in range(2 , n+1):
array.append(array[i-1] + array[i-2])
... |
2c286ae6ad3f07d0ea17ad3773fa94485c592386 | JorenW/UltimateAdventSolver2020 | /Day2/main.py | 791 | 3.5625 | 4 | class PolicyPass:
password = None
policy_max = None
policy_min = None
policy_letter = None
def __init__(self, line):
parts = line.split(":")
self.password = parts[1]
self.policy_min = int(parts[0].split("-")[0])
self.policy_max = int(parts[0].split("-")[1].split(" ")... |
8181d1fede42e40baa812a826ada84e1ec4a09c3 | TaoCurry/Basic_Python3 | /递归例子/迭代求Fibo.py | 567 | 3.8125 | 4 | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
def fibo(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a+b
n += 1
return 'done'
for n in fibo(10):
print(n)
# Update 更简单的方法计算斐波拉契数列:
>>> fibs = [0, 1]
>>> for i in range(8): #
fibs.append(fibs[-2] + fibs[-1])
>>> fibs
[0, 1, 1, 2, 3, 5, 8, 13,... |
1e1d6c3741a392dcfcfce83c1770eeabcea697a5 | rohaan311299/ML | /a_z/26.artificial_neural_networks/ann.py | 1,965 | 3.609375 | 4 | # Importing the libraries
import numpy as np
import pandas as pd
import tensorflow as tf
# Importing the dataset
dataset=pd.read_csv("./Churn_Modelling.csv")
X=dataset.iloc[:,3:-1].values
y=dataset.iloc[:,-1].values
# Encoding categorical Data
# lable encoding the "Gender" Column
from sklearn.preprocessing import... |
933286a486e6e386fac2064ae8616225f6bf4817 | Tarun-coder/Data-science- | /function9.py | 237 | 4.1875 | 4 | # Print multiplication table of 12 using recursion.
num=int(input("Enter the Number:"))
def mult12(num,i=1):
if i<11:
mul=num*i
print(num,"x",i,"=",mul)
i+=1
mult12(num,i)
mult12(num) |
afc50b848db97e86e4f11f793e08d697c539dea7 | EricLin24/SSW567 | /HW01/test_triangle.py | 1,562 | 4 | 4 | import unittest
from math import sqrt
from HW01 import classify_triangle
class HW01Test(unittest.TestCase):
"""test HW01 functions"""
def test_classify_triangle(self):
"""test if it's a triangle"""
self.assertEqual(classify_triangle(1, 2, 3), "It's not a triangle.")
self.assertEqual(cla... |
153180dd03cae378e097ccf25bf401a5d00c85eb | EmolLi/AI | /src/Python/Optimization+DataVisualization/Optimization.py | 3,043 | 3.6875 | 4 | import math
import random
x_MAX = 10
x_MIN = 0
def simulate_annealing_test():
start_p = range(0, 11)
steps = [0.4, 0.1, 0.08, 0.05]
data = [['start point', 'step size', 'temperature', 'X', 'Y']]
temps = [1000, 1000000, 10000000000]
for start in start_p:
for step in steps:
for ... |
7bb877c6275f1233f7f831868169319eca155f51 | Iansdfg/9chap | /3Binary_Search/38. Search a 2D Matrix II.py | 776 | 3.796875 | 4 | class Solution:
"""
@param matrix: A list of lists of integers
@param target: An integer you want to search in matrix
@return: An integer indicate the total occurrence of target in the given matrix
"""
def searchMatrix(self, matrix, target):
# write your code here
rows, cols = le... |
a7682f7bf3d5b0286f5de7f59654342bf351090b | nikolakasev/aoc2020-python | /day22.py | 2,246 | 3.546875 | 4 | a = []
for line in open('day22.txt').read().split('\n'):
a.append(line)
player_one = a[1:a.index('')]
player_two = a[a.index('') + 2:]
while len(player_one) > 0 and len(player_two) > 0:
# take the left most card from both decks
c = int(player_one.pop(0))
d = int(player_two.pop(0))
# append to th... |
b196013acc2430d75e3dce56728f95846b0ac6c2 | jinliangXX/LeetCode | /98. Validate Binary Search Tree/solution.py | 1,432 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
if root is None:
return True
return self.pre_order(root, None, None)
def pre_order(se... |
24d6f74ac8239a11e856bf42deeb2bd77a27df6a | GeorgeJopson/OCR-A-Level-Coding-Challenges | /7-Credit Card Validator/Credit Card Validator.py | 580 | 3.9375 | 4 | #Credit Card Validator
cardNum=int(input("Input your 16 digit credit card:"))
cardList=[int(num) for num in str(cardNum)]
if(len(cardList)==16):
checkSum=cardList[0:15]
checkDigit=cardList[15]
for index in range(len(checkSum)):
if(index%2==0):
checkSum[index]*=2
if(checkSum[i... |
010a909b24e26893d1e386a43d36711c113aae09 | benjaminr/full_stack_web_development_udacity | /movie_trailers_website/media.py | 1,197 | 3.546875 | 4 | #!/usr/bin/env python
import webbrowser
class Video():
def __init__(self, title, description, length):
self.title = title
self.description = description
self.length = length
class Movie(Video):
"""
Attributes
title (str): The title of the movie
... |
016a2632e31ccbacd4ac4b0938b48d9a9d17a6c1 | heyu-rise/Python003-003 | /week08+09/my_map.py | 239 | 3.59375 | 4 | def my_map(func, *seqs):
for args in zip(*seqs):
yield func(*args)
def concat(x, y):
return x * y
if __name__ == "__main__":
a = [1, 2, 5]
b = [3, 4, 9]
result = my_map(concat, a, b)
print(list(result))
|
e60d5b8b554c77cfd06406a06f3455d43225053e | sun1024/py-test | /Bubble-sort.py | 414 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright (c) 2017. All rights reserved by adminsun.
def bubbleSort(alist):
for i in xrange(len(alist)):
print(alist)
for j in xrange(1,len(alist) - i):
if alist[j-1] > alist[j]:
alist[j - 1],alist[j] = alist[j], alist[j - 1... |
5b97ef3bde3589bd8db04d25fd77f942fc5808c0 | tsefcik/Assignment1 | /project/HouseVotes.py | 3,817 | 3.859375 | 4 | import pandas as pd
from sklearn import preprocessing
class HouseVotes:
pd.set_option('display.max_columns', 40)
pd.set_option('display.width', 3000)
votes_names = ["class", "handicapped", "water", "adoption", "physician", "el-salvador", "religious",
"anti", "aid", "mx", "immigration",... |
696d091909c89721a706945b5d7f387daf46307a | Microstrong0305/coding_interviews | /32.把二叉树打印成多行/32.把二叉树打印成多行.py | 874 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if pRoot is None:
return []
self.q = [pRoot]
... |
1a3d4b77bec14cb051ba40a2d567a848acbc85c9 | LesterYHZ/Python-100-Day-Practice | /10_GUI-and-Games/tkinter-GUI.py | 1,601 | 4.15625 | 4 | """
Tk is the default package used to build Python GUI apps. Yet for
better use, switch to PyQt5
Here are the steps of tkinter GUI building:
1. Import the tkinter package and modules
2. Create a top window object to hold all the GUI modules
3. Add GUI parts onto the window object
4. Connect th... |
ae294cd39dd436c46f2f798fabc0689b63e5c8ce | nikitha567nikki/Python-and-Deep-Learning | /ICP-1/calculate_string.py | 451 | 4 | 4 | string_input = input("Enter a sentence ")
letters = 0
words = 0
digits = 0
a = string_input.split()
words = len(a)
print("no of words :", words)
for i in string_input:
if i.isalpha():
letters = letters + 1
elif i.isdigit():
digits = digits + 1
else:
words = string_input.count(" ", 1,... |
20d6b7825a49defe6a813f640e8986db9697f024 | richard-shepherd/crossword-helper | /crossword_libs/cryptic_utils/clue.py | 752 | 3.609375 | 4 | from .bits_and_pieces import BitsAndPieces
class Clue(object):
"""
Parses cryptic clues and provides information on how to solve them.
"""
def __init__(self, clue):
"""
Constructor.
"""
# The original text of the clue...
self.clue = clue
@staticmethod
... |
26b000b76e7b120b0a29cb8e494726364499ddae | leprechaunne/RTS-Takehome-Interview | /prob_1.py | 1,213 | 4.3125 | 4 | #1 Print the number of integers in an array that are above the given input
# and the number that are below,
# e.g. for the array [1, 5, 2, 1, 10] with input 6, print “above: 1, below: 4”.
# I decided not to make this solution class oriented, but if this function became
# more used or complicated, it could be ab... |
9f22bfb7af3a7ed7f8f7f20dcbb7448f74ae3f08 | Mrs-Cui/clean | /thread_lock.py | 4,786 | 3.6875 | 4 | import time
import threading
# 生成一个递归对象
Rlock = threading.RLock()
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self) -> None:
print('thread ident', threading.current_thread().ident)
self.fun_A()
self.fun_B()
def fun_A(self... |
41ba121413daf8409f04c172baa39fff787bfcbb | JuliaGofman/json_graphs | /json_graphs.py | 3,472 | 3.578125 | 4 | # входные данные в формате json. Вывести для каждого предка количество потомков
# import json
# data = json.loads(input())
# data = [{"name": "G", "parents": ["F"]}, {"name": "A", "parents": []},
# {"name": "B", "parents": ["A"]}, {"name": "C", "parents": ["A"]},
# {"name": "D", "parents": ["B", "C... |
1b70fcd857194b20304ae0e62f7c248ec172c91e | wesenu/Leetcode_419_Battleships_in_a_Board | /Battleships_in_a_Board.py | 668 | 3.734375 | 4 | import unittest
class unitest(unittest.TestCase):
def testRow(self):
board = ["XXX"]
self.assertEqual(Solution.countBattleships(self,board),1);
def testColumu(self):
board = ["X","X","X"]
self.assertEqual(Solution.countBattleships(self,board),1);
class Solution():
def count... |
ff36cb193833d9a6af34a3391fbac741a44f6b4c | abdulaziz661/Python-Learning | /variables8.py | 335 | 3.6875 | 4 | a=1
print(a)
b=2
print(b)
print(a)
print(b)
c='hello there'
print(c)
a=2
b=1
print(a,b)
print(a)
a=1
b=a
print(b)
a=10
b=5
print(a)
print(b)
c="hello world"
print(c)
d="hey abdul!"
print(d)
e = a
print(e)
v1 = "first name"
v2 = "second name"
print(v1)
print(v2)
temp = "v1"
v2 = "v1"
str = 'abdul'
str = str + 'goodb... |
ad1e0ee4a96f3e6013baaf5fd1cf44668ac9608d | JamesJ7lx/COMP1531 | /Lectures/Lecture Code/week8/decor4.py | 241 | 3.828125 | 4 | def make_uppercase(input):
return input.upper()
def get_first_name():
return "Hayden"
def get_last_name():
return "Smith"
if __name__ == '__main__':
print(make_uppercase(get_first_name()))
print(make_uppercase(get_last_name())) |
fa2856baf58fe22a47c900bba3bd85b5867d0deb | polku/python_stuff | /timeout.py | 935 | 3.625 | 4 | #!/usr/bin/python3
"""
Mechanism to timeout if a function takes too much time
"""
import random
import signal
import time
from functools import wraps
class TimeoutException(Exception):
pass
def sig_handler(signum, frame):
raise TimeoutException()
def timeout(delay):
def timeout_sec(func):
@w... |
4ed8cd2f46cd3c231f65581ced5b58bc27d54a39 | LourdesOshiroIgarashi/algorithms-and-programming-1-ufms | /Module/Exercícios Adicionais/Thiago/04Linear.py | 381 | 3.890625 | 4 | # Leia um número inteiro de três dígitos e o decomponha. Exemplo:
# Entrada: 342
# Saída: 3 4 2
n = int(input())
# Seleciona o último digito do número dado.
num2 = n % 10
n2 = n // 10
# Seleciona o penúltimo número do número dado.
num1 = n2 % 10
n1 = n2 // 10
# Seleciona o primeiro número do número da... |
1b97a38ad528536308b6f7d78f2e64176aff9bfe | adnanaziz/publicadnan | /python/examples/args.py | 1,302 | 4.0625 | 4 | def printInfo(name, age, gender):
print 'Name: ', name, 'Age: ', age, 'Gender: ', gender
printInfo('Sam Sheperd', 36, 'Male')
# named arguments
printInfo(name='Sherlock Holmes', age=46, gender='Male')
printInfo(age=66, gender='Female', name='Jane Marple')
# mix positional and named args, positionals come first:
pr... |
a586e6ba6108937d1a1e1649512df3a7423d41b0 | Bsnawder85/PythonFundamentals | /Exercises/emoji_art_loops.py | 295 | 4.15625 | 4 | print('with a for-loop')
for i in range(1, 11):
print('🧇' * i)
print('with a while-loop')
n = 1
while n < 11:
print('🌯' * n)
n += 1
print('with nested for- and while-loops')
x = 1
z = ''
for y in range(1, 11):
while x <= y:
z += '🥑'
x += 1
print(z) |
8db012918ac7a17c7e8ac670612943c7ef4754b6 | kbcao/leetcode | /124/124_ckb.py | 931 | 3.640625 | 4 | # 想到的是建立图,变成邻接表,然后做,肯定很烦
# 没想到用递归做,因为是任意一个结点到任意一个结点,所以递归的时候,同步更新一个 最大值 为 当前值+左(若>0)+右(若>0)
# 但递归返回的时候返回的是 当前值+左 or 当前值+右 的较大者,因为路径不能出现分叉
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
... |
cbc658e9a7ca8200e119f50c5b709900df16e8ef | ctnkaan/100DaysOfCode | /10. better calculator/main.py | 555 | 3.96875 | 4 | from art import logo
def addition(fnum,snum):
return fnum + snum
def sub(fnum,snum):
return fnum - snum
def divide(fnum,snum):
return fnum / snum
def multiply(fnum, snum):
return fnum * snum
print(logo)
fnum = int(input("Enter the first number: "))
op = input("+ - / * pick an operation: ")
snum = int(inp... |
094278e50ea67b912e74907e9c125a2a684ad7d0 | AlexanderJDupree/CS160 | /codefights/lotto.py | 1,386 | 3.703125 | 4 | from random import randint
lottoMatrix = []
# Asks for numbers to be scrambled, converts it to a list
series = int(input("How many series of numbers to be inputed? "))
for n in range(series):
lottoNumbers = input('Enter your lottery numbers for row %r: ' % n)
lotto_numbers = list(map(int, lottoNumbers.split())... |
7c24c682881070159b56fa0ae5bf367396004aa6 | 851984709/Junjie-Hu | /code/python/study/Python/23.集合.py | 773 | 4 | 4 | num = {}
type(num)
# 此时num的种类为dict字典
num = {1, 2, 3, 4, 5}
type(num)
# 此时num的种类为set集合
# 集合没有顺序
num = {1, 2, 3, 4, 5, 3, 4, 5, 6}
# 集合具有唯一性,每个元素只会出现一次
num = set((123, 234, 345))
num = set(['哈哈', '妖精', '初音ミク'])
# set工厂函数,建立集合
string = [1, 2, 3, 4, 2, 3, 4, 8, 9, ]
string = list(set(string))
# 删除列表中的重复... |
96de137b14aaebcf3729aa44ffa67afc8ec67f39 | andylws/SNU_Lecture_Computing-for-Data-Science | /HW4/P10.py | 1,232 | 4.03125 | 4 | """
There is a set of words and a query word.
You must change exactly one character of the query word.
Implement a function that determins whether the changed word can be the element of the set.
* Condition: Words consist of only lower-case alphabet(s) and no space.
>>> P10({"data", "science"}, "data")
False
Explana... |
c14bfb5da8bd5c70c7a52ab4cb4138438e795a63 | ArataKagan/external-sorting-python | /external-sorting-main.py | 5,915 | 3.515625 | 4 | import os
import tempfile
import sys
import collections
class headNode:
def __init__(self, letter, fileHandler):
# letter to be stored in heap
self.letter = letter
# file handler for each letter
self.fileHandler = fileHandler
class externalSort:
def __init__(self):
... |
27808456514fe17079cd8e3071612541109616aa | NikhilManu/Algoexpert | /Binary Search Tree/Binary Tree Level Order Traversal.py | 893 | 3.734375 | 4 | """
Same Name in LeetCode
"""
"""
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
3
/ \
9 20
/ \
15 7
Output:
[
[3],
[9,20],
[15,7]
]
"""
# Solution 1 --- Iterative , I think this is more Easier than recursive
# Time ... |
9a386ead0f62f7e0b5963ebefe1f9cb21aae29be | candyer/leetcode | /numJewelsInStones.py | 953 | 4.03125 | 4 | # https://leetcode.com/problems/jewels-and-stones/description/
# 771. Jewels and Stones
# You're given strings J representing the types of stones that are jewels,
# and S representing the stones you have. Each character in S is a type of stone
# you have. You want to know how many of the stones you have are also ... |
0e6e54f7fa1237d012cf7490fd2141eee902fa10 | adarrah/CS-101 | /program 8/wumpusworld.py | 5,971 | 3.6875 | 4 | import map
## creates wumpusworld object for program 8.py to call to run the game
class WumpusWorld(object):
## initializes the map and variables
def __init__(self):
self.worldmap = map.Map()
self.wumpusAlive = True
self.playerAlive = True
self.playerHasGold = False
... |
147341c7bb0cdabccb3e4f50a8f415ebd6a6c730 | lizyang95/leetcode | /leetcode3/triangleNumber.py | 703 | 3.515625 | 4 | class Solution(object):
def twoSum(self, A, n):
i = 0
j = len(A) -1
count =0
while i< j:
if A[i] + A[j] > n:
count += j-i
j-=1
else:
i+=1
return count
def triangleNumber(self, nums):
"""
... |
44d782807db440381ded1dc755b9b3c0f3b8c387 | aurel1212/Sp2018-Online | /students/ChrisH/lesson04/exercises/mangler_mod.py | 1,317 | 3.609375 | 4 | #!/usr/bin/env python3
"""
Simple metaclass example that creates name doubled versions of
all non-dunder class attributes
"""
class NameMangler(type): # deriving from type makes it a metaclass.
def __new__(cls, clsname, bases, _dict):
new_class_attr = {}
for name, val in _dict.items():
... |
da8256f741776e437934a08c6745000a95f5ea9f | lee-saint/lab-python | /lec03_function/function03.py | 1,167 | 4.125 | 4 | """
함수 정의:
def 함수이름(파라미터: 타입, 파라미터2: 타입, ...) -> 리턴타입:
함수 기능(body)
"""
def subtract(x: int, y:int) -> int:
return x - y
result = subtract(1, 2)
print(result)
# 파이썬은 함수를 호출할 때 함수 파라미터 타입과 리턴 타입을 검사하지 않음
result = subtract(1.1, 0.9)
print(result)
def my_sum(numbers: list) -> float:
"""
숫자(int, float... |
2b9f42f0b3166ef8ef6772b841c406d4457987b6 | cloi1994/session2 | /Amazon/742.py | 1,453 | 3.78125 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: the root
@param k: an integer
@return: the value of the nearest leaf node to target k in the tree
"""
def findClosestLe... |
100582eccb549a5e5855d10eb72b5e42bdc573b8 | workready/pythonbasic | /ejercicios_resueltos/t06/t06ejer01.py | 1,253 | 3.890625 | 4 |
class Rectangle:
def __init__(self, l, w):
# Aqui estamos llamando a los setters (ver abajo)
self.length = l
self.width = w
@property
def area(self):
return self._length*self._width
@property
def perimeter(self):
return self._length * 2 + se... |
6821d376bbc5722a54d7b5fd431b889221f132e8 | freddyfok/cs_with_python | /problems/leetcode/9_palindrome_number.py | 276 | 3.515625 | 4 | def isPalindrome(x) -> bool:
if x < 0:
return False
old_number = x
tmp = 0
while x != 0:
x, remainder = divmod(x, 10)
tmp = tmp*10 + remainder
if tmp == old_number:
return True
else:
return False
|
7956f2b9b18474e90288a94891ffb691d4b4344d | AngelAmadi/StudentRegistrater | /Database.py | 8,111 | 3.953125 | 4 | import pickle # pickle is a storing agent storing agent
from tkinter import *
# for my graphical user interface
# gui create a GUI window
receptionist= [
"Remi Floyd",
"Corrina Carroll",
"Franco Gillespie",
"Finbar Campos",
"Nadia Oconnell",
"Theia Mcbride",
"Anastazja Copeland",
"Nadia Oconnell",
"Orla ... |
72451406a9d0a10990cd92b14dc90e083eba991e | mi6eto/SoftUni | /Programming Fundamentals/data_types_and_ariables_exercise/triples_of_latin_letters.py | 408 | 4.15625 | 4 | number = int(input())
number_in_ascii = ord('a')
for first_number_in_ascii in range(number_in_ascii, number_in_ascii + number):
for second_number_in_ascii in range(number_in_ascii, number_in_ascii + number):
for third_number_in_ascii in range(number_in_ascii, number_in_ascii + number):
print(f"... |
d097b423d443f4628812655ecb214190dc7faeca | YoloSw4g/writeups | /2016/SharifCTF7/Pwn-Guess/guess.py | 342 | 3.5 | 4 | #!/usr/bin/python
s = ""
with open("output.txt","r") as f:
s = f.read()
s = s.strip()
s = s.split("-")
s_int = map(int, s)
s_hex = map(hex, s_int)
s_hex16 = map( lambda x : x[2:].zfill(16) if not 'L' in x else x[2:-1].zfill(16), s_hex)
s_string = map(lambda x : x.decode('hex')[::-1], s_hex16)
#print s_string
pr... |
6900356d1796eea659ed03e840d820bc1f447461 | ElleGis/csdc105-n1-Regaspi | /Prelim-exam/Regaspi_proba.py | 1,220 | 4.1875 | 4 | # Author : Ma. Giselle N. Regaspi
# Course and Year : BS IT-2
# Filename : Regaspi_proba.py
# Description : A program that prints a triangle shape composed of specific ASCII character.
# Honor Code : I have not given nor received any unathorized help in
# completing this exerc... |
e798410a575afc3c274b2c95eb26028e518866b7 | mvieiradev/CursoemVideoPython3 | /exe16.py | 174 | 3.828125 | 4 | #Quebrando im numero
from math import trunc
num = float(input('Digite um valor: '))
print('O valor digitado foi {} e a sua porçao interna e {}'.format(num, math.trunc(num))) |
1ee0c8d62be3ff11b7b286a8e22c3c1896c16e63 | Sabaoon96/University-of-Auckland | /COMPSCI 101/A2Files/skha787A2.py | 4,589 | 4.34375 | 4 | """
Sabaoon Raza Khan
skha787 - 983957824
This game of Dicey consists of 3 rounds, with two players getting a turn each at rolling the dice in every round. The player with the highest score at the end, wins.
"""
import random
def display_welcome():
print()
print("Welcome to DICEY, written by skha787")
p... |
024763d1460843269a9a78687fcd364b6ae6c51d | whztt07/tpclient-ogre | /sandbox/tp/client/strptime.py | 12,144 | 3.609375 | 4 | """Strptime-related classes and functions.
CLASSES:
TimeRE -- Creates regexes for pattern matching a string of text containing
time information
FUNCTIONS:
strptime -- Calculates the time struct represented by the passed-in string
"""
import time
import calendar
from re import compile as re_co... |
4db97444f06f8a25d3de5251283996faa6312e2d | AaronTho/Python_Notes | /lists_bottega_lessons.py | 235 | 3.953125 | 4 | # A list creates a true data structure.
users = ['Kristine', "Tiffany", 'Jordan']
users.insert(1, 'Anthony')
users.append('Ian')
# Adds the end of the list
print(users[2])
users[4] = 'Brayden'
# Reassigns index 4.
print(users)
|
8d029381b55623a8268042f5fb9376a4c563c76a | KokiIijima24/Python-Pazzle | /GoodTalent.py | 1,299 | 3.609375 | 4 | '''
2次元の表をリストで表す
'''
Talents = ['Sing', 'Dance', 'Magic', 'Act', 'Flex', 'Code']
Candidates = ['Aly', 'Bob', 'Cal', 'Don', 'Eve', 'Fay']
CandidateTalent = [['Flex', 'Code'], ['Dance', 'Magic'], ['Sing', 'Magic'], ['Sing', 'Dance'], ['Dance', 'Act', 'Code'], ['Act', 'Code']]
a = ['test']
def Hire4Show(Candidates, Tal... |
e90c83f3ce88c3f371ca0b4443cf076c810182be | JaeHeee/algorithm | /Kakao 코딩 테스트/2019 KAKAO BLIND RECRUITMENT/오픈채팅방.py | 534 | 3.5625 | 4 | def solution(record):
answer = []
records = dict()
result = []
for r in record:
temp = r.split(' ')
if temp[0] == 'Leave':
result.append([temp[1], "님이 나갔습니다."])
elif temp[0] == 'Enter':
records[temp[1]] = temp[2] # key=유저 아이디 value=이름
result.... |
6bca188e77648260089541e488cfa0437f83f184 | kim-byoungkwan/Coding_Test_1 | /알고리즘강의_1_prog.py | 1,119 | 3.5 | 4 | ###.1
import time
n = int(input("Number of elements: "))
haystack = [k for k in range(n)]
print("Searching for the maximum value...")
ts = time.time()
maximum = max(haystack)
elaspsed = time.time() - ts
print("Maximum element = %d, Elapsed time = %.2f" % (maximum, elaspsed))
# 리스트의 요소값의 최대값을 구하는 ... |
8f066dc5e9a23844e628f18c39d514411563832d | daniel-reich/ubiquitous-fiesta | /bYDPYX9ajWC6PNGCp_19.py | 243 | 3.578125 | 4 |
def track_robot(*steps):
lt = [0, 0]
for i in range(len(steps)):
if i%2:
lt[0] += steps[i]*((-1)**(len(steps[1:i+1:2])+1))
else:
lt[1] += steps[i]*((-1)**(len(steps[0:i+1:2])+1))
return lt
|
0a0d06a627c41ccc0b53ec8d5bc807ba66a36721 | chohan/Test | /P/test2.py | 6,714 | 3.5625 | 4 | import numpy as np
import time, datetime
import random
def my_numpy():
l = []
for i in range(100):
lsub=[]
for j in range(100):
lsub.append(0)
l.extend([lsub])
a=np.zeros((100, 100))
tl1 = time.time()
for i in range(100):
for j in range(10... |
3ddf738a764c93a61768386b17cda9de17931de4 | stevenhorsman/advent-of-code-2019 | /day-03/crossed_wires.py | 1,474 | 3.59375 | 4 | import sys
input_file = 'day-03/input.txt'
def produce_tick_map(path_string):
deltas = dict(zip('RLUD', [(1, 0), (-1, 0), (0, 1), (0, -1)]))
x = 0
y = 0
tick = 0
wire_path = {}
for path in path_string:
direction = path[:1]
length = int(path [1:])
for _ in range(length):
x += deltas[dir... |
f9b114b53352ee9bb7637783bee0271aca188509 | Jhonathanalvesbr/URI | /INICIANTE/1143 - Quadrado e ao Cubo.py | 606 | 3.609375 | 4 | # -*- coding: utf-8 -*-
'''
Escreva a sua soluo aqui
Code your solution here
Escriba su solucin aqu
'''
x = int(input())
contador = 0
sequencia = 0
y = 0
multiplicador = 0
resultado = 0
if (1 < x < 1000):
while y < x:
sequencia = sequencia +1
contador = contador +1
multiplicador = sequencia... |
636afcfde72a78d319ff78e74d495f91fbf86b45 | beeva-manueldepaz/ninja_taller_python_3 | /sample_003/propByName.py | 463 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
# Ejemplo de clase tradicional (POJO)
class Car:
def __init__(self):
self.peso = 1000
self.modelo = "GTR"
self.marca = "Nissan"
c = Car()
print(c.modelo)
# Alternativa, tuplas nombradas
CarDos =namedtuple(... |
46ef4fd9f4f541cdc8ce62f30fa8ad752184b304 | hotheat/LeetCode | /17. Letter Combinations of a Phone Number/dfs.py | 864 | 3.5625 | 4 | from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
numberdict = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',... |
aa02117cf05bd5e918dfdca4590d18726a5da268 | arpan-code/CSC-376-Distributed-Systems | /Homework/HW1/input_program.py | 2,758 | 4.5625 | 5 | #Arpan Patel#
#csc376#
#Programming Exercise 1 #
# this program that properly handles two types of input command line and standard input.
import sys ## module allow us to access the some varaibles used or maintained by the python interpreter.
# In this program I used sys.argv is the list of command line arugments pas... |
857ea5b899cc92b8853b0ca27acb442e30e9a634 | tarunluthra123/Competitive-Programming | /Leetcode/Set Matrix Zeroes.py | 512 | 3.515625 | 4 | class Solution:
def setZeroes(self, a: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
p,q = set(),set()
for i in range(len(a)):
for j in range(len(a[i])):
if a[i][j]==0:
p.add(i)
... |
6dd107faabcfc892944a20b5902f0a5e4c8f6cb7 | tumanjongbt/python_stack | /python_fundamentals/for_loop_basic1.py | 1,092 | 4.03125 | 4 | # Basic - Print all the numbers/integers from 0 to 150.
number = 151
for i in range(number):
print("number: ", i)
# Multiples of Five - Print all the multiples of 5 from 5 to 1,000,000.
for i in range(5, 1000000, 5):
print(i)
# Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Cod... |
0e6d66f8abc937e3f7ebbfa8844c74021811578d | RichardlauCx/Game_script_first | /ship.py | 1,589 | 3.578125 | 4 | # -*- coding: utf-8 -*-
# @ Date : 2019/5/20 13:14
# @ Author : RichardLau_Cx
# @ file : Richard.py
# @ IDE : Pycharm
import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self, first_settings, screen): # 初始化飞船并设置其初始化位置
super(Ship, self).__init__()
self.first... |
35d2a4e07859f43a1aba6e23b407e283cbabd92b | KinggCode/Python-Files | /code/Registrar/register.py | 2,272 | 3.71875 | 4 | import csv
class Registration:
def __init__(self,fname,lname,birthdate,phone,address,email,password,pin):
self.fname = fname
self.lname = lname
self.birthdate = birthdate
self.address = address
self.email = email
self.password = password
self.phone = phone
... |
c07603dfca71f702fe584b870a726c500ccdfdf7 | YOGESH-TECH/python-basic-problems | /sum.py | 142 | 3.671875 | 4 | num=int(input("enter the no. here: "))
sum=0
while num>0:
new=num%10
print(new,"+",end=" ")
sum=sum+new
num=num//10
print("=",sum) |
4fc5ce5b6cda2de74e91de56b65c8ec785c1ed5c | mbichoffe/coding_challenges | /longest_palindrome.py | 1,345 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example:
Input: "cbbd"
Output: "bb"
"""
"""
Approach = Expand aroun... |
274f1a1eb24f3bafc5a3ec49f219f27e0be77305 | JevonWei/scripts | /python-03.py | 534 | 3.875 | 4 | import random
secret = random.randint(1,10)
print ("---------danran----------")
temp = input("please input you choise chanse: ")
chanse = int(temp)
while chanse > 0 :
number = input("please input number: ")
guess = int(number)
if guess == secret:
print ("you are right")
break
elif guess ... |
aa4b2e7384950bcbbce34fe2d96862eb1699ca10 | ju-c-lopes/Univesp_Algoritmos_I | /Semana 2/exercicio2.1.py | 1,056 | 4 | 4 | """
Escreva expressões algébricas Python correspondentes aos seguintes comandos:
a) A soma dos 5 primeiros inteiros positivos.
b) A idade média de Sara (idade 23), Mark (idade 19) e Fátima (idade 31).
c) O número de vezes que 73 cabe em 403.
d) O resto de quando 403 é dividido por 73.
e) 2 à 10ª potência.
f) O va... |
9d890195441d7bc7f5e8fc6087b63faf4d0389c2 | Prawal-Sharma/Python-Projects | /99bottles.py | 680 | 4.09375 | 4 | question = raw_input("How many bottles of beer are on the wall? ")
numbers = range(int(question) + 1)
numbers = numbers[::-1]
for i in numbers:
if i > 2:
print str(i) + " bottles of beer on the wall " + str(i) + " bottles of beer",
print "take on down pass it around " + str(i-1) + " bottles of beer on the wall ... |
f4848b4e15dd217bfdfca6e310f2adbf112ed047 | kckotcherlakota/algoexpert-data-structures-algorithms | /Medium/valid-starting-city.py | 368 | 3.734375 | 4 |
# VALID STARTING CITY
# O(N) time and O(1) space
def validStartingCity(distances, fuel, mpg):
# Write your code here.
validCity = 0
milesLeft = 0
idx = 0
while idx < len(distances):
milesLeft += fuel[idx] * mpg
if milesLeft >= distances[idx]:
milesLeft -= distances[idx]
else:
validCity = idx + ... |
330894bbaad0945484f6d24b7b332b517df16ea0 | PythonDayMX/MLaaS | /full/sigmoid.py | 1,475 | 3.765625 | 4 | import numpy as np
class SigmoidNeuron():
def __init__(self, n):
np.random.seed(123)
self.synaptic_weights = 2 * np.random.random((n, 1)) - 1
def __sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def __sigmoid_derivative(self, x):
return x * (1 - x)
def train(self, tra... |
1a917910977bebcfc9abac63d0b6952a3a5d9bdf | zephyrfalcon/adventofcode-2016 | /day01a.py | 1,447 | 3.65625 | 4 | # day01a.py
# Code is kinda messy here with duplication and the exception to break out of
# things, but hey, what is a guy to do... :-)
# which direction are we facing if we turn left/right once?
TURN_RIGHT = {"N": "E", "E": "S", "S": "W", "W": "N"}
TURN_LEFT = {"N": "W", "W": "S", "S": "E", "E": "N"}
with open("inp... |
c217f8e968324903d65b0da411f9df9fcbef7cd8 | r4k0nb4k0n/Programming-Challenges | /Advent_of_Code/2017/Day_3_Spiral_Memory/Part_1/solution.py | 1,047 | 3.578125 | 4 | import sys
# up, down, left, right
mv_x = [0, 0, -1, 1]
mv_y = [1, -1, 0, 0]
def distance_to_access(pos):
manhatan_distance = 0
x, y = 0, 0
n = 1
dimension = 0
while True:
if n>=pos:
break
# go right and increase dimension.
x, y = x+mv_x[3], y+mv_y[3]
dimension += 1
n += 1
if n>=pos:
break
# ... |
cf8e2a64b80474b8124991078a23730a986ab351 | sudha2327/Smal-factorials | /factorial.py | 130 | 3.78125 | 4 | for _ in range(int(input())):
a=int(input())
fact=1;
for i in range(1,a+1):
fact=fact*i
print(fact)
|
4952bf98a1fb1fc735b8c7555534947417a85fba | skgtrx/Python-OOP | /Basics/2-Attributes.py | 2,455 | 4.96875 | 5 | ''' In this section we will see attributes '''
# In this section we'll be learning about.
# Types of attributes : Class and Instance Attributes
### Class Attributes and Instance Attributes
## Class Attributes : The attributes which are same for all the instances.
## Instance Attributes : The attributes which... |
972e4b7a9a9f81b05943965e5780cabbc4dd43a7 | errorcodexxx/tugaskuliah | /Tugas-DasProg5.py | 2,192 | 3.71875 | 4 | #Tugas DasProg ke 5
print(" DODONGKAL DONG ")
print("===============================")
print(" DAFTAR VARIANT HARGA ")
print("===============================")
print("O Original 13000")
print("K Keju 15000")
print("P Pisang 15000")
print("PK Pisang keju 1800... |
6d2ef9729ee2a24ca65bd7c47046b2b97d1cae90 | Aasthaengg/IBMdataset | /Python_codes/p02987/s851541289.py | 135 | 3.5625 | 4 | s = input()
u = list(set(list(s)))
if len(u) == 2 and s.count(u[0]) == 2 and s.count(u[1]) == 2:
print("Yes")
else:
print("No") |
dcc4e184155a1ad848f528e2df11a86c2c3a5428 | giselemanuel/programming-challenges | /100DaysOfDays/Dia04/ex16.py | 321 | 4.15625 | 4 | """
Exercício Python 16: Crie um programa que leia um número
Real qualquer pelo teclado e mostre na tela a sua porção Inteira.
"""
print('-' * 40)
print(f'{"Exibe um número inteiro":^40}')
print('-' * 40)
numero = float(input("Insira um número real: "))
print(f"O número inteiro de {numero} é {round(numero)}") |
cdc2a8c7260893336f62dc78104f8a96b52916ae | fvictorio/project-euler | /063/problem_063.py | 124 | 3.625 | 4 | def is_n_power(a, n):
an = len(str(a**n))
if an < n: return -1
elif an == n: return 0
elif an > n: return 1
|
14eb08f6f34744104586242e4a58d8723d23bcdc | Sin-Yejun/PPS | /week2/9-9_신예준_20210717.py | 190 | 3.515625 | 4 | n = int(input())
c = 1
i = 1
while True:
if n==1:
print(1)
break
elif n > c and n <= c+6*i:
print(i+1)
break
c = c + 6*i
i += 1
|
140500d32cee2acbd612049ee230fe495f8fb87a | kocdaniel/showmethecode | /0006/0006.py | 1,874 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
**第 0006 题:**
你有一个目录,放了你一个月的日记,都是 txt,
为了避免分词的问题,假设内容都是英文,请统计出你认为每篇日记最重要的词。
"""
import os
import re
def findWord(DicPath):
if not os.path.isdir(DicPath):
return
filelist = os.listdir(DicPath)
reObj = re.compile('\b?(\w+)\b?')
for file in filelist:
filePath = os.path.join(DicPath,... |
025f538eae1dcd49bc2b0b94415367458e60086f | sarabegermy/Bikeshare | /Bikeshare.py | 19,527 | 3.546875 | 4 | import tkinter as tk
from tkinter import scrolledtext
from tkinter import messagebox
import CoreCalculations as cc
def main():
#window
root = tk.Tk()
root.title("Bike Share Project")
#City label
Label2 = tk.Label(text='City')
Label2.grid(row=0, column=0, sticky='w')
#Chicago... |
f751ca6ceb663c0beb4d5be48df1ec71f79c75c2 | ay701/Coding_Challenges | /string/rotateString.py | 812 | 3.671875 | 4 | # Use stack, time complexity: O(N)
def rotateString(L, k):
if L is None or len(L)==0 :
exit("Error input")
if k>len(L):
k = k%len(L)
L_ = []
i = k
while i>0:
L_.append(L[-i])
i-=1
i = 0
while i<len(L)-k:
L_.append(L[i])
i+=1
return L_
L... |
2099f3dc6804e71de7ec1991f86d508f73d42b39 | patel-jaimin/Competitive-Programming | /CodeChef/Python/Chef And Ice Cream(CHFICRM).py | 2,074 | 3.765625 | 4 | # Chef and Icecream | Problem Code: CHFICRM
# Chef owns an icecream shop in Chefland named scoORZ. There are only three types of coins in Chefland: Rs. 5, Rs. 10 and Rs. 15. An icecream costs Rs. 5.
# There are N people (numbered 1 through N) standing in a queue to buy icecream from scoORZ. Each person wants to buy ex... |
a65a9dad17587e5ca8d7d411f36b675be1d08359 | raczandras/szkriptnyelvek | /HF/8/hangrendenum.py | 771 | 3.5625 | 4 | #!/usr/bin/env python3
from enum import Enum
class Beturendek(Enum):
MELYHANGOK = 'aáoóuú'
MAGASHANGOK = 'eéiíöőüű'
class Hangrendek(Enum):
SEMMILYEN = 0
MÉLY = 1
MAGAS = 2
VEGYES = 3
def hangrend(word):
mely = False
magas = False
eredmeny = 0
for c in word:
if c in... |
3ceaa3cedf1ae998074d3314b6d67d09c433c754 | Ty-Jo-B/Python | /homeschool.py | 1,559 | 3.671875 | 4 | '''
CREATED BY: JOEY BURGEE
DATE CREATED: 7-10-17
'''
# IMPORT MODULES
from Tkinter import *
# MAKE THE GRADE-CALCULATION FUNCTION
def grade():
Math = int(math.get())
Grammar = int(grammar.get())
History = int(history.get())
Science = int(science.get())
add = Math + Grammar + History + Science
Grade = Label(roo... |
d961196a17537b43bac1d3ba1bffddd2eaa914d7 | jpcifuentes16/antlr-python3 | /Test/Estructura.py | 248 | 3.5 | 4 | class Estructura:
def __init__(self):
self.campos = []
'''
Campo de tipo <Variable>
'''
def agregar(self, campo):
self.campos.append(campo)
def __repr__(self):
return f"<Estructura>{self.campos}"
|
6618daa74cab5ad62c6cf9bff3af28f45dd65a76 | MasterIceZ/Data_Science | /Kaggle_Data_Science/Python/boolean_and_conditionals/evenodd.py | 105 | 3.890625 | 4 | def is_odd(n):
return (n % 2) == 1
print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1)) |
f44b024bcf5cbf95625de416fb2ff64bdb7df27f | magdapoppins/pycourse-unittest | /sample_utests.py | 837 | 3.9375 | 4 | import unittest
import calc
# Create a class that inherits from unittest.TestCase
class TestCalc(unittest.TestCase):
# as any method of class, takes self as first arg
def test_add_success(self):
self.assertEqual(calc.add(5, 7), 12)
self.assertEqual(calc.add(-5, -7), -12)
self.assertEqu... |
272cc5cf4ade9c58707bd875bbf5edf33bc79a0e | mpatek/runcalc | /runcalc/cli.py | 4,177 | 4.09375 | 4 | import datetime
import click
import re
_multipliers = {
's': 1,
'm': 60,
'h': 3600,
}
_pattern = re.compile(
'(?:(?:(?P<h>\d+):)?(?P<m>\d+):)?(?P<s>\d+(?:\.\d+)?)'
)
def time_str_to_seconds(s):
"""
Convert a string representation of a time to number of seconds.
Args:
s (str): A ... |
5129284a465d7abde6a0565f9a28ca665a609535 | james-xi/gui-python-tkinter | /src/examples/crud_sqlachemy/database/SQLAchemyConnectSQLite.py | 3,326 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""Exemplo de CRUD com Python, SQLAlchemy e SQLite3"""
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# Para debug utilizar ``echo=True``:
# engine = create_engine('sqlite:///db.sqlit... |
6f7fa21080c6ca2a1fca1c56a75725f360ea134d | meganandree88/mathematical_cootie | /finalProject.py | 18,492 | 4.0625 | 4 | '''
File name: finalProject.py
Project Owners: Megan Andree and Amelia McDowell
This file includes the necessary function to play a game Mathematical Caterpillar where a user answers mathematical equations and builds a caterpillar.
'''
import random
from cImage import *
def instruction():
'''
This function ... |
4488b12fba49fe0604696d6d3e323cf5580306d7 | XceptionalDee/DataScienceProjects | /data_exploration.py | 565 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 4 17:07:59 2021
@author: 100431522
"""
def explore_data(dataset, start, end, rows_and_columns=False):
""" slice and print out a dataset between start and end, and
if necessary, print out the number of rows and columns
"""
dataset_slice = dataset[start... |
11a0d1e1a28dc7b0938c32c7c4f4a778d3a47cf7 | cwwillard/python-challenge | /PyRoll/main.py | 2,315 | 3.859375 | 4 | #import dependencies
import os
import csv
#set data source file path
file_path = os.path.join("Resources", "election_data.csv")
candidate_list = {}
myTotalNum_votes = 0
#read in data
with open(file_path) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
for row in c... |
9973f69c156d4e48c0cb664c14610005b501cd35 | yaolinxia/algorithm | /360/3.py | 109 | 3.921875 | 4 | d=[]
for i in range(3):
d1 = []
for j in range(3):
d1.append(i*j)
d.append(d1)
print(d) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.