blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
c85644e7f61671bb32dea7ab98b4213c03163019 | raqueloropeza/CodingDojo_Python_LoopsPart1 | /for_loops_basic1.py | 1,182 | 3.953125 | 4 | #Basic- Print all integers from 0 to 150
for i in range (0,151):
print (i)
#multiples of five - print all the multiples of 5 from 5 to 1,000
for i in range (5,1001):
if i % 5 == 0:
print(i)
#Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If devisible by ... |
124bfa11a7c1c566422faad790e410707941b542 | Babecherry/CP1404_Practicals | /prac_03/oddnames.py | 325 | 3.8125 | 4 | """Sable Ching"""
def get_name():
global main
def main():
while True:
name = str(input("Please enter your name: \n"))
if name == '':
print("Invalid, please enter your name.")
else:
print(name[1::2])
break
get_name()... |
d10f46ff0f2f0214215beedd4076cac2af014814 | mauricioklein/algorithm-exercises | /challenge-43/solver.py | 257 | 3.703125 | 4 | #
# Time complexity: O(n)
# Space complexity: O(1)
#
def max_subarray(nums):
# Kadane's algorithm
current_sum, max_sum = 0, 0
for num in nums:
current_sum = max(0, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
|
81aa44bf4cbeef632e7f1c3af87401c4734eeb5b | Retrojb/python-practice | /Section 2/for_loops.py | 1,066 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 19:20:02 2018
@author: johnbaltes
"""
primes = [2,3,5,7,11,13]
for prime in primes:
print(f'{prime} is a prime number')
kids_age = [4, 6, 9]
for age in kids_age:
print(f'I have a {age} year old kid')
for i in range(20):
p... |
7a7e2be161742b171fa8e1e102604aa802cb3ac2 | apenaloza7/testing-repository | /Models/Employee.py | 2,321 | 4.125 | 4 | # Employee Model
#
# Author: Alejandro Penaloza
# Last Updated: May 16 2020
class Employee:
annual_raise_amount = 1.07
# creates an instance of an Employee
def __init__(self, firstName, lastName, dept, salary):
self.firstName = firstName
self.lastName = lastName
self.dept = dept
... |
c5f06d02cf1cc01334495bd0d0d86e1631f0c464 | zdimon/lyceum | /8/code/init_ex.py | 297 | 3.765625 | 4 |
class Car(object):
def __init__(self):
self.doors = 2
def move(self):
return 'dr-dr-dr-d'
c = Car()
print c.doors
class Lorry(Car):
def __init__(self):
self.color = 'red'
#super(Lorry, self).__init__()
l = Lorry()
print l.color
print l.doors
|
c2678a16c9d6148735098b535bf0d0ef882a1dbf | Bannerli/Machine_Learning_Algorithms | /assignments/Sizheli_hw2/general_function.py | 900 | 3.6875 | 4 | import numpy as np
import matplotlib.pylab as plt
# define some classification
def step_function(x):
return np.array(x > 0, dtype = np.int)
def sign(x):
a_1 = np.array(x > 0, dtype = np.int)
a_2 = np.array(x < 0, dtype = np.int)
return a_1 * 1 + a_2 * (-1)
def relu(x):
return np.maximum(0,x)
def model(x, w):
... |
f4b052d260e18b3669d4ddf816ca61ed9754b9d9 | MauricioDinki/python-technical-test | /vocals.py | 902 | 4 | 4 | text = input('Insert a text: ')
vocals_count = 0
transformed_text = ""
for char in text:
if char is 'a':
char = 'e'
vocals_count += 1
elif char is 'A':
char = 'E'
vocals_count += 1
elif char is 'e':
char = 'i'
vocals_count += 1
elif char is 'E':
ch... |
6191ea20f3a2da11d3709e4c321cd1a3a7b5c8e1 | mpigelati/B_Python_work | /class/4-conditional/1-ifelse.py | 206 | 3.84375 | 4 | a=40
b=40
c=40
if (a > b):
if (a > c):
print ("A is big")
else:
print ("C is big")
elif( b > c):
print ("B is big")
else:
print ("C is big")
|
95aab18c49f3923b6fbad2e06c27813f7f5e9c24 | EduOporto/play-my-beat | /spotify_api/playlist_functions/pl_sorter.py | 2,898 | 3.5 | 4 | import pandas as pd
def playlist_sorter(run_intervals, playlist_df):
# Create a dict with each of the intervals as keys and empty lists as values
range_box = {}
for i in range(run_intervals.shape[0]):
range_box[i] = []
# List with the number of elements, in order to control the loop throug... |
dc1e7c6f3a5237bf13b5c59020c59767a0c56db4 | aamir7shahab/FellowshipPrograms | /Logical Programs/TicTacToe.py | 5,847 | 3.984375 | 4 | from random import randint, choice
class TicTacToe:
# Global variables
board = [['-', '-', '-'],
['-', '-', '-'],
['-', '-', '-']]
availablePositions = [0, 1, 2, 3, 4, 5, 6, 7, 8]
winner = None
isGameIsGoing = True
currentPlayer = None
# display Board fun
@s... |
442282eac04d78e60b6f73cb6f0fed12fe8fe3e6 | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/201-400/000257/000257.py | 1,568 | 3.75 | 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):
currPath = ''
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
... |
992b2df418b2e64e0a42e211cbde1692976f8b1a | anaCode26/PythonPractice | /BDD1.py | 1,024 | 3.5 | 4 |
import sqlite3
miConexion=sqlite3.connect("PrimeraBase")
miCursor=miConexion.cursor()
#miCursor.execute("CREATE TABLE PRODUCTOS(NOMBRE_ARTICULO VARCHAR(50),PRECIO INTEGER, SECCION VARCHAR(20))")
#miCursor.execute("INSERT INTO PRODUCTOS VALUES('BALON',15,'DEPORTES')")
# miCursor.execute("INSERT INTO PRODUCTOS VALUE... |
e48eb64ff23ebb6084d9319e49bbe6c03ab988c1 | raghuboreda/examplecode | /python/firecode/queue.py | 784 | 4.25 | 4 | class Queue( object ):
'''
Implement a FIFO queue using
two lists
'''
def __init__( self ):
self.enqL = []
self.deqL = []
def enqueue( self, item ):
self.enqL.append( item )
def dequeue( self ):
if len(self.deqL) == 0 and len(self.enqL) == 0:
ret... |
dde48612c77cfaa02f23b5d5b0b317fd3e07a1ad | codewithjulie/CS106A-Completionist-Files | /Section-8/poll/poll.py | 1,607 | 4.375 | 4 | """
File: poll.py
-------------
Contains the Poll class, which powers a poll where people vote for options and
the poll computes a winner.
"""
import math
class Poll:
def __init__(self):
self.poll={}
def add_option(self, option):
"""
Adds option as a valid poll choice.
Argum... |
261b9bb1dcb40a3265c8c66cf611703c420b4900 | zz4455zz/Python | /Complete Python Programming/Session 11/32. Root windows of application.py | 221 | 3.703125 | 4 | from tkinter import *
def print_new_line():
print("=================")
def example1():
root = Tk(className="First window")
root.mainloop()
if __name__ == '__main__':
print_new_line()
example1()
|
865f35f7e24ee6f1b0c87dc01e2e920a754b9a44 | Bronan/Agave | /connection.py | 833 | 3.96875 | 4 | #!/usr/bin/python
'''this guy will prompt the user for connection type and return local_IP or public_IP.
You're welcome.'''
import string, urllib2, socket
def connectionPrompt():
connectionType = raw_input("Local(L) or Remote(R) or Manual(M) Connection?: ")
connectionType = str(connectionType)
connectionType =... |
48bd64bbebf39e75d31a2ca2c803f336ebfb784e | tahinpekmez/MyPython | /lambda | 444 | 4.125 | 4 | #!/usr/bin/python
def double(x):
return x*2
double_numbers = map(double, [2,3,5,7])
print(double_numbers)
# we only use name of outer function
def f(x):
z = 2
return lambda y: z*x+y
a = 60
b = 1
print(f(a)(b)) # output is 121
"""
def area_of_rect(l,w):
return l*w
print(f'{area_of_rect(7,8)}')
pri... |
602aebf07835e6afa93e95992e55c90d153be69a | simplesoftMX/Mathematical-Programming | /Module1.py | 5,635 | 4.09375 | 4 |
def m1p1(n):
'''Project Euler Problem 1
Given a positive integer n calculate the sum of all multiples of 3 and 5 less than n.
'''
sum = 0
for x in range(1, n):
if(x % 3 == 0 or x % 5 == 0):
sum += x
return sum
def m1p2(n):
'''Project Euler Problem 2.
Given a positive integ... |
70ff5ca1cebbd5eb9e44ad6b4ed92eb94898caa4 | casprice/leetcode | /math/reverse-integer.py | 899 | 4.1875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range:
[−2^31, 2^31 − 1]. For the... |
35dc00d43b16423d6f7222bafa41c3d139bf7d72 | Na3r94/Practice6 | /S6-Matris.py | 455 | 3.828125 | 4 | import random
def matrix(a,b):
mat = [[random.randint(0,10) for i in range(a)]for j in range(b)]
return mat
k = int(input('Enter K :'))
n = int(input('Enter N :'))
m = int(input('Enter M :'))
Matrix1 = matrix(m,n)
Matrix2 = matrix(k,m)
Matrix3=[[0 for i in range(k)]for j in range(n)]
for i in range(n):
... |
cd149bf196cb1eb404954d88431768ae1f0e2deb | SaTuR/plataforma_digital | /python/ejercicio002.py | 357 | 3.953125 | 4 | """
calcular la area y el perimetro del cuadrado
OJO puedo ingresar valores de punto flotante!!!!
"""
print("Ejercicio que calcula le area y perimetro del cuadrado ")
lado = float(input("Por favor ingrese el valor del lado:\t"))
print(f"El resultado del area del cuadrado es {lado * lado}")
print(f"El resultado del pe... |
4dc14b857c89ca280e3ecb3b452df887ca0ba872 | osy123/pythonexample | /05_2 comprehension.py | 2,838 | 4.21875 | 4 | number_list = [] # 리스트생성
number_list.append(1) #정수 추가하기
number_list.append(2)
number_list.append(3)
number_list.append(4)
number_list.append(5)
print(number_list)
number_list= [] # 리스트생성
for number in range(1,6): # number에 range1~5까지를 넣는다.
number_list.append(number) # 넘버리스트에 추가한다 윗줄에서 number에 추가햇던 1~5
print(number... |
14766ef61f5910970123a7790f7563dee370a4ca | PMiskew/DP_CS_Code | /DP_CS_Code/Tools Files/findabsoluteDifference.py | 126 | 3.625 | 4 | def findabsoluteDifference(int1,int2):
difference = int1 - int2
return abs(difference)
print(findabsoluteDifference(3,5)) |
a22c16bbed2058cc2c9fd598178cd22b5e086470 | JamesAUre/First-year-of-python | /PythonSem1/BasicsDone/week3extension.py | 614 | 3.703125 | 4 | import random
userlength = int(input("Enter amount of cards: "))
list = []
for i in range (0,userlength):
if random.randint(0,1) == 1:
list.append('X')
else: list.append('O')
print (list)
while ('X' in list):
userinput = int(input("Enter card to flip: "))
if list[userinput-1] == 'X':
... |
be5add42a96d07851c95620f75333cda291157a4 | FebLee/Algorithms | /Leetcode/7.py | 509 | 4.25 | 4 | # reverse integer ,given a 32-bit signed int, reverse digits of an int
def reverse(x):
''' input type: int
rtype: int
'''
is_nagative = 1
reverse_int = 0
if x < 0:
is_nagative = -1
x *= -1
while x > 0:
remainder = x % 10
x //= 10
r... |
0810269161a56087044cff273973508d0bad7f72 | gitah/sandbox | /python/hex2ascii.py | 514 | 3.78125 | 4 | # hex2ascii.py
# Converts a hexstring to ascii
#
# Author: Fred Song
import sys
import binascii
def usage():
print "usage: %s HEXSTRING [delimiter]" % sys.argv[0]
if len(sys.argv) < 2:
usage()
exit(1)
hexstr = sys.argv[1]
try:
delim = sys.argv[2]
if len(delim) > 1:
raise Exception()
e... |
8759972ace14b3357f7cdb694fb3ba20d85949bf | yuzumei/leetcode | /官方堆.py | 3,065 | 4.25 | 4 | def heappush(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap)-1)
def heappop(heap):
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empt... |
2c7ceea6bdd2fd2d195e1adb11d77740e6be6c26 | Kamil-Ru/turtle_crossing | /car_manager.py | 1,263 | 3.71875 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class Car(Turtle):
def __init__(self):
super().__init__()
self.shape("square")
self.shapesize(stretch_wid=1, stretch_len=2)
self.c... |
072f81a31b06b21f512823b41b5ede232106a0a5 | AnatoliyChabanenko/lesson2 | /leson 3.py | 641 | 4.09375 | 4 | '''String manipulation
Write a Python program to get a string made of the first 2 and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string.
Sample String: 'helloworld'
Expected Result : 'held'
Sample String: 'my'
Expected Result : 'mymy'
Sample String: ' x'... |
f1c3ccdf14def8183f0dc1d392d928a5e6719ba7 | ccs258/python_algothrim | /框架/BFS广度优先/BFS.py | 1,775 | 3.78125 | 4 | import queue
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
def solution(start, target):
q = queue.Queue()
depth = 1 # min_depth = 0
step = 0
root = TreeNode()
while (root != None):
if root.left ... |
5b2879bc6a971279e638af5c4d1e5a1405f67016 | Mentaldisease/Python | /07.py | 167 | 3.703125 | 4 | from functools import partial
def mul_by_two(*args):
s = 2
for n in args:
s = s * n
return s
a = partial(mul_by_two)
print(mul_by_two(20)) |
4224434aec09ab02d1fcb8a52f0c51840f1ba3ec | 41Guilherme/URIbcr | /URIS/1065.py | 212 | 3.5625 | 4 | lista = []
nValores = 0
for i in range(5):
x = int(input())
lista.append(x)
for i in lista:
if i % 2 ==0:
nValores = nValores + 1
print("{} valores pares".format(nValores)) |
b9d2234a765c27cff86169f2d96b78ed4c695a50 | kmenon89/python-practice | /filemanipchallenge2.py | 954 | 3.765625 | 4 | #get guestlist , input list, print the guest list
import csv
filename="guestlist.csv"
read="r"
write="w"
accessmode="r+"
#input guest name from user
guestname=[]
guestage=[]
name=""
age=int(10000)
while name.upper() != "DONE":
name=input("pleases enter name of the guest(once completed enter name of ... |
18f9fab3a518d08217c1a0ed681cb555d1283137 | jlassi1/holbertonschool-interview | /0x1F-pascal_triangle/0-pascal_triangle.py | 505 | 3.953125 | 4 | #!/usr/bin/python3
"""
Pascal's Triangle
"""
def pascal_triangle(n):
"""that returns a list of lists of integers
representing the Pascal’s triangle of n"""
if n <= 0:
return []
if n == 1:
return [[1, ], ]
res = [[1], [1, 1]]
if n == 2:
return res
for i in range(2, n... |
f0620aaf12cc0a7d15abd15ee75259b2a458353d | 824zzy/Leetcode | /F_PrefixSum/BasicPrefixSum/L1_2017_Grid_Game.py | 923 | 3.828125 | 4 | """ L1: https://leetcode.com/problems/grid-game/
It is a min-max problem: find minimal maximized the prefix or suffix.
The inspiration is the first robot only move down once due to the 2 by n grid.
robot 2 optimal chose: max(pre_down[i], suf_up[i+1])
robot 1 optimal chose: min(ans, robot2 choose)
"""
class Solution:
... |
a10fcbd3afba3613c3ff809e6d7ebb75587db34e | murali3036/myPython_Works | /21. findError.py | 687 | 4.0625 | 4 | total = input('What is the total amount for your online shopping? ')
country = input('Shipping within the US or Canada? ')
if country == "US":
if float(total) <= 50:
print("Shipping Costs $6.00")
elif float(total) <= 100:
print ("Shipping Costs $9.00")
elif float(total) <= 150:
... |
f6d292763ff6a4738ea4c015fc1e341a467f2f89 | rocioregina/Python | /funciones_SOPA.py | 3,161 | 3.5625 | 4 | import random
def insertar_palabra_horizontal (BOX_SIZE,palabra,matriz,g,filas_validas,fuente,colores,caps): #en filas validas se le debe mandar una lista con las filas que todavia no tienen una palabra insertada
pos_maxima=15-len(palabra)
pos=random.choice(range(0,pos_maxima))
fila=random.choice(filas_vali... |
099b09729b1f5377cbc0405a6e16bbdd604f6804 | HussainAther/mathematics | /diffeq/bulirschstoer.py | 2,702 | 4.0625 | 4 | import matplotlib.pyplot as plt
import numpy as np
"""
In numerical analysis, the Bulirsch–Stoer algorithm is a method for the numerical solution of
ordinary differential equations which combines three powerful ideas: Richardson extrapolation,
the use of rational function extrapolation in Richardson-type applications,... |
4936522d7f50f6e0fdd259a26358053372e6c354 | ZhangY2018/Homework | /practice/min.py | 290 | 4.125 | 4 | def min(nums):
smallest = nums[0]
for candidate in nums:
if(candidate < smellest):
smellest = candidate
return smallest
list_of_numbers = [5,1,6,8,3,4,9,-5,-3]
print(min(lists_of_numbers))
list_of_numbers = [5.3,4.0,0.2]
smallest_float = min(list_of_floats)
print(smallest_float)
|
8a0f9562c4cef61ab2d929b8c213b862730f02a7 | ffismine/leetcode_github | /剑指offer/剑指 Offer 56 - I. 数组中数字出现的次数.py | 796 | 3.90625 | 4 | # -*- coding: utf-8 -*-
# Time : 2020/8/5 9:54
# Author : Zhang Xie
""""
一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。
示例 1:
输入:nums = [4,1,4,6]
输出:[1,6] 或 [6,1]
示例 2:
输入:nums = [1,2,10,4,1,4,3,3]
输出:[2,10] 或 [10,2]
限制:
2 <= nums.length <= 10000
"""
# 思考: 第一反应 哈希
from typing import... |
fa19aa482e7219bd6a2f9db69235aeed83626eed | Shashwat15/GitHackeve | /skeleton.py | 1,258 | 4.0625 | 4 | #Welcome to HackEve v20
#takes a string s as argument and converts it from binary to decimal form
def bin_to_dec(s):
return n #Number n in decimal form will be returned
#takes a number n as argument and converts it from decimal to hexadecimal form
def dec_to_hex(n):
lst=[]
while 0>=16:
... |
835a257a3f1db3322e3be638f260c7a723c38a67 | CHENGLIUBI/Fall2018-PY210A | /students/JackieCao/Lesson09/mailroom_oo/donor_models.py | 1,924 | 3.671875 | 4 | #!/usr/bin/env python3
"""
Donor and DonorCollection classes
"""
class Donor:
def __init__(self, name):
self.name = name
self.donations = []
self.new_donation = 0
def add_donation(self, donation):
self.new_donation = donation
self.donations.append(donation)
@propert... |
427c26c25f92f36ffd5a8b860e74dc98c41e0aa5 | KATO-Hiro/AtCoder | /ARC/arc001-arc050/arc024/a.py | 512 | 3.53125 | 4 | # -*- coding: utf-8 -*-
def main():
from collections import Counter
left, right = map(int, input().split())
left_shoes = Counter(list(map(int, input().split())))
right_shoes = Counter(list(map(int, input().split())))
pair_count = 0
for left_size, left_shoe_count in left_shoes.item... |
33b662683c7b1e6f3b7ceaaec4d7eec561b189a1 | BrandonLau-liuyifei/liuyifei_sourse | /21天学通Python_源代码/C5/a5_10.py | 320 | 3.65625 | 4 | def change(aint,alst):
aint = 0
alst[0]=0
alst.append(4)
print('函数中aint:',aint)
print('函数中alst:',alst)
aint = 3
alst = [1,2,3]
print('调用前aint:',aint)
print('调用前alst:',alst)
change(aint,alst)
print('调用后aint:',aint)
print('调用后alst:',alst)
|
66fcdd36cb8e854c7e2f0ce572c28ed405435169 | EscFrog/Try-helloworld-python | /function5.py | 205 | 3.5 | 4 | def root(a,b,c):
r1 = (-b + (b**2 - 4 * a * c) ** 0.5) / (2 * a)
r2 = (-b - (b**2 - 4 * a * c) ** 0.5) / (2 * a)
return r1, r2
r1, r2 = root(1,2,-8)
print("근은 {}와/과 {}".format(r1,r2))
|
c39c96b97f01ccfdc384791b68f743a8c5edd98e | Marcoakira/Desafios_Python_do_Curso_Guanabara | /Mundo2/Desafio040.py | 608 | 3.9375 | 4 | name_aluno = str(input('Insira o nome do Aluno'))
nota1sem = float(input('Insira a nota do 1º Semestre'))
nota2sem = float(input('Insira a nota do 2º Semestre'))
notafinal = (nota1sem+nota2sem)/2
print(notafinal)
if notafinal < 5:
print(f"Sua nota media foi {notafinal}, estude mais.\nVocê foi \033[2:31m REPROVADO!\... |
9cec3fd233382a6474c8768eb0b4abca8b8e7ae1 | ccoo/Multiprocessing-and-Multithreading | /Multi-processing and Multi-threading in Python/Multi-threading/Race Condition Demo by Raymond Hettinger/comm_via_locks.py | 2,619 | 4.34375 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple demo of solution of race conditions with locks.
Note that the race conditions in this demo are also amplified by fuzzing
technique
In order to be away with race conditions, we need to
1. Ensure an explicit ordering of the operations (on the shared resources)
... |
2a57172985ba426c01f2f242a94082c0d305b583 | skshabeera/question-bank | /centimeter to kilometer.py | 97 | 3.6875 | 4 | c=int(input("enter the centimeter"))
m=c/100
k=c/100000
print("meters:",m)
print("kilometers:",k) |
2f84f98f429ba877aa69c851f6b3a54e6f1e1dd3 | melvin5281/python | /Task1.py | 223 | 4.4375 | 4 | # Write a program which accepts a string as input to print "Yes" if the string is "yes", "YES" or "Yes", otherwise print
# "No".
x = input()
if x == ("yes", x == "YES", x == "Yes"):
print("Yes")
else:
print("No")
|
d062d6bd3e6cf5c58b2bb8a62cce5e3b6e47e963 | sarah-young/the-cake-is-a-lie | /interview_cake_1.py | 1,654 | 4.125 | 4 | """Suppose we could access yesterday's stock prices as a list, where:
The indices are the time in minutes past trade opening time, which was 9:30am local time.
The values are the price in dollars of Apple stock at that time.
So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500.
Write an efficient fu... |
889abeeadb9e87ba29ef21aeb38921e85fab2149 | LucasParsy/AoC2019 | /days/d17/p1/turtle_mode.py | 2,764 | 3.734375 | 4 | #!/usr/bin/env python3
from __future__ import annotations
from turtle import Screen, RawTurtle, Canvas
from dataclasses import dataclass
import turtle
from typing import List, NamedTuple
@dataclass
class Point:
x: int
y: int
def __add__(self, other: Point):
return Point(self.x + other.x, self.y ... |
a6197dd05f692d993b4ca4c3338e02ab8d42e864 | UperYang/Python | /OOP/01.py | 721 | 3.765625 | 4 | '''
定义一个学生类,用来描述学生
'''
#定义一个空的类,pass代表直接跳过
class Student():
pass
#定义一个对象
pingping = Student()
#再定义一个类
class PythonStudent():
#用none给不确定的值赋值
name = None
age = 18
course = "Python"
# 需要注意
# 1. def DoHomework的缩进层级
# 2. 系统默认由一个self参数
def doHomework(self):
print("我干着呢")
... |
c2f0e5b2622e7a692ab34e68b8d425fbd50ede13 | zingpython/kungFuShifu | /day_two/3.py | 709 | 3.921875 | 4 | #Take user input
word1 = input("Enter a word: ")
word2 = input("Enter a word: ")
#Create two empty dictionaries. These will have a key of a letter and a value of how many times that letter has appeared
letters1 = {}
letters2 = {}
#For each letter in word1 check if letter is in letters1. If not add it with a value of 1... |
d1982802d243ce73a0dfa4c201fcacbec3c52dc0 | MajedBadawi/Vision | /1-image-basics.py | 571 | 3.65625 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load an color image in: grayscale (0) || colored (1) || unchanged (-1)
image = cv2.imread("images/basic.png", 0)
# show the image by passing the title and path
cv2.imshow("image", image)
# wait for any key to be pressed, then close windows and save imag... |
ea7af0479df42125f9bb322e02cf25f7f8d330ff | jessicp0249/retail_item | /main.py | 889 | 3.734375 | 4 | # File: main.py
# Description: Program will print out a table of retail items.
# Author: Jessica Priester
# Email: jessicp0249@student.vvc.edu
# Created: 30 October 2019
# Class stores information about a retail item.
class RetailItem:
def __init__(self, descript="none", units=0, price=0.0):
self.descript = desc... |
6ba247eef078aab866445bc41211e73c62198c92 | Georycoco/pythonTutorial | /python基础/21_student-info-sys.py | 3,486 | 4.0625 | 4 | # 局部变量 variable
a = 100
def test():
global a # 允许在一个函数里修改全局变量
a = 33
def test1():
pass
test() # 必须调用这个函数运行,变量值才会被改变
print(a)
# -------------------student information system--------------
# -----------------------------------------------------------
# methods:
# student_List = [{'Name':'George','Ag... |
8f777fa00356a251ec8e503ba2f745707b1e2679 | green-fox-academy/judashgriff | /Week 4/Day 2/garden.py | 2,302 | 3.984375 | 4 | class Garden(object):
def __init__(self, plants):
self.garden = plants
def all_in_garden(self):
for plant in self.garden:
print("There is a " + str(plant.plant_name) + " in the garden.")
def give_water(self, amount):
thirsty = []
for i in self.garden:
... |
f2339b143a34fbbadd14600277016d585d85ded0 | zzggbb/rosalind | /revc.py | 230 | 4 | 4 | #!/bin/env python3
import sys
import util
"""
Given: A DNA string s.
Return: The reverse complement of s.
"""
dna_string = sys.stdin.readline()[:-1]
reverse_complement = ''.join(util.revc(dna_string))
print(reverse_complement)
|
38c363fad8b3d837f1a6fb146090232456939284 | Yueleng/design_of_computer_programs | /lesson5/11quiz_tuesday.py | 1,996 | 3.90625 | 4 | import itertools
from fractions import Fraction
sex = 'BG'
def product(*variables):
"The cartesian product (as a str) of the possibilities for each variable."
return map(''.join, itertools.product(*variables))
two_kids = product(sex, sex)
two_kids = [s for s in two_kids]
one_boy = [s for s in two_kids if '... |
eb397333aa3d5c8fc1bdd49382b8b51a0568bf36 | Shaunwei/Leetcode-python-1 | /String/RegularExpressionMatching/isMatchII2.py | 2,218 | 4.15625 | 4 | #!/usr/bin/python
"""
Regular Expression Matching
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch... |
eaab1db4563c3fa109e4fce9d94ff32647d36a23 | nivotko/bmg | /bmgsum.py | 440 | 3.546875 | 4 | N = int(input())
sum = 0
for i in range(1,N+1):
if i < N:
if i % 15 == 0:
print("BMG", end = " , ")
elif i % 15 == 14:
print(i, end=" , ")
sum += i
else:
print(i, end=" + ")
sum += i
else:
if i % 15 == 0:
... |
09c913866ae62f68f76453f20b455cad02040157 | djawlths3/python_practice1 | /problem01.py | 517 | 3.984375 | 4 | # 문제1. 키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요문제1. 키보드로 정수 수치를 입력 받아 그것이 3의 배수인지 판단하세요
def isnumber(no):
try:
int(no)
return int(no)
except ValueError:
print('정수가 아닙니다')
exit(0)
number = input('수를 입력하세요: ')
number = isnumber(number)
if(number % 3 != 0):
print('3의 배수가 아닙니다')
... |
38b5eb1da626338965d6dffacf79874e76d7c1bc | rishabh-github/fsdse-python-assignment-105 | /build.py | 228 | 3.90625 | 4 |
def find_diff(str1 , str2):
for x in str1:
if x not in str2:
return x
for y in str2:
if y not in str1:
return y
print find_diff('aaabbcdd', 'abdbacade')
|
9a0e56341d479248809a86c728de05a74df56b70 | marvincosmo/Python-Curso-em-Video | /ex076 - Lista de preços com tupla.py | 609 | 3.9375 | 4 | """ 76 - Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência.
No final, mostre uma listagem de preços, organizando os dados em forma tabular."""
lista = ('Lápis', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Transferidor', 4.20,
'Compasso', 9.99, '... |
66b20965db4d1fc9315bd0983d3cb8fed8b06e5b | DidioArbey/MisionTIC2022-Ciclo1-FundamentosDeProgramacion | /clase13/pandas_workshop.py | 3,078 | 3.703125 | 4 | """
* Series: Estructura de una dimensión.
* DataFrame: Estructura de dos dimensiones (tablas).
* Panel: Estructura de tres dimensiones (cubos).
"""
import pandas as pd
import numpy as np
# Series(data=lista, index=indices, dtype=tipo) : Devuelve un objeto de tipo Series
# con los datos de la lista lista, las fila... |
918abfa28827fa7536592185a7fb80c399a562e7 | salam1416/100DaysOfCode | /day46.py | 826 | 3.984375 | 4 | # Day 46 challenge
class Library():
# default values are added
def __init__(self, shelf = 0, book = 0):
self.shelf = shelf # number of shelves
self.book = book # number of books
# an example of a Library Object
myLib = Library(shelf = 45, book = 300)
# inherited class
class science_section(L... |
d7c49d6bf151ff8dbffd38bfc9615c7d17eb2cb2 | Ally0601/Python_Project | /Project1/age.py | 127 | 3.875 | 4 | def calculate():
age = int(input("Enter your age:"))
print("Your age in seconds is " + str(age*365*60*60))
calculate() |
6100afe2ead0e59d9b26821f4fb255a09b1d1f72 | GathuBoswell/Gathu_Andelabs | /fib_factorial.py | 375 | 4.09375 | 4 | def iterative_factorial(n):
fact = 1
if n == 1 or n < 1:
return 1
for i in range(1, n+1):
fact = fact * i
return fact
def recursive_factorial(n, prod=1):
if n == 1 or n < 1:
return (prod * 1)
else:
prod = (prod * n)
return (recursive_factorial((n-1... |
c9789aad581b4427603918f2d5e65f420d5762f7 | benterris/chordstransposer | /chordstransposer/transposer.py | 4,577 | 4 | 4 | import re
import sys
from .config import ALLTONES, CHORDSYMBOLS, EQUIVALENT, SCALES
def transpose(text, from_tone, to_tone):
"""
Given a text with words and chords, keep the words and transpose
the chords
Args:
text (str): the lyrics and chords of the song to be transposed
from_tone (... |
54e524afb5840730cb1823570a0cb3027d7ac449 | Dirzys/ComputerScienceLargePractical | /calculate_events.py | 3,212 | 3.734375 | 4 | from objects import Road
def canBoardBus(state):
''' Find all passengers who can board some bus and add them to possible events list.
Passenger can board bus only if all of the following holds true:
--- Bus is at the same stop as passenger
--- Bus is on top of the bus queue
--- Bus ... |
7a08a166e6c0bdee140d8a7066fd1ddbaf1163d8 | maitrikpatel2025/100_day_of_python | /Day_26/Day_26_Exercise_4/Day_26_Exercise_4.py | 916 | 4.0625 | 4 |
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 🚨 Do Not Change the code above 👆
#Exercise_1
#Write your 1 line code 👇 below:
multi_numbers = {num:num*num for num in numbers}
squared_numbers = {num: multi for (num, multi) in multi_numbers.items() if multi == num*4}
#Write your code 👆 above:
print(multi_n... |
8e37b175bda7ab1aac33ea16aab821dd6069aed3 | rubayetalamnse/Basic-Python-Codes | /function-cel-farenheit.py | 157 | 3.78125 | 4 | celsius = int(input())
def converter(celsius):
return ((celsius * (9.0/5.0)) + 32.0)
temp_in_farenheit = converter(celsius)
print(temp_in_farenheit)
|
9535db56a3e5b27a1a2bf61b0bf98821db63d242 | mickbos/AAI | /NN/4_3/neuron.py | 797 | 3.65625 | 4 | import math
class neuron:
def __init__(self, inputs, weights = None, bias = 0):
self.inputs = inputs
self.weights = weights
self.bias = bias
self.output = None
def generateOutput(self):
total = 0
if self.weights == None:
self.output = self.in... |
e9cf6ccf059767155ffba14859aad97aa4b15703 | rafaelperazzo/programacao-web | /moodledata/vpl_data/21/usersdata/132/8324/submittedfiles/exercicio24.py | 225 | 3.890625 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a=input(' digite a:')
b=input(' digite b:')
i=2
if a>=b:
i=a
else:
i=b
while True:
if a%i==0 and b%i==0:
print(i)
break
i=i-1 |
dfd390f2666d491c79863c0095b8b5e2eaa7dc03 | liuxver/python_code | /udp_server.py | 644 | 3.53125 | 4 | #! /usr/bin/env python3
#-*- coding:utf-8 -*-
import socket
#SOCK_DGRAM指定了这个Socket的类型是UDP。
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定端口,绑定端口和TCP一样,但是不需要调用listen()方法,
#而是直接接收来自任何客户端的数据:
s.bind(('127.0.0.1',9999))
#recvfrom()方法返回数据和客户端的地址与端口,
#这样,服务器收到数据后,
#直接调用sendto()就可以把数据用UDP发给客户端。
print('Bind UDP on... |
a1adb38ba23296bbe303e997b2a0aeb16b394090 | Luckyaxah/leetcode-python | /二叉树_判断完全二叉树.py | 875 | 3.734375 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isCBT(head):
if not head:
return
from queue import Queue
q = Queue()
isMeet = False
q.put(head)
while not q.empty():
cur = q.get()
l = cur.left
... |
9584fc80cdefc52351f0313edea0f2207eb4a45e | mcorbridge/testPython | /testGlobal.py | 1,128 | 3.625 | 4 |
# testing the concept of python global
import time
i = 0
n = 0
def f():
global i
global n
i += 1
n += 1
return "file:" + str(i + n)
class Foo:
i = 0
n = 0
@classmethod
def f(self):
self.i += 1
self.n += 1
return "klass:" + str(i + n)
def g(self):
l = [0,1,2,3,4,5,6... |
e5f3055e5a63dbf651c7d1de7334ad2cfdfb9e82 | linhx13/leetcode-code | /code/795-number-of-subarrays-with-bounded-maximum.py | 526 | 3.65625 | 4 | from typing import List
class Solution:
def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
res = [0]
pre = -1
for i in range(len(A)):
if A[i] < L:
res.append(res[-1])
elif A[i] > R:
res.append(0)
pre... |
6895e4104e012b08e946447adab2373d05ac833c | LePrat/GeneticDots | /sample/Vector.py | 463 | 3.671875 | 4 | import math
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def x(self):
return self.x
def y(self):
return self.y
def add(self, vector):
self.x += vector.x
self.y += vector.y
def get_magn(self):
return math.sqrt(math.pow(sel... |
cc93030d14fc751dc957a46769c6d6dbd35eb0c1 | DamonZCR/PythonStu | /47Tkinter/Text文本输入/14-2-4Text中Mark的用法.py | 271 | 3.59375 | 4 | from tkinter import *
'''删除Mark标记
'''
root = Tk()
text = Text(root, width=30, height=20)
text.pack()
text.insert(INSERT, 'Damon wants to sleep')
text.mark_set('here', 1.2)
text.mark_unset('here')
text.delete('1.1', 1.7)
text.insert('here', '一个')
mainloop() |
1942d8b22936ab1eb18bd840041e639583d69e7b | thiagoAlexandre3/cursos-auto-didata | /curso-python/exercicios/exercicio-009.py | 459 | 4.0625 | 4 | n1 = int(input('Digite um numero: '));
print('{} X 0 ='.format(n1), n1 * 0);
print('{} X 1 ='.format(n1), n1 * 1);
print('{} X 2 ='.format(n1), n1 * 2);
print('{} X 3 ='.format(n1), n1 * 3);
print('{} X 4 ='.format(n1), n1 * 4);
print('{} X 5 ='.format(n1), n1 * 5);
print('{} X 6 ='.format(n1), n1 * 6);
print('{} X 7 =... |
04d723768e5f659ab9604cd9696b875414888316 | pomonykr/DataScience | /Python,Pandas,Mysql/Python_8일차/Pandas02_01_FunEx6_김병수.py | 467 | 3.9375 | 4 | # return문을 2번 사용하면,
# 두 번째 return문인 return a*b는 실행되지 않는다
def add_and_mul(a, b):
return a+b
return a*b
result = add_and_mul(2,3)
print(result)
print('-'*10)
# [return의 또 다른 쓰임새]
# return을 단독으로 써서 함수를 즉시 빠져나갈 수 있다
def say_nick(nick):
if nick == "바보":
return nick
# print("나의 별명은 %s 입니다." %nick)
say_nick('야호')
s... |
06925a148bc9aa315f6f9f3fdeb0b94a0d51ec5d | 22thomas1/pitest | /move.py | 1,402 | 3.515625 | 4 | from pycreate2 import Create2
import time
import math
# functions
def initBot(port):
bot = Create2(port)
bot.start()
bot.full()
return bot
def senDistance(bot):
data = bot.get_sensors()
return abs(int(f"{data.distance:4}"))
def senAngle(bot):
data = bot.get_sensors()
return abs(int(f"{data.angle:4}"... |
c196099e295dde4657456c785063dcb7d553cd3e | rembrandtqeinstein/learningPy | /pp_e_14.py | 407 | 3.6875 | 4 | import random
leng_1 = random.randint(1,50)
a = list()
for x in range(0, leng_1):
a.append(random.randint(1,20))
def remove_duplicates(x):
c = list(set(x))
print(c)
def remove_duplicates_for(x):
n_lis = list()
for y in x:
if y not in n_lis:
n_lis.append(y)
else:
... |
bc508320e06fe2856fe05d253384556dd29b98d5 | bryano13/holbertonschool-higher_level_programming | /0x0B-python-input_output/8-load_from_json_file.py | 262 | 3.5625 | 4 | #!/usr/bin/python3
"""Module with function load_from_json_file"""
import json
def load_from_json_file(filename):
"""
This funcion loads from a json file
"""
with open(filename, encoding="utf-8") as file:
return json.loads(file.read())
|
469dc42aadc7e48c8fd4d92ad3a646198835f216 | ruchou/NTHU_OS_Assignment | /103011227-hw5/hw5.py | 2,923 | 3.6875 | 4 | import threading
def MakeParkingLot(N):
global sem # semaphore for the parking lot
global spots # list for the spots
global spotsSync # for synchronizing access to spots
spots = [None for i in range(N)]
# your code to initialize sem and spotsSync
sem=threading.BoundedSemaphore(N) #integer b... |
675249dcb33cf794a29df33d0f650d1d2de9ad76 | snramadan/101 | /lab8/funcs_objects/funcs_objects_tests.py | 1,609 | 3.671875 | 4 | # Stane, Danielle & Ramadan, Saba
# Lecture Section #13
# Lab Section Number: 08
import unittest
from objects import *
from funcs_objects import *
class TestCases(unittest.TestCase):
def test_point1(self):
p = Point(2, 3)
self.assertEqual(p.x, 2)
self.assertEqual(p.y, 3)
pass
def test_p... |
d405886aca11d30f9b46afc6806dd42b49bbbf84 | swa4n/unscramble-challenges- | /easy_difficulty/jump_on_clouds.py | 766 | 3.59375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
jumps = 0
position = 0
if len(c) == 2:
return 1
while position < len(c)-2:
if c[position+2] == 0:
position += 2
else:
... |
3141be41980d581d97774afb0937ad24d71adee4 | mguenther/advent-of-code-2020 | /9.py | 1,073 | 3.8125 | 4 | def find_invalid_number(numbers, window_size):
for i in range(len(numbers)-window_size):
window = numbers[i:i+window_size]
probe = numbers[i+window_size]
probe_valid = False
for j in range(len(window)):
for k in range(len(window)):
if j == k:
... |
f72cad21178ed20fe09d37a5a1168a07d6ec9d4c | brombaut/BEC | /ctci/ch3/ex5_sort_stack/python/sort_stack.py | 1,727 | 3.8125 | 4 | import unittest
class Stack:
def __init__(self):
self.stack = []
self.index = -1
def push(self, value):
self.index += 1
self.stack.insert(self.index, value)
def pop(self):
if self.index < 0:
return None
result = self.stack[self.index]
s... |
ee234418d802f6f3ee3a0b591073a44a4c814799 | CMagnoDFB/Exercicios-Python | /LPTHW exercises/ex8.py | 532 | 3.640625 | 4 | #Definindo a variável string com 4 espaços para formatação
formatter = "{} {} {} {}"
#Print the str formatter, using the format function, and passsing 4 arguments
print(formatter.format(1, 2, 3, 4))
print(formatter.format("one", "two", "three", "four"))
print(formatter.format(True, False, False, True))
print(formatter.... |
24eace8d54c00a7aa70f0a865d77f18951f48c85 | wargreimon501/CYPRafaelSA | /for2.py | 98 | 3.625 | 4 | tabla=int(input("que tabla"))
for V in range( 1, 11, 1):
print(f" {tabla} * {V} = {tabla*V}")
|
8dc464db051b0073da5f7254048369806a55e22f | JoseCaarlos/Python | /Seção 17 - Herança e Polimorfismo/heranca_multipla.py | 2,025 | 4.25 | 4 | """
POO - Herança Múltipla
# OBS: A herança múçtipla pode ser feita de duas formas:
- Por Multiderivação direta;
- Por Multiderivação indireta;
# Exemplo 01 - Multiderivação Direta
class Base1:
pass
class Base2:
pass
class Base3:
pass
class Multiderivada(Base1, Base2):
pass
# Exemplo 2 -... |
b6e13bdfa87f09482cea6c5929c8a02a7eda34fa | fhqvst/practice-python | /algorithms/quicksort-inplace.py | 989 | 3.71875 | 4 | from random import shuffle
from time import time
N = 10000
A = [ i for i in range(N) ]
B = list(A)
shuffle(B)
def quick_sort_inplace(S, a, b):
if a >= b:
return
pivot = S[b] # choose last element as pivot
left = a
right = b - 1
while left <= right:
while S[left] < pivot and left... |
0ea4fa5c3bfdc84a46b45503d43b0014c862a769 | tomlxq/ps_py | /huawei/StudentCompare.py | 586 | 3.515625 | 4 | class StudentCompare:
def compare(self, line1: str, line2: str) -> str:
h, m = map(int, line1.split())
nums = list(map(int, line2.split()))
nums = sorted(nums, key=lambda x: (abs(x - h), x))
# for i in nums:
# print(i, end=" ")
return " ".join(map(str, nums))
if ... |
98f20864ff25fab27b5b8191d6d5f34844d280c5 | suboice114/FirstPythonDemo | /AlgorithmsAndDataStructures/BubbleSort.py | 1,487 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Time : 2019/9/2 9:59
# @Author : su
# @File : BubbleSort.py
"""冒泡排序"""
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'{self.name}: {self.age}'
def __repr__(s... |
a8e77b6d50aa86c6047fedd82b9847e0515df377 | paurbano/holbertonschool-machine_learning | /supervised_learning/0x0D-RNNs/8-bi_rnn.py | 1,372 | 4.125 | 4 | #!/usr/bin/env python3
'''Bidirectional RNN'''
import numpy as np
def bi_rnn(bi_cell, X, h_0, h_t):
'''performs forward propagation for a bidirectional RNN
Args:
bi_cell is an instance of BidirectinalCell that will be used for the
forward propagation
X is the data to be used, ... |
b58645f21596b39580cee92551ca4041c77792dc | TBenjiFern/CSE-212-Final-Project | /week11/stack_student_example_solution.py | 4,744 | 3.84375 | 4 | """
Two Player Full-House Race
Author: Benjamin Fernelius
This is a made-up card game for two players where the goal is to be the first player to get a full-house
(three-of-a-kind and a two-of-a-kind). This program uses a Stack in order to keep track of the discard pile.
The players have the option to draw from... |
669d8f4e2f59a2b8ae4db41d39ba19fad0ef89ba | Tuhin-thinks/DS-and-Algo | /GraphAlgorithms/Floyd_Warshall.py | 1,215 | 3.8125 | 4 | import sys
def print_mat(mat):
for r in range(len(mat)):
for c in range(len(mat[0])):
elem = mat[r][c]
if elem != sys.maxsize:
print(elem, end="\t")
else:
print("__", end="\t")
print()
def accept_edges(mat):
while True:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.