blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ee8c78f491453392d36ee7d33a009b241b357338 | gerph/rosettacode | /json_funcs.py | 1,508 | 4.0625 | 4 | """
Functions for manipulating JSON.
json_iterable + json_encode allow the serialisation of objects which contain the
`__jsonencode__` method. If called, this should return a serialisable object (simple
python objects).
write_json will use those functions to write out a JSON file.
"""
import json
def json_encode(o... |
c71d8d2d61cde1d47e79331750ff1043445aeff1 | poohcid/class | /extra/6.py | 350 | 4.125 | 4 | """Print i"""
def main():
"""main"""
style = input()
num1, num2, num3 = int(input()), int(input()), 1
if num2 < num1:
num3, num2 = -1, num2-2
for i in range(num1, num2+1, num3):
if style == "Vertical":
print("%02d" %i)
elif style == "Horizontal":
prin... |
cad22b24332bf86cc8594ee66df07d821bd9f12e | KaiChen1998/My-Leetcode | /python/110. Balanced Binary Tree.py | 873 | 3.921875 | 4 | class Solution:
"""
Problem:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Solutions:
重点在于如果有一棵子... |
0e723f95f9ccf84205ca06ec38c76fff6e84769a | gabrielgamer136/aula-git-gabriel | /Documentos/lista de exercicios 1 python gabriel/lista de exercicios 2 phyton/exercicio numero 2.py | 206 | 3.828125 | 4 | #Gabriel maurilio
ano = int(input("digite um ano"))
if ano % 4 != 0:
print ("nao e bissesto")
else:
if ano % 100 == 0 and not (ano % 400 == 0):
print("nao e bissesto")
else:
print("e bissesto")
|
4a1bcd557e493b2cd66758308686046bfb8c9355 | chaussen/chinese-character-teaching | /src/common/character_dict.py | 17,032 | 3.59375 | 4 | LESSON_10 = {
"花": ["huā","flower; blossom"],
"园": ["yuán","land used for growing plants; site used for public recreation"],
"门": ["mén","gate; door; classifier for lessons, subjects, branches of technology"],
"前": ["qián","front; forward; ahead; first; top (followed by a number); former"],
"个": ["gè","universal me... |
080f4751a536bf14d07e696ce631cde270cde96e | ny215/LeetcodeExercise | /LinkedList/23. Merge k Sorted Lists.py | 1,854 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
... |
0c28f1cfc41c26680dc42427ce3153de76e94c2c | shyam-SDET/coursera-python | /assignment4.6.py | 302 | 3.8125 | 4 | def computepay(h,r):
if(h>40):
result=h*r;
res=((h-40.0)*(r*0.5));
x=result+res;
else:
result=h*r;
x=result;
return x;
hrs = input("Enter Hours:")
h = float(hrs)
rate=input("Enter Rate:")
r=float(rate)
a=computepay(h,r);
print("Pay",a);
|
27c0313bc762c194b2e2b79229cb20b8577f50ca | ykumards/Algorithms | /dp/RecursiveMult.py | 1,199 | 4.28125 | 4 | """
Multiply two number recursively, without using *.
Runtime is O(k) where k is the minimum of the two operands
"""
def _naive_recMult(addr, multer):
if multer == 0:
return 0
addr += _naive_recMult(addr, multer-1)
return addr
def recMult(a, b):
small = min(a,b)
big = max(a,b)
return _... |
4e8940564ad86b3c49dacf451bf00549abdf6137 | mrstevenaweiss/algorithms | /Cryptography/mental_poker.py | 1,679 | 3.953125 | 4 | ## Mental Poker
import random, math
bitwise_cards = {}
# Create a bitwise hash
suits = ["Clubs", "Hearts", "Spades", "Diamonds"]
cards = [None, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", None]
card = 1
for i in range(1, 53):
if i <= 13:
suit = suits[0]
elif i... |
523975807386a5c92671974287c76f8d3bb5d8f0 | jakabk/interviews | /mutable_default_arguments_gotcha.py | 429 | 3.953125 | 4 | # https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
# What’s the output of this code:
def f(x, l = []):
for i in range(x):
l.append(i * i)
# print(l)
return l
if __name__ == "__main__":
# >>> f(2)
# ...
assert f(2) == [0, 1]
# >>> f(3,[3,2,1])
# ...
... |
e62c3d7d194624b2a42955cbb896d4e306bbd32b | kevinlogan94/CS_Projects | /CS115/theprogram4.py | 6,213 | 3.703125 | 4 | #Prolog Program 4
# Kevin Logan
# Section 10
# kmlo225@g.uky.edu
# November 15, 2012
#Preconditions: user inputs: userid, database filename, search phrase,
# case sensitivity setting, web page filename
#purpose:
# search in database file for search phrase, based on case sensitivity
# setting, and create web pag... |
43a7ef166b6d937846e9cb1052f52a8ccb60eebf | shyamdalsaniya/Python | /test.py | 535 | 4.28125 | 4 | def main():
print("hello world form python")
a=60+60
print(a)
#this is way to write a comment
a,b=10,15
print(a,b)
a,b=b,a
print(a,b)
print("%d %d %s"%(a,b,5*"hello"))
#this tuple.it is static array. it can not change after it is created
arr1=(1,2,3,5)
print(arr1,typ... |
256d5eb43550fde2f2daf2842b12844707cfd0a8 | YektaAkhalili/May-12-2020 | /tuples.py | 247 | 3.828125 | 4 | guests = ("William", "Charlotte")
# print("First person: ", guests[0])
print("original guests: ")
for people in guests:
print(people)
guests = ("HostWilliam", "Holores")
print("replaced guests: ")
for people in guests:
print(people) |
54903180a8a504ffe93ba8f99e6881a02e428f61 | CSant04y/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 920 | 4.09375 | 4 | #!/usr/bin/python3
"""Unittest for max_integer function
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""testing for max integer in list func"""
def test_for_max_int(self):
"""tests successful cases of max_integer"""
self.a... |
0827bb450b1c62049dc09b29c4599a0deb3ce8e0 | brandon-kyle-bailey/project-environment-manager | /manager/tests/test_CreateProject.py | 8,724 | 3.609375 | 4 | #!/usr/bin/env python3
""" A script to create java project environments in the
path the script is run in, or a path specified by the user.
User can specify package names to create and can specify if template
'Main' files should be created for each package.
E.g: environment structure :
# -root_path
# -build
# ... |
999392cd4af0f0e9ed912aa6ccef50698ba8482a | sjain93/python_fundamentals2 | /exercise4.py | 266 | 3.78125 | 4 | def charcheck(arg):
if isinstance(arg, str):
if len(arg) <= 8:
print('False')
else:
print('True')
else:
print('Not a string, enter a string')
charcheck(2)
charcheck('james')
charcheck('Perhaps a longer one')
|
8e93ab92fe2949ee05b3886fc865c4d743a689ec | fargofremling/practiceprograms | /primes_summation.py | 785 | 3.53125 | 4 | # Problem #10
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
#
# Find the sum of all the primes below two million.
import timeit
import math
start = timeit.default_timer()
n = int(raw_input("What prime number would you like to find?\n> "))
primes = [2,3]
for p in range(5, n+1, 2):
if any(p % i == 0 f... |
d5ada4eec915ee6e86545062c21b7d1e275c1929 | zaidjubapu/ZaidAlexa | /zaidAlexa.py | 3,251 | 3.546875 | 4 | import pyttsx3
import datetime
import speech_recognition as sr
import pyaudio
import wikipedia
import webbrowser
import os
import smtplib
engine=pyttsx3.init('sapi5') # engine is nothing but just an object
voices=engine.getProperty("voices") # it return no of voices availble in sapi5 or in engine
# print(voices) # p... |
c9f857bb2db6fc6d59a981a15af972099e90f2c3 | JohnTuUESTC/leetcode_program | /MergeSortedArray.py | 962 | 3.90625 | 4 | #coding:gb2312
'''
leetcode: Merge Sorted Array
'''
import copy
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instea... |
e56819d48c63128e36dce30ee43fb22c92a749c5 | outofboundscommunications/courserapython | /play/negatives.py | 756 | 3.90625 | 4 |
'''
read through the list of negatives and campaigns and store in dictionary
'''
import string
fhand = "negativesList.csv"
f2hand = "Report.csv"
negatives = dict()
acctnegatives = dict()
for line in fhand:
line = line.rstrip()
#split the line, at each comma, into a list
words = line.split(',... |
7072566f63a906f69d6ed436456bd5841633080c | edu-athensoft/stem1401python_student | /py210110d_python3a/day06_210214/homework/stem1403a_hw_5_tengyuhao.py | 2,077 | 4.28125 | 4 | """
[Homework]
Date: 2021-02-07
1. Try out label widget
Description:
create a window based on previous homework
set icon, title, dimension, maxsize, minsize, bg and any other options for the window as much as you know
create at least 2 text Labels
set dimension, font, fg, bg, font and any other options you know.
create... |
e37f8d87b3ef63a808f91d5b6ead1f8b21739184 | DeanHe/Practice | /LeetCodePython/LongestIncreasingPathInaMatrix.py | 1,569 | 4.0625 | 4 | """
Given an m x n integers matrix, return the length of the longest increasing path in matrix.
From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Example 1:
Input: matrix = [[9,9,4],[6,6,8]... |
673483c41223dc70ac46e316683f1db18f3b93f9 | Roentge-nium/ichw | /pyassign1/planets.py | 1,817 | 3.59375 | 4 | import turtle
import math
sun=turtle.Turtle()
sun.color("yellow")
sun.shape("circle")
sun.shapesize(3)
mercury=turtle.Turtle()
mercury.color("blue")
mercury.shape("circle")
mercury.shapesize(0.382)
venus=turtle.Turtle()
venus.color("#ffff24")
venus.shape("circle")
venus.shapesize(0.949)
earth=turtle.Turtle()
earth.c... |
ac2a708e5ecc42b82ee814a228da0de85430a2d6 | AmpersandTalks/CIS106-Cesar-Perez | /Assignment 7/Activity 1.py | 1,390 | 4.09375 | 4 | def calculateOvertime(choice, rateperhour):
overtime = (choice - 40) * rateperhour / 2
return overtime
def calculateweekly(choice, rateperhour):
weekly = choice * rateperhour
return weekly
def displayResult(weekly):
print("$" + str(weekly) + " weekly ")
def displayResultOve... |
fa482e032d3e277db353dedfe6627ab23a74c6a3 | FabianoBill/Estudos-em-Python | /04-Dicionários.py | 385 | 3.84375 | 4 |
linguas = {'BR': "Português", 'EUA': "Inglês"}
print(linguas['BR'])
print(linguas.get('EUA'))
print('BR' in linguas)
linguas['ES'] = "Espanhol"
print(linguas)
for chave in linguas.keys():
print(chave)
for valor in linguas.values():
print(valor)
for chave, valor in linguas.items():
print(chave, valor)
lingu... |
cdaad37ad129119650eda826656372c58bce1b45 | GalaxyZpj/Python_Institutional | /Assignments/A1/6.py | 383 | 4.09375 | 4 | i_grade = input('Enter a grade: ')
try:
i_grade = int(i_grade)
except:
print('Enter a valid grade.')
if i_grade <= 10 and i_grade >= 8.5:
a_grade = 'A'
elif i_grade <= 8 and i_grade >= 7.5:
a_grade = 'B'
elif i_grade <= 7 and i_grade >= 6.5:
a_grade = 'C'
elif i_grade <= 6 and i_grade >= 5.5:
a_... |
051948df314746c81525dd00ebae41be66795be8 | ykoga-kyutech/python_work | /basic7.py | 483 | 3.546875 | 4 | # -*- coding: utf-8 -*-
__author__ = 'tie304184'
"""
問題7.
1コラム目の文字列を集計して表示せよ(文字列/カウントを表示)
の解答。
"""
import sys
from collections import Counter
fname_input = "13tokyo\\13TOKYO.CSV"
col1 = list()
with open(fname_input, "r") as fin:
for m in fin:
col1.append(m.split(",")[0])
counter = Counter(col1)
f... |
0b8d825f4b57217a8ac1c5013185ab59784a39cc | zixcon/python | /script/http/dohttperror.py | 441 | 3.5625 | 4 | import urllib.request
from urllib.error import HTTPError, URLError # 要调用urllib.error模块
req = urllib.request.Request('http://www.baidusxxxx.com')
try:
response = urllib.request.urlopen(req)
except HTTPError as e: # 注意HTTPError别写错了,
print("http error:", e.reason)
print("httperror code:", e.code)
except URL... |
a4653c05a6aeb1730f94abb57a062e17c0e59e62 | Halimeda/Python_Pratice | /Exercices/Exo/homework_21_01_corr.py | 285 | 3.953125 | 4 |
numbers = []
while sum(numbers) < 20:
number = input('Donne moi un nombre: ')
number = int(number)
numbers.append(number)
print('Nombre d''entrées: ' + str(len(numbers)))
print('Plus petit nombre: ' + str(min(numbers)))
print('Plus grand nombre: ' + str(max(numbers)))
|
08e9395c01c6553e52747f16a8c5af44a393eafd | nnaka/breast_cancer_classifier | /script.py | 1,612 | 3.59375 | 4 | import matplotlib
import sklearn
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
def main():
# part 1
breast_cancer_data = load_breast_cancer()
# part 2
print breas... |
ef37214e3541e87fc73054803590865ca28f20a5 | TOMMYzhn/PandasVersusExcel-master | /6-InputFunction/InputFunction.py | 780 | 3.984375 | 4 | # pandasVersusExcel
# http://sa.mentorx.net/course/89/tasks
# 第六课 函数填充
# 2018-10-18
import pandas as pd
books = pd.read_excel('./Books.xlsx',index_col='ID')
print('----计算前----')
print(books)
# 方法一
# books['Price'] = books['ListPrice'] * books['Discount']
# print('----方法一----')
# print(books)
# 方法二(此方法可以对计算的行的范围进行精... |
997fd1edf83a7af4cba922d83329bc8ddfdc4278 | shubhamsinha1/Python | /PythonDemos/Commonly_Asked_Code/Array/1.Is_Unique.py | 367 | 3.953125 | 4 | word='abcd'
def is_unique_1(word: str):
if len(word) == 1:
return True
temp_arr=[]
for char in word:
if char not in temp_arr:
temp_arr.append(char)
else:
return False
return True
def is_unique_2(word:str):
return len(set(word)) == len(word)
pr... |
8babf1cead8da82f5242bcf5889ff3bc91c46bd3 | RainbowwwYQ/InnovScraping_GoogleAPI | /2. Cleaning.py | 1,577 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 14 15:08:20 2020
@author: mayhe
"""
import pandas as pd
import string
# please notice: no comma in original documents!
df = pd.read_csv("GoogleAPI_all.csv", encoding= 'unicode_escape')
remove_url = pd.read_csv("remove_list.csv").drop_duplicates()... |
334c80c4f8c90deb1de73612bda5388e819195ab | brandoneng000/LeetCode | /medium/229.py | 1,187 | 3.765625 | 4 | from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
# num_count = {}
# for n in nums:
# num_count[n] = num_count.get(n, 0) + 1
# return [n for n in num_count if num_count[n] > (len(nums) // 3)]
first_major, first_vot... |
dc666a8f1beaddbff9dcd90854b4bda50df7e2f9 | chandramohank/Logical-Programes | /Python/BalancedParanthesis.py | 595 | 3.890625 | 4 | arr = []
def parens(left, right, string):
print(left,right,string)
# if no more brackets can be added then add the final balanced string
if left == 0 and right == 0:
arr.append(string)
# if we have a left bracket left we add it
if left > 0:
parens(left-1, right+1, string+"(")
# if we have a ri... |
48669b5ebf655a4b34f426aab5966471b93eac70 | kecarrillo/monopoly | /Monopoly/Cell.py | 2,632 | 3.96875 | 4 | from Monopoly.Game import Game
class Cell:
"""This class represents the cells from the board game.
"""
def __init__(self, position, name, group):
"""This method is the constructor of the class.
:param position: Position of the cell on the board.
:type position: integer
:pa... |
30fcfb165f60a8b9d0eb61443e4abdd576ca1d5c | syurskyi/Python_Topics | /120_design_patterns/016_iterator/_exercises/templates/Iterator_003.py | 1,128 | 4.09375 | 4 | # #==============================================================================
# c_ ReverseIterator o..
# """
# Iterates the object given to it in reverse so it shows the difference.
# """
#
# ___ - iterable_object
# list _ ?
# # start at the end of the iterable_object
# index... |
525e3e72e46272b828cb677c783d0b8d4f42d8f1 | vikendu/hackerrank-solutions | /reverse_vowels.py | 956 | 3.765625 | 4 | # Given a string, reverse only vowels in it. Leave the remaining string as it is.
# Input Format
# One string.
# Constraints
# 1 <= Length of string <= 10^5
# Output Format
# One string, the original string with vowels reversed.
# Sample Input 0
# trumpisshit
# Sample Output 0
# trimpisshut
in1 = input('')
lis... |
748b947ce7b8729520f0df0b65d0748b8f019cc0 | scottdaniel/gradschool | /the_beginning.py | 426 | 3.59375 | 4 | program = None
def text_prompt(msg):
try:
return raw_input(msg)
except NameError:
return input(msg)
print('Welcome to Grad School')
program = text_prompt('What program would you like to join?')
print('You have chosen: ',program)
print('It is your first day of grad school')
print('Suddenly, Satan appear... |
0758101b941a0639bd9cae223350b0ec13806b8e | smiszym/maze-walk | /mazewalk/game.py | 1,633 | 3.90625 | 4 | import curses
from .maze import Maze
from .generators import *
from .printers import utf8_printer
def _main_inner(stdscr):
stdscr.addstr("Choose maze generation algorithm:\n")
stdscr.addstr(" 1. Breadth First Search\n")
stdscr.addstr(" 2. Depth First Search\n")
stdscr.addstr(" 3. Horizontal Passag... |
f70f76d2f397700cde822f87dbe0c54f49451a90 | DilaraPOLAT/Algorithm2-python | /5.Hafta(list,tuple)/ornek3.py | 1,008 | 4.09375 | 4 | """
ornek3:
liste veri tipi kullilarak kullanicidan alinan ogrenci isim,numara ve vize notu bilgilerini ayrı listelerde tutunuz.
tum ogrenci bilgilerini ve vize notu 70 den buyuk olan ogrencilerin bilgilerini ayri ayri aliniz.
"""
ogr_ad=[]
ogr_no=[]
ogr_vizenot=[]
syc=int(input("kac ogrenci bilgisi gireceksiniz:"))
fo... |
49c52ec3c4561d45e9bdb9ceaafe72cd8015e64c | tuseto/PythonHomework | /week5/5-Sublist/sublist.py | 544 | 3.625 | 4 | def sublist(list1, list2):
if list1 == []:
return True
for n in range(0, len(list2)-(len(list1)-1)):
if list1[0] == list2[n]:
counter = 0
for i in range(0,len(list1)):
if list1[i] == list2[n+i]:
... |
d361c33c63f97f12d996c654588474a0036222ad | eveafeline/coding-challenges | /python/arrays_n_strings/3_URLify_test.py | 1,293 | 4.28125 | 4 | """
Write a method to replace all spaces in a string with '%20'. You may assume that the string has
sufficient space at the end to hold the additional characters, and that you are given the "true"
length of the string. (Note: if implementing in Java, please use a character array so that you can
perform this operation i... |
a2341225ae36a480c33e9782f2e016ea18c18451 | sharpo101/blackjack | /blackjack.py | 7,323 | 3.65625 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8,
'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King'... |
fac81d3d54cfb70b8cbd540056448be501d3398a | Salman791/Practise | /01_Pattern_Exercises.py | 1,320 | 4.375 | 4 | ############### RIGHT-ANGLED TRIANGLE ###############
# Input = int(input("Please enter the number of rows: "))
#
# for i in range(1,Input + 1):
# for j in range(1, i + 1):
# print("*", end=" ")
# print()
############### RIGHT-ANGLED TRIANGLE (Tilt) ############### (Control or Control Flow is the or... |
22b258f1911c3347979389ccd4b701d2fc61fa55 | akosuawiafe01/PythonPeers | /Project1-Temperature_Converter.py | 338 | 4.375 | 4 | #Temperature Converter: Fahrenheit to Celcius
print("\n Hey there, welcome to the FC Temperature Calculator \n")
print('Please enter your temperature in Farenheit: \n')
temperature = input()
fahrenheit = int(temperature) - 32
celcius = int(fahrenheit) / 1.8
print('Your temperature is ', str(round(celcius,2)) , '... |
3125af0c1212adfc38d3abb64b7927e0f5f02e3a | KC-Simmons/Self-Work | /NNFunc.py | 4,168 | 3.53125 | 4 | import numpy as np
#Activation Function (0,1)
sigmoid = lambda i: (1/(1+np.exp(-i)))
vectorized_sigmoid = np.vectorize(sigmoid)
#Set-up Learning Rate
LR = 0.9
class NN(object):
def __init__(self, NumIL, NumHL, NumOL):
self.NumIL = NumIL
self.NumHL = NumHL
self.NumOL = NumOL
#Cr... |
f0006d3c8991a30d1e202b806a142a380ffe22f9 | Eriklebson/ExerciciosEtecPAPython | /Python questão 02-10.py | 542 | 4.0625 | 4 | print("=========================================================================")
nomeP = input("Informe o nome do produto:")
valorP = float(input("Informe o valor do produto: R$"))
qtdP = int(input("Informe a quantidade de parcelas em ate 5x:"))
valorParcela = float
print("============================================... |
baddebaf428d17541aea325d8c454c89a3909868 | hkristensen/lawn | /lawn.py | 5,488 | 3.6875 | 4 | import random
class Environment():
def __init__(self, growth_rate) -> None:
self.growth_rate = growth_rate
class Lawn():
Lawn_Grid = 0
new_Mower = 0
cut_Percent = 0
current_direction = "x"
def __init__(self, lawn_x, lawn_y) -> None:
self.lawn_x = lawn_x + 2
self.... |
4df39295e7b68748ce92856aad6af258add7a12e | camorazrushimoe/projecteuler | /2done.py | 485 | 3.71875 | 4 | def fib(n):
if n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
lst = fib(n-1)
lst.append(lst[-1] + lst[-2])
return lst
fib_num = fib(33)
print(fib_num) # Цифры фибоначи
sum = 0
current_num = 0
while current_num <= 33:
if fib_num[current_num] % 2 == 0:
... |
ae699be3630e04e637261d0ec9e412c21f7f8761 | shriharshs/AlgoDaily | /leetcode/103-binary-tree-zigzag-level-order-traversal/main.py | 940 | 3.625 | 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 zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
2afaf68e09cfbb25545744616a64a675308769ad | banderquartz/Python-Learning | /weekly_exercises/character_input.py | 325 | 3.875 | 4 | '''
Created on Nov 18, 2014
@author: mike
'''
from datetime import datetime
name = input("Please enter your name: ")
age = int(input("Please enter your age: "))
current_year = datetime.now().year
target_year = 100 - age + current_year
print("You, " + name + " will turn 100 years old in the year " + str(target_year... |
df6e07390006b46c70b8b274d4938cb4a122b11f | razanALaskar/100DaysOfCode | /4th Week.py | 1,371 | 4.09375 | 4 | # Day 20: Sets
thisset ={"Apple","Orange","Banana","Apple"}
print(thisset)
for x in thisset:
print(x)
print("Banana is in the set:",("Banana"in thisset))
thisset.add("Cherry")
thisset.update(["Mango","Grapes"])
print(thisset)
# Day 21: Sets2
print(len(thisset))
thisset.remove("Apple")
thisset.discard("Orange")
prin... |
204d22434977a30b8d6f52347a961054b4ad8df2 | Yegor9151/Algorithms_and_data_structures_in_Python. | /lesson 2 - loops, recursion, functions/lesson2_task2/l2t2.py | 687 | 4.25 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
"""
num = input("Введите любое натуральное число: ")
even_nums = ''
odd_nums = ''
even, odd = 0, 0
for i in num:
if int(i) % 2 == 0:
... |
154bee0c3d9f40810d2693af6b115e25ebd890bb | tjdgus3160/algorithm | /CodeUp/재귀함수/(재귀함수)피보나치 수열.py | 105 | 3.78125 | 4 | def fibo(n):
if n<=2:
return 1
return fibo(n-1)+fibo(n-2)
n=int(input())
print(fibo(n))
|
c5ca250a326990d7597178ac4a85e30127b320e5 | imidya/gogo_design_pattern | /class5/answer_bridge.py | 975 | 4.1875 | 4 | import abc
class Drawer(abc.ABC):
@abc.abstractmethod
def forward(self):
raise NotImplementedError()
@abc.abstractmethod
def rotate(self):
raise NotImplementedError()
class TwoDDrawer(Drawer):
def forward(self):
print('2D forward')
def rotate(self):
print(... |
68a21f1c778236a539ac341bec9dec528eb236e3 | Wil10w/Beginner-Library-2 | /Error handling/Iterate with errors.py | 214 | 3.671875 | 4 | given_items = ["one", "two", 3, 4, "five", ["six", "seven", "eight"]]
for item in given_items:
try:
for j in item:
print(j)
except TypeError:
print('Not iterable')
pass
|
4b6e080b91a5340c8356988d91206fd301a9cbb3 | jgarciakw/virtualizacion | /ejemplos/ejemplos/class_property.py | 526 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#____________developed by paco andres____________________
class Circle(object):
PI = 3.14
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * self.PI * self.radius
@property
def radio(self):
return sel... |
d1fd517e8afc8ed1ac7ee6558a7c036df66de135 | zuoyuanwei/package | /sort/xier.py | 1,068 | 3.9375 | 4 | # 希尔排序,将原始列表分解为多个较小的值列表改进插入排序。
# 最后一步执行完整的插入排序,但是不需要非常多的比较(或移位)
# 因为列表已经被较早的增量插入排序预排序。每个遍历产生比以前一个更有序的列表,使得最终遍历更有效。
# 时间复杂度介于O(n)和O(n^2)。
def shellSort(num):
sublistcount = len(num)//2
while sublistcount > 0:
for startposition in range(sublistcount):
gapInsertionSort(num, startpositio... |
d754ddbdc7242f9ca716c599bb6709a9abb96dad | mjbaucas/BlackJackBot | /dealer.py | 2,081 | 3.59375 | 4 | from random import *
from cards import Cards
cards = Cards()
class Dealer:
def init(self, deck1, deck2, deck3, deck4):
self.deck1 = deck1
self.deck2 = deck2
self.deck3 = deck3
self.deck4 = deck4
self.hand = []
self.score = 0
self.one_card_score = 0
def ... |
52e3f4e8afb6f69a0832c287b3e1eb9923187e4d | geodimitrov/Python-OOP-SoftUni | /Encapsulation/Exercises/01.wild_cat_zoo/project/zoo.py | 4,303 | 3.6875 | 4 | class Zoo:
def __init__(self, name, budget, animal_capacity, workers_capacity):
self.name = name
self.animals = []
self.workers = []
self.__budget = budget
self.__animal_capacity = animal_capacity
self.__workers_capacity = workers_capacity
@staticmethod
def h... |
e6ebd32c4664aa73903da3c0b4fd660c0193557a | tonylixu/devops | /algorithm/keyboard-row/keyboard-row.py | 1,133 | 4.0625 | 4 | def findWords(words):
# We define keyboard rows
keyboard_rows = [
['e', 'i', 'o', 'p', 'q', 'r', 't', 'u', 'w', 'y'],
['a', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 's'],
['b', 'c', 'm', 'n', 'v', 'x', 'z']
]
# We sort and eliminate the duplicate
# because if you can type one, you ... |
5b1e2bd367cd7064713ed7084a4803c65a55cd31 | nurulmisbahudin/Tugas-coding | /LIST.py | 770 | 3.609375 | 4 | jawab = 'ya'
while(jawab == 'ya'):
no = input("NO :")
nama = raw_input("NAMA :")
nim = input("NIM :")
nt= input("NILAI TUGAS :")
nuts = input("NILAI UTS :")
nuas = input("NILAI UAS :")
nakhir = int(nt*30/100)+(nuts*35/100)+(nuas*35/100)
jawab = raw_input("Tambah data (ya/tidak) ... |
bf3540869cd84942f604019fd88db5eea27584a9 | speedybees/dailyprogrammer-165-the-forest | /node.py | 1,327 | 3.859375 | 4 | from enum import Enum
class Direction(Enum):
north = n = 1
northeast = ne = 2
east = e = 3
southeast = se = 4
south = s = 5
southwest = sw = 6
west = w = 7
northwest = nw = 8
class Node(object):
def __init__(self):
self.entities = set()
self.travel_directions = {}
... |
063a238f1355b9f299c459c4afd9ba349c4b5068 | honghen15/checkio_ | /long-repeat.py | 895 | 4.15625 | 4 | def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
# your code here
count = 0
max1 = 1
if(line == ''):
return 0
letter = ''
for i in line:
if letter == '' or not (letter == i):
letter = i
count = 1
... |
a7117cc56c3a2e6e7cb2a4bad21867fde3d29806 | eucortes04/python-challenge | /PyBank/main.py | 2,434 | 3.625 | 4 | import os
import csv
#Path to collect dataset
financials_csv_path = os.path.join('Resources','budget_data.csv')
#Reading in CSV
with open(financials_csv_path) as csvfile:
financials = csv.reader(csvfile, delimiter=",")
#accounting for header
csv_header = next(financials)
#Variables
totalMonths =... |
e8edfea23b9a36a6c73b598fb52dab7e1f2223d0 | Gera2019/gu_python | /lesson_11/task_4.py | 3,889 | 3.609375 | 4 | from collections import defaultdict
class OfficeEqpmt:
type = ''
def __init__(self, name, vendor):
self.name = name
self.vendor = vendor
def __str__(self):
return f'{self.type} {self.vendor.capitalize()} {self.name.capitalize()}'
@property
def _data(self):
return (... |
2a1a3ee56b149231fd7de00d1bf245e7e9c08e9c | mattcpfannenstiel/feudalismSimMulti | /Climate.py | 505 | 3.734375 | 4 | import random as r
class Climate:
"""
This represents the number of growing days for each landunit
"""
def __init__(self):
"""
Creates a new instance of climate class for a landunit
"""
self.growthmax = 300
self.growthmin = 80
self.growthdays = r.randint... |
d0ec06bb7e0a4d418372af1d9dba9e5873ba0ab0 | marcelo046/algoritmo_busca | /main.py | 2,728 | 3.609375 | 4 | %matplotlib inline
import random
import matplotlib.pyplot as plt
import time
# declarações
size = 500 # não pode ser maior que max_number, pois dá erro no random.sample
loops = 25
max_number = 1000
x = []
time_sequential = []
time_binary = []
# comandos iniciais
for i in range(1, size+1):
x.append(i)
# funções
... |
90af3a34ae86ec958603dc1555b61f3be291b4ae | yckfowa/codewars_python | /8KYU/Swap Values.py | 181 | 3.515625 | 4 | #Solution 1
def swap_values(args):
args[0], args[1] = args[1], args[0]
-----------------------------------------
#Solution 2
def swap_values(args):
return args.reverse()
|
8b37912e08d5fc2a6656c7631be698bcd98bbe7f | wjj800712/python-11 | /chengxiangzheng/week3/test.py | 244 | 3.546875 | 4 | #python冒泡排序
list=[1,89,37,98,67,82,12,46,328,15,23,124,65,36,76,83]
print(len(list))
for i in range(len(list)):
for j in range(len(list)-1-i):
if list[j]>list[j+1]:
list[j],list[j+1]=list[j+1],list[j]
print(list) |
a55ad2829bd9bfb2ac8301422302f2fb15cd054b | SophieChien/driving | /driving.py | 742 | 3.984375 | 4 | country = input('請輸入您的國家:')
age = input('請輸入您的年齡: ')
age = int(age)
if country == '台灣':
if age >= 18:
print('您可以考駕照')
else:
print('您還不能考駕照')
elif country == '美國': #根源於if,為if的延伸
if age >= 16:
print('您可以考駕照')
else:
print('您還不能考駕照')
else:
print('只能輸入台灣或美國')
country = input('請輸入您的國家:')
age = input('請輸入您的年齡: '... |
4f76b680e1927bf2d39024e04925451659e34cb0 | thirstycode/GUI_application_python_tkinter | /prog2.py | 1,712 | 4.03125 | 4 | # made by pratik kinage (thirstycode)
# https://github.com/thirstycode
# importing module tkinter
# first you need to install tkinter module
from tkinter import *
# create window using tkinter
win = Tk()
# title for window
win.title("Convertor")
# declaring input variable in tkinter
input1 = String... |
4c1fbefb077ae6a8f94c98814aea7701097b784c | Leo-Mensah/Exercises | /exercise5.py | 260 | 3.828125 | 4 | first = input("Enter the file name: ")
fname = open(first)
lst = list()
for name in fname:
flist = name.split()
for i in flist:
print(i)
if i in lst :
continue
else:
lst.append(i)
lst.sort()
print(flist)
|
018687a13e5dabcf73d1b806b1e3460c16e6e914 | dakotabourne373/CS1110 | /crypto.py | 623 | 3.5 | 4 | # Dakota Bourne (db2nb) Nick Manalac (ntm4kd) Justin Lakier (Jel5hv)
"""
"""
def encrypt(plain_text, key):
cipher_text = '' # accumulator pattern: start with no encrypted test
for i in range(0, len(plain_text), 1): # look one chunk at a time
chunk = plain_text[i:i+1] # all chunks th... |
a25f46ecfeeac8deadf77142a35e199ff9a978fc | Carb-X/Exercise | /Mlog.py | 2,564 | 3.6875 | 4 | """类的内省和装饰器。
定义一个类Mlog,对于继承自Mlog的子类,每当其调用属性方法时,打印如下内容:
类名、被调用的属性方法和参数值列表
开始运行时间
结束运行时间
函数运行的结果
示例:
class Any(Mlog):
def track(*args, **kwars):
pass
a = Any()
a.track(1,2,3, b="xx")
输出:
[Mlog] Any.track(1,2,3, b="xx")
[start] {start_timestamp}
[end] {end_timestamp}
[result] {result}
"""
import datet... |
3cf12c5ad110bd61f13ccb6957afd7cc9c5d1d26 | yoonakim1027/devops_cloud-1 | /myproj02/main06.py | 197 | 3.625 | 4 | def gugudan(number):
# number = 2
print(f"--- {number}단 ---")
for i in range(1, 10):
print(f"{number} * {i} = {number * i}")
for number in range(2, 10):
gugudan(number)
|
b22088c2ebe9734e8382183bdbf7991d50616ed3 | ZhuJiaYou/Interview_Preparation | /leetcode/84_largest_rectangle_area.py | 1,012 | 3.921875 | 4 | def largest_rectangle_area(heights):
largest = 0
def largest_n(i):
low, high = i, i
while low-1 >= 0 and heights[low-1] >= heights[i]:
low -= 1
while high+1 < len(heights) and heights[high+1] >= heights[i]:
high += 1
return (high-low+1)*heights[i]
for ... |
1ea5429aefcacbdd9dc82d94b09d78c793c7ae98 | Fashad-Ahmed/Python-Practices | /duplications.py | 276 | 3.859375 | 4 |
x=int(input("enter character: "))
list1=[]
for i in range(x):
a=int(input("ennter number: "))
if type(a) == int:
list1.append(a)
else:
continue
final=[]
for i in list1:
if i not in final:
final.append(i)
print(final) |
29e122c37046f2f538c20e84ea02cfe3d9b8cbfe | Ardyn77/PythonExamples | /functions.py | 910 | 3.640625 | 4 | def complexFunction(s,*mult,**amt):
sum = 0
for x in mult:
sum = sum +x
print("the legends name is: ",s,"\n %s, the total sum we have gathered is %d"%(s,sum),"and list is as follows")
for i,j in amt.items():
print("Person",i,"Amount",j)
print(complexFunction("sairam",550,650,750,850,pete... |
25c32239f2bf683826b49fa179e6db9c421ff3bc | Big-Wisdom1996/Food | /untitled0.py | 1,268 | 3.578125 | 4 | def grabLine(line):
source = open(r"/users/elihermann/documents/github/food/source.txt",'r')
for x in range (0,line):
data = source.readline()
source.close()
return data
def main():
line = grabLine(1)
x = 1
dish,ingredient, AInv, WInv = "","","",""
while(line... |
c70ca434e2d6f92e899009926301121d23bd5a02 | haohaixingyun/dig-python | /com/ibm/testing/list.py | 467 | 3.65625 | 4 | '''
Created on Mar 30, 2016
@author: yunxinghai
'''
def main():
Squ = [1,2,3,45,6,8]
sums = 0
lists = ['larry', 'curly', 'moe']
for var in Squ:
sums +=var
print sums
if 'curly' in lists:
print 'yay'
for i in range(10):
print i ... |
9a1784c313dd739d4bb344f2b8956693f476b6fb | capitao-red-beard/practice_exercises | /even_or_odd.py | 162 | 4.3125 | 4 | value = int(input('Please enter a maximum value: '))
for i in range(0, value + 1):
if i % 2 == 0:
print(i, 'EVEN')
else:
print(i, 'ODD')
|
f147e4f5a81b178412f789dd5cce5215214a70c8 | maheshmnj/Mathematizer | /rationalnumbertofraction.py | 132 | 3.546875 | 4 | #subscribed codehouse
from fractions import Fraction
value=input("Enter decimal number:")
print(Fraction(value).limit_denominator()) |
35c84a784394d5416fed28805849db854bf1ad81 | maydaymiao/python-training | /L1_String.py | 1,349 | 4.34375 | 4 | '''
print
mulitlines打印分段
len
slice [0] [0:b] [:b] [a:]
string methods: lower, count, index, find, replace
字符串连接(+,+' '+, .format, fstring)
dir, help()
'''
print('hello world')
message = 'Hello World'
print(message)
# mulitlines = '''I like Python,
# Python is awesome.
# '''
# print(mulitlines)
# len()
print('messag... |
a96d52dc9b267087e0dd79073957067074b28c2d | YowKuan/Computer-Networks---UDP-TCP | /UDPClient.py | 1,099 | 3.84375 | 4 | from socket import *
serverName = 'localhost'
serverPort = 8888
#we are not specifying the port number of the client socket when we create it
clientSocket = socket(AF_INET, SOCK_DGRAM)
#Initial "hello message to server"
message = "Hi, the client want to establish the connection!"
while True:
clientSocket.sendto(me... |
6d6699b6a9accd2b63da4bb301fe5cc10441f33a | alex-dukhno/python-tdd-katas | /path_sum_kata/day_11.py | 2,228 | 3.84375 | 4 | import unittest
def path_sum(root, give_sum):
return path_sum_recursive(root, give_sum, [])
def path_sum_recursive(root, given_sum, path):
if root is not None:
path.append(root.val)
if root.is_leaf() and root.val == given_sum:
return [path]
else:
return path_s... |
b42e210b3a90cca0b8c777412d4aecfcd41b5254 | sreerajch657/internship | /practise questions/largest length word.py | 372 | 4.5 | 4 | #Python Program to Read a List of Words and Return the Length of the Longest One
str_string=input("enter a string : ")
length=[]
str_string=str_string.split()
length_string=int(len(str_string))
for i in range(0,length_string) :
item=str_string[i]
x=int(len(item))
length.append(x)
length.sort()
print(... |
1118c34ee7e321a400e66addd558a293395ad387 | beata0422/Python-Function-Population-Growth | /script.py | 792 | 3.84375 | 4 | city_name = 'Istanbul, Turkey'
pop_1927 = 691000
pop_2017 = 15029231
pop_change = pop_2017 - pop_1927
percentage_gr = pop_change / pop_1927 *100
annual_gr = percentage_gr / 90
print(annual_gr)
def population_growth (year_one, year_two, population_one, population_two):
population_change = population_two - population... |
be5b41a44b679b7c9886b4d34b9622db2bf2df75 | jm2242/interviewPrep | /interviewBit/matrix-median.py | 2,557 | 3.84375 | 4 | import sys
class Solution:
# @param A : list of list of integers
# @return an integer
def findMedian(self, A):
# sub_list_len = len(A[0])
# return ([m[sub_list_len/2] for m in A].sort())[len(A)/2]
l =0
h = sys.maxint
m = None
target = (len(A) * len(A[0]) / 2)
... |
a3061f96184e9a8fa27f3900e8eb095c1357e160 | rrwt/daily-coding-challenge | /gfg/trees/covered_uncovered_node_sum.py | 1,595 | 4.21875 | 4 | """
Given a binary tree, you need to check whether sum of all covered elements
is equal to sum of all uncovered elements or not. In a binary tree, a node
is called Uncovered if it appears either on left boundary or right boundary.
Rest of the nodes are called covered.
"""
from typing import Optional
from binary_tree_n... |
6c484975390a734117e88b8ff2d00c1681f8e1fc | jamiejamiebobamie/pythonPlayground | /pallindromeLL.py | 1,430 | 4.03125 | 4 | """
Test whether a link list in pallindromic.
"""
class Node:
def __init__(self, data=0, next=None):
self.data = data
self.next = next
n = Node(0)
m = Node(1, n)
l = Node(2, m)
k = Node(3, l)
j = Node(2, k)
i = Node(1, j)
h = Node(0, i)
g = Node(5)
f = Node(5, g)
e = Node(3, f)
d = Node(3, e)
c... |
2a513e21a2d6c61d592cbf0b6dfc3f32250fed3e | CrtomirJuren/pygame-projects | /beginning-game-development/Chapter 2/tankgame.py | 918 | 3.671875 | 4 | from tank import Tank
tanks = {"a":Tank("Alice"), "b":Tank("Bob"), "c":Tank("Carol") }
alive_tanks = len(tanks)
while alive_tanks > 1:
for tank_name in sorted( tanks.keys() ):
print(tank_name, tanks[tank_name])
first = input("Who fires? ").lower()
second = input("Who at? " )... |
9545fe732a346fe820902d575dd77376ee60c378 | vinaysankar30/Python-Programs | /untitled28.py | 729 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 20:52:47 2019
@author: admin
"""
n = int(input("enter no of rows"))
x = int(input("enter no of coloums"))
a = []
b = []
new = []
for i in range(x):
c = []
s = []
for j in range(n):
e = int(input("enter the number to 1st matrix"))
... |
f02111956cf6b268e3250765a366e0c3738511ce | pchhina/interactive-programming | /pong/pong.py | 5,110 | 3.6875 | 4 | import tkinter as tk
import time
import random
root = tk.Tk()
root.title("Pong")
class Pong:
"""Represents the game of pong.
"""
def __init__(self, master):
self.width = 1000
self.height = 800
self.window = tk.Canvas(master, width = self.width, height = self.height)
self.w... |
c2349bf4d75d17e3c168e1de05dd4ebf57017ed0 | stellahileman/comp110-21f-workspace | /lessons/for_in.py | 215 | 4.21875 | 4 | """An example of for in syntax."""
names: list[str] = ["Stella", "River", "Max", "Claudia"]
i: int = 0
while i < len(names):
name: str = names[i]
print(name)
i += 1
for name in names:
print(name) |
3e7511a47097deda5856235d20113ae794598270 | wtyhome/Python-Learning_Examples | /script24.py | 356 | 3.59375 | 4 | #functions
def f1(inpN):
#2 3 5 8 13 21
n=int(inpN)
if (n==1 or n==2):
return n+1
else:
return f1(n-1)+f1(n-2)
def f2(inpN):
#1 2 3 5 8 13
n=int(inpN)
if (n==1 or n==2):
return n
else:
return f2(n-1)+f2(n-2)
#main
s=0.0
temp=0.0
for i in range(1,21):
temp=(f1(i)/f2(i))
print(temp)
... |
228601f54189accac6c71837b9b8e4521978d00a | smohapatra1/scripting | /python/practice/day29/nested_loop_to_find_number_prime3.py | 157 | 3.546875 | 4 | #Prime number with range of values
for i in range(1,200):
for v in range(2, i):
if (i % v ) == 0 :
break
else:
print (i)
|
8c1813f8121ff282115bb88a1e95a42e0dcc9ea8 | altuhov-as/geekbrains-python-start-homework | /lesson_4/task_7.py | 232 | 3.921875 | 4 | def fact(number: int):
temp_result = 1
if number == 0:
yield temp_result
for i in range(1, number + 1):
temp_result *= i
yield temp_result
my_number = 5
for n in fact(my_number):
print(n)
|
94488040b03c9289533284c4c1a8c9b8a2646a23 | MrN1ce9uy/Python | /my_first_program.py | 1,025 | 4.25 | 4 | #This is a simple program that utilizes variables, functions, & a loop.
#Created by MrN1ce9uy
#Define payroll function
def payroll():
#Payroll calculations
hours = float(input("Enter number of hours worked: "))
rate = float(input("Enter hourly rate: "))
amount = hours * rate
#Print values
print ("Hours worked:",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.