blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
8f4cb8cbb8f0b0b47c32ae695ff90be71d0ddc32
gioliveirass/atividades-pythonParaZumbis
/Lista de Exercicios I/Ex01.py
219
3.953125
4
# Exercicio 01 print('Exercicio 01: Calculando a Soma de dois números!') n1 = int(input('Insira um número: ')) n2 = int(input('Insira outro número: ')) soma = n1 + n2 print(f'A soma dos números inseridos é {soma}')
ad5a4b4510f4fba1c1439b99a4e4a6167709997c
lbtdne/Coffee-Machine
/coffee_machine.py
3,078
3.984375
4
machine_steps = ["Starting to make a coffee", "Grinding coffee beans", "Boiling water", "Mixing boiled water with crushed coffee beans", "Pouring coffee into the cup", "Pouring some milk into the cup", "Coffee is ready...
296cc9fc649aec65aa297645babfe674d91232ad
DenVankov/Numerical-Methods
/Lab1/NM_1_1.py
4,860
3.671875
4
from random import randint class MatrixException(Exception): pass def getCofactor(A, tmp, p, q, n): # Function to get cofactor of A[p][q] in tmp[][] i = 0 j = 0 # Copying into temporary matrix only those element which are not in given row and column for row in range(n): for col in range...
69df0ffef277af6e3466541e8e07265ed79b960e
GGGomer/AoC2020
/02/02b.py
1,012
3.609375
4
import re def main(): f = open("./02input", 'r') line = f.readline() lowest_indices = [] highest_indices = [] characters = [] passwords = [] # Loop through all lines while line: # deconstruct line into elements for lists decimals = re.findall(r'\d+', line) lowest_indices.append(int(decima...
2d120b9d6eb107bbd9404e0a20c88b354f0944cc
aaskorohodov/Learning_Python
/Обучение/Range comprehension.py
189
3.515625
4
list = [eo * 2 for eo in range(10,1,-1) if eo % 2 != 1] print(list) words = ["hello", "hey", 'goodbey', "guitar", "piano"] words2 = [eo + "." for eo in words if len(eo) < 7] print(words2)
ab1df5f6495bf2de81da4b47c6f82acf8b9645ae
aaskorohodov/Learning_Python
/Обучение/Set (множество).py
477
4.15625
4
a = set() print(a) a = set([1,2,3,4,5,"Hello"]) print(a) b = {1,2,3,4,5,6,6} print(b) a = set() a.add(1) print(a) a.add(2) a.add(10) a.add("Hello") print(a) a.add(2) print(a) a.add("hello") print(a) for eo in a: print(eo) my_list = [1,2,1,1,5,'hello'] my_set = set() for el in my_list: my_set.add(el) ...
7e39b989796a5177bff5ea327f1566012aeb5a37
aaskorohodov/Learning_Python
/Обучение/Вывод чисел меньше х.py
189
3.59375
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for elem in a: if elem < 5: print(elem) print([elem for elem in a if elem < 5]) b = 0 while a[b] < 5: print(a[b]) b += 1
32b882820ebdb60f96270d0e908bc0ba2cf559f6
aaskorohodov/Learning_Python
/Обучение/What do U want to eat.py
266
4
4
print("Введите выше имя, затем нажмите Entr") name = input() print(name + ", что вы хотите поесть?") food = input() print("") print(name + ", немедленно идите в магизин и купите " + food + "!")
f1aae24aa9c84713a937dace34fdbda5d367cb50
aaskorohodov/Learning_Python
/Обучение/Думать на языке Питон/Is_sorted.py
292
3.640625
4
a = ['a', 'v', 'a'] b = [1, 2, 3, 5, 4] def is_sorted(lis): i = 0 for el in lis: try: if lis[i] <= lis[i+1]: i = i + 1 else: return False except IndexError: pass return True print(is_sorted(a))
f407b77eda6e4ceaf757b664a2cf0d03ec59337d
aaskorohodov/Learning_Python
/Обучение/Думать на языке Питон/Metathesis pair.py
4,342
4.03125
4
'''Ищет пары-метатезисы – такие слова, где перестановка дищь 2х букв дает другое слово''' file = open('C:\word.txt') words = '' for eo in file: words += eo '''Превращаем файл в строку, где каждое слово идет с новой строки.''' def anagrams(all_words): ''' Ищем анаграмы, собирая их в словарь, где ключ = ...
ffbda9f72900acc80ed03bf871db381d5ce5fc5e
aaskorohodov/Learning_Python
/Обучение/Думать на языке Питон/Avoids.py
2,388
3.8125
4
avoid_ths = input() '''Принимает от пользователя набор стоп-букв''' file = open('C:\word.txt') '''открывает файл с большим количеством слов''' words = '' for eo in file: words += eo words = words.replace('\n', ' ') '''собирает из файла строку со словами через пробел''' def avoids(list, avoid_ths): '''приним...
db236bab002eac619047121dde53949450c3daf6
aaskorohodov/Learning_Python
/Обучение/Dict counter 2.py
680
3.625
4
text = "привет привет привет пока пока здрасьте" my_dict2 = {} for eo in text.split(): my_dict2[eo] = my_dict2.get(eo, 0) + 1 #часть до знака = присваивает словарю ключ, часть справа присваивает значение, при этом... #...get возвращает значение по ключу eo, чтобы ег...
c6bfbae89417c7307e7ff93ea916db38b789ac6c
aaskorohodov/Learning_Python
/Обучение/Классы - наследование.py
857
4.03125
4
class Person: def __init__(self, name, age): self.name = name self.age = age print("Person created") def say_hello(self): print(f"{self.name} say hello!") class Student(Person): def __init__(self, name, age, average_grade): #Person.__init__(self, name, age) ...
9beefaee0cd2529075f223c1e2fb39871d45f24c
bjlovejoy/workoutPi
/challenge.py
5,594
3.515625
4
import os import datetime from time import time, sleep from gpiozero import Button, RGBLED, Buzzer from colorzero import Color from oled import OLED ''' Creates or appends to file in logs directory with below date format Each line contains the time of entry, followed by a tab, the entry text and a newline ''' def lo...
aed5cd14882ef0a82e36f8b3bed9cf81748bd3ae
LeaderRushi/PythonForKids
/basic data.py
455
3.671875
4
# -*- coding: utf-8 -*- """ Created on Mon May 25 11:54:29 2020 @author: giris """ subject_list = ['math', "science", "LASS", "PE"] subject_list.append("music") print (subject_list) subject_list.remove("PE") print (subject_list) subject_list.sort() print (subject_list) teacher_list = ['Harder','Drake', ...
1ce5004cdc178694f616e2ea4eabe0f73c3581b2
riterdba/magicbox
/cl9.py
337
3.984375
4
#!/usr/bin/python3 class Horse(): def __init__(self, name, color, rider): self.name = name self.color = color self.rider = rider class Rider(): def __init__(self, name): self.name = name riderr = Rider('Миша') horsee = Horse('Гроза', 'черная', riderr) print(horsee.rider.name) ...
9de3f927d4cd56dc1f3b0d3397cebad9b61f67a8
riterdba/magicbox
/4.py
426
3.6875
4
#!/usr/bin/python3 #Определение високосного года. x=input('Введите год:') y=len(x) x=int(x) if (y==4): if((x%4==0) and (x%100!=0)): print('Год високосный') elif((x%100==0) and (x%400==0)): print('Год високосный') else: print('Год не високосный') else: print('Вы ввели неправильный...
e0dd4c5a6ead7cd585d9d4cf387e6d4c8849accb
riterdba/magicbox
/cl11.py
283
4.125
4
#!/usr/bin/python3 class Square(): def __init__(self, a): self.a = a def __repr__(self): return ('''{} на {} на {} на {}'''.format(self.a, self.a, self.a, self.a)) sq1 = Square(10) sq2 = Square(23) sq3 = Square(77) print(sq1) print(sq2) print(sq3)
cf0e08f57baf9bb7b3e9a2f27acce377fdf33c1d
mayIlearnloopsbrother/Python
/chapters/chapter_7/ch7b.py
400
3.890625
4
#!/usr/bin/python3 #7-8 deli sandwich_orders = ['ham', 'chicken', 'brocoli'] finished_sandwiches = [] while sandwich_orders: sandwich = sandwich_orders.pop() print("making you a " + sandwich.title() + " sandwich") finished_sandwiches.append(sandwich) print("\n") print("following sandwiches have been made") for ...
9f3e5247a1c58d8c2e625138306b8422bc430afc
mayIlearnloopsbrother/Python
/chapters/chapter_6/ch6a.py
300
4.15625
4
#!/usr/bin/python3 #6-5 Rivers rivers = { 'nile': 'egypt', 'mile': 'fgypt', 'oile': 'ggypt', } for river, country in rivers.items(): print(river + " runs through " + country) print("\n") for river in rivers.keys(): print(river) print("\n") for country in rivers.values(): print(country)
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...