blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f6e25c99907892d2248f05f37664c7db0df53741 | adafruit/circuitpython | /tests/float/float1.py | 2,193 | 3.65625 | 4 | # test basic float capabilities
# literals
print(0.12)
print(1.0)
print(1.2)
print(0e0)
print(0e0)
print(0e-0)
# float construction
print(float(1.2))
print(float("1.2"))
print(float("+1"))
print(float("1e1"))
print(float("1e+1"))
print(float("1e-1"))
print(float("inf"))
print(float("-inf"))
print(float("INF"))
print(... |
60da82971cb1246a1cd3fe9fa928462de7231f25 | adafruit/circuitpython | /tests/basics/int_big1.py | 2,637 | 3.84375 | 4 | # to test arbitrary precision integers
x = 1000000000000000000000000000000
xn = -1000000000000000000000000000000
y = 2000000000000000000000000000000
# printing
print(x)
print(y)
print('%#X' % (x - x)) # print prefix
print('{:#,}'.format(x)) # print with commas
# addition
print(x + 1)
print(x + y)
print(x + xn == 0)
... |
00795510ff2cfec8b55f3b86d783f24c6d6234e0 | adafruit/circuitpython | /tests/basics/list_slice_assign_grow.py | 422 | 3.890625 | 4 | x = list(range(2))
l = list(x)
l[0:0] = [10]
print(l)
l = list(x)
l[:0] = [10, 20]
print(l)
l = list(x)
l[0:0] = [10, 20, 30, 40]
print(l)
l = list(x)
l[1:1] = [10, 20, 30, 40]
print(l)
l = list(x)
l[2:] = [10, 20, 30, 40]
print(l)
# Weird cases
l = list(x)
l[1:0] = [10, 20, 30, 40]
print(l)
l = list(x)
l[100:100]... |
90cd30723429f6553da5db0172d901309453ae23 | adafruit/circuitpython | /tests/basics/class_super_closure.py | 552 | 3.65625 | 4 | # test that no-arg super() works when self is closed over
class A:
def __init__(self):
self.val = 4
def foo(self):
# we access a member of self to check that self is correct
return list(range(self.val))
class B(A):
def foo(self):
# self is closed over because it's referenced... |
198222e72db081a00dfd5d66a14e7bb94dc60af4 | adafruit/circuitpython | /tests/basics/for_else.py | 716 | 4 | 4 | # test for-else statement
# test optimised range with simple else
for i in range(2):
print(i)
else:
print('else')
# test optimised range with break over else
for i in range(2):
print(i)
break
else:
print('else')
# test nested optimised range with continue in the else
for i in range(4):
print(... |
1024b3212efc5b7db070ebed88691e5c8e63f689 | adafruit/circuitpython | /tests/float/inf_nan_arith.py | 585 | 4.15625 | 4 | # Test behaviour of inf and nan in basic float operations
inf = float("inf")
nan = float("nan")
values = (-2, -1, 0, 1, 2, inf, nan)
for x in values:
for y in values:
print(x, y)
print(" + - *", x + y, x - y, x * y)
try:
print(" /", x / y)
except ZeroDivisionError:
... |
1e746e4e63a7aaa71bf0aa41111c9235f6306d0d | adafruit/circuitpython | /tests/micropython/viper_binop_arith.py | 992 | 3.640625 | 4 | # test arithmetic operators
@micropython.viper
def add(x: int, y: int):
print(x + y)
print(y + x)
add(1, 2)
add(42, 3)
add(-1, 2)
add(-42, -3)
@micropython.viper
def sub(x: int, y: int):
print(x - y)
print(y - x)
sub(1, 2)
sub(42, 3)
sub(-1, 2)
sub(-42, -3)
@micropython.viper
def mul(x: int, y... |
4fa4bd67a15d02fd6ff3c3b5406f866f752ed414 | adafruit/circuitpython | /tests/basics/subclass_native_init.py | 887 | 3.96875 | 4 | # test subclassing a native type and overriding __init__
# overriding list.__init__()
class L(list):
def __init__(self, a, b):
super().__init__([a, b])
print(L(2, 3))
# inherits implicitly from object
class A:
def __init__(self):
print("A.__init__")
super().__init__()
A()
# inherits e... |
24cb82a62255c4ae666b853dc3ad793f5fd32c40 | adafruit/circuitpython | /tests/basics/with_continue.py | 257 | 3.75 | 4 | class CtxMgr:
def __enter__(self):
print("__enter__")
return self
def __exit__(self, a, b, c):
print("__exit__", repr(a), repr(b))
for i in range(5):
print(i)
with CtxMgr():
if i == 3:
continue
|
11fb0b6ed14aca0e24d7a8e1d7d7a4f6556076a3 | adafruit/circuitpython | /tests/basics/fun_varargs.py | 558 | 3.59375 | 4 | # function with just varargs
def f1(*args):
print(args)
f1()
f1(1)
f1(1, 2)
# function with 1 arg, then varargs
def f2(a, *args):
print(a, args)
f2(1)
f2(1, 2)
f2(1, 2, 3)
# function with 2 args, then varargs
def f3(a, b, *args):
print(a, b, args)
f3(1, 2)
f3(1, 2, 3)
f3(1, 2, 3, 4)
# function with 1 ... |
b87d28fa19412838de3035728276c8e5e74f230b | adafruit/circuitpython | /tests/basics/bytes_mult.py | 247 | 3.859375 | 4 | # basic multiplication
print(b'0' * 5)
# check negative, 0, positive; lhs and rhs multiplication
for i in (-4, -2, 0, 2, 4):
print(i * b'12')
print(b'12' * i)
# check that we don't modify existing object
a = b'123'
c = a * 3
print(a, c)
|
cfe9daba1c78afcdaaefea68f4074ebaf4a66875 | adafruit/circuitpython | /tests/float/string_format_modulo.py | 1,363 | 3.859375 | 4 | print("%s" % 1.0)
print("%r" % 1.0)
print("%d" % 1.0)
print("%i" % 1.0)
print("%u" % 1.0)
# these 3 have different behaviour in Python 3.x versions
# uPy raises a TypeError, following Python 3.5 (earlier versions don't)
# print("%x" % 18.0)
# print("%o" % 18.0)
# print("%X" % 18.0)
print("%e" % 1.23456)
print("%E" %... |
3f84254bab0444fa1d9fb4068fb2056c220e2a62 | adafruit/circuitpython | /tests/basics/subclass_native2_tuple.py | 411 | 3.609375 | 4 | class Base1:
def __init__(self, *args):
print("Base1.__init__", args)
class Ctuple1(Base1, tuple):
pass
a = Ctuple1()
print(len(a))
a = Ctuple1([1, 2, 3])
print(len(a))
print("---")
class Ctuple2(tuple, Base1):
pass
a = Ctuple2()
print(len(a))
a = Ctuple2([1, 2, 3])
print(len(a))
a = tuple([1,... |
f9078ba2f424061292bd061d5b8e6e54203870d9 | adafruit/circuitpython | /tests/basics/list_reverse.py | 69 | 3.5 | 4 | a = []
for i in range(100):
a.append(i)
a.reverse()
print(a)
|
d8095b7251675ca70ee1d714335a0736d789b847 | adafruit/circuitpython | /tests/basics/try_finally_return3.py | 2,049 | 4.25 | 4 | # test 'return' within the finally block, with nested finally's
# only inactive finally's should be executed, and only once
# basic nested finally's, the print should only be executed once
def f():
try:
raise TypeError
finally:
print(1)
try:
raise ValueError
finally:... |
ad8f8d45167f58f0f412866da1d6bf62c13e7922 | adafruit/circuitpython | /tests/basics/try_finally_return4.py | 1,761 | 4.09375 | 4 | # test try-finally with return, where unwinding return has to go through
# another try-finally which may affect the behaviour of the return
# case where a simple try-finally executes during an unwinding return
def f(x):
try:
try:
if x:
return 42
finally:
try:... |
aa06b906117063aea0f24930eeed60e6e513e26e | adafruit/circuitpython | /tests/basics/for1.py | 359 | 4.34375 | 4 | # basic for loop
def f():
for x in range(2):
for y in range(2):
for z in range(2):
print(x, y, z)
f()
# range with negative step
for i in range(3, -1, -1):
print(i)
a = -1
# range with non-constant step - we optimize constant steps, so this
# will be executed differently
... |
e63180d18cc746db0876a6440284801e98a655d7 | adafruit/circuitpython | /tests/basics/comprehension1.py | 421 | 3.9375 | 4 | def f():
# list comprehension
print([a + 1 for a in range(5)])
print([(a, b) for a in range(3) for b in range(2)])
print([a * 2 for a in range(7) if a > 3])
print([a for a in [1, 3, 5]])
print([a for a in [a for a in range(4)]])
# dict comprehension
d = {a : 2 * a for a in range(5)}
... |
e8d51c2e967f93e5f2f4eb6b9734442de4d0ce00 | adafruit/circuitpython | /tests/basics/for_range.py | 1,318 | 3.890625 | 4 | # test for+range, mostly to check optimisation of this pair
# apply args using *
for x in range(*(1, 3)):
print(x)
for x in range(1, *(6, 2)):
print(x)
# zero step
try:
for x in range(1, 2, 0):
pass
except ValueError:
print('ValueError')
# apply args using **
try:
for x in range(**{'end':... |
38d0dc24b67f176003fdb066fab262a432ace694 | adafruit/circuitpython | /tests/basics/string_replace.py | 591 | 3.703125 | 4 | print("".replace("a", "b"))
print("aaa".replace("b", "c"))
print("aaa".replace("a", "b", 0))
print("aaa".replace("a", "b", -5))
print("asdfasdf".replace("a", "b"))
print("aabbaabbaabbaa".replace("aa", "cc", 3))
print("a".replace("aa", "bb"))
print("testingtesting".replace("ing", ""))
print("testINGtesting".replace("ing... |
eb434551d6fceeb391e1decb7799a287cdc404c2 | adafruit/circuitpython | /tests/basics/generator_exc.py | 907 | 3.78125 | 4 | # Test proper handling of exceptions within generator across yield
def gen():
try:
yield 1
raise ValueError
except ValueError:
print("Caught")
yield 2
for i in gen():
print(i)
# Test throwing exceptions out of generator
def gen2():
yield 1
raise ValueError
yield 2
... |
c1af1c77afaedcc1e638f90b4f7db5be681f0856 | adafruit/circuitpython | /tests/basics/while_cond.py | 386 | 3.984375 | 4 | # test while conditions which are optimised by the compiler
while 0:
print(0)
else:
print(1)
while 1:
print(2)
break
while 2:
print(3)
break
while -1:
print(4)
break
while False:
print('a')
else:
print('b')
while True:
print('a')
break
while not False:
print('a... |
eddd1c65b5275b34e6cd78a16e5af3d361c3c129 | adafruit/circuitpython | /tests/basics/int_big_xor.py | 732 | 3.53125 | 4 | # test + +
print(0 ^ (1 << 80))
print((1 << 80) ^ (1 << 80))
print((1 << 80) ^ 0)
a = 0xfffffffffffffffffffffffffffff
print(a ^ (1 << 100))
print(a ^ (1 << 200))
print(a ^ a == 0)
print(bool(a ^ a))
# test - +
print((-1 << 80) ^ (1 << 80))
print((-1 << 80) ^ 0)
print((-a) ^ (1 << 100))
print((-a) ^ (1 << 200))
pri... |
8e005c3965bfa0df7483c9721ffa9ed2cc332444 | adafruit/circuitpython | /tests/basics/gen_yield_from.py | 483 | 3.734375 | 4 | # Case of terminating subgen using return with value
def gen():
yield 1
yield 2
return 3
def gen2():
print("here1")
print((yield from gen()))
print("here2")
g = gen2()
print(list(g))
# StopIteration from within a Python function, within a native iterator (map), within a yield from
def gen7(x... |
c0f9c5ea7344d52a77322bedeef12cba1946cd25 | Bombjack88/Python-for-Everybody--PY4E- | /Pyton_Codes/Using Python to Access Web Data/5.Regular_Expressions/examples_11.py | 357 | 3.765625 | 4 | #Regular expressions
import re
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print(y)
x = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
y = re.findall('\S+?@\S+', x)
print(y)
x = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008'
y = re.findall('@(\S+)', x)
print(y)
x = 'From ... |
b68f2ccc34ce52186caacb6e65ddf3a652b5f2cc | Bombjack88/Python-for-Everybody--PY4E- | /Pyton_Codes/Python Data Structures/2. Files/ex_8.1.py | 264 | 3.953125 | 4 | #sort lists
# file name: romeo.txt
filename=input('Enter the file name:')
file=open(filename)
lista=list()
final=list()
for line in file:
lista=line.split()
for i in lista:
if i not in final:
final.append(i)
final.sort()
print(final)
|
0460a845000cf0f652d33ae9bfb419e15021c794 | MRMYSTERY003/Convert-Img-To-Pencil-Sketch | /img-to-pencil-sketch.py | 674 | 3.734375 | 4 | ''' image to pencil art
by Mr_Mystery check out our yt channel link in readme file
'''
import cv2 #importing opencv2
img = cv2.imread('image.jpg') # reading the image you can give the path of your image file here insted of image.jpg
#converting the image to pencil sketch
gray_image = cv2.cv... |
015f347e9d42164e41b3c1a085c2c82cc9110665 | Abdirahmaanabdikarim/PYTHON-PROJECT | /Error.py | 287 | 3.90625 | 4 | try:
a = int(input("Enter the first number"))
b = int(input("Enter the second number"));
result = a/b
print("the div of a and b =" , result)
except:
print('you ca not divide by zero !! kindly try agian')
list2= ['mango', 'Banana','Avo']
for i in list2:
print(i) |
ffeb56873cdabce16c2528cd13c69ec7792cbf56 | Abdirahmaanabdikarim/PYTHON-PROJECT | /OOP.py | 1,091 | 4.1875 | 4 | #class in oop - is the blue print of an object
# class Animal:
# Name="Cat"
# age = 12;
# color=' black'
# def dislay(self):
# print('Name:', self.Name,'Age:', self.age,"Color", self.color)
# cat1 =Animal();
# cat1.dislay()
# class Rectangle:
# legnth = 7;
# width =9
# ... |
a45a032b4555b04baecb1554c46b2fa009458b96 | IoAdhitama/CP1404 | /prac_05/word_occurences.py | 517 | 3.96875 | 4 | word_occurences = {}
text = str(input("Text: "))
words = text.split()
for word in words:
if word in word_occurences:
word_occurences[word] += 1
else:
word_occurences[word] = 1
word_occurences_keys = [key for key in word_occurences]
word_occurences_keys.sort()
max_word_length = 0
for word in ... |
f46f9ff0a03e5122b96de4a9f22a8e4a8d498051 | IoAdhitama/CP1404 | /prac_01/loops.py | 482 | 4.21875 | 4 | print('1 : Display all of the odd numbers between 1 and 20')
print('2 : Count in 10s from 0 to 100')
print('3 : Count down from 20 to 1')
choice = int(input('Select loop to display: '))
if choice == 1:
for i in range(1, 21, 2):
print(i, end=' ')
print()
elif choice == 2:
for i in range(0, 110, 10)... |
dcd5765b51ea546b5b1fdc22a8b532c774fbbc20 | amithmarilingegowda/projects | /python/python_programs/second_highest_num.py | 219 | 4.15625 | 4 | # Python program to find second largest number in a list.
# list of numbers - length of list should be at least 2
list = [10, 20, 4, 45, 99]
list.sort()
print "Second highest number in the list is", list[-2]
|
a405ab9c9944e8e65deaeed4adfa4b7cfa04623e | amithmarilingegowda/projects | /python/python_programs/area_of_circle.py | 180 | 3.90625 | 4 | # Area Of Circle = PI * (Radius ^ 2)
import sys
PI = 3.1415
radius_of_circle = float(sys.argv[1])
print "Area Of Circle = %f units" %(radius_of_circle * radius_of_circle * PI)
|
793236f31cd5b4a7fd67481f0f005b868fbaba8d | amithmarilingegowda/projects | /python/python_programs/rotate_array_by_n.py | 1,347 | 4 | 4 | import sys
array = [1, 60, 7, 20, 15, 50, 40, 3, 30]
n = input("Enter an integer to rotate the array by that number\n")
def rotate_left( n ):
print "\nRotate Array by %d times to left" %n
for x in range( n ):
temp = array[0]
for y in range( length-1 ):
array[y] = array[y+1]
... |
0c03fb04d83bb8c5d3d76b61a4bdf0ac579cf28a | taratep123/workshop2 | /Python lists/Sort List.py | 170 | 3.921875 | 4 | #EXAMPLE 1
thislist = [100 , 50 , 65 , 82 ,23]
thislist.sort()
print(thislist)
#EXAMPLE 2
thislist = [100 , 50 , 65 , 82 ,23]
thislist.sort(reverse=True)
print(thislist) |
0da91333f5ca605c5e81434b29a85372e26785c8 | yinhao5969/Python-study | /8-9_function.py | 1,731 | 3.796875 | 4 | #8-9
magicians = ['a', 'b ', 'c', 'd']
def show_magicians(name_list):
for item in name_list:
print(item)
show_magicians(magicians)
#8-10
def make_great(need_process_name_list):
for index in range(len(need_process_name_list)):
need_process_name_list[index] = 'great '+need_process_name_list... |
6f06782d51d7759f5b236ee133406c3012dc936e | yinhao5969/Python-study | /002_username_upper_low.py | 292 | 3.625 | 4 | username = "yinhao"
print(username.title()+":"+" "+"Hello eric, would you like to learn more Pyhton today?")
print(username.upper()+":"+" "+"Hello eric, would you like to learn more Pyhton today?")
print(username.lower()+":"+" "+"Hello eric, would you like to learn more Pyhton today?")
|
2f78be58373d349883e016ea9b843726bb3540eb | yinhao5969/Python-study | /class_9_1.py | 4,140 | 3.84375 | 4 | #9-1
class Restaurant():
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
def des(self):
print('Restaurant', self.name.title(), 'has cuisine', self.cuisine.title())
def open(self):
print('We are open')
#9-2
cangying = Restaurant('Shit', 'chuan')
pri... |
ba1fb843cd3068a0b1d2c3551df7cc9ab1f7267a | yinhao5969/Python-study | /5-1_if.py | 1,563 | 4 | 4 | breakfast = "bing"
breakfast_big = "Bing"
lunch = "chaofan"
dinner = "noodles"
print("Is breakfast == bing? I predict True.")
print(breakfast == "bing")
print("\nIs breakfast == shit? I predict False.")
print(breakfast == "shit")
print("\nIs breakfast == breakfast_big? I predict False.")
print(breakfast == breakfast... |
3ff2c791dbeadac0b470873caf9a7b15b841e8b7 | yinhao5969/Python-study | /10_6/exception.py | 479 | 4.0625 | 4 | #10-6
def plus():
a = input('Please input a value:\n')
b = input('Please input another value:\n')
quitflag = True
if(a == 'q' or b == 'q'):
quitflag = True
else:
try:
print('The result is', int(a)+int(b),'.')
except ValueError:
print('Only numbers can ... |
672b492b18e5b4ba7e48cbd9178c0260570690d7 | ajaypraj/gittest | /operator_overloading1.py | 355 | 3.78125 | 4 | class Employee:
def __init__(self,name,salary):
self.name=name
self.salary=salary
def __mul__(self,other):
return self.salary * other.time
class Timesheet:
def __init__(self,name,time):
self.name=name
self.time=time
e=Employee("Durga",1000)
... |
8d412d63ecf3f973c11fffe60ec26d0613f84192 | ajaypraj/gittest | /date_time.py | 337 | 4 | 4 | import time
import datetime
initial=time.time()
k=0
while k<10:
print("Hi,Friends")
#time.sleep(1)
k+=1
print("Remaining time",time.time()-initial)
initial2=time.time()
for i in range(10):
print("Hi,Friends")
#time.sleep(1)
print("Remaining time",time.time()-initial2)
today=datetime.datetime.n... |
d2edb0647a6dd5ff6d9be2bcfd3311cf96e9ad42 | Sinjebos/EcUtbildningDevOps | /Linux and Script Languages/Python/exercise2/bank_controller.py | 1,975 | 4.125 | 4 | import bank_outputs as outputs
import math
def get_int_from_user() -> int:
try:
return int(input())
except Exception:
outputs.invalid_input()
return -1
def get_length_of_pin(number: int) -> int:
return int(math.log10(number)) + 1
def valid_pin_length(user_input: int) -> int:
... |
2741742e711918e27d33220e3f9457175020cb97 | Sinjebos/EcUtbildningDevOps | /Linux and Script Languages/Python/Self Studies/HelloWorld/sliceback.py | 315 | 3.5625 | 4 | letters = 'abcdefghijklmnopqrstuvwxyz'
backwards = letters[25::-1]
print(backwards)
print(letters[25 - 9: 25 - 12:-1])
print(letters[16: 13:-1])
print(letters[25 - 21::-1])
print(letters[4::-1])
print(letters[:-9:-1])
# letters = ""
print(letters[-4:])
print(letters[-1:])
print(letters[:1])
print(letters[0])
|
672540334af79e2ff011aaca252b13f7d66b10bd | Sinjebos/EcUtbildningDevOps | /Linux and Script Languages/Python/Self Studies/HelloWorld/strings.py | 851 | 4.125 | 4 | print("Today is a good day to learn python")
print('Python is fun')
print("Python's string are easy to use")
print('We can even include "quotes" in strings')
print("Hello" + " world")
greeting = "Hello"
name = "Bruce"
# Comment
print(greeting + ' ' + name)
# name = input('Please enter your name: ')
print(greeting + ... |
1efa567ead0dc1fa3ed026af786e4dd3e10741d5 | Sinjebos/EcUtbildningDevOps | /Linux and Script Languages/Python/exercies1/9.py | 362 | 3.84375 | 4 | from collections import Counter
# 9. Skriv ett Python-program för att hitta de upprepade objekten
# i en tupel.
tuple = ('g', 'e', 'e', 'k', 's')
print('Original list = {}'.format(tuple))
# Get duplicate tuples from list
# Using list comprehension + Counter() + items()
result = [ele for ele, count in Counter(tup... |
1e731d6886850af89ec770de05a7256909d9031f | Sinjebos/EcUtbildningDevOps | /Linux and Script Languages/Python/Self Studies/Sequences/more_print.py | 235 | 3.6875 | 4 | name = 'Lars'
age = 19
print(name, age, "Python", 2020)
print(name, age, "Python", 2020, sep=', ')
print(name, age, "Python", 2020, sep='-')
print(name, age, "Python", 2020, sep='-', end=' ')
print(name, age, "Python", 2020, sep='-')
|
982e83338f75b029e2e6d1c8774cc57b1efbfd77 | dvprknsn/python_monk | /4_5_hangman_play.py | 634 | 3.6875 | 4 | #4_4_hangman_play
import random
words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
lives_remaining = 14
def play():
word = pick_a_word()
while True:
guess = get_guess(word)
if process_guess(guess, word):
print ('You win! Well Done!')
break
if lives_remaining == 0... |
6008664bed0356073907705b2bdbbd70baa005df | mazenmoaaz461/Python_Newton-Method | /Source_Code.py | 1,207 | 4.25 | 4 | # Python Code using Jupiter in anaconda IDE to solve an Equation in Newton's method (Jacobian)
from sympy import *
from sympy.interactive import printing
printing.init_printing(use_latex=True)
#Q.1
#x+xy=2
#x+y=2
x,y=symbols('x y')
f1 = x + x * y - 2
print("First Equation:\nf1= ")
display(f1)
f2 = x + y - 2
print("... |
b61fafebdfb93c0bc605f42409b43a18263749a1 | flo62134/hyperskill_python_tic_tac_toe | /Problems/A list of words/task.py | 356 | 4 | 4 | # work with the preset variable `words`
def start_with_letter(word: str, letter: str):
first_letter = word[0]
starts_with_letter = first_letter.upper() == letter.upper()
if starts_with_letter:
return True
else:
return False
starting_with_a = [word for word in words if start_with_letter... |
607b44d837da7ef9f88ebfcdac8b6b5715d00fbc | NathanKr/python-playground | /oop/property_decorator.py | 309 | 3.75 | 4 | class Person:
def __init__(self,first_name,last_name):
self.first_name = first_name
self.last_name = last_name
@property
def full_name(self):
return f"{self.first_name} {self.last_name}"
p = Person('Barak','Obama')
print(p.full_name)
p.first_name='xxx'
print(p.full_name) |
e45ab2c3897ac8655df58ce4dc1ad677cafd27d1 | NathanKr/python-playground | /collections_try.py | 432 | 4.34375 | 4 | # list
mylist = ["apple", "banana", "cherry"]
print(mylist)
print(mylist[0])
for it in mylist:
print(it)
# tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple[0]) # print apple
a, b, c = thistuple # unpack tuple
print("a,b,c : ",a,b,c)
# set
myset = {3,4,5}
print (myset)
for it in myset:
print(i... |
76640b8b77cb5610af5f640e2bd772f7fd02cdd2 | NathanKr/python-playground | /ordered_dict_try.py | 412 | 3.609375 | 4 | from collections import OrderedDict
ordered_dict = OrderedDict()
print(f'type(ordered_dict) : {type(ordered_dict)}')
print(f'isinstance(ordered_dict,OrderedDict) : {isinstance(ordered_dict,OrderedDict)}')
# add values
ordered_dict['key1']=1
ordered_dict['key2']=2
ordered_dict['key1'] += 1
ordered_dict['key2'] += 2
#... |
1b4693e82eb21c2dbe52e389386a192f0607df39 | NathanKr/python-playground | /mutable_object_vs_immutable_object.py | 809 | 4.4375 | 4 | # all data in python is stored in an object
# mutable object :
# - an object whos state CAN be updated after its creation
# - e.g. containers like list,dict, set
# immutable object :
# - an object whos state can NOT be updated after its creation
# - e.g. primitives like string , number
# string is an imm... |
91a79d4d7737debc4594d477568cb09d809a802a | mariotalavera/collatz_conjecture | /collatz_stub.py | 1,212 | 3.734375 | 4 | import streamlit as st
import numpy as np
import pandas as pd
import time
min_value=5
max_value=27
cur_value=6
def compute():
i = num_beg
while i <= num_end:
st.write('Testing number ',i)
if i == 1:
print("We have reached 4-2-1 Loop!")
return 1
else:
if i % 2:
# If i is odd
# doOdd(i, itera... |
29b55e9a1ba40cf17491ef0218531c313657cd57 | john321875/aa | /data/json2sqlite.py | 725 | 3.59375 | 4 | #!/usr/bin/env python
import os
import time
import json
import sqlite3
JSON_FILE = "nflscores.json"
DB_FILE = "nfl.db"
# read file
with open('nflscores.json', 'r') as nflscores:
data = nflscores.read()
# parse file
request = json.loads(data)
nflscores = request["nflscores"]
for item in nflscores:
data = (item... |
14ca546b0cbb0e26d6db1a5a78a582712e20460d | quinalt/leetcode_problems | /rev_string.py | 133 | 3.921875 | 4 | # basic problem - return a reversed string
def rev_string(s):
for i, char in enumerate(list(reversed(s))):
s[i] = char
|
a3d18c309e918717fcab6e32a0ab591020a03d06 | charliechocho/py-crash-course | /x75_cinema_fee.py | 430 | 3.84375 | 4 | question = "\nBiljett pris beror på ålder!"
question += "\nSå, hur gammal är du? "
age = ""
while True:
age = input(question)
if int(age) <= 0:
print("\nHejdå Välkommen Åter!")
break
elif int(age) < 3:
print(f"Du går in gratis")
elif int(age) < 12:
print("Ditt pris är ... |
f96afb82399890e478006863fd221fb694a5832b | charliechocho/py-crash-course | /parrot.py | 1,043 | 3.734375 | 4 | intro = "Hej och välkommen till denna enkät! Vi börjar med att lära känna \
dig lite granna! Skriv 'quit' om du vill sluta!"
intro += "\n\tVi börjar med vad du heter? "
storage = []
print(intro)
active = True
while active:
message = input("Fyll i ditt förnamn: ")
message_2 = input("Fyll i ditt efternamn: ")
... |
083857474e6cb9725b035ef5a3e6263591d25a44 | charliechocho/py-crash-course | /ex_3_4.py | 828 | 3.859375 | 4 | #guest list creation
guests = ['nina','robin','linnéa']
print(f"I hereby invite you {guests[0].title()} to dinner on New Year's Eve!")
no_show = guests.pop(2)
print(f"Sorry you couldn't make it {no_show.title()} :-(")
print(guests)
guests.append('toffe')
print(guests)
guests.insert(0,'anna-clara')
guests.insert(2, 'kev... |
9adcc5aa9d001aef0aeb236df5f44a6bf15d4c10 | charliechocho/py-crash-course | /fav_albums.py | 608 | 4.15625 | 4 | fav_albums = {
'elp':'karnevil 9',
'ayreon':'final experiment',
'marillion':'misplaced childhood',
'magnum':"on a storteller's night",
}
print("These are my all time favorite albums!!")
for key, value in fav_albums.items():
print(f"\n\t{value.title()} by {key.upper()}!")
print("My favorite artists:... |
dc5407ffe0dd52f38a26edc22ed002d9ade8d77e | charliechocho/py-crash-course | /exc10_6.py | 418 | 4.09375 | 4 | check = True
def add_num(num1, num2):
try:
solution = int(num1) + int(num2)
except ValueError:
print("Är du säker på att du angav två NUMMER?")
return False
else:
print(f"Summan av dessa nummer blir {solution}")
while check != False:
first_num = input('Enter first nu... |
c3ba59b58886b131c32687671099064934badbf9 | charliechocho/py-crash-course | /record_store.py | 448 | 3.65625 | 4 | vinyls = {'artist':'abba', 'album':'visitors', 'year':'1980'}
for key, value in vinyls.items():
print(f"{key}:{value}")
vinyls['album'] = 'Super Trouper'
print(vinyls)
vinyls['genre'] = 'pop'
print(vinyls)
if vinyls['year'] == '1981':
vinyls['album'] = 'visitors'
elif vinyls['year'] == '1980':
vinyls[... |
980924d1e642a3b3148d1bcfb9ff0004e4a0ac44 | MilesAlmond/Competitions | /Showcode - Unicode/Challenge_1/ready_player_x.py | 854 | 3.671875 | 4 | class Cipher:
def halliday(self, message):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ciphertext = ""
for character in message:
if character.isalpha():
if character.isupper():
... |
d3770df59a36948ddbcff3ffc2f8fa9b98f71808 | RiddMa/PythonOJ | /3/1015.py | 1,370 | 3.609375 | 4 | # encoding = utf-8
"""
题目描述
某电商在给它所有的书排序时比其他电商多了一个排序依据,就是依据书名的缩写排序。如果我们规定书名的缩写为书名中所有的大写字母,请你写一段依据此规则的排序程序。
样例解释:
TheCProgrammingLanguage的缩写为TCPL,CPrimerPlus的缩写为CPP,TheArtofComputerProgramming的缩写为TACP,ComputerSystemsAProgrammersPerspective的缩写为CSAPP
输入
第一行为一个正整数n(0<n<10000)。后边是n行,每行一个字符串,代表书名,每个字符串中仅包含大写字母和小写字母,且长度小于1000... |
be9800d70781044ac2584cd1e23abcf0a25c9b2a | RiddMa/PythonOJ | /5/6-6.py | 2,858 | 4.09375 | 4 | """
6-6 jmu-python-发牌 (10分)
从键盘输入一个整数作为随机种子,随机生成一副扑克牌(去掉大小王),循环分给4位牌手,每人5张牌(第1、5、9、13、17张牌给第一个玩家,第2、6、10、14、18给第二个玩家。。。以此类推)并输出。
函数接口定义:
create( )
shufflecard(pokers)
deal(pokers,n)
其中create( )的功能是生成一副不含大小王的扑克牌序列并返回;shufflecard(pokers)的功能是随机洗牌并返回洗牌后的扑克牌序列,其中 pokers 是传入的参数,表示52张扑克牌的序列;deal(pokers,n) 是发5张牌给一个玩家并将发给该玩家的牌... |
2651be795f53fc7d8a68e8bcd4c161cae08c4595 | RiddMa/PythonOJ | /6/7-4.py | 1,069 | 3.5 | 4 | """
7-4 解析车间里的阀门状态 (高教社,《Python编程基础及应用》习题5-4) (10分)
CPU通过一个8位IO口读取了1个字节的内容,现在存储在一个bytes对象里,示例: b'\x45';这8位分 别代表了车间里8个阀门的当前状态,1表示该阀门通,0表示该阀门断。请设计一个程序,从bytes对象解析出8个 阀门的当前状态,True表示通,False表示断。这8个状态应组织在一个列表中,其中,第i个元素对应输入字节的第i 位。
输出格式示例:[True, False, False, True, True,True,False,False]
输入格式:
形如 b'\x45'的单字节bytes。(注意是16进制)
... |
f41f560e18c0bab5ebed2f0f58d1176dc5926495 | Tri-Carrot/EZLabelTool | /EZlabelTool/back-end/model/ProjectDB.py | 2,221 | 3.5625 | 4 | # -*- coding:utf-8 -*-
# Date: 11 April 2021
# Author:Yan Zhou a1807782
# Description:the database connection process of project
import sqlite3
class ProjectDB:
def __init__(self, db):
self.conn = sqlite3.connect(db, check_same_thread=False)
self.cur = self.conn.cursor()
self.cur.execute("... |
ecd7cc7643055f5563b2caee88088f70980861d0 | rajesh-kanakabandi/learning | /automobile/Car.py | 625 | 3.546875 | 4 | """
Name: Car.py
Description: Car class
"""
from Automobile import Automobile
class Car(Automobile):
"""
class for all cars
"""
def __init__(self, period_between_services=3500):
"""
Description: initializes an object of type car
@param period_between_services: int
"""
Automo... |
e4014cc47cfbf3a7b7c2ab58b2795ce2417c1d74 | jkramarz/winton-kafka-streams | /winton_kafka_streams/processor/serialization/_deserializer.py | 841 | 3.546875 | 4 | """
Base class for deserializer implementations
"""
import abc
class Deserializer(metaclass=abc.ABCMeta):
"""
Configure this deserializer.
Parameters:
-----------
configs : dict
configs in key/value pairs
is_key : bool
whether is for key or value
"""
@abc.abstractmet... |
322f5ec9a35c55082b883bbf80a1e319b30cf780 | amitchoudhary13/Python_Practice_program | /19.py | 2,041 | 4.53125 | 5 | #!/usr/bin/python
'''
19.Using loop structures print even numbers between 1 to 100.
a) By using For loop , use continue/ break/ pass statement to skip odd numbers.
i) break the loop if the value is 50
ii) Use continue for the values 10,20,30,40,50
b) By using while loop, use continue/ break/ pass statement to skip o... |
c0160b61fcca6824cbcdb83aa38dfe3b4b0ee568 | amitchoudhary13/Python_Practice_program | /calendar_mod.py | 558 | 4.3125 | 4 | '''
Using calendar module perform following operations.
a) Print the 2016 calendar with space between months as 10 characters.
b) How many leap days between the years 1980 to 2025.
c) Check given year is leap year or not.
d) print calendar of any specified month of the year 2016.
'''
import calendar as calendar
pri... |
d288751b1e3cb8436161bcccb7d767c41b7922e8 | amitchoudhary13/Python_Practice_program | /12.py | 948 | 4.25 | 4 |
#!/usr/bin/python
'''
Read 10 numbers from user and find the average of all.
a) Use comparison operator to check how many numbers are less than average and print them
b) Check how many numbers are more than average.
c) How many are equal to average.
'''
#variable declaration
num = 10;
total_sum = 0;
number = [];
numle... |
ff525ef5fcbfa811090ca3ef588c78b37cb139a1 | SaiPhani-Erlu/pyScript | /3_DeepDive/CaseStudy1/13_Binary_div.py | 849 | 3.984375 | 4 | '''
Q13. Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input
and then check whether they are divisible by 5 or not.
The numbers that are divisible by 5 are to be printed in a comma separated sequence.
Example: 0100,0011,1010,1001
Then the output should be: 1010
'''
# 0001,00... |
09e9062445c5ba88636db44bba26e1849681008e | SaiPhani-Erlu/pyScript | /3_DeepDive/CaseStudy1/14_CaseCount.py | 460 | 4.1875 | 4 | """
14. Write a program that accepts a sentence and calculate the number of upper case letters and lower case letters.
Suppose the following input is supplied to the program:
Hello world!
Then, the output should be:
UPPER CASE 1
LOWER CASE 9
"""
input_str = input("Enter string: ")
print('Uppercase count:', len(list(... |
a6da85ca0ef3e35459ed5e2e53f80f5ed90377aa | SaiPhani-Erlu/pyScript | /3_DeepDive/CaseStudy1/04_GeoDistance.py | 867 | 4.03125 | 4 | '''
Q4. Write a program to find distance between two locations when their latitude and
longitudes are given.
Hint: Use math module.
'''
from math import radians, cos, sin, asin, sqrt
class City:
def __init__(self, lat, lon):
self.latitude = radians(lat)
self.longitude = radians(lon)
def calc_d... |
267346a75c4b68c8bcb1b7d62c6dd55aab7bd8ad | SaiPhani-Erlu/pyScript | /7_WebMap_Dev/CaseStudy2/SFO_Police/NewCrimeAnalysis.py | 2,539 | 3.71875 | 4 | """
Business challenge/requirement
SFO Police has shared crime data for year 2016. Data contains various incidents which have happened throughout
the year, along with the geolocation of the crime. You need to prepare effective web-maps to analyze and present
the data. SFO Commissioner of Police will reassign the forces... |
e67ae23ac052ef26feb96683f997b306dd6de6e5 | SaiPhani-Erlu/pyScript | /5_Data_Visualisation/CaseStudy1/4_SampleSales.py | 931 | 4.15625 | 4 | """
Create csv file from the data below and read in pandas data frame
1. Reading Data
2. Describe the data on the unit price
3. filter the data: Create new dataframe having columns 'name','net_price','date'
and group all the records according to name
4. Plotting graph: Plot the graph after calculating total sales b... |
dd946df035aabad360c1ee20222484771d4ce3e9 | SaiPhani-Erlu/pyScript | /5_Data_Visualisation/CaseStudy1/3_CarPie.py | 478 | 3.640625 | 4 | """
Plot a pie-chart of the number of models released by every manufacturer, recorded in the data provide.
Also mention the name of the manufacture with the largest releases.
"""
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('Cars2015.csv')
df['Make'] = df['Make'].str.strip()
new_df = df.groupb... |
13cd6bd57ceb5f66fa6cfe35f2a4533d856f925e | radam9/CPB-Selfmade-Code | /04 Object Oriented Programming/L6E2_OOP_ClassObjectAttribute_Methods.py | 1,280 | 4.3125 | 4 | #Object Oriented Programming (OOP)
#Class Object Level Attribute
class Dog():
#Class Object Attribute
#Same for any instance of a class (i.e. same for any dog)
species = 'Mammal'
def __init__(self,breed,name,spots):
self.breed = breed
self.name = name
self.spots = spots
mydog =... |
44058340ad1578cdafef3d82118ab25c980cffa2 | radam9/CPB-Selfmade-Code | /08b_Generators_Homework.py | 447 | 3.796875 | 4 | #Problem 1
def square(x):
for i in range(x):
yield i**2
for x in square(10):
print(x)
#Problem 2
import random
def gener(l,h,x):
for _ in range(x):
yield random.randint(l,h)
for x in gener(1,10,12):
print(x)
#Problem 3
s = 'Hello'
s_it = iter(s)
print(next(s))
#Credit Problem
#Gener... |
ede9edb9f7877df9f59d6fb9b9934ece38cf1bb9 | radam9/CPB-Selfmade-Code | /03 Functions and Methods/L5E3_arguments_KeywordArguments.py | 1,220 | 4.625 | 5 | #Arguments *args and Keyword Arguments **kwargs
def func(a,b):
#returns %5 of the sum of a and b
return sum((a,b)) * 0.05
func(40,60)
# a and b are positional arguments
# 40 was assignemt to a because it was in the first position/argument
# 60 was assignemt to a because it was in the second position/argument
# ... |
5eeafcd6333d4a412ccea26a9049928f503cd1ff | radam9/CPB-Selfmade-Code | /04 Object Oriented Programming/L6E1_OOP_ObjectOrientedProgramming.py | 595 | 4.09375 | 4 | #Object Oriented Programming (OOP)
#Class Keywords and Attributes
#Creating a class
class Sample():
pass
mysample = Sample()
print(type(mysample))
#Step 2 Create attributes
class Dog():
def __init__(self,breed,name,spots):
self.breed = breed
mydog = Dog(breed='Lab')
print(type(mydog))
print(mydog.bre... |
7f61bcfc11c62b52d1acbb59f481d80314d7922b | radam9/CPB-Selfmade-Code | /01 Data Types - Variables - Printing - File IO/L3E7_Sets.py | 432 | 4.25 | 4 | #Sets
myset = set()
myset.add(1)
print(myset)
myset.add(2)
print(myset)
#Sets only carry 1 of each item so if we add 2 again nothing happens to the set
myset.add(2)
print(myset)
#Sets can only carry Numbers and Strings
myset = {1,2,'abc',0.1,-300}
print(myset)
#you can convert a list to a set in the following way
#noti... |
5a23e8cb0291f1779a1156227249fda8547de36a | DeveloperArthur/treinamento-ICPC-2019 | /2006/F.py | 355 | 3.703125 | 4 | while True:
cont=0
numeroParticipantes = input()
partidasJogadas = input()
if int(numeroParticipantes) == 0 and int(partidasJogadas) == 0:
break
for i in range(0, int(numeroParticipantes)):
time = input()
pontuacao = input()
if int(pontuacao) == 1:
... |
275621428182080e5f1107201f13da07c17905ae | krystiankkk/rekr | /matrixdiameter.py | 439 | 3.515625 | 4 | i=0
all=[]
mat = '248'
mat1 = '-260'
mat2 = '123'
all.append(mat)
all.append(mat1)
all.append(mat2)
d1 = 0
d2 = 0
i = 3
print(all)
#for i in range(0, i):
#print(all[i][i])
# d1 = d1+int(all[i][i])
#print(all[i][-i-1])
# d2 = d2+int(all[i][-i-1])
#print(abs(d1-d2))
def dia(all):
d1=0
d2=0
f... |
9078e135ee693b59cbc6da2505e2773c2874b5ca | sravyapara/python | /icp4/icp4/venv/try.py | 802 | 3.6875 | 4 | class Employee(object):
numOfEmp = 0
def __init__(self):
self.type = "Developer"
def calculate(self):
# to calculate number of employees
self.numOfEmp += 1
print("Number of employee:", self.numOfEmp)
def display(self, name, sal):
print("Employee Name:",name)
... |
10e804ed3fe21897c9a57d60da278e4c5ad95a3e | sravyapara/python | /icp1/randomnumber.py | 307 | 4.0625 | 4 | import random
num = random.randint(0, 10)
while True:
print("enter the number to guess")
guess = int(input())
if guess == num:
print("the number is correct")
break
elif guess < num:
print("the number is low")
elif guess > num:
print("the number is high") |
71ed01a8c9c0aa07b6e9fd34538ce8b835a964ad | sravyapara/python | /icp2/lists.py | 179 | 3.890625 | 4 | wordList = ["PHP", "Exercises", "Backend"]
leng = []
for x in wordList:
leng.append(tuple((len(x),x)))
print(leng)
sortList = sorted(leng);
print(sortList)
print(sortList[-1]) |
d1f7cf1eeae6d64a9b6cf9af2024a89c4e41dc58 | hasunesirasaki/Personal-study | /practice/twodice.py | 222 | 3.515625 | 4 | import random
def dice(n):
d = random.randrange(n)+1
return d
x = dice(10)
print(x)
def twodice():
ans = dice(6)+dice(6)
return ans
a = twodice()
print(a)
#x = 6
#a = random.sample(range(x),2)
#print(a)
|
235153c6ec03962d45c3be6ee8cf591abaa369ed | hasunesirasaki/Personal-study | /openfile/outfile.py | 190 | 3.53125 | 4 | # アウトファイル
outfile = "new.txt"
with open(outfile,"w") as fout:
while True:
data = input("#")
if data == "":
break
print(data,file=fout)
|
a561d8a79fdab8816f424bf036189a9f8f584c13 | jrestrepot/ST0245-032 | /talleres/taller07/Taller07.py | 1,245 | 3.734375 | 4 | class Nodo():
def __init__(self, obj, nxt = None):
self.obj = obj
self.nxt = nxt
class Lsimple():
def __init__(self):
self.first_Node = None
self.size = 0
def contains(self,element):
if self.size==0:
return False
else:
... |
40630dd5fae81e66691077af714b73a23e54d276 | MrRa1n/Python-Learning | /DatatypeCasting.py | 1,047 | 4.25 | 4 | # Python determines the datatype automatically
x = 3 # Integer
y = "text" # String
x = 4
y = 2.15315224522
print("We have defined two numbers, ")
print("x = " + str(x)) # Datatype cast to String using str()
print("y = " + str(y)) # Datatype cast to String using str()
a = "135.24552"
b = "13... |
17eba7bcc0b449eaba26161f2d231300c98036a4 | MrRa1n/Python-Learning | /Random.py | 524 | 3.921875 | 4 | # The 'random' module can generate pseudo-random numbers
from random import *
# Random floating point number between 0 and 1
print(random())
# Random whole number between 1 and 100
print(randint(1,100))
x = randint(1,100)
print(x)
# Random floating point number between 1 and 10
print(uniform(1,10))
# Fun with lis... |
e5062e4c19d2cdd50e4d1f40b9bd7a093fc772f1 | MrRa1n/Python-Learning | /GlobalVariables.py | 313 | 3.5 | 4 | # Local variables
def sum(x,y):
sum = x + y
return sum
print(sum(8,6))
# Global variables
z = 10
def afunction():
global z
z = 9
afunction()
print(z)
# Exercise
z = 10
def func1():
global z
z = 3
def func2(x,y):
global z
return x+y+z
func1()
total = func2(4,5)
print(total)
|
aafbb959818d625afbb7a5ed77663c076817e0fe | marktoregan/scripting_assignment_2 | /copyfile.py | 1,295 | 3.796875 | 4 | import sys
class CopyFile(object):
def __init__(self, source_file, destination_file):
"""A class that copies a source file to a destination file.
Args:
source_file: The source file, e.g. /home/mark/cit_cloud_comp/scripting/assignment2/sourcefiles/one.txt
destinat... |
141ba30e3010dd23d5a0faed64d473082787ba81 | HectorRamosJunior/Interesting-Interview-Problems | /11.py | 4,098 | 3.546875 | 4 | """Find the no of possible patterns in android lock screen.
Write a program to count them.
Assumes nodes needed for a pattern are 4 <= n <= 9
https://www.careercup.com/question?id=5663422257561600
"""
# Calls the first recursive function, returns the number of patterns
def get_num_patterns(min_length, max_length, no... |
9041530574ace03e06374ba9663fe60c610dff74 | HectorRamosJunior/Interesting-Interview-Problems | /1.py | 1,973 | 3.890625 | 4 | """Given an arbitrary tree starting at 'root' where each node contains a
pair of values (x, y), write a boolean function find(Node root, int x, int y)
that returns true iff:
* x is equal to a value "x" of any node n1 in the tree
* and y is equal to a value "y" of any node n2 in the tree
* and both n1 and n2 are at ... |
a9347290728f44fbcd30afb54b30d1216fae7618 | wpy-111/python | /month01/day13/exercise07.py | 895 | 4.125 | 4 | """
定义:
1.存储所有图形
2.计算所有图形的面积he
"""
class GraphicManager:
def __init__(self):
self.__list_graphic=[]
def add_figure(self, target):
self.__list_graphic.append(target)
def totally_area(self):
sum_area=0
for item in self.__list_graphic:
sum_area=item.calc... |
2fd7fff8c65483ab722a3b345645d49b95971e67 | wpy-111/python | /DataAnalysis/day06/demo05_add.py | 413 | 3.765625 | 4 | """
加法通用函数
"""
import numpy as np
ary = np.arange(1,7)
print(np.add(ary,ary))#数组对应位置相加
print(np.add.reduce(ary))#数组累加
print(np.add.accumulate(ary))#累加过程
print(np.add.outer([10,20,30],ary))#ary作为列标签和前面相加
print(np.prod(ary))#累乘的结果
print(np.cumprod(ary))#累乘的过程
print(np.outer([10,20,30],ary))#ary作为列标签和前面累乘
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.