blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
40392333c565f642a9bd0d795dc57cd899409954
KangFrank/Python_Start
/Judgement_loop.py
1,414
3.96875
4
#!/usr/bin/env python3 #-*-coding:utf-8 -*- """ #Judgements age=20/2 if age>=18: print("Your age is %d"%age) print("Your age is ",age) elif age>=8: print("Teenager, your age is ",age) else: print('Your age is %d'%age) #The %d used here is to make the result an integer print('Get away,lit...
71bdc71f499e6ef9b8dc9610e5670aa43ff800f3
mirii-ai/DFESW3
/birds_subclasses.py
1,357
4.0625
4
from abc import ABC, abstractmethod class Bird(ABC): fly = True babies = 0 def noise(self): return "Squawk" def reproduce(self): self.babies += 1 @abstractmethod def eat(self): pass extinct = False class Owl(Bird): def reproduce(self): self.babies ...
dabe2b025c035113c49fa0406677eff69b2233b7
fangpings/Leetcode
/104 Maximum Depth of Binary Tree/untitled.py
794
3.625
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def maxDepth(self, root): if not root: return 0 rootd = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 return rootd def build_tree(l)...
835db71e4e6daf85f698761ba7a77c9f86437ef6
Sergey-Laznenko/Stepik
/Python Programming/1_Operators. Variables/1.12_Tasks_1st_week/5.py
795
4.25
4
""" Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три строки сначала максимальное, потом минимальное, после чего оставшееся число. """ n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 >= n2 >= n3: print(n1) print(n3) print(n2) elif...
6d93455da9505e4e8df2893cce3ee6880bec1881
gabriellaec/desoft-analise-exercicios
/backup/user_299/ch27_2020_04_06_16_37_11_502842.py
201
3.984375
4
duvidas = True while duvidas: temduvidas = input("você tem duvidas?") if temduvidas == 'não': print("Até a próxima") duvidas = False else: print("Pratique mais")
77db6a0822f4195355b481fd9b0a84d1c407d156
JadoRob/NCI-AWS-Restart
/Programming/Exercises/main.py
659
3.96875
4
import os import math from os import system from Programming.Exercises.calculate import calculateGallonPrice, displayGallonsNeeded, caclulateWallArea #Ask user for the length width and height length=int(input('Please enter the length of the room: ')) width=int(input('Please enter the width of the room: ')) height=int(...
a279c8144ba86ed0feab729acc82b8c94d5b5891
Matrixuniverses/AI
/Lab2/LCFSFrontier.py
753
3.671875
4
from search import * class LCFSFrontier(): def __init__(self): self.container = [] def add(self, path): self.container.append(path) def __iter__(self): return self def __next__(self): self.sort_container() value = self.container.pop(0) return value ...
d31ee72e51f015c0f56c6a888d91a7483bc790c9
korchalovsky/python-learn
/sort and search algorithms/binary_tree.py
7,351
3.796875
4
class Leaf: def __init__(self, value=None, left=None, right=None): self.value = value self.left = left self.right = right def min_left_in_right(current_elem): current_elem = current_elem.right while current_elem.left: current_elem = current_elem.left return current_elem...
a0bccfb67a18cd3a01e4fac1e493b74f74c48f7e
mrtbld/practice
/leetcode/125-valid-palindrome/125.py
1,144
3.953125
4
class Solution: # t:O(n), s:O(1) def isPalindrome(self, s): """Return True if given string is a palindrome, False otherwise. Only consider ASCII alphanumeric chars, case-insensitively. >>> Solution().isPalindrome('A man, a plan, a canal: Panama') True >>> Solution().isPa...
ef420579f3470b8335c3f26c38490d519e319b60
tuhiniris/Python-ShortCodes-Applications
/patterns1/alphabet pattern_16.py
419
4.125
4
''' Pattern: Enter the number of rows: 5 A A B A A B C A B A B C D A B C A B C D E A B C D ''' print('Alphabet Pattern: ') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): print(' '*(number_rows-row),end=' ') for column in range(1,row+1): pri...
2e7cdf76cbf5cd22f69c7137874e17b887a14357
velichkosa/gkb_study
/HW/Les1/hw1_2.py
496
4.1875
4
# 2 # Пользователь вводит время в секундах. Переведите время в часы, минуты и # секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. sec= input("Введите количество секунд: ") sec= int(sec) hh= sec//3600 mm= (sec-((sec//3600)*3600))//60 ss= sec%60 print('%(hour)02d:%(minute)02d:%(second)02d' % {"h...
92efea4153f4fd452c2ad4209cda157e1c36fcd4
DenisFuryaev/PythonProjects
/papacode/word_shuffle.py
555
3.65625
4
import re import string def dict_from_str(str): dict = {} for char in str: if char in ',.!?': if char in dict: dict[char] = dict[char] + 1 else: dict[char] = 1 for word in re.split('[ ,.!?]+', str.lower()): if len(word) == 0: ...
b8bc2685a062df699e286019bba4ad3f37ddf3a2
jocelinoFG017/IntroducaoAoPython
/01-Cursos/GeekUniversity/Seção07-Coleções/Tuplas.py
2,280
4.5625
5
""" Tuplas Imutáveis e são representadas por () #cuidado 1: As tuplas são representadas por (), mas veja tupla1 = (1 , 2, 3, 4, 5, 6) print(tupla1) print(type(tupla1)) tupla2 = 1 , 2, 3, 4, 5, 6 print(tupla2) print(type(tupla2)) # CUIDADO 2: Tuplas com 1 elemento tupla3 = (4) # isso não é uma tupla print(tupla3) ...
5fc7e7a7af529ad1045a50ad0cf5aed391b3dea9
devAmoghS/UC-Berkeley-CS61A
/custom_count_method.py
154
3.53125
4
def count(sequence): if not sequence: return 0 else: return 1+count(sequence[1:]) array = [i for i in range(1, 101)] print(count(array))
b30d1bf6d9fc37dc0b5b0b719996c95ac8d91bcc
kelly-gilbert/preppin-data-challenge
/2022/preppin-data-2022-02/preppin-data-2022-02.py
6,169
3.703125
4
# -*- coding: utf-8 -*- """ Preppin' Data 2022: Week 2 The Prep School - Birthday Cakes https://preppindata.blogspot.com/2022/01/2022-week-2-prep-school-birthday-cakes.html - Input data - Removing any unnecessary fields (parental fields) will make this challenge easier to see what is happening at eac...
9ed49fe07a6685a4401b7a9c7c64603e7c8346f1
linfengzhou/LeetCode
/archive/python/Python/two_pointers/parition_array.py
886
3.609375
4
class Solution: """ @param: nums: The integer array you should partition @param: k: An integer @return: The index after partition """ def partitionArray(self, nums, k): # write your code here if not nums or len(nums) == 0: return 0 left, ri...
433506ca5d26ff24f8a4e9abce66732fe0eb8d9e
alzaia/applied_machine_learning_python
/evaluation_metrics/metrics_linear_regression.py
1,407
3.5625
4
# linear regression evaluation metrics on diabetes dataset import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn import datasets from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, r2_score from sklearn.dummy i...
0a3e0998719daba5314a2bbba9114e604a0a3417
buy/leetcode
/python/93.restore_ip_address.py
950
3.578125
4
# Given a string containing only digits, restore it by returning all possible valid IP address combinations. # For example: # Given "25525511135", # return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) import re class Solution: # @param s, a string # @return a list of strings # 11:04 ...
243b84cadc29a40c9a005151203e207cc1ed62c0
iCiaran/hopson-weekly
/week3/main.py
2,117
3.640625
4
from maze import Maze from PIL import Image, ImageDraw from random import random from math import sin,cos from sys import exit def main(): # Super basic config loading config = load_config() width = int(config[0]) height = int(config[1]) border = int(config[2]) length = int(config[3]) diffi...
826d752b55a28b22dc312691579688766fcfa18d
cneal/ProjectWork
/graph.py
5,750
3.5625
4
import numpy as np class Graph(object): """ Une classe generique pour representer un graphe comme un ensemble de noeuds. """ def __init__(self, name='Sans nom'): self.__name = name self.__nodes = [] # Private. Array of nodes self.__num_nodes = 0 # Private. Size of graph ...
d6e0a4089398c8fcbfc850663720d82446b5ca43
sonikku10/3vs5
/untitled/Project Euler #1.py
508
4.65625
5
# ------ print("This program will take a number, x, then add up all multiples of 3 and 5 up to that number and") print("display it.") print("") # ------ # Input x = int(input("Go ahead and enter a positive integer: ")) # Set your current sum my_sum = 0 for i in range(0, x): if i % 3 == 0 or i % 5 == 0: m...
524860c56a8e490fa923a81aeae444b954e7a9a9
Likhi-organisations/100-days
/pattern numbers.py
180
3.671875
4
n=5 x=1 for i in range(1,n+1): for j in range(n,i,-1): print(' ' ,end='') for k in range(1,x+1): print(abs(k-i),end='') x+=2 print()
a6199602fa7912d4be188e2e4b2e5cb62152bd7d
nilsso/challenge-solutions
/exercism/python/pig-latin/pig_latin.py
422
3.9375
4
import re # 1. a vowel (that isn't u) # 2. u if it's proceeded by q # 3. x or y if followed by a consonant p = re.compile("[aeio]|(?<!q)u|[xy](?![aeiou])") def translate_word(word): s = p.search(word).start() return word[s:]+word[:s]+"ay" def translate(text): return (" ".join(map(translate_word, text.l...
2268ef5387bdb0db374fad226d58f5068b99766d
AdityaShidlyali/Python
/Learn_Python/Chapter_12/2_args_with_normal_parameter.py
267
3.546875
4
# *args with the normal parameters def tot_all(num, *args) : # the first '2' from the formal parameter will not be considered as the args it will be considered as the num total = 0 for i in args : total += i print(total) tot_all(2, 2, 2, 2)
1962cddcd2c28af37f3d174c8dbafe7aa6c878be
Easoncer/swordoffer
/栈的实现.py
972
4.125
4
class stacklist: def __init__(self): self.slist=[] self.top=None def push(self,x): self.slist.append(x) self.top=len(self.slist)-1 def pop(self): if len(self.slist)==0: return 'stack is empty!' temp=self.slist.pop() self.top-=1 return temp def isEmpty(self): return True if not len(self.slist)...
fd0f820c96618fc7959f9cf5c006eded6dcc295a
clonbg/Curso-python-Manuel-J-Davila
/ficheros.py
483
3.703125
4
# w escribe y reemplaza si existe # a escribe si no existe y añade al final # r leer fichero = open('fichero.txt', 'w') texto = 'Vamos a escribir una línea' fichero.write(texto) fichero.close() fichero = open('fichero.txt', 'a') texto = '\nVamos a escribir otra línea' fichero.write(texto) fichero.close() fichero = ...
cfd30dd8aee84042558bd87b5b27cd5550cf2759
cecetsui/pygameAndProjects
/cityScroller.py
7,358
4.3125
4
#Import needed modules import pygame import random # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLUE = (0, 0, 255) GREY = (129, 129, 129) colors = [BLACK, GREEN, BLUE, RED] #Helper function : Provides random color def random_color(): return random.choice(col...
c92f4b5edc98427e15770e024765efafc2233240
Balaji0112/System-design-programmer
/Loop_detection.py
744
3.90625
4
class Node: def __init__(self,data): self.data=data self.next=None class LinkedList: def __init__(self): self.head=None def append(self,new_data): new_node=Node(new_data) new_node.next=self.head self.head=new_node def detect_loop(self): s=set() ...
27328a55e926a3c3f1b5695605f3d346221c396c
JackMGrundy/coding-challenges
/common-problems-leetcode/medium/subarray-sum-equals-k.py
2,105
3.953125
4
""" Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note: The length of the array is in range [1, 20,000]. The range of numbers in the array is [-1000, 1000] and the range of the integer k is ...
b2b9038c6ec5060902b93fb90a2abfef362dd5e3
faiqashraf32/PersonalProjects
/Logica/main.py
7,287
4.125
4
class Logica: def start(self): # welcome user print("Welcome to Logica!\n") # seek user input # a,b,c,d,e,f = [],[],[],[],[],[] self.a = [] self.b = [] self.c = [] self.d = [] self.e = [] self.f = [] self.u = [] # universal se...
99120d8b935daca2990959db1686d67bc656a844
btrif/Python_dev_repo
/BASE SCRIPTS/generators.py
3,865
3.96875
4
print('--------------the SIMPLEST POSSIBLE GENERATOR ------------------------') s = 'abc' IT = s.__iter__() # or IT = iter(s) # function returns an iterator object that defines the method __next__() print('IT, function returns an iterator object that defines the method __next__() :\t\t ', IT ) print('next ...
3097a88421e23a48afba0ee24cf33c3059087f41
xibaochat/crescendo_projects
/guess_the_number/baobe.py
664
3.90625
4
def compare_num(): import random random_num = random.randint (0, 10000) try: user_give_number = int (input ('please enter a number:')) except: print ('please enter an integer!') while(random_num != user_give_number): if random_num < user_give_number: ...
a53e0b591ae5a72ae93ddd5d53b4a03dee86bb84
AyrtonDev/Curso-de-Python
/aula09.py
675
4.1875
4
# Aula que trata sobre tratamento de strings frase = 'Curso em Video Python' print(frase[9]) print(frase[9:14]) print(frase[9:21]) print(frase[9:21:2]) print(frase[:5]) print(frase[15:]) print(frase[9::3]) print(len(frase)) print(frase.count('o')) print(frase.count('o',0,13)) print(frase.find('deo')) pri...
963af2ccfcb9feb468d4ad7cc39447976abe868c
hankyeolk/PythonStudy
/sorting/binary search.py
1,210
4
4
# 이분 탐색 ''' 1. 중간 위치를 찾는다 2. 찾는 값과 중간 위치 값을 비교한다 3. 같다면 원하는 값 찾은 것 4. 찾는 값이 중간 값보다 크다면 오른쪽을 대상으로 1번부터 반복 5. 찾는 값이 중간 값보다 작다면 왼쪽을 대상으로 1번부터 반복 * 이분 탐색은 미리 정렬된 리스트의 자료를 가지고만 할 수 있다. ''' # ver1 def binary_search(a, x): start = 0 end = len(a) - 1 while start <= end: mid = (start + end) // 2 if x == a[m...
eed9e3c5784097a60c2a0d6c942303bb1808cfa8
nathanesau/data_structures_and_algorithms
/_courses/cmpt225/practice4-solution/question14.py
407
4
4
""" write an algorithm that gets two binary trees and checks if they have the same inOrder traversal. """ from binary_tree import in_order, build_tree7 def are_equal_in_order(tree1, tree2): in_order1 = in_order(tree1) in_order2 = in_order(tree2) return in_order1 == in_order2 if __name__ == "__main__": ...
c5171d47acad85b24b821a97ff19fd5cf6440953
Ing-Josef-Klotzner/python
/2017/hackerrank/root_with_min_height_(graph_center).py
1,501
4.0625
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- from collections import deque # find root for minimum height to tree (root = graph center) # Graph is an undirected graph with adjacency list representation class Graph: def __init__ (self, V): self.V = V self.adj = [[] for i in range (V + 1)] sel...
609679da2132f8f4f39e85043802a692d33ff7b1
RobertGuerra/Projects
/Edabit Practice Problems/A-G/Find Nemo.py
397
4.09375
4
def find_nemo(sentence): i = 1 sentence = sentence.split(" ") for word in sentence: if word == 'Nemo' or word == 'nemo': return "I found Nemo at {}!".format(i) i += 1 return "I can't find Nemo :(" print(find_nemo('No nemo here!')) def factorial(n): if n <= 1: ...
7b1d357f50a754ab772653d318272421972ddd5e
Sun0921/untutled1
/jump7(1).py
169
3.734375
4
i=1 while i<101: a = int(input("请您输入一个数字:")) if a%7==0 or a%10==7 or a//10==7: print("跳过") else: print(a) i+=1
cd61518d2b2a8c962ff487aa3938e07b8bc474d4
mali44/PythonNetworkScripts
/BruteFoceFTP.py
671
3.53125
4
import urllib, sys import ftplib from ftplib import FTP urllib.FancyURLopener.version = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36' _link = 'ftp.barankaraboga.com' _user = 'testuser@barankaraboga.com' ftp = FTP(_link) f = open('passwordlist.txt','r') x...
89e992ca9f261c8fa9db4f444b1a7f8a7a0c00e6
RohanMiraje/DSAwithPython
/DSA/tree/bst.py
20,814
4.34375
4
import sys class Node: """ Binary tree node with three instance attributes data: holds key/value inserted in node left: reference to left child node right: reference to right child node """ def __init__(self, key): self.data = key self.left = None self.right = None...
0b0968fca112dfc52a74ebd375f67b7a01603785
cicekozkan/python-examples
/is_sorted.py
332
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 29 23:23:28 2014 @author: Ozkan """ def is_sorted(t): """takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise.""" i = 0 for i in range(len(t) - 1): if t[i] > t[i+1]: return False ...
8be23258154a3b4afa793791a205fdf589b44ed8
Eleanoryuyuyu/LeetCode
/python/Backtracking/46. 全排列.py
958
3.53125
4
from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if not nums: return [[]] self.res = [] self.dfs(nums, []) return self.res def dfs(self, nums, path): if len(path) == len(nums): self.res.append(path) ...
f88c4ef601c3dc1fe71e8b22bd01d618b7ebe7a5
benjamin22-314/codewars
/data-reverse.py
478
4.03125
4
# https://www.codewars.com/kata/data-reverse def data_reverse(data): list_of_lists = [] for l in range(int(len(data)/8)): list_of_lists.append([data[d] for d in range(l*8, l*8 + 8)]) return [a for b in list_of_lists[::-1] for a in b] # tests data1 = [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1...
cd2ee8b63cde2545b7848e58b320c06fea840776
TomekPk/Python-Crash-Course
/Chapter 7/7.10.Dream Vacation/dream_vacation.py
757
4.28125
4
''' 7-10. Dream Vacation: Write a program that polls users about their dream vacation. Write a prompt similar to If you could visit one place in the world, where would you go? Include a block of code that prints the results of the poll. ''' question = "If you could visit one place in the world, where would you go?" qu...
c211fda0ac255cd8d9777c70abd78e158bf5e7bd
UX404/Leetcode-Exercises
/#746 Min Cost Climbing Stairs.py
1,299
4.09375
4
''' On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: c...
1b4acf8d493dc9bc4c337444fb7937f3502922b7
Mr-ZDS/Python_Brid
/Leetcode/L392 判断子序列.py
916
3.578125
4
''' 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 示例 1: s = "abc", t = "ahbgdc" 返回 true. 示例 2: s = "axc", t = "ahbgdc" ''' class Solution: def isSubsequence(self, s: str...
726a4f920ad0ebd5ffcb15b463ccfd0ea65d4a67
yatengLG/leetcode-python
/question_bank/insertion-sort-list/insertion-sort-list.py
1,052
3.8125
4
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:160 ms, 在所有 Python3 提交中击败了94.60% 的用户 内存消耗:15.3 MB, 在所有 Python3 提交中击败了7.93% 的用户 解题思路: 见代码注释 """ class Solution: def insertionSortList(self, head: ListNode) -> ListNode: result = ListNode(float('-inf'), next=head) r = result # 指针r.next指向当前节点 ...
373e18e363c5fcb3d1510d8ac22ee12523f23414
titf512/FPRO---Python-exercises
/sum_dictionaries.py
267
3.78125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 14 09:15:34 2021 @author: teresaferreira """ def sum_dicts(lst): dic=dict() for i in lst: for key,value in i.items(): dic[key]=dic.get(key,0)+value return dic
ffe35ed4b1346d6fd6293261e457363ea28238d8
christiancyint/python_crashcourse
/chapter3/3_bicycles.py
396
4.4375
4
# Chapter 3 practicing lists in Python # You can access values in a list by specifying their index, which starts at 0. bicycles = ['trek', 'cannondale', 'redline', 'specialized'] print bicycles[0].title() print bicycles[2].title() print bicycles[-1].title() # Values in an index can be used like any other variable me...
872dd8a6489062e83409d23100938ef8cb421837
katiebug2001/project-euler
/highly_divisible_triangular_number.py
3,596
4.21875
4
import unittest import math def factor(num): """returns ALL (not just prime) factors of a number""" limit = int(math.sqrt(num)) factors = [1] if num > 1: factors.append(num) if limit > 1: if num/limit == limit: factors.append(limit) elif num % limit == 0: ...
6874a8fc7f288dc0bed8be071dad175dfea667bc
daniel-reich/ubiquitous-fiesta
/sKXWQym3xg6uBLrpY_0.py
374
3.515625
4
def iqr(lst): lst = sorted(lst) first_half = lst[:len(lst) // 2] second_half = lst[-(-len(lst) // 2):] first_half_median = (first_half[len(first_half) // 2] + first_half[~(len(first_half) // 2)]) / 2 second_half_median = (second_half[len(second_half) // 2] + second_half[~(len(second_half) // 2)]) /...
8d8fe9bf85798a4ff157387081f6d7d0dbd19e6b
AsanakaF/tasks4sm
/laba2.py
177
3.5625
4
koren = float(input('Enter number: ')) a = 0 x = 0.5 * (1 + koren) while a * a - abs(koren) > 0.01 or a * a - abs(koren) < -0.01: a = 0.5 * (x + koren / x) x = a print(a)
6f405b653a7170f946f5867a50c12763d0379ad2
KivyAcademy/Kivy_training
/basic/03_custom_app.py
1,046
3.546875
4
# -*- coding: utf-8 -*- ## https://kivy.org/doc/stable/guide/basic.html#quickstart from kivy.app import App import kivy kivy.require('1.10.1') ## This class is used as a Base for our Root Widget (LoginScreen) defined later from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label from kivy.uix.textin...
52d4022e10c0bcdc12545bfd3db1d836a15714b4
chin8628/Pre-Pro-IT-Lardkrabang-2558
/Prepro-Onsite/W5_D2_CallSum.py
653
3.625
4
""" W5_D2_CallSum """ def main(limit, step, total=0, index=1): """ this is a main function """ if limit == 1: return 1 elif step > 0 and limit > 1 and index <= limit: return main(limit, step, total + index, index + step) elif step < 0 and limit < 1 and index >= limit: return main...
b46e32ac6c9d72854994a41af8c86a86e4df6fe6
KyoungSoo1996/python-coding-practice
/python project/This is Coding Test/DFS.py
470
3.5
4
#그래프 DFS 구현하기 graph = [ [], [2,3,8], [1,7], [1,4,5], [3,5], [3,4], [7], [2,6,8], [1,7] ] checked = [False] * 9 answer = [] def DFS(graph, checked, currentPos): answer.append(currentPos) if not checked[currentPos]: checked[currentPos] = True for i in graph[cu...
18c1b93743fa8979f4af98f50c4c732dfec5f9d1
sonam2905/My-Projects
/Python/Exercise Problems/full_binary_tree_preorder_postorder.py
2,139
4.21875
4
# Python3 program for construction of # full binary tree # A binary tree node has data, pointer # to left child and a pointer to right child class Node: def __init__(self, data): self.data = data self.left = None self.right = None # A recursive function to construct # Full from pre[] and post[]. # preInde...
a235690ed6710748ccb66eb3257aa2e2c3197db2
viveknathani/pps-labwork
/31-03-20/modules/fib.py
329
3.5625
4
def fib(n): if n<1: return -1 elif n==1: return 1 elif n==2: return 1 else: return fib(n-1)+fib(n-2) def fib_series(m): series=[] for var in range(1, m+1): x=fib(var) if x==-1: break else: series.append(x) retur...
0ac7d5fefdeea3c97a0c42002e0562eb45d48a7a
KatiraOrellana/CienciaDatos
/Laboratorio2/.ipynb_checkpoints/FuncionTupla-checkpoint.py
591
3.765625
4
import sys def main(): try: elementos = sys.argv[1] lista = [] a = 1 while a <= int(elementos): valor = input('Ingrese registro {}: '.format(a)) lista.append(valor) a = a+1 salida = '' for a in lista: salida = salida + ...
89ac4b1185b80c089458c10a62992a9cd9470526
gmr50/exec-dash-project
/exec_dash_revisited.py
1,314
3.65625
4
import pandas as pd def to_usd(input): result = "${0:,.2f}".format(input) return result def get_top_sellers(worked_data): #deal with item list counter = 0 item_list = [] sales_list = [] total_sale = 0 overall_total_sales = 0 for index, row in worked_data.iterrows(): overall_total_sales = overal...
e07b146c23cf354fa9de566bdddd6c4554451282
ViniciusQueiros16/Python
/PythonExercicios/ex113.py
899
3.921875
4
def leiaint(num): while True: try: valor = int(input(num)) except (ValueError, TypeError): print('\033[31mERRO! Digite um número inteiro válido.\033[m') except KeyboardInterrupt: print('O usuário preferiu não digitar esse número.') return 0 ...
66462fbdcb604a7c730540fca0002e69b996d643
nvkwo3314200/pyTest
/com/study/17/12-.py
619
3.765625
4
#coding=utf-8 ''' Created on 2018年9月6日 @author: Pan ''' def tester(start): state = start def nested(label): nonlocal state print(label, state) state += 1 return nested F = tester(0) F("spam") F("ham") F("eggs") G = tester(43) G("spam") G("ham") F("bacon") #边界情况 ''' def tester(s...
8a51cdfe45dc52ec23e8e793d41aaea6fa8d4ade
Voronica/CS_1134
/hw3/sz2417_hw3_q2.py
2,772
3.734375
4
import ctypes def make_array(n): return (n * ctypes.py_object)() class ArrayList: def __init__(self): self.data_arr = make_array(1) self.n = 0 self.capacity = 1 def __len__(self): return self.n def append(self, val): if self.capacity == self.n: self...
63ad5bd197c0c9c26d7a1ba16e278578c3c6b87a
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/chktak002/push.py
3,907
4.25
4
def push_up (grid): """merge grid values upwards""" for i in range (3): for row in range(1,4): for col in range(4): if grid[row-1][col] == grid[row-1][col] ==0: grid[row-1][col] = grid[row][col] #Make the item in the row below equal the curr...
282ff700d555884a480812d5265bb99f7c048ef6
Georges1998/MealCare
/backend/scripts/setup_db.py
1,132
3.515625
4
# Script to create a Database, User/Role with Password, and grant all privileges on Database import psycopg2 from psycopg2 import sql from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT try: con = psycopg2.connect(dbname="template1") db_name = sql.Identifier("mealcare_dev") db_test_name = sql.Ident...
2e96414fc1eddb9d58a961b8b8c4daf549722fca
AssiaHristova/SoftUni-Software-Engineering
/Programming Basics/conditional_statements/fuel_tank.py
271
4.0625
4
fuel = input() liters = int(input()) if fuel == 'Diesel' or \ fuel == 'Gasoline' or \ fuel == 'Gas': if liters >= 25: print(f'You have enough {fuel}.') else: print(f'Fill your tank with {fuel}!') else: print(f'Invalid fuel!')
97e0ab09685126863f7b7874d7660fd1ecaf27c5
DrEaston/CodingNomads
/labs/13_aggregate_functions/13_03_my_enumerate.py
406
4.125
4
''' Reproduce the functionality of python's .enumerate() Define a function my_enumerate() that takes an iterable as input and yields the element and its index ''' def my_enumerate(iterable): count = 0 output = [] for item in iterable: count += 1 output.append((count, item)) return out...
cfcfc9efba2ab93678df517eac6104e3dd4bea68
tom1mol/python-fundamentals
/indexing and lists/list2.py
1,448
4.3125
4
fruits = ["apple", "banana", "peach", "pear", "plum", "orange"] counter = 0 while counter < len(fruits): print(fruits[counter]) counter += 1 # OUTPUT: # Python 3.6.1 (default, Dec 2015, 13:05:11) # [GCC 4.8.2] on linux # apple # banana # peach # pear # plum # orange # NOTES: # Here ...
0ec4208b74f5b970c3e580346215088b3f24c1f6
Raushan117/Python
/029_Rename_Filename_Date_Format.py
2,097
3.53125
4
# https://automatetheboringstuff.com/chapter9/ # Project rename files with American style dates to Eurpoean style dates # American style = MM-DD-YYYY # European style = DD-MM-YYYY # Write program that will handle it for you :) # Step 01: Search all the filesname in current working directory for AM style # Step 02: W...
2b3579c5ca13c5b9f9386fe46770d8423c755632
lydxlx1/LeetCode
/src/linked-list-in-binary-tree.py
1,271
3.765625
4
"""1367. Linked List in Binary Tree It is hard to solve the problem in a top-down fashion since each tree node can have two choices. However, since each node has a unique parent, the upwards paths ending at any node are also unique (by its length). This suggests a DFS approach, where we just need to check whether the ...
fda905fe3749cc743490f832440692d0cd9bee96
Shaileshsachan/Machine_Learning
/data_preprcossing.py
1,536
3.609375
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.impute import SimpleImputer dataset = pd.read_csv('data.csv') x = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values imputer = SimpleImputer(missing_values=np.nan, strategy='mean') imputer.fit(x[:, 1:3]) x[:, 1:3] = imputer.tr...
9609e4c0ac1261c24163a4b37fed90735a086b3e
pylarva/Python
/day2/shopping_cart/shopping_chart.py
4,487
3.703125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:lichengbing import sys, time def shopping_home(user_name,salary): FLAGE_A = True shopping_car = [] while FLAGE_A: product_dict = { '家电类':[('乐视TV',1999),('海尔冰箱',1500)], '数码类':[('Mac Pro',9888),('iphone',5888)], ...
b673803b73d1ccf30151bd61b48fad0f8f796cb6
hrishitelang/100-days-of-python
/Day 29/main.py
3,279
3.671875
4
from tkinter import * from tkinter import messagebox import random import pyperclip # ---------------------------- PASSWORD GENERATOR ------------------------------- # def generate(): letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', '...
91359afece49e2aa34f686c2ea6f8d5d39319f00
gahakuzhang/PythonCrashCourse-LearningNotes
/9.classes/9.1.2 dog.py
1,273
4.71875
5
#9.1.2 making an instance from a class 根据类创建实例 # accessing attributes 访问属性 class Dog(): """a simple attempt to model a dog""" def __init__(self,name,age): """initialize name and age attributes 初始化属性""" self.name=name self.age=age def sit(self): """simulate a dog sitt...
fbd421dc8e8edc5cc16a3d1857c53a0a6bf00dfc
Veterun/Interview-1
/language/python/note.py
3,407
4.34375
4
#comparison chaining testing whether a number is the largest of three: a < x > b a == b < c actually means a == b and b < c in python! ****************** str.join(iterable) #Return a string which is the concatenation of the strings in the iterable iterable ex : ["->".join(["22","33","11"])] ['22->33->11'] ********...
35944d653998cddab0a3e4a228b853f0f864124f
juliadejane/CursoPython
/ex017.py
179
3.625
4
import math c1 = float(input('Qual é a medida de um cateto? ')) c2 = float(input('Qual é a medida do outro cateto? ')) print('A hipotenusa é {:.2f}'.format(math.hypot(c1, c2)))
ecad01e55c18479cbee5aff3242b78dceab4091e
Success2014/Leetcode
/maximumDepthofBirnaryTree.py
1,386
4
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 22 12:52:21 2015 Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Tags: Tree Depth-first Search Similar Problems (E) Balanced Binary Tree (E) Minimum Depth of...
75b50501d33d3a2ecc33d28e4c10008a8f9ea6c8
smiroshnikov/ebaPo4tu
/haim/lecture3/practice3.py
1,247
4.09375
4
import fractions a = 3 b = 4 print("hello" if b > a else "salam") print('haifa' if b > a and b > 0 else 'ramat gan') print(109 if a > b else "rehovot") print("tel aviv" if 'a' in 'abcd' else 'noope') print('blue ' if 'b' not in "moish" else "red") print('winter ' if a > 2 and a % 2 == 1 else "summer") print(123 if 'y...
b7a4e06cd313134bba3d7914d06c545f0feb9535
mayankmahajan/datavalidation
/learnPython/passwordGenerator.py
982
3.90625
4
import random def generatePassword(strength): lowerCap = False upperCap = False numChar = False specialChar = True password = '' while True: randomInt = random.randrange(32,126) if randomInt in range(48,58): numChar = True password = password + chr(rando...
4943e3a4e1052cf99184daa0dd613c99c4713de3
SociallyAwkwardTurtle/Python
/kilpkonn.py
282
3.765625
4
#Karolina 10IT from turtle import* col = input("What is your favourite colour? ") side = input("How long should the side be? ") color(col) begin_fill() forward(int(side)) left(90) forward(int(side)) left(90) forward(int(side)) left(90) forward(int(side)) end_fill() exitonclick()
140d044640b7a648fb5f8a610c5ba81adf1e4020
stasi009/FDSA
/hanoi_tower.py
1,698
4.21875
4
 def __move(N,frompole,topole,withpole): """ plate 1~N are on from pole we are going to move plate 1~N from 'frompole' to 'topole' via 'withpole' """ if N == 1: print "%d: %s ==> %s"%(N,frompole,topole)# move directly else: __move(N-1,frompole,withpole,topole) print "%d:...
21481840664b9b9eff9f9fb4e6a2781d6a3aa6f2
stalnaya/H__W
/task_01_01.py
92
3.640625
4
y=int(input()) if ((y%4==0) and (y%100 != 0)) or (y%400==0): print ('yes') else: print('no')
49eee157f074aeb05e323bf592ebc4e05ecb39fc
chhenning/python_tutorial
/Advent Of Code/2018/8/solution_2.py
870
3.5
4
# %% input = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2' with open('8/input.txt') as fp: input = fp.readline() it = map(int, input.split()) counter = 0 def parse(it): global counter num_childs, num_meta = next(it), next(it) name = chr(ord('A') + counter) counter += 1 childs = [parse(it) for c...
55ed781220297c41bfd9ddc6de6e4a6bf195f989
txjzwzz/leetCodeJuly
/Decode_Ways.py
1,205
4.03125
4
#-*- coding=utf-8 -*- __author__ = 'zz' """ A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encoded message "12", it could be d...
06cf5e2c10cbb82b026f6eb33e2462c535f3a1b9
trangnguyen1010/python
/functions.py
2,233
3.703125
4
import random from collections import namedtuple global connection, cursor import sys def luhn_algorithm(acc_number): acc_number = list(map(int, str(acc_number))) for i, _ in enumerate(acc_number, 1): if i % 2 != 0: acc_number[i-1] *= 2 if acc_number[i-1] > 9: a...
d26edaccbd046da13fe6d69a578c235769055b32
rishi772001/Competetive-programming
/Algorithms/Dynamic Programming/01 knapsack.py
960
3.640625
4
''' @Author: rishi https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/ ''' def knapsack(totweight, wt, val, n): """ :param totweight: total weight of knapsack :param wt: weight array of items :param val: values array of items :param n: number of items or len of wt or val """ dp = [[0...
aa1f63db7444dcdfe7d5e894bdbf02c36c01a874
shrenik-jain/HackerRank-Solutions
/1.Python/05.Math/002.FindAngleMBC.py
322
4.0625
4
''' Question : You are given the lengths AB and BC. Your task is to find angle MBC (angle theta, as shown in the figure) in degrees. Link : https://www.hackerrank.com/challenges/find-angle/problem ''' import math a = int(input()) b = int(input()) print(round(math.degrees(math.atan(a/b))), u'\N{DEGREE SIGN}' , sep=''...
60feef496ed09e8c327ca1753229dba5cf1a66f1
chanmile/Cryptography
/fermat_factorization.py
1,253
4.4375
4
# # Fermat's Factorization Method # # Author: chanmile ''' Fermat's Factorization method relies on the following equation: N = a^2 - b^2 = (a+b)(a-b) If (a+b) != 1 and (a-b) != 1, then N has been factored. Starting at a = sqrt(N), we will compute various values of b^2 using b^2 = a^2 - N ...
c37dc6c4343d633be027a5c0e74822e851451ae9
Panuvat-Dan/100-Day-project
/day2/Day2-tip-genarator.py
734
4.15625
4
# Greeting users print("Welcome to the tip calculator") individual_pay = 0 while individual_pay >= 0 : # to ask user the total bill total_bill = input("What was the total bill?: ") # to ask percentage tip percentage_tip = input("What was your tip would you like to give? 10 or 12 or 15%: ") # to ask the nu...
71c72c92b258285239ea15db1de67bff49254bbe
lucas-deschamps/tiny-python-PoC
/numerosprimos_trabalho.py
716
4.09375
4
# a small program that prints out all prime numbers in a user-defined range. # written for a college assignment. numeros_primos = [] numero_inicial = int(input("\nDigite o número inicial: \n")) numero_final = int(input("Digite o número final: \n")) range_primos = range(numero_inicial, numero_final) print(f"\n\t\t\t[N...
5402068009616069a4f436d2ddd990bdb1aed7c6
rosauraruiz-lpsr/class-samples
/chooseHaiku.py
498
3.9375
4
# Opens the haiku 3 and 4 myThirdHaiku = open('haiku3.txt', 'r') myFourthHaiku = open('haiku4.txt', 'r') # Welcomes you and gives you options print("Hi, welcome to the Haiku Reader!") print(" 3 For a haiku about a silly person. ") print(" 4 For a haiku about writing haiakus. ") response = raw_input() # It will print ...
46fc2c7caeb690e77e9d38aa849612a16e64c359
shamanengine/HackerRank
/src/18_stuff/task01.py
247
3.59375
4
''' Sum all 2-digit numbers from the sequence ''' arr = list(map(int, input().strip().split())) print(sum([x for x in arr if (10 <= x <= 99) or (-99 <= x <= -10)])) ''' Input 1 2 3 11 322 20 9989 99 1 2 3 11 322 20 9989 -99 Output 130 -68 '''
3dfee1aeb967e714860bc24630e4793001023aef
WeeJang/basic_algorithm
/LinkedListCycle.py
779
3.953125
4
#!/usr/bin/env python2 #-*- coding:utf-8 -*- """检测环,快慢指针 """ """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param: head: The first node of linked list. @return: True if it has a cycle, o...
d516acdb263862143336541eaed3d8ca03e6c2ea
kstager/Python300-SystemDevelopmentWithPython-Spring-2014
/week-06/datetime/examples/datetime_naive_to_sqlite.py
1,158
3.96875
4
import datetime import itertools import sqlite3 import pytz """Dates and times in sqlite3 are stored as TEXT, REAL, or INTEGER values TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregor...
42cc260b3b53e13ef8f99713a53e55c056ae6e84
danielgu88/bill-splitter
/stage2.py
525
4.125
4
list_of_friends = [] friends_dict = {} friends = int(input("Enter the number of friends joining (including you):\n")) if friends >= 1: print("\nEnter the name of every friend (including you), each on a new line:") for i in range(friends): list_of_friends.append(input()) print("\nEnter the total ...
a895728f18ef4173e12440ce680c04205882d878
prajjaldhar/basic_python
/basic_python/09_dictionary.py
1,002
3.9375
4
#indexed #mutubale #unordered #must have unique keys mydict={ "fast":"car", "mahatma":"Gandhi", "knowledge":"vivekenand", "pacer":"cheeta", "captain":"prajjal", "honest":"harsihchandra", "marks":[1,3,5], "anotherdict":{"brothers":"Prajjal,Abhra,Shubra"}, "anothertuple"...
10244dfc2865dd651b03225b0d3e41f190195019
shuzhancnjx/leetcode-
/Programming-Algorithm/Jump_Game_II.py
1,771
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 21 14:55:13 2015 @author: ZSHU """ """ recursive and greedy, but too many recursive steps and over the limit """ nums = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,...
f1789b8d178f5a4dfc646d0bdc648f5fd610cf79
FatalTsai/Data-Structures-and-Algorithms
/Data Structures/Graph/BFS.py
397
3.859375
4
import collections def BFS(g, r): visited = set() queue = collections.deque([r]) while queue: v = queue.popleft() print(v) for nbr in graph[v]: if nbr not in visited: visited.add(nbr) queue.append(nbr) if __name__ == "__main__": gra...
3af5c6a803ae19375ead94f947238231ca57a2b5
UKDR/eng57_2
/Week_3_Python/Exercises/102_more_strings_variables.py
698
4.09375
4
# Practice strings # Welcome to Sparta - exercise # Version 1 specs - with concatenation # define a variable name, and assign a string # prompt the user for input and ask the user for his/her name # re assign the original variable this this input # use concatenation to print a welcome message and use methods to form...
26f9468d089f17977f201176ae635f00567b4219
jemcghee3/ThinkPython
/06_11_exercise_4.py
698
4.21875
4
"""Exercise 4 A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case.""" def is_power(a, b): if a < 0 and b < 0: # to take care of negative...
7ce76a9af58986a37151e63036edf1da66f33f39
Nishantballa16/ATM_program_python
/ATM Project/atmdemo.py
1,053
3.53125
4
#atmdemo.py---main program from atmmenu import menu from bankexcep import DepositError,WithdrawError,InSuffFundError from bankoperations import deposit,withdraw,balenq import sys while(True): try: menu() ch=int(input("Enter Ur Choice:")) if(ch==1): try: deposit() except DepositError: p...