blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
db4a5f858f0bb998963b9e4eabfd843a4369baac | Refuse0126/My-Python-Code | /Moudles/Function/instance_tree.py | 515 | 3.546875 | 4 | """
查找实例的继承类树
Date:2019.5.14
"""
def classtree(cls,indent):
print('.'*indent+cls.__name__)
for supercls in cls.__bases__:
classtree(supercls,indent+3)
def instancetree(instant):
print('Tree of %s'%instant)
classtree(instant.__class__,3)
def selftest():
class A: pass
class B(A): pass... |
128a65494634499255bf12a38afcb4a2f1e4527d | MagdalenaKoltuniak/Practice | /zframez_exercise.py | 6,972 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 18:56:14 2020
@author: Magdalena
"""
# =============================================================================
# 1. Write a python program to print the square of all numbers from 0 to 10
# =========================================================================... |
33b66a2a5cbce1ac653f4f8ad8d710dc586dba69 | SamSSY/ObjectAndClass | /python練習/LeapYear_NotOOP/LeapYear_NotOOP.py | 365 | 4.03125 | 4 | def isLeapYear(newYear):
if newYear % 4 == 0:
if newYear % 100 != 0 or newYear % 400 == 0:
return True
else:
return False
for i in range(0, 3, 1):
newYear = int(input())
if isLeapYear(newYear):
print("The", newYear, "is leap year.")
else:
... |
9b7d3d148a01de9361a4283bc701ae9934606900 | SamSSY/ObjectAndClass | /練習/4/BinarySearch.py | 826 | 3.828125 | 4 | def binarySearch(lst, key):
low = 0
high = len(lst) - 1 # Last index in lst
while high >= low:
mid = (low + high) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
return -1
list1... |
f3543b7840f1d43d53abfe9c303836825ddacc63 | javaInSchool/python1_examples | /les2/example1.py | 363 | 4.34375 | 4 | print("Почему сегодня идет снег?")
fred = "Привет, меня зовут фред!"
text = "Как дела?"
string = 'Что-то пошло не так'
print(string)
name = "д'Артаньян"
#name = 'д'Артаньян'
print(name)
name2 = 'д\'Артаньян'
name3 = '''д'Арта"нья"н
и три
мушкетера''' |
175baa04d3c3ea4a26217534b8dbe6528494cb39 | javaInSchool/python1_examples | /les5/task.py | 407 | 3.53125 | 4 | # task 1 = def convert(weightOnEarth)
# input weight from keyboard
# create method with 2 parameters def power2(number, stepen)
# 2^4 = 16, 2 * 2 * 2 * 2
import sys
def convert(weightOnEarth):
weightOnMars = weightOnEarth / 2.64
print("Weight %s on Mars: %s" % (weightOnEarth, weightOnMars) )
print("Input yo... |
81e7940644dfe68495c8c2cfb315a8efa768defc | javaInSchool/python1_examples | /les9/test.py | 1,702 | 3.59375 | 4 | from tkinter import *
import pickle
class User:
def __init__(self, name, password):
self.name = name
self.password = password
def __eq__(self, other):
if not isinstance(other, User):
# don't attempt to compare against unrelated types
return NotImplemented
... |
51ba7aa694e601eda12ed91a1d62dead7baa4652 | javaInSchool/python1_examples | /les7/ex4.py | 348 | 3.6875 | 4 | print( eval("10*5") )
#print( eval("if True: 10*5"))
sentence = input("Що обчислити? ")
print(eval( sentence) )
myProgram = "print('Hello, world')\nprint('my program')"
myProgram = '''print('Hello, world')
print('my program')'''
exec(myProgram)
text = "56"
number = int(text)
print(text * 2)
print(number * 2)
print(... |
6f0802b130fe922630ba0e511a2fd0713c1b5f8c | javaInSchool/python1_examples | /les5/les4_home.py | 204 | 3.59375 | 4 | surname = ["Ivanov", "Petrov", "Sidorov"]
name = ["Ivan", "Petro", "Serg"]
elements = len(surname) # API - application programming interface
for n in range(0, elements):
print(n, surname[n], name[n]) |
84eb3f359ba39dad0f03e91c2ca056f63abf1073 | raym0ndev/Passwordgen | /PassGen.py | 1,028 | 3.578125 | 4 | # 0's will b x's
# t and h will never be beside each other the h will be moved to the end
# letters "raymnd" will be "evans8"
# the 4,8 vowel will be ?s a8e3i4o\u%
#
#
#
import config
website = "gmail.com"
code = "disicpline and preparation create opportunity forcing growth in a world that doesn't love us bu... |
6c097284b46c51a72dda8cba987e6d576a8a4ba7 | qRedd/SapiensSerpentis | /SapiensSerpentis_v1/SapiensSerpentis_v1.py | 764 | 3.71875 | 4 | import turtle
import random
from turtle import *
import math
import time
import tkinter
t = turtle.Turtle()
ecran = turtle.Screen()
t.getscreen().bgcolor("white")
turtle.title("The maze of LIFE")
ecran.setup(800,800)
ecran.bgpic('maze.gif')
ecran.addshape("logo3.gif")
t.shape("logo3.gif")
time.sleep(2... |
d90b8f4134725a0dbc4d7fb0ee562599bd0a69dd | PandABlocks/PandABlocks-server | /python/test_extension/interval.py | 549 | 3.53125 | 4 | from __future__ import division
# Simple conversion from centre/range to start end interval
class Range:
def __init__(self, n):
self.centre = 0
self.range = 0
def set_centre(self, centre):
self.centre = centre
return self._interval()
def set_range(self, range):
se... |
5b846619a8fe7c717e7ad5e3dbb01ce500dfd5b0 | Muckler/python-exercises-feb | /february_exercises/python_part2_exercises/positive_num2.py | 148 | 3.578125 | 4 | my_num = [1, -5, 4, 32, -8, 7, 18, -21, 5]
new_nums = []
for num in my_num:
if num > 0:
new_nums.append(num)
else:
pass
print(new_nums)
|
fd51ac24855450077ea1fdf4627062e311f30182 | Muckler/python-exercises-feb | /february_exercises/python_part2_exercises/leet.py | 298 | 3.890625 | 4 | my_str = input("Enter some text...").upper()
my_str = my_str.replace("A", "4")
my_str = my_str.replace("E", "3")
my_str = my_str.replace("G", "6")
my_str = my_str.replace("I", "1")
my_str = my_str.replace("O", "0")
my_str = my_str.replace("S", "5")
my_str = my_str.replace("T", "7")
print(my_str) |
2ff2715419ab5ff91a3c55cd79107d71c51b39e4 | Muckler/python-exercises-feb | /february_exercises/python_part3_exercises/Challenges_alg2.py | 162 | 3.671875 | 4 | my_list = []
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
my_list.append(i)
total_sum = 0
for j in my_list:
total_sum += j
print(total_sum)
|
788fb1d0570e6181b464bc6ce5c49d036b44afc8 | Muckler/python-exercises-feb | /february_exercises/python_part2_exercises/de_dup.py | 160 | 4.03125 | 4 | my_num = [2, 8, 3, 5, 2, 7, 8]
new_num = []
#new_num.append(my_num[0])
for num in my_num:
if num not in new_num:
new_num.append(num)
print(new_num) |
85c5b44cdd44a23af6a1f7378e3ec40ef0d77b8e | Muckler/python-exercises-feb | /february_exercises/python_part2_exercises/mult_list.py | 135 | 3.765625 | 4 | my_num = [1, 4, 32, 7, 18, 5]
new_num = []
the_factor = 3
for num in my_num:
new_num.append(num * the_factor)
print(new_num)
|
806f023c7ae0af568708561112b4c59335abf1b1 | Muckler/python-exercises-feb | /february_exercises/python_part3_exercises/turtle1_square.py | 313 | 3.828125 | 4 | from turtle import *
# move into position
def square():
up()
forward(50)
left(90)
forward(50)
left(90)
down()
# draw the square
pencolor('orange')
forward(100)
left(90)
forward(100)
left(90)
forward(100)
left(90)
forward(100)
if __name__ == "__main__":
square()
mainloop() |
53981b4d6f048dc0fb1e9a95e787a1f5f9d31fd0 | Hibrit/rubikstimer | /databasemanagement.py | 5,613 | 3.609375 | 4 | from random import randrange
import sqlite3
class Time():
def __init__(self, scramble, time):
self.scramble = scramble
self.time = time
self.avgo5 = 5
self.avgo12 = 12
self.db = Database()
self.calc_avgo12()
self.calc_avgo5()
def calc_av... |
8abd47f10f699c8503db24cf8bf3f568ae479607 | ngraham20/Whitworth-Advanced-Algorithms | /submission/main.py | 387 | 4 | 4 |
def main():
the_input = input("Enter a number\n>>")
the_primes = find_primes_less_than(int(the_input))
print(the_primes)
def find_primes_less_than(n):
the_range = list(range(2, n))
for i in the_range:
for j in the_range:
if j != i and j % i == 0:
the_range.remo... |
73c6add305047fee56465059b77c5201d5284921 | LucasManza/AM4 | /TP1/TP1.py | 2,593 | 3.890625 | 4 | import math
from decimal import Decimal
from math import pi
import decimal
def selectionNumber():
print(
"\nPresione 1 para ver el valor de pi propuesto por la libreria de python \nPresione 2 para calcular pi con "
"el algoritmo de Gauss-Legendre usando tipo float \nPresione 3 para calcular pi con... |
bf0e360370d704920509e4a61e7c0b79f983c2de | Maxim1912/python | /list.py | 352 | 4.15625 | 4 | a = 33
b = [12, "ok", "567"]
# print(b[:2])
shop = ["cheese", "chips", "juice", "water", "onion", "apple", "banana", "lemon", "lime", "carrot", "bacon", "paprika"]
new_element = input("Что ещё купить?\n")
if new_element not in shop:
shop.append(new_element)
print('We need to buy:')
for element in shop:
pri... |
f6e7041c500d122cdc8cbedd02523e6b6996c188 | keyi/Leetcode_Solutions | /Algorithms/Python/Insert-Interval.py | 1,388 | 3.828125 | 4 | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
:rtype: Li... |
f3d3c209c048e958e26bd840937c7135890c448d | keyi/Leetcode_Solutions | /Algorithms/Python/Binary-Tree-Right-Side-View.py | 1,334 | 3.890625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# METHOD 1: DFS
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
... |
b8ba7e3c413140f95dd2c1c0f86e8916c7bfccd0 | keyi/Leetcode_Solutions | /Algorithms/Python/Reverse-Words-in-a-String.py | 998 | 3.515625 | 4 | class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
start, end, flag = 0, 0, True
for i in range(len(s)):
if s[i] != ' ':
if flag:
start = i
flag = False
... |
7fd6dd2c100957a4291ec13e901ddfcb3446f0b3 | keyi/Leetcode_Solutions | /Algorithms/Python/Count-Primes.py | 414 | 3.671875 | 4 | class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
import math
if n < 2:
return 0
arr = [True for x in range(n + 1)]
for i in range(2, int(math.sqrt(n)) + 1):
if arr[i]:
for j in ... |
fc7a7856b6ff8af5b627d51965e2f0f9fff6d772 | keyi/Leetcode_Solutions | /Algorithms/Python/Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal.py | 1,607 | 3.875 | 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 buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]... |
1aa88b8a696c8d51a92590f3f41b52249b5eaa25 | keyi/Leetcode_Solutions | /Algorithms/Python/Partition-List.py | 951 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if not he... |
1bc7469a0d24219c012fe00420bfcd2f73430d62 | keyi/Leetcode_Solutions | /Algorithms/Python/Reorder-List.py | 967 | 3.890625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
... |
aef6c669393d2febdf28cc55777cfdfa06a9e282 | naren-m/algos | /data_structures/stack.py | 1,748 | 4.03125 | 4 | """
Stack: A stack is a basic data structure that can be logically thought as
linear structure represented by a real physical stack or pile, a structure
where insertion and deletion of items takes place at one end called top of
the stack. The basic concept can be illustrated by thinking of your data set... |
851bafa8ed1c9ab75b80fb0f69b8e6e6da88d7d8 | naren-m/algos | /algos/merge_sort.py | 1,195 | 4.03125 | 4 | def merge_sort(arr):
if len(arr) == 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right, arr)
def merge(left, right, arr):
l = r = i = 0
ll = len(left)
lr = len(right)
while l < ll and r < lr :
if le... |
86de52a241ae3645d41c693383b7b232c95126c5 | gcnTo/Stats-YouTube | /outliers.py | 1,256 | 4.21875 | 4 | import numpy as np
import pandas as pd
# Find the outlier number
times = int(input("How many numbers do you have in your list: "))
num_list = []
# Asks for the number, adds to the list
for i in range(times):
append = float(input("Please enter the " + str(i+1) + ". number in your list: "))
num_list.append(ap... |
4a868363a85154ba1e591184c3b368e918dd9086 | dupark3/PythonPractice | /AutomateTheBoringStuff/collatz.py | 697 | 4.09375 | 4 | def collatz(number):
if number == 1:
return
elif number % 2 == 0:
number = number // 2
print(number)
collatz(number)
else:
number = number * 3 + 1
print(number)
collatz(number)
def game():
try:
print('Enter your number to call collatz seq ... |
03362a677a4b090f092584c63197e01151937781 | ihanda25/SCpythonsecond | /helloworld.py | 1,614 | 4.15625 | 4 | import time
X = raw_input("Enter what kind of time mesurement you are using")
if X == "seconds" :
sec = int(raw_input("Enter num of seconds"))
status = "calculating..."
print(status)
hour = sec // 3600
sec_remaining = sec%3600
minutes = sec_remaining // 60
final_sec_remaining = sec_remaini... |
fefabb34fcca4fa218ea7631b7325fdab1e3607f | GaureeshAnvekar/ProblemSolving | /UCSDProblems/week4/different_summands.py | 923 | 3.984375 | 4 | # Uses python3
"""
You are organizing a funny competition for children. As a prize fund you have n
candies. You would like to use these candies for top k places in a competition
with a natural restriction that a higher place gets a larger number of candies.
To make as many children happy as possible, you are going to f... |
084a4fcaf7dad390db3bfea5bc14c515617cf969 | GaureeshAnvekar/ProblemSolving | /UCSDProblems/week5/majority_element.py | 1,332 | 3.90625 | 4 | # Uses python3
"""
Given a sequence of elements a 1 , a 2 , . . . , a n , you would like to check whether
it contains an element that appears more than n/2 times. Naive method
would be O(n2) going through all pairs. Using divide-n-conquer it is
O(nlogn)
"""
import sys
def get_majority_element(a, left, right):
if ... |
6d703b8444f8e2a96e5da70381ce97fbee68b1bc | pcrystal/Python-basic | /loops.py | 262 | 3.984375 | 4 | def numbers():
i = 6
while (i >5 and i < 19):
i = i + 1
print (i)
def numerals():
for m in range (12,20,2):
print (m)
numerals()
def numbers():
for n in reverse range(12,20,2):
print (n)
numbers()
|
2eb3a9153f37894dd0d979b731201e2c3f01e04e | tony2heads/OddNotebooks | /OLD/00_notebook_intro_screencast.py | 8,759 | 3.640625 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# # A brief introductory tour of the IPython notebook (the screencast version)
#
# This document will give you a brief tour of the capabilities of the IPython notebook.
# You can view its contents by scrolling around, or execute each cell by typin... |
3f240992c08ffae7f4f894b7772637f9abf70a8e | sAMARTH-crypto/python | /buystock.py | 981 | 3.796875 | 4 | #BEST TIME TO BUY STOCKS(leetcode)
#main concept is that the buying price should be always less than the selling price
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
ans = 0 #starting with ans = 0
mini = prices[0] ... |
b6c77d20d9968dc7581ec1f355a3cd55f8801df8 | Ocimas/proyectobioinfo | /Bacbonetracker.py | 2,299 | 3.53125 | 4 | ##Programa que lee un archivo backbone generado por Mauve. Devuelve 2 archivos.
#El backbone contiene los fragmentos presentes en todas cepas
#El islas devuelve si un fragmento esta presente "1" o ausente "0" en una una secuencia (solo en fragmentos no backbone)
#Lee el archivo backbone de Mauve
archivo = str(input("D... |
228c0ecfc5442ac3b6f11f0dab3a647bcefc28f1 | eman602/pythonIntroduction | /day1.py | 498 | 3.71875 | 4 | import coursewareexercise
coursewareexercise.entergrade()
coursewareexercise.awasome_names()
cool_cows = ["WinnietheMoo", "Moolan", "Milkshake", "Mooana"]
cool_sheep = ["Baaaart", "Baaaarnaby"]
cool_pigs = ["Chris P. Bacon", "Hamlet", "Hogwarts"]
cool_animals = [cool_cows, cool_sheep, cool_pigs]
putting={}
i=0
numbe... |
59809062a63c30a989fc41c3b4d6dc74276b6b8a | eman602/pythonIntroduction | /intermediate-questionpart1.py | 255 | 3.96875 | 4 | number1 = int(input("please enter a number: "))
number2= int(input("Please enter a second number: "))
if number1>21 or number2>21:
print(0)
if number1<=21 and number2<=21:
my_list=[21, number1,number2]
my_list.sort()
print(my_list[1])
|
e5435398c38136a088754d895004fa0e39c219f1 | C-CCM-TC1028-102-2113/tarea-3-programas-que-usan-funciones-Varuneishon | /assignments/10Bisiesto/src/exercise.py | 310 | 3.5625 | 4 |
def main():
#escribe tu código abajo de esta línea
def areaRect(x):
w=x/4
w2=round(w,0)
if w == w2:
print("TRUE")
return w
else:
print("FASE")
return w
a = int(input("Dame un año: " ))
r = areaRect(a)
pass
if __name__=='__main__':
main()
|
4785fd11ab80f0e29f7f8ef7ec60a8dab5c893de | japneet121/Python-Design-Patterns | /facade.py | 1,006 | 4.21875 | 4 | '''
Facade pattern helps in hiding the complexity of creating multiple objects from user and encapsulating many objects under one object.
This helps in providing unified interface for end user
'''
class OkButton:
def __init__(self):
pass
def click(self):
print("ok clicked")
class Can... |
0982540847b378e6ee2279c6eb3ab0e9cb8621cc | ToTHXaT/SisprogLabs | /constants.py | 3,228 | 3.53125 | 4 | from typing import *
from bitstring import Bits
from num import to_int_safe
def twos(num: int, bt: int) -> str:
return Bits(int=num, length=bt).bin
class ConstantRepr(NamedTuple):
code: str
length: int
def reverse_bits(s: str) -> str:
return ''.join(reversed([s[i:i+2] for i in range(0, len(s), 2... |
1c42aa345b266481dc20d1de3ea1a4c794a6edcb | Kenny-W-C/Tkinter-Examples | /layout/calculator.py | 2,510 | 3.90625 | 4 | #!/usr/bin/env python3
"""
ZetCode Tkinter tutorial
In this script, we use the grid manager
to create a skeleton of a calculator.
Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""
from tkinter import Tk, W, E
from tkinter.ttk import Frame, Button, Entry, Style
class Example(Frame):
def... |
2f9f0e381ba3e08a5a2487967a942d82292ab48c | Kenny-W-C/Tkinter-Examples | /drawing/draw_image.py | 866 | 4.1875 | 4 | #!/usr/bin/env python3
"""
ZetCode Tkinter tutorial
In this script, we draw an image
on the canvas.
Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""
from tkinter import Tk, Canvas, Frame, BOTH, NW
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self):
super()... |
e885582fd43b3438f804cc8c6a82348eea873396 | andrejdobric/programiranje | /hotel dom.py | 690 | 3.640625 | 4 | class smestaj:
def __init__(self, naziv, adresa, grad):
self.naziv = naziv
self.adresa = adresa
self.grad = grad
def __str__(self):
return (self.naziv,self.adresa,self.grad)
class hotel(smestaj):
def __init__(self, naziv, adresa, grad, brojzv):
smestaj._... |
49c0a130928382fc9fdfdcd87b2aeb543de1ffbc | tushar686/hackerrank | /SwapNodes.py | 2,243 | 3.71875 | 4 | class Vertex(object):
heightOfTree = 0
def __init__(self, val):
self.val = val
self.left = -1
self.right = -1
self.height = 0
def swap(self):
left = self.left
self.left = self.right
self.right = left
def __str__(self):
return str(self.val... |
43976dd93e1ccb0f0876e90627dcf35f2a8d4255 | tushar686/hackerrank | /maximiseXOR.py | 252 | 3.578125 | 4 | def maxXOR(L, R):
l = L
mx = 0
while l <= R:
r = L
while r <= R:
mx = max(mx, l ^ r)
r += 1
l += 1
return mx
L = int(raw_input())
R = int(raw_input())
print maxXOR(L, R)
|
9dcfb2a9bba4a8758093499c17c01a81a6e7e843 | tushar686/hackerrank | /MaximumSubArray.py | 854 | 3.5 | 4 | def calculateContiguousSum(L):
best_sum = 0
current_sum = 0
for ele in L:
if current_sum + ele > 0:
current_sum += ele
else:
current_sum = 0
if current_sum > best_sum:
best_sum... |
f725e9acc1af7281cd821a28a3f6d853b39f0412 | airoak/practice1 | /between.py | 121 | 3.78125 | 4 | first = raw_input("First digit: ")
last = raw_input("Last digit: ")
for i in range(int(first)+1,int(last)):
print i
|
a68900edb7a3debfac4334f66a46eb7077d586a7 | ejimenezdelgado/ext_logico_algoritmo_1_2018 | /Semana 5/ejercicio4.py | 238 | 3.765625 | 4 | #Creado por Efrén Jiménez Delgado
#Fecha:14/03/2018
#objetivo: Plantea un algoritmo que visualice los números del 1 al 10.
def ImprimeNumero():
contador=1
while contador<11:
print(contador)
contador=contador+1
ImprimeNumero() |
26dae3c45c5aafa8c6cae4dd1c87a39953f4f006 | ejimenezdelgado/ext_logico_algoritmo_1_2018 | /Semana 13/Main.py | 1,915 | 3.921875 | 4 | #Fecha: 09/05/2018
#Objetivo: Proyecto POO
from Frase import Frase
opcion=0
listaFrases=[]
print("Bienvenidos al mejor sistema del mundo para las frases")
while(opcion<7):
print("1. Agregar un autor")
print("2. Agregar una frase a un autor")
print("3. Primera frase de un autor")
print("4. Ultima fras... |
26ae8d355eac77544468fdf055cd9230d80f581c | forever0136789/python-100 | /python-38.py | 106 | 3.515625 | 4 | mat=[[1,2,3],
[3,4,5],
[4,5,6]
]
he=0
for i in range(len(mat)):
he+=mat[i][i]
print(he)
|
1906ad6ffe6ce10b436099a23a5fbd34cc7071ea | forever0136789/python-100 | /python-20.py | 244 | 3.828125 | 4 | #记录每次落地前最高高度(上一次反弹高度)
h=100
#记录落地时经历路程
total=100
#i代表第i次落地
for i in range(2,11):
h=h/2
total+=2*h
print('共经过:%fm'%total)
print('第十次反弹:%fm'%(h/2))
|
f67e0b49c839823e81130ef13693d21dbf8cf9b8 | forever0136789/python-100 | /python-56.py | 318 | 3.625 | 4 | from tkinter import *
#指定canvas组件宽度、高度、背景色
canvas=Canvas(width=800,height=600,bg='yellow')
#将canvas添加到主窗口
canvas.pack(expand=YES,fill=BOTH)
k=1
j=1
for i in range(26):
canvas.create_oval(310-k,250-k,310+k,250+k,width=1)
k+=j
j+=0.3
#让以上工作起来
mainloop()
|
aee3b2b4b5327f68f0c92fca411debf9dbc2a488 | d003kk/ff | /book.py | 846 | 3.671875 | 4 | """This module contains the Book class."""
class Page():
"""Page base class"""
def __init__(self):
""" Initialize Page."""
self.nextpage = []
self.text = ""
def play(self, player):
""" Print Text"""
print(self.text)
class PageNexus(Page):
"""A Page that just ... |
5a9c60245722eb710122e1af18778d212db4a84a | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m07_stacks/min_parenthesis_to_make_valid.py | 1,008 | 4.25 | 4 | #
# Given a string S of '(' and ')' parentheses, we add the minimum number of
# parentheses ( '(' or ')', and in any positions ) so that the resulting
# parentheses string is valid.
#
# Formally, a parentheses string is valid if and only if:
# It is the empty string, or
# It can be written as AB (A concatenated with B)... |
a34a3a968c04893b68bd75a18b239e399da680b9 | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m05_search/first_bad_version.py | 1,770 | 4.0625 | 4 | # You are a product manager and currently leading a team to develop a new
# product.
# Unfortunately, the latest version of your product fails the quality check.
# Since each version is developed based on the previous version, all the
# versions
# after a bad version are also bad.
#
# Suppose you have n versions [1... |
c54de8b4e0e074fe9f7b36d2b7ef5621cf249a7c | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m04_strings/valid_anagram.py | 229 | 3.625 | 4 | def valid_anagram(s, t):
# contains same characters in varying order
return sorted(s) == sorted(t)
print(
valid_anagram("bsoy", "byo")
)
# using collections
# return collections.Counter(s) == collections.Counter(t)
|
e978f07ced6f205af8593c88b55503e436f75a88 | catwang42/Algorithm-for-data-scientist | /basic_algo_sort_search.py | 2,886 | 4.4375 | 4 |
#Algorithms
"""
Search: Binary Search , DFS, BFS
Sort:
"""
#bubble sort -> compare a pair and iterate though 𝑂(𝑛2)
#insertion sort
"""
Time Complexity: 𝑂(𝑛2),
Space Complexity: 𝑂(1)
"""
from typing import List, Dict, Tuple, Set
def insertionSort(alist:List[int])->List[int]:
#check from index 1
for i... |
0f46fbffad62d52b3d3249fbb58522bcc9242b75 | catwang42/Algorithm-for-data-scientist | /dfs_employee_importance.py | 1,700 | 3.671875 | 4 | #PROBLEM
#690. Employee Importance
"""
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
"""
employees = [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]]
d = 1
def getImportance( employees, id: int) -> int:
weight_sum = 0
def find_child(master, alist, child):
if master == []:
return ... |
741251e55fdaa801639975ac10a052ebd01a8cf2 | catwang42/Algorithm-for-data-scientist | /tree_longest_univalue_path.py | 1,003 | 3.671875 | 4 | #687. Longest Univalue Path
"""
nput:
5
/ \
4 5
/ \ \
1 1 5
Output: 2
Input:
1
/ \
4 5
/ \ \
4 4 5
Output: 2
depth first search, need to find the max path and then add up
reset the ... |
9c2e9b4efeb3072ae4caaec95d7e8adcd0b4fad0 | catwang42/Algorithm-for-data-scientist | /valid_parentheses.py | 518 | 3.859375 | 4 | ################################
#MAP
#Problem
#check Valid Parentheses
def testFun():
assert isValid("{[]}") is True, "Funtion failed, should be True"
assert isValid("{[]") is False, "Funtion failed, should be False"
def isValid(s:str)->bool:
deque=[s[0]]
mapping = {'(': ')', '{': '}', '[' : ']'}
... |
70394dbd9832dfeb202979304b7704e3606aa1b3 | catwang42/Algorithm-for-data-scientist | /recursion-fibonacci.py | 927 | 3.9375 | 4 | #Fibonacci
from typing import List, Dict, Tuple, Set
def fib(x:int)->int:
if x < 0:
raise("negative value ")
elif x<=1:
return x
else:
return(fib(x-1)+fib(x-2))
[fib(x) for x in range(10)]
#dynamic programming
def fib_dp(x:int)->int:
mome = [None]*(x+1) #1 larger than numb... |
1661afdc5f44bd4f996849e76ad22872f41a7f8f | catwang42/Algorithm-for-data-scientist | /LL_add_two_linked_list.py | 717 | 3.625 | 4 | #2. Add Two Numbers
"""
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
sum_list= ListNode()
temp = sum_list #an temp mode to establish link to others
sum_val, pass_val = 0,0
#check num for the... |
b07040dcdf45ca0f60e8ecfe741fdc56e6b24c06 | kmfonagy/Python_3_Bootcamp | /code_files/rps_v3.py | 779 | 4 | 4 | import random
print("Rock...")
print("Paper...")
print("Scissors...")
player = input("Player, make your move: ").lower()
rand_num = random.randint(0,2)
if rand_num == 0:
computer = "rock"
elif rand_num == 1:
computer = "paper"
else:
computer = "scissors"
print(f"Computer plays {computer}")
res1 = "You w... |
47a4e1dded6cf9380c1543acf09044226332b33f | sophiejohnson26/comp171 | /Lab8 copy.py | 2,074 | 3.75 | 4 | '''
Author: Sophie Johnson
Date: November 28
Purpose: To do a webscrape for netpass usernames and passwords
'''
import urllib.request
def scrape(url,names,netpass):
'''
This function identifies names and corresponding netpass IDs and adds them to
lists
Args: a url,an empty list to add names to, and emp... |
fd84dcb1ea5513f1a8447155147761d345f2e0dd | Taranoberoi/PYTHON | /practicepython_ORG_1.py | 580 | 4.28125 | 4 | # 1 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
import datetime as dt
Name = input("Please Enter the Name :")
# Taking input and converting into Int at the same time
Age = int(input("Plea... |
de4dd804df9777ac13b9e1f4ba3b0b96c701da3a | Taranoberoi/PYTHON | /Practise1.py | 874 | 4.15625 | 4 | #1 Practise 1 in favourites
#1Write a Python program to print the following string in a specific format (see the output). Go to the editor
#Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what... |
be8f25e9e34c87f52a9c14525c51a6fbc9650e7b | plengkeek/Minor-Project-Group-2 | /src/Final/process_knmi.py | 935 | 3.515625 | 4 | # NOTE:
# Data geselecteerd vanaf KNMI site:
# FG, DR, RH, VVN, VVX
def process_knmi(file, path):
"""Convert a KNMI weather data text file to a PySpark DataFrame"""
def change_format(x):
"""This function converts a line of KNMI weather data to a list format
for use in a RDD"""
# conve... |
8c5ace68efef34e45b70c72c120e8c5c4c4bb8da | markopuza/algo_library | /mathematics/sum_of_divisors.py | 1,292 | 3.921875 | 4 | def modified_prime_list(n):
''' Modified primes list sieve. '''
prime = [False, False] + [True for _ in range(n)]
for i in range(2,int(n ** 0.5) + 1):
if prime[i] == True:
for j in range(i, n // i + 1):
prime[i * j] = i # composite numbers have this entry
return prime... |
180d52e523f5f57c07e23c43af16b8bb5c1464f4 | markopuza/algo_library | /memoize.py | 749 | 3.875 | 4 | def memoize(f):
''' memoization decorator '''
class memodict(dict):
def __init__(self, f):
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return memodict(f)
... |
04cc11daed1b361b5d64eafda9145eb1d7be7da1 | pghanem/Data-Structures-Algorithms | /hashMap.py | 2,007 | 3.984375 | 4 | class HashMap:
def __init__(self):
self.size = 10
self.map = [None] * self.size
def getHash(self, key):
hash = 0
for char in str(key):
hash += ord(char)
return hash % self.size
def add(self, key, value):
key_hash = self.getHash(key) #generate in... |
39a34d0c8e530b0a5a55cb177677886e57a0e6f4 | pghanem/Data-Structures-Algorithms | /3_1_threeInOne.py | 1,372 | 4.3125 | 4 | class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(s... |
23433d8c0b334133680234aff65f8a9077156ee7 | pghanem/Data-Structures-Algorithms | /2_4_partition.py | 2,690 | 3.84375 | 4 | class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
class... |
f807fa4ca3358d59e17a4c62d6de0c84b353c803 | zdutta/code-interviews | /rabbit.py | 5,400 | 4.09375 | 4 | '''
There is a rabbit that starts in the middle of an n x m matrix, n > 0, m > 0.
Each element of a matrix is an integer representing points gained for being on the spot.
If there are multiple possible "middles" then choose the one which has the highest point value to start on.
On each iteration, the rabbit can move ... |
b5c65b127bd73e309ab64b3a81a059adcd995da6 | saurabh-deochake/DS | /sorting/bubblesort.py | 541 | 4.25 | 4 | #!/bin/python
"""
Copyright 2016 Saurabh Deochake
1. Bubble Sort
O(n^2)
"""
def sort_bubblesort(my_list):
for pos_upper in xrange(len(my_list)-1,0,-1):
for i in xrange(pos_upper):
if my_list[i] > my_list[i+1]:
my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
... |
fc83e328871f9a85e6653732c9b03939144b0322 | main1015/co-work | /util/date.py | 361 | 3.875 | 4 | # -*- coding: utf-8 -*-
import datetime
__author__ = 'myth'
def add_hours_to_day(day, offset):
"""
Returns the date n hours before or after day
"""
return day + datetime.timedelta(hours=offset)
def add_days_to_day(day, offset):
"""
Returns the date n days before or after day
"""
ret... |
81e5bd642345c074b4ac9c55ee4e630a7d6ebd73 | BSchweikart/CTI110 | /M3HW1_Age_Classifier_Schweikb0866.py | 726 | 4.25 | 4 | # CTI - 110
# M3HW1 : Age Classifier
# Schweikart, Brian
# 09/14/2017
def main():
print('Please enter whole number, round up or down')
# This is to have user input age and then classify infant, child,...
# Age listing
Age_a = 1
Age_b = 13
Age_c = 20
# 1 year or less = infant
# 1 y... |
e720ec6ebd8e106e3cc983c73767c6271f358cef | ccannon94/python-workshop | /lists/lists.py | 1,895 | 3.984375 | 4 | # Create an empty list
items = []
items.append('Eggs')
items.append('Bacon')
items.append('Grits')
print items[1]
myName = []
myName.append('Christopher')
myName.append('Charles')
myName.append('Cannon')
print myName
# So that's weird, this is apparently a circular linked list
print myName[-1]
# One line instantia... |
bf613370b09222a10f029727bb4fa5b8ceedcc83 | chocotorroblue/WSQ-S | /wsq12.py | 367 | 3.9375 | 4 | #lol
def gcd(a,b):
if(a == b):
answer = a
elif(a > b):
answer = gcd((a-b), b)
else:
answer = gcd(a, (b-a))
return answer
#lel
print("Here is the GCD of two integer numbers")
x = int(input("Give me the first number: "))
y = int(input("Give me the second number "))
rgcd = gcd(x, y)... |
d2f68016e63d8248ed93c4dc934994386b624624 | sheetal804/Python-Repo | /Sets/union.py | 647 | 3.53125 | 4 | '''
It's so we can't have the satisfaction of one-liners like
print(len(set(map(int, input().split()))|set(map(int, input().split()))))
e="(set(input().split())if input()!='-1'else '')";print(len(eval(e)|eval(e)))
16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52
4
intersection_update 10
2 3 5 6 8 9 1 4 7 11
update 2
5... |
b74b4f7412e419e9cee84dd4ba14814a61822c0e | sheetal804/Python-Repo | /Itertools/group by.py | 157 | 3.5 | 4 | from itertools import groupby
data='1222311'
print(*[(len(list(k)),int(g)) for g,k in groupby(data)])
# for g,k in groupby(data):
# print(len(list(k)),g) |
438d9274af9649f9e99ea681691a9e1ffa9163bc | sheetal804/Python-Repo | /Built-ins/Sorting.py | 555 | 3.78125 | 4 | # string_input=input()
# lower=[]
# upper=[]
# digiteven=[]
# digitodd=[]
# for i in string_input:
# if(i.islower()):
# lower.append(i)
# elif(i.isupper()):
# upper.append(i)
# elif(i.isdigit()and int(i)%2==0):
# digiteven.append(i)
# elif(i.isdigit()and int(i)%2!=0):
# d... |
4bd2765c5c80cdb85fa9a2f6c1d9603ac6f26bd6 | Varunaditya/practice_pad | /Python/stringReversal.py | 1,454 | 4.125 | 4 | """
Given a string and a set of delimiters, reverse the words in the string while
maintaining the relative order of the delimiters.
For example, given "hello/world:here", return "here/world:hello"
"""
from sys import argv, exit
alphabets = ['a', 'b', 'c', 'd', 'e',
'f' , 'g', 'h', 'i', 'j',
'k', 'l', 'm', ... |
91c5976e429e09729f3857b8e5a633073837b368 | Varunaditya/practice_pad | /Python/merge_accounts.py | 1,915 | 4.28125 | 4 | """
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name,
and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email
tha... |
96dde2b69dc3a0baf27902b01a2884188f6dcc43 | DenysShvets/LaboratoryWork8 | /1.3.1(1).py | 950 | 3.703125 | 4 | import numpy as np
while True:
while True:
try:
n = int(input('Enter amount of digits')) #задаем введение количества цифр
a = np.zeros((n), dtype=int) #выделяем место для массива
b = np.zeros((n), dtype=int) #выделяем место для массива
break
... |
596b7cd8942209e21a401eceb37b4cb3374ca469 | harshrajm/Python-Algo-DS | /09 Sorting/practice.py | 3,670 | 4 | 4 | #1 Bubble Sort
def bubble(arr):
for x in range(len(arr)-1,0,-1):
for i in range(x):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
return arr
#------------------------------------------------------
#2 Selection ... |
2da57007eb640ee6bd9147d1d8d07be05bec8985 | harshrajm/Python-Algo-DS | /01 arrays/test.py | 134 | 3.703125 | 4 | def sum1(n):
final_sum = 0
for x in range(n+1):
final_sum += x
return final_sum
print(sum1(10)) |
8aede935d4fe562ae2432b680f2920f4c92451f8 | harshrajm/Python-Algo-DS | /05 LinkedList/singleLinkedList.py | 239 | 3.71875 | 4 | class Node:
def __init__(self,value):
self.value = value
self.next =None
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a.value)
print(a.next.value)
print(a.next.next.value)
print(a.next.next.next) |
6be9ff8332f30f8b62cf38243356cec8f154c443 | harshrajm/Python-Algo-DS | /02 Stacks/balanced paranthesis.py | 1,245 | 3.71875 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def isEmpty(self):
retur... |
d3638a4af1ee7456ab50ba97e3b3329c054a4d46 | irene-lin/course-scheduling | /common_courses.py | 1,314 | 4.0625 | 4 | # common_courses.py
# Irene Lin
# iwl@alumni.cmu.edu
# This file contains data processing to find which courses are taken together
# Input two courses and get a chart of which third course was most commonly
# taken in the same semester as the two courses
import data_fmt
def common_third_course(student_scheds,course1,... |
3eaaedff8af009d100a0f993f943494fdd0c6a4d | cskor/practice | /sudoku/other_method.py | 3,445 | 3.75 | 4 |
def m_read_table(filename):
#Parse given file into list containing each number
with open(filename) as f:
numbers = f.read()
numbers = [n.strip() for n in numbers]
numbers = [n for n in numbers if n]
numbers = list(map(int, numbers))
if len(numbers) != 81:
print('Input ... |
53d858dfe69ca7bd343388d0dba3e5d3a2f74b71 | Thanakrit22/CP3-Thanakrit-Charoenrat | /Assignments/Exercise11_Thanakrit_C.py | 135 | 3.734375 | 4 | inputNumber = int((input("Input Number : ")))
for k in range(inputNumber):
print(" " * (inputNumber - k - 1) + ("*" * (2 * k + 1))) |
a76e5199d329185092dbbe5402c6c6693436df07 | vatsal-sodha/Coding | /quick_sort.py | 374 | 3.65625 | 4 | def quick_sort(arr, l, r):
if (l < r):
q = partition(arr, l, r)
quick_sort(arr, l, q-1)
quick_sort(arr, q+1, r)
def partition(arr, l, r):
i = l - 1
x = arr[r]
for j in range(l, r):
if arr[j] < x:
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[r] = arr[r], arr[i+1]
return (i + 1)
arr = [5,... |
e72f1fb73912d8862c676d4f5e8a6564dae448c9 | gpastor3/Google-ITAutomation-Python | /Course_2/Week_2/lab_reading_and_writing_files.py | 1,481 | 3.9375 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 11/28/2020
"""
# Add guests to list
guests = open("guests.txt", "w")
initial_guests = ["Bob", "Andrea", "Manuel", "Polly", "Khalid"]
for i in initial_guests:
guests.write(i + "\n")
guests.close()
with open("guests.txt") as guests:
for line... |
dc363f27cc6e52277b539fbaabd2aedae1691933 | gpastor3/Google-ITAutomation-Python | /Course_2/Week_2/iterating_through_files.py | 971 | 4.5 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 11/28/2020
"""
with open("Course_2/Week_2/spider.txt") as file:
for line in file:
print(line.upper())
# when Python reads the file line by line, the line variable will always have
# a new line character at the end. In other words, the ne... |
9a03364338e57d43505a95c853999597e001c8a8 | gpastor3/Google-ITAutomation-Python | /Course_4/Week_1/Module_Review/scripts/greetings.py | 221 | 4.0625 | 4 | #!/usr/bin/env python3
import random
def greeting():
name = input("Hello!, What's your name?")
number = random.randint(1, 101)
print("hello " + name + ", your random number is " + str(number))
greeting()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.