blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
09edd262401ff7625c07393136a0cc1ff8df7391
Algar487/Iniciacion-a-la-programacion-con-Python
/Alejandro Python/Calculadora.py
772
4.15625
4
operacion = input("¿Qué operación quieres realizar? (Multiplicar/Dividir/Sumar/Restar): ").upper() primer_numero = int(input("Ecribe aquí el primer número: ")) segundo_numero=int(input("Ecribe aquí el segundo número: ")) if operacion== "MULTIPLICAR": resultado=primer_numero*segundo_numero elif operacion=="DIVI...
06ab9c93ad3ca076faacb09c96564d0a94bf1679
renan-suetsugu/Livro_Introdcao-programacao-com-Python_Nilo-Ney
/Exercício_3_9.py
667
3.859375
4
# Escreva um programa que leia a quantidade de dias, horas, minutos e segundos do usuário. # Calcule o total em segundos. SEGUNDOS_EM_MINUTOS = 60 MINUTOS_EM_HORAS = 60 HORAS_EM_DIAS = 24 dias = int(input("Entre com a quantidade de dias a serem convertidos: ")) horas = int(input("Entre com a quantidade de ...
7ddb8e9d8a463cfbd2845f64098ece0cef4a3c97
tjturnage/satellite
/lightning.py
6,632
3.765625
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 15 10:21:20 2019 @author: tjtur """ def make_cmap(colors, position=None, bit=False): """ Creates colormaps (cmaps) for different products. Information on cmap with matplotlib https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipula...
1de92919ffe15f5d915a59526d58223957eb0143
xywgo/Learn
/LearnPython/Chapter 3/motorcycles.py
1,059
3.921875
4
motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') # motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) # motorcycles[0] = 'ducati' # print(motorcycles) # motorcycles.append('ducati') # print(motorcycles) # motorcycles.insert(0, 'ducati') # print(motorc...
4963369aed33a05ccf3abb1a003406cf8b5545a8
manimaran1997/Python-Basics
/ch_08_OOP/Projects/ch_03_Methods/ch_01_Regular Methods With Self/Regular+Methods+With+Self.py
617
3.71875
4
# coding: utf-8 # In[1]: class Employee : #this is class variable employeeCounter = 0 #constructor def __init__(self,firstName,lastName): self.firstName =firstName self.lastName = lastName Employee.employeeCounter += 1 #normal or regular method and the first parameter is ...
643a6d34f4752dfebf802ae14b6e2b4cf325bfd9
itsolutionscorp/AutoStyle-Clustering
/assignments/python/series/src/155.py
277
3.65625
4
def slices(digits, n): """Get all possible consecutive number series of length n in a string of digits""" if n > len(digits) or n == 0: raise ValueError digits = map(int, digits) return [digits[i:i+n] for i in range(0, len(digits)-n+1)]
5f9414ad84c72994c01811d808eeb05e1d7a151f
slopey112/intro_to_python
/review/ps1/problem12.py
88
3.578125
4
l = list(range(34)) for i in l print(i) else (i + 3) % 3 == 1: print(i)
63492d0047b3d413e3ca0f38b1cee2ef364f14b2
wasiwasi/pycote
/ch11_greedy/11-6.py
2,447
3.59375
4
# 무지의 먹방 라이브 # 기본답 # def search_index(food_times, index): # while food_times[index] == 0: # index += 1 # return index % len(food_times) # def solution(food_times, k): # answer = 0 # i = 0 # for _ in range(k): # if food_times[i] != 0: # food_times[i] -= 1 # ...
9e4a0e3d3a3a8a37750297c27ee1a0ddb8b781ec
nirajann/workshop
/lab1/exercise8.py
344
4.15625
4
""" write the python program which accepts the radious of a circle from the user and complete the area . area of circle = pi * r **2 """ radious_of_circle = int(input("enter the raidous of circle")) pi = 3.14 radious_square = radious_of_circle ** 2 area_of_circle = pi * radious_square print(f"the radious of circl...
428e1996c9e085e752cf1471e21761769940295b
jvpb/PYTHON3
/CAPITULO8/capitulo8.py~
162,646
3.515625
4
#!/usr/bin/env python3 '''tecnicas avanzadas de programacion''' # importar modulo import sys print ('VERSION en uso de PYTHON\n') print (sys.version,'\n') print ('¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬¬\n') print ('bifurcacion con diccionarios \n') print ('c...
f9504f2aa05b3046795474cb206acb56a6614a39
shreeji0312/learning-python
/python-Bootcamp/assignment5/assignment5_solutions/2dlistAssign3.py
1,710
3.859375
4
# WPCC from random import randint # 30x30 list that holds a 'X' where a tree is, and '_' where there's no tree backyard = [] for i in range(30): l = [] for j in range(30): l.append('_') backyard.append(l) # 10x2 list that holds all coordinates for the 10 trees we're going to plant trees = [] for i...
fd61ad8c1639173b0d708193fcb8d3053e0c433b
b1ueskydragon/PythonGround
/leetcode/p0088/merge_sorted_array_inplace.py
824
3.734375
4
class Solution: def merge(self, nums1: [int], m: int, nums2: [int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ if m == 0 and n != 0: # edge case? nums1[0] = nums2[0] k = m + n - 1 # rightmost index of zero that can hold an el...
d3031bcb6dcc6ea6d609a00373597199692833c7
jakubbaron/advent_of_code
/2019/day_4/main.py
1,745
3.796875
4
# --- Day 4: Secure Container --- # You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out. # However, they do remember a few key facts about the password: # It is a six-digit number. # The value is within the ran...
d4ccc9f6702dc0ddb9baa047f9bef379175f72d3
SimonSlominski/Data_Science
/03_Computer_Vision_OpenCV/05_bitwise_operations.py
952
3.546875
4
import cv2 import imutils # Load imgages and change the logo shape img = cv2.imread('images/view.jpg') logo = cv2.imread('images/python.png') logo = imutils.resize(logo, height=150) # Show both images # cv2.imshow('img', img) # cv2.imshow('logo', logo) # Cut Region of Interest rows, cols, channels = logo.shape roi =...
7ad62f7a04beebf792280e1bf7fa1e667c2bc527
rafa3lmonteiro/python
/python3-course/aula09/aula09-desafio22.py
571
4.21875
4
# Crie um programa que leia o nome completo de uma pessoa e mostre: O nome com todas as letras # maiúsculas e minúsculas - Quantas letras ao - todo sem considerar espaços - # Quantas letras tem o primeiro nome. nome = str(input('Digite o seu nome completo: ')) print('Nome:',nome) print('Nome Maiusculo: {}'.format(nom...
b1cd2a546373842963e40dce9dcd7b997873ad1a
KamozZze/Programming0
/week1/1. IO-Simple-Problems/names.py
189
3.78125
4
# names.py first_name = input("First name? ") second_name = input("Second name? ") third_name = input("Third name? ") name = first_name + " " + second_name + " " + third_name print(name)
83c93adadf9113f467c23cfa70ae1ec977813e91
joningehe/ITGK_Oving
/Eksamen/host_2015.py
2,112
4.1875
4
#Oppgave 3 #a) def readTime(): hours = int(input('Enter hours: ')) while not hours < 24: print('Error: Hour must be between 0 and 23!') hours = input('Enter hours: ') minutes = int(input('Enter minutes: ')) while not minutes < 60: print('Error: Minute must be between 0 a...
f616d756865ec0ea43649ee3d1e01cfee322fbdc
rudra0008/python
/1arg.py
427
3.796875
4
#!/usr/bin/python -tt def hello(name): print"program entered hello() function" var1="hello"+name print"program leaving hello() function" return var1 print"this live will not be printed" def main(): name="tinku" print"program calling hello() function" str1=hello(name) print"program execution returned back to m...
c4c2cc2bf2a84e307a7e6332c36958391b853364
ntien/CminusCompiler
/enumeratePossibleConcreteTrees.py
3,228
3.703125
4
#format of data structure is: # {"name_of_rule": ["first_rule", "second_rule", ... , "last_rule"], "name..." : [...]} # format of auxiliary list: # ["name_of_rule", "name_of_rule", ... , "name_of_rule"] --the index of the name is the rule's number import re import json def build_concrete_trees(rules_dict, start, vis...
0144c33d4dd756cc7c1aeb4a441f709a3f08416d
rafabermudez16/primer-programa-python
/uuu/caracter.py
258
3.546875
4
#caracter# mensaje=input("Escribe alguna frase:\n \n") print("Tu frase es:\n \n",mensaje) var2=int(input("escribe el caracter a visualizar (numerico):\n \n")) print("caracter :","\n",mensaje[var2]) input("Pulse cualquier tecla para continuar....")
736d298e7a24fe58950c37b9d36305ace756fa4d
ThomasSeaver/ProjectEulerSolutions
/023.py
2,181
3.828125
4
import math # keep track of our abundant numbers abundantNums = [] # build a list of abundant numbers < 15000, because we know by mathematical # analysis that every number > 28123 can be summed from two abundant numbers, # so we just have to check up to 15000 for potential half of sums for i in range(1, 15000): #...
e089b6b4fcf57dc26e8b18ed23dce3bfe0e99916
BoyanH/Freie-Universitaet-Berlin
/OOP/Python/PythonOOPExercise/decideColor/decideColor.py
1,506
3.65625
4
from turtle import * import math class ColourfulSquare: def __init__(self, x, y, size): self.coords = (x,y) self.sideLength = size def getIncrementedCoords(self, numberToAdd): return (self.coords[0] + numberToAdd, self.coords[1] + numberToAdd) def isUnderDiagonal(self, coords): xSideLength = coords[0]...
54dd65cf337e1383ee913e86b792495b2c766be2
remixknighx/quantitative
/exercise/leetcode/running_sum_of_1d_array.py
455
3.71875
4
# -*- coding: utf-8 -*- """ 1480. Running Sum of 1d Array @link https://leetcode.com/problems/running-sum-of-1d-array/ """ from typing import List class Solution: def runningSum(self, nums: List[int]) -> List[int]: result = [] last_sum = 0 for num in nums: last_sum += num ...
587ef2b23c841a88fc244a4eae37a2101b595be3
MadhaviSattiraju/Python-coding
/fibno.py
159
3.71875
4
def fib(n): a=0 b=1 print(a,b,end=" ") i=2 while i<n: c=a+b print(c,end=" ") a=b b=c i+=1 fib(10)
01d397338c1c8fa9c318ca6ef1e32fa0c2d9fc3e
SpadinaRoad/Python_by_Examples
/Example_023/Example_023.py
1,638
4.53125
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- # To run in terminal # $ cd /home/james/Documents/Edoc/3Nohtyp/Python_By_Example/Example_023 # $ python3 Example_023.py # $ python3 Example_023.py <Input.txt >Output.txt """ Python by Example: Learning to Program in 150 Challenges by Nichola Lacey 023 Ask the user to type i...
3bcb59cfee428aff8c5afe74795be8fd4bf59764
RainhugTiny/commom_algorithm
/binary_search_insert.py
1,580
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def binary_search_insert(nums, value): l, r = 0, len(nums) - 1 while l <= r: """ 最后一次循环、l与r一定相等。因此m与l、r相等。 若待插入值value大于nums[m],l应该加一,则value插入到l的位置,就是nums[m]后面的位置, 若待插入值value小于nums[m],r应该减一,则value插入到l的位置,就是nums[m]现在的位置,即插入之后nums[m]之前的...
8debcf6c5d45a715eecb2c29c20071de84ed6be5
Aliena28898/Programming_exercises
/CodeWars_exercises/Even or Odd.py
401
4.125
4
''' Create a function that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers. ''' #SOLUTION: def even_or_odd(number): if number % 2 == 0: return "Even" else: return "Odd" #TESTS: test.expect(even_or_odd(2) == "Even") test.expect(even_or_odd(0) == "...
38b05517f6fa16b03ae7ff53ac1bf81b0c6b57eb
tuzianna/pythoncode
/computing principle/word wrangler.py
3,890
3.984375
4
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted lis...
3550234103e3405adeb2a939073116b8a0cb22e4
AdrianMulawka/Udemy-Course
/userAge2.py
478
3.9375
4
# this program take age from user and give them information in which year he will be a hundred years man import datetime name=input(str("Hi what's Your name")) print("Hello ", name) wiek=int(input("Please give me information about your age and I told you in \n" "witch year you will be a hundred years old man. S...
f18ca1e6d73cf9aada6c6891d83e5422309fee67
nekapoor7/Python-and-Django
/GREEKSFORGREEKS/List/sum_nestedlist.py
143
3.796875
4
def column_sum(list1): return sum(sum(x) if isinstance(x, list) else x for x in list1) list1 = [1,3,5,6,[7,8]] print(column_sum(list1))
14e829f1641c67e57d07d4b028e85825e1265d73
kevin510610/Book_AGuideToPython_Kaiching-Chang
/unit22/hello_demo.py
404
3.984375
4
from tkinter import * root = Tk() root.title("Hello") text = Label(root, text="請輸入暱稱:", width="30", height="2") text.pack() name = Entry(root, width="30") name.pack() button = Button(root, text="執行") button.pack() result = Label(root, text="", width="30", height="2") result.pack() root.mainlo...
fa1b76092ae8d16ce4dcb2baa61af3023236d86b
soniaarora/Algorithms-Practice
/Solved in Python/LeetCode/String/lengthOfLastWord.py
329
3.9375
4
class lengthOfLastWord(object): def main(self): print(self.LastWordLen("Hello World")) def LastWordLen(self, s): if s == None: return 0 s = s.strip() words = s.split(" ") return len(words[len(words)-1]) if __name__=="__main__": lengthOfLastWord...
40def3ee5c25ed4fa5febf05c9c8791afc4e0fa2
Ale1120/Learn-Python
/Fase2-Manejo-de-datos-y-optimizacion/tema6-Funciones/recursivas.py
392
3.90625
4
# funcion recursivas sin retorno def cuenta_atras(num): num -=1 if num > 0: print(num) cuenta_atras(num) else: print('Booom!') print('Fin de la funcion', num) cuenta_atras(5) def factorial(num): print('valor inicial ->', num) if num > 1: num = num * factorial(n...
1e58ec79d42c2acd0e3e1d44dc63f224782d41c3
scotcorm/pythonClassAssignments
/evenOdd.py
543
4.3125
4
print("-------------") print(" Even or Odd ") print("-------------") print('Enter a number and the program will tell us if it is "Even" or "Odd"') print() attempt_limit = 5 attempts = 0 while attempts < attempt_limit: number = input("What is your mystery number? ") num = int(number) remai...
3b4ea7a26b95d8998931d68016cea5590331e3d5
bbkbbbk/Data-Structure
/data_structures/sorting/counting_sort.py
1,515
3.8125
4
''' Counting sort is the wrong sorting algorithm for string. The counting sort algorithm is designed to sort integer values that are in a fixed range, so it can't be applied to sort strings. ''' def count_sort(input_list): min_val = min(input_list) max_val = max(input_list) count = [0 for _ in range(min_v...
4f740bcb75ce9c768f347460df70b6d6a666ba45
ricardofelixmont/python-course-udemy
/6-files/copying_files.py
895
4.15625
4
# ask the user for a list of 3 friends # for each friend, we'll tell the user whether they are nearby # for each nearby friend, we'll save their name to 'nearby_friends.txt' friends = list() friends.append(input('Friend1: ')) friends.append(input('Friend2: ')) friends.append(input('Friend3: ')) friends = list(set(frie...
58662e6b91eb313d03a37740f601bbb84344be04
Brockfrancom/pythonProjects
/src/pythonBasics/bingo/Deck.py
2,259
3.671875
4
""" Brock Francom A02052161 CS-1440 Erik Falor 10/17/2018 3: Bingo Cards """ import sys import Card import NumberSet class Deck(): def __init__(self, cardSize, cardCount, numberMax): self.__cardSize = cardSize self.__m_cardCount = cardCount self.__numberMax = numberMax sel...
f4c651531be57cef06bd170493285eadf618cc28
vesteinnbjarna/Forritun_Vesteinn
/Hlutapróf 1 undirbúningur/Programming exercises/P1.py
167
4.0625
4
num1 = int(input('Enter a number: ')) num2 = int(input('Enter a number: ')) num3 = int(input('Enter a number: ')) sum_of_numb = num1 + num2 + num3 print(sum_of_numb)
1ff008183f610f798eef1e20cb06dd1948fac6e7
pashchuk/Algorithms
/SelectionSort.py
377
3.703125
4
import generator def SelectionSort(array): for i in xrange(len(array)-1): minindex = i elem = array[minindex] for j in xrange(i,len(array)-1): if array[j] <= elem: elem=array[j] minindex=j array[i], array[minindex] = array[minindex], array[i] def main(): a=generator.Generate(30,100) print a Se...
c89678656be12f84ebcff87e527e71c2026a6169
szachovy/School-and-Training
/Extended Programming Challenges Python/Emulacja Stosu/menu.py
886
3.859375
4
class Menu(object): @classmethod def starter(cls): return "Welcome in stack emulation program, results will be saved in stosdb" \ "\nHere are the oprions supported by the program\n" \ "1. Push item\n" \ "2. Pop item\n" \ "3. Check that selecte...
9c6a22b2ef555bafd321971e4f91c527baf6bb4a
srinivasanc22071986/python_all_features
/File Handling - Completed.py
12,421
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Difference between console and local files # Python have function for creating, reading, updating and deleting files. ''' open () function in Python to open a file in read or write mode. "r" - Read - Default value. Opens a file for reading, error if the file does ...
25fa57c5949cbe652f4d645d62429de016cce823
hwillmott/csfundamentals
/EPI/ch15/bst.py
4,296
3.6875
4
import random class Node: def __init__(self, value, parent=None, left=None, right=None): self.value = value self.left = left self.right = right self.parent = parent def insert(self, value): if self.value > value: if self.left is not None: sel...
2ea7e3e8fd4f05be82bbee822a99d8cba6b5d5ce
gabriellaec/desoft-analise-exercicios
/backup/user_222/ch47_2019_03_28_12_22_57_662078.py
175
3.859375
4
mes=int(input('numero do mes')) lista=['janeiro','fevereiro','março','abril','maio','junho','julho','agosto','setembro','outubro','novembro','dezembro'] print(lista[mes-1])
02d3e3f67cc2e993d1bbe6cb245416d1508e715c
ankushp11/FSDP_2019
/FSDP2019/day6/map2.py
162
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 10 17:04:56 2019 @author: user """ names = ['Mary', 'Isla', 'Sam'] l1=list(map(lambda i:hash(i),names)) print(l1)
91e0a4ce3349f2b28125fe1e6650c0db5f63194e
agatanyc/just_playing
/sq.py
56
3.9375
4
x = int(input("Enter the number: ")) r = x * x print(r)
01b75ceb5e36d699441ceb44b94f340194c499a4
SrikarNanduri/PythonExercises
/students.py
311
3.828125
4
students = { "Alice": {"id":"ID0001", "age":26, "grade":"A"}, "Bob": {"id":"ID0002", "age":27, "grade":"B"}, "Clare": ["ID0003", 17, "C"], "Dan": ["ID0004", 21, "D"], "Emma": ["ID0005", 22, "E"] } print(students["Alice"]) print(students["Clare"][0]) print(students["Alice"]["age"])
c248816f501afb033b7aacc29bbae6fde7070597
reenadhawan1/Django
/Python/OOP/intro_to_TDD.py
2,148
3.78125
4
import unittest def reverseList(arr): for i in range(int(len(arr)/2)): hold = arr[i] arr[i] = arr[len(arr)-1-i] arr[len(arr)-1-i] = hold # arr.reverse() return arr def isPalindrome(randStr): randStr = randStr.upper() for i in range(int(len(randStr)/2)): if randStr[i...
b6c44a187dd56b91f85aeb3f226b2e8dbb91a4ab
dimitar-daskalov/SoftUni-Courses
/python_fundamentals/labs_and_homeworks/07_dictionaries_exercise/08_company_users.py
602
3.8125
4
command = input() companies_employees = {} while not command == "End": company_name, user_id = command.split(" -> ") if company_name not in companies_employees: user_id = [user_id] companies_employees[company_name] = user_id else: if user_id not in companies_employees[company_name]:...
2de328cfa4d08f74f42aedf8c747267c301bf778
roryjnmurphy/university-projects
/ftpbrute/ftpbrute.py
1,429
3.78125
4
# Imports import ftplib, sys, os, socket # Variables global host, username, line, input_file line = "\n------------------------------------------------------\n" #Functions def ftp_connect(password, code = 0): server = ftplib.FTP() try: server.connect(host, port=21, timeout=5) server.login(username, password) ...
08f7079ee876870e2b0e3bcd6be40f8e5b5ad6cd
MakeSchool-17/twitter-bot-python-lesliekimm
/9_tokenization/tokenization.py
1,749
4.125
4
import sys import re # hard code text file name to open SOURCE_TEXT = open('the_hobbit.txt') # if the name of a text file is passed in as command line argument, set # SOURCE_TEXT to argument if len(sys.argv) > 1: SOURCE_TEXT = open(sys.argv[1]) # take an opened file as an argument and read the content, split t...
13f0efaeb173203bb58be73fde4cd24663842347
akojif/codevscolor
/python/sum_string_nos.py
460
4.21875
4
#example 1: #1 def calculateSumFor(first,second): return int(first) + int(second) #2 firstNumber = "100" secondNumber = "200" #3 print(calculateSumFor(firstNumber,secondNumber)) #example 2: def calculateSumFor(first,second): try: return int(first) + int(second) except ValueError: return -1 firstNumber = ...
2712f7c41a47497dbc2c54b5e4f425e5fdd96f1e
Adithya-Chandrashekar/Python_Projects
/Pong_game/main.py
1,125
3.625
4
from turtle import Screen,Turtle from paddle import Paddle from ball import Ball from scoreboard import Score import time screen=Screen() screen.bgcolor("black") screen.setup(800,600) screen.title("Pong") screen.tracer(0) r_paddle=Paddle((350,0)) l_paddle=Paddle((-350,0)) ball=Ball() score=Score() scr...
9b71c5b75811a36f60eea517f5df786d51b7a93c
Nonac/Python_practise
/Long Repeat Inside.py
1,434
3.8125
4
def repeat_inside(line): import re x = [i for i, k in re.findall(r"((.{2,})\2+)", line) + re.findall(r"((.)\2+)", line)] return sorted(x, key=len, reverse=True)[0] if x else "" """ first the longest repeating substring # your code here words = [] words_n = [] res = '' target =...
71b291f178cef87a47e0461bdb6fc0bc95eb6543
CamiloMolano01/IPV4
/main.py
2,259
3.546875
4
def print_hi(name): while True: ip = input('Ingrese la IP: ') # ip_bin = input('Ingrese la IP en Binario: ') ip = bina(ip) mask = int(input('Ingrese el prefijo: ')) mask = llenado(mask) print('ip: ') print(dev(ip)) print('mascara: ') print(de...
e2906cf24f73e876a7c82600055493a7c4345378
three3stones/Algorithms
/二叉树/二叉树的最大深度.py
2,971
3.65625
4
# coding=UTF-8 # 二叉树的最大深度 """ 1. 迭代法:从上到下按层级遍历二叉树,有多少层即二叉树有多深(即为求二叉树的深度) 2. 递归法:比较每一条路径的长短 """ class BiNode: def __init__(self, val): self.left = None self.right = None self.val = val class BiTree: def __init__(self): self.root = None # 添加节点 """ 判断根结点是否存在,如果不存在则插入根结点...
d14c0f6ff3d2381d01a6700893eedb8fe88eb1a7
aytona/PythonIntro
/Variable-String.py
283
4.0625
4
#!/usr/bin/python3 def main(): n = 42 s = 'This is a {} \nstring!'.format(n) i = r'This is a {} \nstring!'.format(n) # Raw string y = '''multiple line of strings this is a string''' print(s) print(i) print(y) if __name__ == "__main__" : main()
6feee0bd14316e4c820394e89d46561672c943d6
vbuzato/Exercises-Python
/ex015.py
241
3.625
4
km = float(input('Digite a kilometragem rodada: ')) dias = int(input('Digite a quantidade de dias utilizados: ')) valorkm = km * 0.15 valordias = dias * 60 total = valordias + valorkm print('O valor total é de: R${:.2f}'.format(total))
f7794d7641f2c6b1a304046f3b08bdf64c132b9a
sistre/python-challenge
/pypoll/main.py
2,296
3.90625
4
# First we'll import the os module # This will allow us to create file paths across operating systems import os # Module for reading CSV files import csv # Module for importing the collections module to use the Counter class import collections as ct csvpath = os.path.join('Resources', 'election_data.csv') txtpath =...
1471a5cfb97b7860061824135212f5604851019d
FelixZFB/Python_data_analysis
/002_Python_data_analysis_from_entry_to_master/ch11_Pandas/01_Pandas_Series_一维索引数组/005_Series属性_index_value.py
460
3.75
4
# -*- coding:utf-8 -*- # pandas创建Series创建index索引 import pandas as pd import string # 创建一个字典 a = {string.ascii_uppercase[i]:i for i in range(10)} # 字典转换为一维索引数组 b = pd.Series(a) # print(b) # 获取index(键), 可迭代的,类似于一个列表 print(b.index) print(type(b.index)) for i in b.index[0:3]: print(i) # 获取values(值) print(b.values)...
9d6c004444639e2688d216f3a2cba3e3a34493a7
anjalilajna/Bestenlist
/day11.py
568
3.78125
4
#1. x=list((1,2,3,4,5)) y=list((6,7,8,9,10)) z=zip(x,y) print(tuple(z))#((1, 6), (2, 7), (3, 8), (4, 9), (5, 10)) #2. lst1= ["one","two","three","four","five","six","seven"] rn = list(range(1, 8)) lit= zip(lst1, rn) print(tuple(lit)) #3. print(sorted([323,536,664,457656,674,43535,656,354556]))#[323, 536,...
d3281f75a4a13347d76487403e3432ccc33a4e8e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sieve/23e76b2cf0304cf79e285bee5ab80ed2.py
340
3.6875
4
import math def sieve(maxPrime): primeList = [True] * (maxPrime - 1) for i in range(0, int(math.sqrt(maxPrime))): if primeList[i] == True: for j in range(2 * (i+2), maxPrime + 1, i+2): primeList[j-2] = False return[x+2 for i,x in zip(primeList, range(len(primeLis...
dec3826fa77916535ad6115c88d55c1962e39c91
Elangovanvijayalakshmi/hackerrank-practice
/python/staircase.py
412
3.9375
4
#github.com/Elangovanvijayalakshmi import math import os import random import re import sys # # Complete the 'staircase' function below. # # The function accepts INTEGER n as parameter. # def staircase(n): for i in range(n): for j in range (n): if i+j == n-1: print...
f9388b8fab16947d20ac2ae0182ec4ec4f3710b5
Samrat132/Printing_Format
/Lab3/showstars.py
258
3.75
4
#Write a function called show_stars(rows). # If rows is 5, it should print the following:*************** def show_stars(rows): for i in range(0, rows): print("\r") for j in range(0,i+1): print("*", end="") show_stars(5)
08bac78e687d4775dcb68b160399bdb368bfc4b5
znb888/USTCcomputer
/2018Autumn/Optim/test1.py
268
3.71875
4
#!/usr/bin/env python3 import math import dis def foo(i, length, thres): j = i while j < length: j += 1 def fooslow(i, length, thres): for j in range(i, length): pass print("dis foo:") dis.dis(foo) print("dis fooslow:") dis.dis(fooslow)
2ce509243f81e0444048014ea4a2984b2bb63293
sreejakvs/Absolute_beginner
/smaller.py
117
3.890625
4
def Smaller(a,b): if a<b: print(a) else: print(b) p=int(input()) q=int(input()) Smaller(p,q)
69bd49ce125bf433cdc67ef83adf744ea51db63c
hrishikeshtak/Coding_Practises_Solutions
/leetcode/LeetCode-150/Binary-Search/74-Search-a-2D-Matrix.py
1,378
3.890625
4
""" 74. Search a 2D Matrix Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties: 1. Integers in each row are sorted from left to right. 2. The first integer of each row is greater than the last integer of the previous row. Input: ma...
b9e31ab721eea70fa606f1bdfec53f7369db0aa6
jashingden/Python
/Python教材/example/EX04_04.py
316
3.796875
4
#-*-coding:UTF-8 -*- # EX04_04.py # # 不定個數參數 ** (dict) # 傳入多個成員資訊 姓名=年齡(數量可以動態增減)當引數 # 對每個成員打招呼 def hello(**names): for n in names: print("Hello %s, you're %d years old"%(n,names[n])) hello(John=25, Tom=20, Bob=33, Tony=18)
e13118ea67ddc05b3c5c810b92fb705cf88dd848
Scnappi97/leetcode
/344 reverse string.py
377
3.578125
4
class Solution(object): def reverseString(self, s): """ :type s: List[str] :rtype: None Do not return anything, modify s in-place instead. """ def helper(left,right,s): if left<right: s[left], s[right] = s[right],s[left] ...
1f8b944220d237d62a363abe7966544245b7e6b3
Rakcheyev/Lessons
/Lesson_10/DZ_task 6.py
599
4.34375
4
''' Задание 6 Напишите функцию, высчитывающую степень каждого элемента списка целых. Значение для степени передаётся в качестве параметра, список тоже передаётся в качестве параметра. Функция возвращает новый список, содержа- щий полученные результаты. ''' def square(nums, square_arg): out = [] out.append(...
bc9206364c7d90f5f8fb09bd2e60452c2c67041a
BelfortJoao/Curso-phyton-1-2-3
/codes/Ex056.py
287
3.609375
4
n = str(input('Escreva uma frase: ')) s = n.split() j = ''.join(s) i = '' for L in range(len(j) -1, -1, -1): i += j[L] if i == j: print('{} e {} são iguais\nisso é um palindromo'.format(i, j)) else: print('{} e {} não são iguais\nisso não é um palindromo'.format(i, j))
2d1e2810dc0e6b9f22799796706ed5a93d3767c9
vitorsergiota/Python
/fichas/ficha7/ficha 7/ficha7 ex3.py
1,422
4.5
4
''' 3. Defina a classe estacionamento que pretende simular o funcionamento de um parque de estacionamento. a. A classe deve receber um valor inteiro que determina a lotação do parque; b. Deverá ter um método “saída” que liberta um lugar; c. Um método “entrada” que ocupa um lugar, e mostra uma mensagem de “Parque comple...
4ab12aee699c5b093b57b64bc60ef9dbf36b0e51
matiasandov/facebookABCS2021
/trees/preorderTras.py
475
3.671875
4
class BinarySearchTreeNode: def __init__(self, node_data): self.data = node_data self.left = None self.right = None def preorder_traversal(root: BinarySearchTreeNode): if root is None: return #------aqui no necesitas hacer return porque imprimes #imprimes primero el actu...
8a30e1086e706e865bb9e825d8f4e5cdb55e7090
jrgreenberg/devnet2020
/challenge2/ChuckNorrisJoke.py
1,473
3.625
4
import requests import json def joke(category): if category is not "": url = f'https://api.chucknorris.io/jokes/random?category={category}' else: url = f'https://api.chucknorris.io/jokes/random' payload = {} headers = { } response = requests.request("GET", url, headers=header...
c9b50c700f8acd1bcce0131fd0fac0b9f3049cce
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/strchr016/question3.py
843
4.34375
4
"""Counting votes Christopher Sterley 20/04/2014""" print("Independent Electoral Commission") print("--------------------------------") #Get party names for program party_name=input("Enter the names of parties (terminated by DONE):\n") party_list=[] party_number_list=[] #create lists to be used to coun...
2eb7b52a14a4720a84eabec525e42230170d3b09
LawrenceGao0224/LeetCode
/matrix.py
2,442
3.796875
4
# 73. Set Matrix Zeroes # Input: matrix = [[1,1,1],[1,0,1],[1,1,1]] # Output: [[1,0,1],[0,0,0],[1,0,1]] class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ m = len(matrix) n = len(matrix[0]) ...
bfdc07bf6ef9adc6bed30c70d201c289423542ef
betty29/code-1
/recipes/Python/578890_Dice/recipe-578890.py
440
3.953125
4
import random min=1 max=12 roll_again = 'yes' die1=random.randint(min,max) die2=random.randint(min,max) while roll_again == 'yes' or roll_again == 'y': die1=random.randint(min,max) die2=random.randint(min,max) print ('shake, shake, shake!') print ('you got a:') print die1 print die2 pr...
7c35ff4ac400d87cc1951148cad59d0987d97968
thalytacf/PythonClass
/AULAS_30/method_radom/ex2.py
3,176
3.96875
4
# Aula 21 - 16-12-2019 #Operadores in is == from geradorlista import lista_simples_int_str from geradorlista import lista_simples_int from geradorlista import lista_simples_str from geradorlista import embaralhar # A função embaralhar() irá criar listas aleátorias, copiar-las # e embaralhar. Desta forma não se sabe ...
0e167b76eb2c2abc7bdae5cbfb130f813eeba25b
bimri/learning-python
/chapter_11/auto_stream_redirection.py
1,485
4.09375
4
# sys.stdout is just a normal file object import sys x, y, z = 'spam', 12, [12, 23, 45] temp = sys.stdout # Save for restoring later sys.stdout = open('log1.txt', 'a') # Redirect prints to a file print('spam') ...
1063c0d8326a22300f5c1c23b5582ec67bdc4255
kpranshu/python-demos
/07-Oops/bankclient.py
1,130
3.90625
4
from bankmodel import Bank b=Bank() while(True): print("1. Create Account") print("2. Change Name") print("3. Change Branch") print("4. Deposit Amount") print("5. Withdrawl Amount") print("6. Check Balance") print("7. Check Branch") choice=int(input("Enter Choice : ")) ...
b8a8c8a07909deb5ed39492bf2d1590d842d94b5
Bongkot-Kladklaen/Programming_tutorial_code
/Python/Python_Beginners/Dictionarie/dic.py
274
4.03125
4
temp = {} temp['sun'] = 33.4 temp['mon'] = 45 temp['tue'] = 30 print(temp) mail_address = {'amul':'amul@gmail.com','jenni':'jenni@gmail.com'} print(mail_address) print(mail_address.keys()) print(mail_address.values()) num = {1:'one',2:'two',3:'three'} numbers = dict(num) print(numbers)
824254dedc333e0fa4a816930647b591edd1e009
Galikss/0502_project
/homework_module_4/season_function.py
826
4.15625
4
def season_finder(month): # CAUTION - HARD CODE arg = str(month) if arg.isdigit() and not arg.isalpha() and arg < str(13): if int(arg) < 3 or int(arg) == 12: print('It is Winter Season') if 9 <= int(arg) <= 11: print('It is Autumn Season') if 3 <= int(arg) <=...
9678a535d2bd1c347fadb34138f9239171991613
peekachoo/dangthuhuyen-fundamental-c4e25
/Session4/list_dict.py
610
3.5
4
p1 = { "nickname": "L", "yob": 1991 } p2 = { "nickname": "N", "yob": 1999 } p3 = { "nickname": "M", "yob": 1995 } p_list = [] # p_list = [p1, p2, p3] # p_list = [ # { # "nickname": "L", # "yob": 1991 # } # { # "nickname": "N", # "yob": 1999 # }...
4f5ac4a5876d8760625e1aafa90c838133972f42
ANKITPODDER2000/Python-Lab-2nd-Year
/qube.py
119
3.71875
4
import math def qube(num): return math.pow(num,3) for i in range(1,11): print("Qube of %d is : %d"%(i,qube(i)))
0f42e8d138dd9cfad4b8d9d002add2a322fda85c
heerdemoglu/sample_projects
/QM - Basics of Logistic Regression and Neural Networks/1_logistic_regression/ml_assgn1_ex4.py
3,240
3.546875
4
from load_data_ex1 import * from normalize_features import * from gradient_descent_training import * from return_test_set import * import matplotlib.pyplot as plt import os figures_folder = os.path.join(os.getcwd(), 'figures') if not os.path.exists(figures_folder): os.makedirs(figures_folder, exist_ok=Tru...
11aab2f5e194a4d2743ab34be83bc0ddebb33797
hshrimp/letecode_for_me
/letecode/other/剑指offer/11.py
933
4
4
#!/usr/bin/env python # encoding: utf-8 """ @author: wushaohong @time: 2020/2/25 16:44 """ """面试题11. 旋转数组的最小数字 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。 例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。 示例 1: 输入:[3,4,5,1,2] 输出:1 示例 2: 输入:[2,2,2,0,1] 输出:0 注意:本题与主站 154 题相同:https://leetcode-cn.com...
cf5e1e9fc35bbce784f1f686ca4f2becdcee1054
cutz-j/TodayILearned
/MLP/lec9-1.py
842
3.640625
4
class MulLayer: def __init__(self): self.x = None self.y = None def foward(self, x, y): self.x = x self.y = y out = x * y return out def backward(self, dout): dx = dout * self.y dy = dout * self.x return dx, dy class AddL...
7c1d1b9455cbb8acd4430723f27c8dd4fc2b1a4f
misaka-umi/Software-Foundamentals
/01 混杂/10 文件中数字的倍数.py
492
3.8125
4
integer = int (input ("Enter an integer: ")) file_name =input ("Enter a filename: ") f = open (file_name , "r") neirong = f.readlines() num=[] for i in neirong: number=i.split() for a in number: num.append(int(a)) j=0 for i in num : if i%number1 ==0: j=j+1 if j < 2: print ("There is {} m...
20c211450f54cbf08addb9c391c0131d8cf09305
liuxiaonan1990/leetcode
/22. Generate Parentheses.py
845
3.5
4
class Solution(object): def func(self, num_a, num_b, list, total): if total > 0: return False if num_a == 0 and num_b == 0: if total == 0: self.result.append(list) return True else: return False if num_a > ...
77d0ec8aea0469de20ec805246b2b6eba77ff54b
kuronekonano/Pythontest
/BinaryTree.py
1,546
3.734375
4
class BinaryTree: def __init__(self,value):#构造函数 self.__left=None self.__right=None self.__data=value def insertLeftChild(self,value): if self.__left: print('left child tree already exists.') else: self.__left=BinaryTree(value) ...
c8f1ab71e379fa318049968c66500c230b00bdab
xtreia/pythonBrasilExercicios
/03_EstruturasRepeticao/42_numeros_intervalo.py
652
3.65625
4
numero = 0 intervalo025 = 0 intervalo2650 = 0 intervalo5175 = 0 intervalo76100 = 0 while (numero >= 0): numero = int(raw_input('Informe um numero: ')) if (numero >= 0): if (numero <= 25): intervalo025 += 1 elif (numero <= 51): intervalo2650 += 1 elif (numero <=...
d1aa76e52e0426295b5a729d1d2f327466b58202
lithiumcomputing/2D-Neural-Network-Classification-
/GenerateDataset.py
1,685
3.5625
4
## # @file GenerateDataset.py # # @author jimli # @version 23 May 2019 # # Generates a random data set for a 2D plot. # The data set will be used for the 2D Classification # Neural Network program. import numpy as np ## # Checks if a point is in a circle. # # @param x x-coordinate of the point. # @param y y-coordina...
922af652a66035e4e66a3f89f8c169a49441f0d2
ppipee/Compro
/matrix.py
799
3.890625
4
def matrix_multiplication(a, b): total = [] for i in range(len(a)): result = [] for j in range(len(b[i])): sum = 0 for k in range(len(a[i])): sum += a[i][k]*b[k][j] result.append(sum) total.append(result) for m in range(len(total)):...
e362515f57650e00dd4ae6208acfe4a03cefd27a
Karla-BJ/Programaci-n-2020
/Talleres/While/While2.py
564
4.03125
4
print (" Hola, a continuación se le pedirá que ingrese dos números enteros") #-----Mensajes-----# PreguntaNúmero1= ("Ingrese el primero : ") PreguntaNúmero2= ("Ingrese el segundo : ") MensajeDeDespedida= ("Hasta luego, gracias por jugar ♥") MensajeRepetición= "Debes ingresar un número mayor al primero" NúmeroIngresado...
49301fb85df2c56ee954301728c87deda1f344d6
gita87/Tipe-data-dictionary
/Python_Course_2_Fungsi.py
2,214
3.859375
4
"""" Program menghitung luas segituga """ alas = 10 tinggi = 6 luas_segitiga = alas*tinggi / 2 print(f'segitiga dengan alas{alas} dan tinggi{tinggi} maka luasnya adalah {luas_segitiga}') def hitung_luas_segitiga(alas, tinggi): luas_segitiga = alas * tinggi / 2 return luas_segitiga hitung_luas_segitiga(10, 6...
1180b2825e91ec034502a3cf43e282039db9d5bc
shibaji7/SCUBAS
/scubas/utils.py
2,996
3.765625
4
"""utility.py: Module is used to implement utility methods. """ __author__ = "Chakraborty, S." __copyright__ = "" __credits__ = [] __license__ = "MIT" __version__ = "1.0." __maintainer__ = "Chakraborty, S." __email__ = "shibaji7@vt.edu" __status__ = "Research" import math from types import SimpleNamespace import num...
7ba5ac3593871329cef81c799456f854fe20acbd
itizarsa/python-workouts
/findFirstLastDigit.py
234
4
4
# program to find first and last digit of a number n=int(input("Enter Number ")) a=[] i=0 c=0 while i<n: x=n%10 n=n//10 a.append(x) c=c+1 print("The First Digit is ",a[c-1]) print("The Last Digit is ",a[0])
728b8981302efea81c1e832347506e1636fcf37c
adjy/Fibonacci
/fibonacci.py
373
3.765625
4
# coding:utf-8 from sedar_007 import * sedar_007() a=0 b=1 i=1 nombre =0 while nombre <= 0: nombre=input("Entrer le nombre (nombre positif): ") nombre=int(nombre) if nombre==1: c=1 else : while i<nombre: c=a+b a=b b=c i=i+1 print("Pour ...
239609578964a4e16916de79ffa9f5c8e0c83818
KuldeepJagrotiya/python
/List/ReverseList.py
215
4.28125
4
# ## Q : reverse the list without using reverse functions ##M-1 l1 = [1,3,8,7,3,1,5,3] l2 = l1[::-1] print(l2) ##M-2 l1 =[1,3,8,7,3,1,5,3] l2 = list() for i in range(len(l1)-1,-1,-1): l2.append(l1[i]) print(l2)
c86585ae6baf8cd8772c752f335e161ce6382f38
vladskakun/TAQCPY
/tests/TestQuestion24.py
753
4.15625
4
""" 24. Buggy Uppercase Counting In the Code tab is a function which is meant to return how many uppercase letters there are in a list of various words. Fix the list comprehension so that the code functions normally! Examples count_uppercase(['SOLO', 'hello', 'Tea', 'wHat']) ➞ 6 count_uppercase(['little', 'lower...
7c08c9cf56d8454bd0bfa4fe106f15277c2556d5
tdchua/halim-competitive-programming
/UVa10943.py
482
3.671875
4
def count_ways(n, K): global dp_memo if(K == 1): return 1 else: sum = 0 for X in range(n+1): if(dp_memo[n-X][K-1] == -1): #Haven't traversed dp_memo[n-X][K-1] = count_ways(n-X, K-1) else: print("DP!") sum += dp_memo[n-X][K-1] return sum return something if ...