blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
81c1f5f69ba843cc0b996778d4f3993fbf497564 | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7a.py | 422 | 3.953125 | 4 | #!/usr/bin/python3
#7-4 Pizza Toppings
info = "enter pizza toppings "
info += "\n'quit' to finish: "
topps = ""
while topps != 'quit':
topps = input(info)
if topps != 'quit':
print("\nAdding " + topps + " to your pizza\n")
print("\n")
#7-5 Movie Tickets
age = input("age? ")
age = int(age)
if age < 3:
print("... |
06ce2b33b58fde002588bf8bdf6b93d7d7f3e94d | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6c.py | 693 | 3.90625 | 4 | #!/usr/bin/python3
#6-8 Pets
petname = { 'chicken':'bob'}
petname2 = {'giffare': 'rob'}
petname3 = { 'dinosaur':'phineas'}
petname4 = {'dog': 'ben'}
pets = [petname, petname2, petname3, petname4]
for pet in pets:
print(pet)
print("\n")
#6-9 Favorite Places
favorite_places = {
'bob': ['italy', 'jtaly', 'ktaly'],
... |
ecf4b82877c2884532f159e46e16be8a1c6e029b | benbovy/4learners_python | /notebooks/Day2_AM1/temp_module.py | 1,086 | 3.765625 | 4 | absolute_zero_in_celsius = -273.15
def fahrenheit_to_kelvin(temperature):
"""This function turns a temperature in Fahrenheit into a temperature in Kelvin"""
return (temperature - 32) * 5/9 - absolute_zero_in_celsius
def kelvin_to_celsius(temperature):
"""This function turns a temperature in Kelvin into a ... |
83a49d59eecbcceefc04ab923b85f939e97f33f1 | brennannicholson/ancient-greek-char-bert | /data_prep/greek_data_prep/split_data.py | 2,172 | 3.78125 | 4 | """Splits the sentence tokenized data into train, dev and test sets. This script shuffles the sentences. As a result the dataset created this way can't be used for next sentence prediction."""
from greek_data_prep.utils import write_to_file
import random as rn
import math
def get_data(filename):
with open(filenam... |
867d4f98f69124194b73b20d3bb442093e9445c9 | meldhose/profile_values | /profile_values/profile_encoding.py | 3,829 | 3.921875 | 4 | """Analysing the encoding styles"""
import pandas as pd
def encoding_analysis(df_column):
"""
Checks the encoding style of the strings and
Args:
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
dict (dict)
"""
dict_encoding_analysis = {}
co... |
743f5fd285c9045048bbf81c376c7e4d39d13fc2 | bcarlier75/python_bootcamp_42ai | /day01/ex00/recipe.py | 2,439 | 3.859375 | 4 | class Recipe:
def __init__(self, name, cooking_lvl, cooking_time, ingredients, description, recipe_type):
# Init name
if isinstance(name, str):
self.name = name
else:
print('Type error: name should be a string')
# Init cooking_lvl
if isinstance(cooking... |
9c051053eec8ffb84bc16b987c2fefa664e38415 | bcarlier75/python_bootcamp_42ai | /day00/ex04/operations.py | 1,290 | 3.953125 | 4 | from sys import argv
if len(argv) == 1:
print(f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) == 3:
try:
my_sum = int(argv[1]) + int(argv[2])
my_diff = int(argv[1]) - int(argv[2])
my_mul = int(argv[1]) * int(argv[2])
... |
aad16f725e29145b9217e9d0fd70d675fca9fc64 | bcarlier75/python_bootcamp_42ai | /day01/ex02/vector.py | 3,787 | 3.53125 | 4 | class Vector:
def __init__(self, values, size, my_range):
flag = 0
if values:
if isinstance(values, list):
for elem in values:
if not isinstance(elem, float):
flag = 1
if flag == 0:
self.value... |
e65ff801f6792b85f1878d3520b994f2e9dfa682 | Ernestbengula/python | /kim/Task3.py | 269 | 4.25 | 4 | # Given a number , check if its pos,Neg,Zero
num1 =float(input("Your Number"))
#Control structures -Making decision
#if, if else,elif
if num1>0:
print("positive")
elif num1==0 :
print("Zero")
elif num1<0:
print(" Negative")
else:
print("invalid") |
1bf95b285168d5e332de9f082227a89833161fde | Ernestbengula/python | /kim/Payroll.py | 448 | 3.859375 | 4 | # create a payroll
#Gross_Pay
salary =float(input("Enter salary"))
wa =float(input("Enter wa"))
ha=float(input("Enter ha"))
ta =float(input("Enter ta"))
Gross_Pay =(salary+wa+ha+ta)
print("Gross Pay ", Gross_Pay)
#Deduction
NSSF =float(input("Enter NSSF"))
Tax =float(input("Enter Tax"))
Deductions=(NSSF+Tax)
print(... |
3e021c8066e885499ca01ada8d90b3dd60b956d7 | Gholamrezadar/data-structures | /Quera_3_HanoiTowers.py | 437 | 3.78125 | 4 | From = []
Aux = []
To = []
def hanoi(n, A, B, C):
if n==1:
B.append(A.pop())
show_towers()
return
hanoi(n-1, A, C, B)
B.append(A.pop())
show_towers()
hanoi(n-1, C, B, A)
def show_towers():
print(sum(From), sum(Aux), sum(To))
def fill_bars():
for i... |
319365deb464f4b690e1066ca52e69c9ce2622a9 | Evgen8906/homework_modul_14 | /calc.py | 1,199 | 3.796875 | 4 | """calc v5.0"""
def input_number():
num=input("Vvedite chislo: ")
if num == '':
return None
try:
num=float(num)
except ValueError:
num = num
return num
def input_oper():
oper=input("Operaciya('+','-','*','/','^','**'): ")
if oper == '':
oper ... |
de3d8e0821036c101002cdfb771f190f4e1eb5b7 | Armadillan/TensorFlow2048 | /pg_implementation.py | 16,201 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class for a visual interface for the 2048 environment using pygame.
Playable by both humans and robots.
"""
import time
import os
import pygame
import numpy as np
class Game:
"""
Class for a visual interface for the 2048 environment using pygame.
Playab... |
ff55c37cedb184c2d2c8399ca9717e775bd34e9c | txkxyx/atcoder | /practice/abc081a.py | 471 | 3.8125 | 4 | import sys
# 0 と 1 のみから成る 3 桁の番号 s が与えられます。1 が何個含まれるかを求めてください。
class ABC081():
def __init__(self, s):
self.s = s
def checkCount(self):
count = 0
for c in s:
if c == '1':
count += 1
return count
if __name__ == '__main__':
args = sys.argv
s = a... |
e326bc60c7ca49876b9948df9dc5758455a9ce64 | JianxiangWang/LeetCode | /70 Climbing Stairs/solution.py | 525 | 3.671875 | 4 | # encoding: utf-8
# dp[i] = dp[i-1] + dp[i-2]: 跨到第i台阶 == 从i-1跨过来的次数 + 从i-2跨过来的次数
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
if n == 1: return 1
dp = [None] * n
dp[0] = 1
dp[1] = 2
... |
42e46dadf6d6e53f7c42146761113cf4e6e3f848 | JianxiangWang/LeetCode | /129 Sum Root to Leaf Numbers/solution.py | 921 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, s, res)... |
8eee6e6b52fd476f0de22c3e59cb37317597aa45 | JianxiangWang/LeetCode | /Intersection of Two Arrays II/solution.py | 842 | 3.71875 | 4 |
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict_num1_to_count = {}
dict_num2_to_count = {}
for x in nums1:
if x not in dict_num1_to_count:
dict_num1_to_count[x] = 0
... |
9d12f4df1ade28b51f2f562ff900fbb75f808d11 | JianxiangWang/LeetCode | /203 Remove Linked List Elements/solution.py | 807 | 3.53125 | 4 | #encoding: utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
... |
d2c1cd0d01c93d0c59ba25541031a78ce7e0bbe9 | JianxiangWang/LeetCode | /130 Surrounded Regions/solution.py | 2,024 | 3.578125 | 4 | # encoding: utf-8
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) <= 0:
return
m, n = len(board), len(board[0])
visited = [[Fal... |
9181573ba65b9aca1551f88c49f69650a2af4ad7 | JianxiangWang/LeetCode | /47 Permutations II/solution.py | 737 | 3.625 | 4 |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(seq, ans, res):
seq = sorted(seq)
prev_x = None
for idx, x in enumerate(seq):
if x == prev_x:
... |
ab061ca7ac9f33f8fd5f2e7c9e3c1530e59b2024 | alvdena/SWMM-EPANET_User_Interface | /src/core/inputfile.py | 15,166 | 3.515625 | 4 | import inspect
import traceback
from enum import Enum
class InputFile(object):
"""Input File Reader and Writer"""
def __init__(self):
self.file_name = ""
self.sections = []
self.add_sections_from_attributes()
def get_text(self):
section_text_list = []
try:
... |
5930c2407c62aeee242a0a1340e49d2372d27d0c | Vishnushetty14/assignments | /swapping_of_two_numbers.py | 109 | 3.875 | 4 | a=float(input("enter a value"))
b=float(input("enter b value"))
temp=a
a=b
b=temp
print("a=",a)
print("b=",b) |
c06b507656eb5fa8e0471507532ef4de8a3167d9 | easyra/Sprint-Challenge--Data-Structures-Python | /names/names.py | 1,548 | 3.546875 | 4 | import time
import sys
sys.path.append('../search')
#from binary_search_tree import BinarySearchTree
start_time = time.time()
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
direction = "right" if value > self.value... |
400be22da09455720e76805e79cda13b8e025a83 | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/packages.py | 356 | 3.90625 | 4 | import random # generates random values
#members = ['Mary', 'John', 'Bob', 'Mosh']
#leader = random.choice(members)
#print(leader)
#for i in range(3):
#print(random.randint(10, 20))
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, sec... |
2a048d0c0cd4709d4b9b856b03190105f8006cee | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Loops!!.py | 275 | 3.875 | 4 | Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> for x in range(0, 5):
print('hello')
hello
hello
hello
hello
hello
>>> print(list(range(10, 20)))
|
df441f7479925dbf77b009cd401a692876965abb | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Varibles.py | 429 | 3.890625 | 4 | print("Create your character")
name = input("What is you character called?")
age = input("How old is your character?")
strengths = input("What is your character's strenghts?")
weakness = input("What are your character's weaknesses?")
print("Your character's name is", name)
print("Your character is", age, "years old")
... |
b124c829284bc4aea81d34cfa8d487eadb6f180e | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Mass Defense.py | 1,373 | 3.734375 | 4 | #
#
#
#
import turtle
import random
wn = turtle.Screen()
wn.setup(1200, 800)
wn.bgcolor("black")
wn.title("Mass Defense Game")
class Sprite():
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()
def __init__(self, x, y, shape, color):
self.x = x
self.y = y
s... |
7737b93b5c93234ab9a28e8a3b6d3b23f740dd76 | abhiranjan-singh/DevRepo | /calculater.py | 383 | 4.1875 | 4 | def mutiply(x, y):
return x*y
print(mutiply(int(input("enter the 1st number ")),int(input("Enter the second number "))))
#m = int(input("enter the 1stnumber "))
#n = int(input("enter the second number "))
# print(mutiply(input("enter the 1st number"),input("enter the second number")))
#print(mutiply(m, n))
#pr... |
dce0cf3caa43263a93aba2b4cd1de6e10e2efb03 | rexos/python_data_mining | /fibonacci.py | 147 | 3.9375 | 4 | def fibonacci(n):
ary = [1,1]
for i in range(2,n):
ary.append(ary[i-1]+ary[i-2])
return ary[n-1]
print fibonacci(10)
|
356f25da7e3e31a653955de095d7a12392d3b331 | marclacerna/ormuco | /question_b.py | 560 | 3.796875 | 4 | class CheckInputs:
def __init__(self, input1, input2):
try:
self.input1 = float(input1)
self.input2 = float(input2)
except ValueError:
print('Both inputs must be a number')
def compare(self):
if self.input1 > self.input2:
return '{} great... |
67ca1707453a15e4c6ea0983a8e11ee83b7c1b97 | agvaibhav/Dynamic-Programming | /rod_cutting_to_max_profit.py | 1,646 | 3.515625 | 4 | # rod cutting
# we are given profit of each length of rod
# we have to max profit
# recursion method
'''
def maxProfit(arr, totalLen):
if totalLen == 0:
return 0
best = 0
for len in range(1, totalLen+1):
netProfit = arr[len] + maxProfit(arr, totalLen-len)
best = ... |
ea6180b91169567ad23ba823d65587a2151c76d2 | agvaibhav/Dynamic-Programming | /fibonacci_memoized.py | 373 | 4.03125 | 4 | def fib(n,lookup):
if n==0 or n==1:
lookup[n]=n
if lookup[n] is None:
lookup[n]=fib(n-1,lookup)+fib(n-2,lookup)
return lookup[n]
def main(n):
lookup=[None]*(n+1)
print("fibonacci number is:",fib(n,lookup))
if __name__=="__main__":
n=int(input("write the number you want t... |
817ff7a48e120dde311d2efe4ed5af3653c3a421 | nan0445/Leetcode-Python | /Recover Binary Search Tree.py | 803 | 3.71875 | 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 recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place i... |
3e6d1270046132f91ba5cadc072ca19307865178 | nan0445/Leetcode-Python | /Balanced Binary Tree.py | 660 | 3.75 | 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 isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
de... |
4513ff87de71790ef509b716ab2457c32241ac06 | nan0445/Leetcode-Python | /Power of Three.py | 250 | 3.8125 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0: return False
while n>1:
n, m = divmod(n, 3)
if m!=0: return False
return True
|
50fac474fbcefc14ff6ae95edde0ecce61f8ccd2 | nan0445/Leetcode-Python | /Binary Tree Right Side View.py | 654 | 3.609375 | 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 rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
de... |
62edcf7046115e564e295034c50102711b71c688 | nan0445/Leetcode-Python | /Linked List Cycle II.py | 821 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return None
s... |
cff739a27abb4061b8d01e34d056580f77981790 | nan0445/Leetcode-Python | /Self Crossing.py | 599 | 3.5625 | 4 | class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if len(x)<=3: return False
flag = True if x[2] > x[0] else False
for i in range(3,len(x)):
if flag == False:
if x[i]>=x[i-2]: return True
... |
35b9c6dc1b7ce2b5b4a6d9d1f2ca09d4cf119735 | nan0445/Leetcode-Python | /Different Ways to Add Parentheses.py | 651 | 3.546875 | 4 | class Solution:
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
if input.isdigit(): return [int(input)]
res = []
def helper(n1, n2, op):
if op == '+': return n1 + n2
elif op == '-': return n1 - n2... |
e55d1042b514fb55cff0e831b1d83872cf4c550a | nan0445/Leetcode-Python | /Search Insert Position.py | 545 | 3.71875 | 4 | class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l,r = 0,len(nums)-1
if r==-1: return 0
while l<r:
mid = (l+r)//2
if target>nums[mid]:
l = mid + 1
... |
d1b02071edd187ca634a03c63b86db4b7838b758 | nan0445/Leetcode-Python | /House Robber III.py | 488 | 3.71875 | 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 rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node):
if no... |
9186c1fb4552a1b862f949cd36b35a126a90061f | nan0445/Leetcode-Python | /Remove Nth Node From End of List.py | 742 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
count = 0
dum... |
753690e49ef2149ccea76603a17de27766f9e8f6 | nan0445/Leetcode-Python | /Fraction to Recurring Decimal.py | 739 | 3.5 | 4 | class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator*denominator<0: sign = '-'
else: sign = ''
numerator, denominator = abs(numerator), abs(denominator)
... |
26ff62a19dc23bb66d05ac34c2f87e6c2095a87c | nan0445/Leetcode-Python | /Word Search.py | 859 | 3.578125 | 4 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
m = len(board)
n = len(board[0])
def helper(p,q,t,board,word):
if p<0 or p>=len(board) or q<0 or q>=len(board[0]) or board[p][q]... |
363fb60fab73ad320aac80101cf924305254ca94 | nan0445/Leetcode-Python | /Palindrome Pairs.py | 654 | 3.609375 | 4 | class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
dic = {word: i for i, word in enumerate(words)}
res = []
for j, word in enumerate(words):
for i in range(len(word)+1):
... |
0e0078f97b8be6d5e53b5da55670433ff1034a3b | chae-heechan/Python_Study | /3. 문자열/practice_2.py | 812 | 3.515625 | 4 | print("a" + "b")
print("a", "b")
# 방법 1
print("나는 %d살입니다." % 20) #굉장히 C스럽네
print("나는 %s를 좋아해요." % "파이썬")
print("Apple 은 %c로 시작해요." % "A")
# %s
print("나는 %s살입니다." % 20)
print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간"))
# 방법 2
print("나는 {}살입니다.".format(20))
print("나는 {}색과 {}색을 좋아해요.".format("파란", "빨간"))
print("나는 {1}색과 {0}색을... |
aebd7a8b4bfed4166b0c2294ab90c48acc6ce8df | chae-heechan/Python_Study | /3. 문자열/practice_1.py | 411 | 4.0625 | 4 | python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python", "Java"))
index = python.index("n")
print(index)
index = python.index("n", index + 1)
print(index)
print(python.find("Java")) # 없을 경우 return -1
# print(python.index("J... |
dc24a69fde9b47505c07f6e16a95c9497be4763c | chae-heechan/Python_Study | /4. 자료구조/set.py | 662 | 3.859375 | 4 | # 집합 (set)
# 중복 안됨, 순서 없음
my_set = {1, 2, 3, 3, 3}
print(my_set)
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])
# 교집합 (java와 python을 모두 할 수 있는 사람)
print(java & python)
print(java.intersection(python))
# 합집합 (java나 python을 할 수 있는 사람)
print(java | python)
print(java.union(python))
# 차집합 (java는 할 수 있지만 p... |
c1423dde6c4d142d9028e4d6953e1293d1e0ae29 | Andrew4me/byte | /except/try_except.py | 273 | 3.5 | 4 | try:
text = input('Введите что-нибудь -->')
except EOFError:
print('Ну зачем вы сделали мне EOF?')
except KeyboardInterrupt:
print('вы отменили операцию')
else:
print('Вы ввели {0}' .format(text))
|
3c0a49d57c23bfcd8d38c64fefe23231efd6c5e7 | xswxm/Smart_Fan_for_Raspberry_Pi | /fan.py | 1,446 | 3.71875 | 4 | #!/usr/bin/python2
#coding:utf8
'''
Author: xswxm
Blog: xswxm.com
This script is designed to manage your Raspberry Pi's fan according to the CPU temperature changes.
'''
import RPi.GPIO as GPIO
import os, time
# Parse command line arguments
import argparse
parser = argparse.ArgumentParser(description='Manage your R... |
1e894d45be1e1e01e00d89c35e8169d3b3ad5652 | DGEs2018/python_4_django | /functions.py | 197 | 3.546875 | 4 | import functiontobeimported
def multiplication(x, y, z):
return x*y*z
# def square(x):
# return x*x
for i in range(10):
print(f"The square of {i} is {functiontobeimported.square(i)}") |
43d6e2b5da96f94c5037c2a0d19a6330fb5febec | sebastiandifrancesco/web-scraping-challenge | /scrape_mars.py | 3,975 | 3.53125 | 4 | # --- dependencies and setup ---
from bs4 import BeautifulSoup
import pandas as pd
from splinter import Browser
import time
def init_browser():
# Set executable path & initialize Chrome browser
executable_path = {"executable_path": "./chromedriver.exe"}
return Browser("chrome", **executable_path, ... |
71b154af653eadaf81bfb74ba900427383f54235 | yan-yf/pyhomework | /hanoi&fib.py | 284 | 3.9375 | 4 | def hanoi(n, A, B, C):
if n == 1:
print A, '->', B
else:
hanoi(n - 1, A, C, B)
print A, '->', B
hanoi(n - 1, C, B, A)
hanoi(5, 'A', 'B', 'C')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib (n - 2)
print fib(6) |
a203f7b2a316c3f9eaef8f3ae9ab5d2abd3454cb | leftan/D07 | /HW07_ch10_ex06.py | 928 | 4.09375 | 4 | # I want to be able to call is_sorted from main w/ various lists and get
# returned True or False.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
def is_sorted(list_of_items):
try:
new_list = sorted(list_of_items)
except:
print('T... |
83c83339f9279481ccb83273ae84555c316e3fc6 | HelalChow/Data-Structures | /Labs/Lab 8.py | 1,135 | 3.875 | 4 | class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
def push(self, item):
self.data.append(item)
def pop(self):
if self.is_empty==0:
raise Exception("Stack is e... |
6219eeb03cac0b97952fe8e2599a006421073865 | HelalChow/Data-Structures | /Classwork/10/10-17 ADT.py | 878 | 3.90625 | 4 | def Algorithm():
pass
'''
***Stack ADT***
Data Model: Collection of items where the last element in is the first to come out (Last in, first out)
Operations:
s = Stack()
len(s)
s.is_empty()
s.push() #Adds Item
s.pop() #Removes last item and returns it
s.top() #Returns last it... |
8561124801f526b472e5f3b3182b7efccb6f1a0f | HelalChow/Data-Structures | /Labs/Lab 6.py | 1,454 | 3.71875 | 4 | def find_lst_max(lst):
if len(lst)==1:
return lst[0]
else:
hold = find_lst_max(lst[1:])
return max(lst[0],hold)
print(find_lst_max( [1,2,3,4,5,100,12,2]))
def product_evens(n):
if n==2:
return n
else:
if n%2==0:
return n*product_evens(n-2... |
9f6eb2c3ca0d17db7a68b94e7ddd51b1a88592c8 | HelalChow/Data-Structures | /Labs/Lab 2.py | 1,964 | 3.78125 | 4 | class Polynomial:
def __init__(self,lst=[0]):
self.lst = lst
def __repr__(self):
poly = ""
for i in range(len(self.lst)-1,0,-1):
if i == 1:
poly += str(self.lst[i])+"x^"+str(i)+"+"+str(self.lst[0])
else:
poly += str(self.ls... |
31a03d615d586ef55b70874d973d5a68cd1d4ae1 | HelalChow/Data-Structures | /Homework/HW3/hc2324_hw3_q3.py | 307 | 3.6875 | 4 | def find_duplicates(lst):
counter = [0] * (len(lst) - 1)
res_lst = []
for i in range(len(lst)):
counter[lst[i] - 1] += 1
for i in range(len(counter)):
if (counter[i] > 1):
res_lst.append(i + 1)
return res_lst
print(find_duplicates([0,2,2])) |
68ee8286c000c5c0512432a0d808be49dc8ab6a9 | HelalChow/Data-Structures | /Homework/HW2/hc2324_hw2_q6.py | 593 | 3.671875 | 4 | def two_sum(srt_lst, target):
curr_index = 0
sum_found = False
count =0
while(sum_found==False and curr_index < len(srt_lst)-1):
if (count >= len(srt_lst)):
count = 0
curr_index += 1
elif srt_lst[curr_index] + srt_lst[count] == target and curr_index != cou... |
fe0871327bdc40129abafafc866406b13995f722 | MafihlwaK/Pre-Bootcamp-coding-Challenges-python- | /Task 11.py | 206 | 3.8125 | 4 | def common_characters():
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
s1 = set(str1)
s2 = set(str2)
first = s1 & s2
print(first)
common_characters() |
4359dd4f67584016be61c50548e51c8117ee2bc7 | xpbupt/leetcode | /Medium/Complex_Number_Multiplication.py | 1,043 | 4.15625 | 4 | '''
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:... |
f5368db904d1ec8e53ba06e9c529751ed9982f67 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/StringHandling.py | 7,782 | 3.9375 | 4 | #String handling
#isupper
'''
MyString="HELLO"
MyString1="HELLO%&^%&"
MyString2="HELLO%e"
result=MyString.isupper()
result1=MyString1.isupper()
result2=MyString2.isupper()
print(result)
print(result1)
print(result2)
output:
True
True
False
---------------------
#islower
MyString="hello"
MyString1="hello%&^%&"
... |
4f4be5077a2ec1945975bc34b0c05c20af8e6600 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/OddOrEven.py | 527 | 4.0625 | 4 | #odd or even from 1-100
'''
####method: 1
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
print("even = {0}".format(i))
elif(i%2==1):
print("odd = {0}".format(i))
'''
###Method 2:
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
... |
1c749cd9a5612b07f817fe9ae2b5df307e896ff1 | leonardo185/Data-Structures-using-Python | /binary_search.py | 527 | 3.78125 | 4 | def binarySearach(list, value):
first = 0
last = len(list) - 1
found = False
index = None
while(first <= last and not found):
midpoint = int((first + last)/2)
if(list[midpoint] == value):
found = True
index = midpoint + 1
else:
... |
eae2e47d12de9e59fcf8637f16e4349e78efa153 | Mystic67/Game-Mac-Gyver | /controller/events.py | 1,860 | 3.6875 | 4 | #! /usr/bin/python3
# -*-coding: utf-8-*-
import pygame
class Events:
'''This class listen the user inputs and set the game variables '''
main = 1
home = 1
game = 1
game_level = 0
game_end = 0
# self.listen_events()
@classmethod
def listen_game_events(cls, instance_sprite=None):
... |
9e0d6c1a5ccda5e204d5ab171e22afc74f63261b | francico4293/Sudoku-Solver-v2 | /sudoku_board.py | 21,643 | 4.125 | 4 | # Author: Colin Francis
# Description: Implementation of the sudoku board using Pygame
import pygame
import time
from settings import *
class SudokuSolver(object):
"""A class used to solve Sudoku puzzles."""
def __init__(self):
"""Creates a SudokuSolver object."""
self._board = Board()
... |
b716e509279d0f192f5128489d752690a4d303ed | subham09/Comp9021 | /Quizes/quiz 4.py | 3,442 | 3.625 | 4 | # Randomly fills a grid of size height and width whose values are input by the user,
# with nonnegative integers randomly generated up to an upper bound N also input the user,
# and computes, for each n <= N, the number of paths consisting of all integers from 1 up to n
# that cannot be extended to n+1.
# Outputs t... |
7000f0861768fb5c3cccb7e6dc7bc017190d456b | AlexseySukhanov/HomeWork3 | /Task_add_1.py | 360 | 3.734375 | 4 | flat=int(input("Введите номер квартиры "))
if flat<=144 and flat>0:
ent=int(flat/36-0.01)+1
floor=int(flat/4-0.01)+1-(ent-1)*9
print(f"Квартира находится в {ent} подъезде, на {floor} этаже")
else:
print("Квартиры с таким номером не существует в доме")
|
1def0b375d6b7f6d8ec10e58f8aefc784c923486 | Egan-eagle/python-exercises | /week1&2.py | 3,145 | 4.3125 | 4 | # Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno... |
8fdad961a6692877342af74576cda9610090de77 | yuvraajsj18/CS50 | /intro/week6/tuple.py | 115 | 3.609375 | 4 | tuple = [
(1, 'a'),
(2, 'b'),
(3, 'c')
]
for num, alpha in tuple:
print(f"{alpha} - {num}") |
312c19e4e77b383d412b06a7ca482e7930e94b8a | yuvraajsj18/CS50 | /intro/week6/swap.py | 174 | 3.5625 | 4 | from cs50 import get_int
x = get_int("x = ")
y = get_int("y = ")
print(f"Before Swap: x = {x} & y = {y}")
x, y = y, x
print(f"After Swap: x = {x} & y = {y}")
|
29df6be4c64bd613e10323d60edf59d28f8b1386 | yuvraajsj18/CS50 | /intro/week6/hello1.py | 133 | 3.515625 | 4 | from cs50 import get_string
name = get_string("Name: ")
print("Hello,",name)
print(f"{name}, Hello!!!") # formated string output |
f27f0ec182b9da2d7ffac680b2c6cbab78494f9a | Sir-Benj/Python-First-Game | /enemy.py | 1,621 | 3.765625 | 4 | # Enemy Class
# Creating as a module.
# Creating the Enemy Class.
class Enemy:
"""For Each Enemy in the game"""
def __init__(self, name, hp, maxhp, attack, heal_count, heal, magic_count, magic_attack):
self.name=name
self.hp=hp
self.maxhp=maxhp
self.attack=attack
self.heal_count=heal_co... |
c5db71efe8b6a60f65ae9b00bb6b5258f468cf0c | ShamiliS/Java_Backup | /practice/funct2.py | 232 | 3.609375 | 4 | '''
Created on 4 Apr 2018
@author: SHSRINIV
'''
import function1
result = function1.calcuator_add(4, 5)
print("Addition:", result)
listofvalues = [3, 6, 7, 8, 2]
listresult = function1.listCheck(listofvalues)
print(listresult)
|
e25be21c2647af9c32be52f2891770f2b5177ece | ShamiliS/Java_Backup | /SimplePython/pException.py | 478 | 3.53125 | 4 | '''
Created on 9 Apr 2018
@author: SHSRINIV
'''
def KelvinToFahrenheit(temp):
result = 0
try:
assert(temp > 0), "Colder than absolute zero!"
except AssertionError:
print("AssertionError: Error in the input", temp)
except TypeError:
print(TypeError)
else:
result = ... |
2f69991dd752fee0a0fe55ca276bc3b9db4ca8df | JacobRoyster/GroupMe | /GroupMeFunctions/RemoveFromGroup.py | 1,971 | 3.609375 | 4 | import requests
import json
import sys
"""
userToken should be a valid GroupMe user token. (string)
groupID should be a valid group that you have access to. (string)
userID should be a valid ID for the user you want to remove. If this userID is yours, you leave the group. (string)
purpose of this function is to remove... |
70499b8516182a300a1a47dd14bb226fbaa7a696 | yzzyq/Machine-learning | /贝叶斯/病例预测/naiveBayes.py | 5,349 | 4.03125 | 4 | #贝叶斯算法
import csv
import random
import math
import copy
#整个流程:
##1.处理数据:从CSV文件载入数据,分为训练集和测试集
## 1.将文件中字符串类型加载进来转化为我们使用的数字
## 2.数据集随机分为包含67%的训练集和33%的测试集
##
##2.提取数据特征:提取训练数据集的属性特征,以便我们计算概率并作出预测
## 1.按照类别划分数据
## 2.写出均值函数
## 3.写出标准差函数
## 4.计算每个类中每个属性的均值和标准差(因为这里是连续型变量,也可以使用区间)
## 5.写个函数... |
7da84a0ef5b3fad6a422adf7242707c31f07bbe7 | seales/EulerSolutions | /Solutions/Solution30.py | 1,152 | 3.859375 | 4 |
def get_nth_digit(number, n):
if n < 0:
return 0
else:
return get_0th_digit(number / 10**n)
def get_0th_digit(number):
return int(round(10 * ((number/10.0)-(number/10))))
def digit_count(number):
return len(str(number))
def nth_digit_sum_upper_bound(n):
i = 0
while digit_c... |
8b7e67918be7f322b2243df81fec613e61815cbb | seales/EulerSolutions | /Solutions/Solution47.py | 2,021 | 3.71875 | 4 |
import math
def find_factors(n, factors):
if n == 1:
return factors
divisor = math.floor(math.sqrt(n))
# loop until integer divisor found
while (n/divisor) != int(n/(divisor*1.0)):
divisor -= 1
if int(divisor) == 1:
break
a = int(n/(divisor*1.0))
b... |
bf16f46f94cad68da94c323d0d506b450e0cefc0 | patiregina89/Exercicios-Logistica_Algoritimos | /Questionario.py | 1,945 | 4.0625 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Questionário")
print(("*"*42))
'''
3) Crie um programa que leia a idade e o sexo de várias... |
e7fcefbf8508b463718639ae1098f2933eff8c24 | patiregina89/Exercicios-Logistica_Algoritimos | /Funcao_calculos.py | 771 | 3.921875 | 4 | import sys
'''ARQUIVOS NÃO EXECUTAVEIS. sao apenas funções pré-determinadas.'''
def somar():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Somar: ', x + y)
def subtrair():
x = float(input('Digite o primeiro número: '))
y = float(input... |
509db82ab08a4667d0642c5f952301717c291fb9 | patiregina89/Exercicios-Logistica_Algoritimos | /Condicao_Parada999.py | 1,444 | 4.21875 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Condição parada 999")
print(("*"*42))
'''
Crie um programa que leia vários números intei... |
ec39f6b56f562c88fb97f60df1037443664419f4 | patiregina89/Exercicios-Logistica_Algoritimos | /repeticao_aninhada.py | 260 | 3.984375 | 4 | tabuada = 1
while tabuada<=10:
numero = 1
while numero <= 10:
print("%d x %d = %d"%(tabuada, numero, tabuada*numero))
numero = numero + 1
#numero += 1 ---> mesma coisa da sequencia acima
print("="*14)
tabuada+=1 |
7bb23b547c4e1c5993093195c726b8b54f42a820 | patiregina89/Exercicios-Logistica_Algoritimos | /Dic_comparando_paises.py | 1,543 | 3.984375 | 4 |
print()
#Criar dicionário
dic_Paises = {'Brasil': 211049519,
'França': 65129731,
'Portugal': 10226178,
'México': 10226178,
'Uruguai': 3461731}
#utilizar os métodos do dicionário
print('********************** 1 - Método **********************')
print(d... |
dcf778368e954f93a6ae7e05677ad4b1f37384c8 | patiregina89/Exercicios-Logistica_Algoritimos | /Exercicio3_Notas.py | 695 | 4 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício 3 - Média notas")
print(("*"*42))
#3. Faça um Programa que leia 4 notas, mostre as notas e ... |
9c2c799fbfd1d11762fcf1c25a2a413ae2087b91 | patiregina89/Exercicios-Logistica_Algoritimos | /Lista_Soma_Notas2.py | 229 | 3.765625 | 4 | notas = [0.0, 0.0, 0.0]
notas[0] = float(input("Informe a nota 1: "))
notas[1] = float(input("Informe a nota 2: "))
notas[2] = float(input("Informe a nota 3: "))
print("A somas das notas é: ", notas[0]+notas[1]+notas[2]) |
0b6d65ee7e88de9c04723eba487b5e807571cd2f | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 1.py | 1,216 | 3.5 | 4 | """
slightly
adv.轻微地,轻轻地;细长地,苗条地;〈罕〉轻蔑地;粗
exactly
adv.恰恰;确切地;精确地;完全地,全然
SyntaxError
语法错误
Usually
adv.通常,经常,平常,惯常地;一直,向来;动不动,一般;素
cryptic
adj.神秘的;隐藏的;有隐含意义的;使用密码的
Drills
n.钻头;操练( drill的名词复数 );军事训练;(应对紧急情况的)演习
v.训练;操练;钻(孔)( drill的第三人称单数 );打(眼)
explain
vt.& vi.讲解,解释
vt.说明…的原因,辩解
vi.... |
a83d4a66c989c107a57dadf4dcfb8e597e14a107 | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 18.py | 1,416 | 4.71875 | 5 | """
Exercise 18: Names, Variables, Code, Functions
1.Every programmer will go on and on about functions
introduce
vt.介绍;引进;提出;作为…的
about to
即将,正要,刚要;欲
explanation
n.解释;说明;辩解;(消除误会后)和解
tiny
adj.极小的,微小的
n.小孩子;[医]癣
related
adj.有关系的;叙述的
vt.叙述(relate过去式和过去分词)
break down
失败;划分(以便分析);损坏;衰弱... |
c0c7eb4b9ada3385e0f96acca76bcf758080851e | AlphaBitClub/alphabit-coding-challenge | /alphabit-coding-challenge-01/03_zeros/solutions/zeros.py | 432 | 3.625 | 4 | # count the multiplicity of the factor y in x
def multiplicity(x, y):
count = 0
while x % y == 0:
x //= y
count += 1
return count
n = int(input())
two = 0
five = 0
for _ in range(n):
x = int(input())
if x % 2 == 0:
two += multiplicity(x, 2)
if x % 5 == 0:
five... |
a71c8a60aafc290dab24730570a42709f24d5627 | luislama/algoritmos_y_estructuras_de_datos | /algoritmos/17_suma_de_primos/suma_de_primos.py | 1,570 | 3.59375 | 4 | '''
Encuentre la suma de los numeros primos menores a 2 millones
'''
'''
Analisis
Anteriormente, el numero primo mayor a calcular fue el 10001, el algoritmo de buscar los numeros primos no era eficiente,
pero no representaba un problema
En este caso, el tope es de 2000000 y necesita otro enfoque
... |
55ba0cf476b6e3bb1b11adfee422b27374244d74 | sukritsangvong/Hearts | /main.py | 4,422 | 4 | 4 | #Final project for CS 111 with DLN
#PJ Sangvong and Ben Aoki-Sherwood
#Hearts
from heartCard import *
from playable import *
from turnFunction import *
from calculateScore import *
from roundFunction import *
from takeCardFromBoard import *
from botswap import *
from heartsBoard import *
def main():
'''Run... |
d5ae00e795446869e908aeec451a5dd8012dd487 | Darkman94/autoencoder | /encode_tf.py | 2,742 | 3.8125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
#not sure this is working the way I think it is
#if it is it's a really poor model
#don't think I need one_hot, since I'm training an autoencoder
#not attempting to learn the classification
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
imp... |
01d4eeafaf9ddbb6966fe3c9a3a29755942931be | pankajgupta119/Python | /piggy.py | 779 | 4.0625 | 4 | #A Piggybank contains 10 Rs coin, 5 Rs coin , 2 Rs coin and 1 Rs coin then calculate total amount.
print("\tPIGGY BANK")
num1=int(input("Enter the number of 10rs coin\n "))
result1=num1*10
print("The total amount of 10rs coin is",result1)
print("\n")
num2=int(input("Enter the number of 5rs coin\n "))
re... |
008a644d92b235fb12c932f9d8d32785aa557c8b | pankajgupta119/Python | /swap.py | 176 | 3.984375 | 4 | num1=int(input("ENTER NUMBER1"))
num2=int(input("ENTER NUMBER2"))
print("nuber1=",num1)
print("nu2mber=",num2)
num1,num2=num2,num1
print("num1=",num1)
print("num2=",num2) |
7e64a3f0004ba7103ae527be9e661e18a548eef8 | Romko97/Python | /Codawars/1.py | 743 | 3.515625 | 4 | # boolean_list= [True, True, False, True, True, False, False, True]
# print(f"The origion list is{boolean_list}")
# res_true, res_false = [],[]
# for i, item in enumerate(boolean_list):
# temp = res_true if item else res_false
# temp.append(i)
# print(f"True indexes: {res_true}" )
# print(f"False indexes: {res_... |
a6ca59324734f9e4fcf75d443b17070b2b14138b | Romko97/Python | /Softserve/HOME_WORK_03.py | 2,926 | 3.625 | 4 | Zen = '''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although prac... |
62e85e9955191e8612ad7252c04c248315e3030e | Romko97/Python | /Codawars/06.02.20/Reversing_Words_in_a_String.py | 219 | 4.03125 | 4 | def reverse(st):
st = st.split()
st = st[::-1]
st = ' '.join(st)
return st
def reverse(st):
print(' '.join(st.split()[::-1]))
def reverse(st):
return " ".join(reversed(st.split())).strip()
|
c1cc2522e99d5022a7d680103e1a7c1431aafdf3 | steeju/Free-python-class-with-friends | /DAY 3.py | 1,144 | 3.984375 | 4 | #leap year program
name = int(input("year : "))
if (name%4==0 and name%100!=0) or (name%400==0):
print( name, "is a leap year")
else:
print( name, "not a leap year")
# leap year แต่ไม่ทัน
start = int(input())
end = int(input())
count = 0
for year in range (start, end+1):
if(year%4==0 and year%100!=0) or (year... |
ce715c678ac816847a3939e61700f50637ef1210 | samcoh/FinalProject206 | /finalproj.py | 39,723 | 3.578125 | 4 | import requests
import json
from bs4 import BeautifulSoup
import sys
import sqlite3
import plotly.plotly as py
import plotly.graph_objs as go
#QUESTIONS:
#1. How to write test cases
#2. Check to see if table okay (list parts)
#3. Joing the table and the data processing for plotly (is okay that i use some part classes)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.