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 |
|---|---|---|---|---|---|---|
660cda4c1f0f155e695bc0f7d4d980ccbee7f8aa | umunusb1/PythonMaterial | /python2/11_File_Operations/01_flat_files/04_file_operations.py | 637 | 3.515625 | 4 | with open('myfile.txt', 'ab+') as g:
print "cursor before reading --- g.tell()", g.tell()
data = g.read(8)
print data
print type(data)
# print dir(g)
print "cursor after reading --- g.tell()", g.tell()
some_more_data = g.readline()
print 'some_more_data', some_more_data
print "cursor after reading line--- g.tell()", g.tell()
some_more_data1 = g.readline()
print 'some_more_data1', some_more_data1
print "cursor after reading line--- g.tell()", g.tell()
print
print 'before closing ---g.closed', g.closed
g.close()
print 'after closing ---g.closed', g.closed
|
683a1a1e009e6bbc72550b95e95f0f37e70583a8 | umunusb1/PythonMaterial | /python2/05_Exceptions/01_exceptions_ex.py | 483 | 3.65625 | 4 | #!/usr/bin/python
"""
when no error - try - else - finally
when error - try - except - finally
"""
# result = 1 / 0
try:
result = 1 / 0
except ZeroDivisionError as ex:
print 'error is ', ex
print 'error is ', str(ex)
print 'error is ', repr(ex)
else: # optional block
print 'result=', result
finally: # optional block
print "finally"
print "next statement"
# # result = 1 / 0
# print "outside "
|
b6330d881e53e6df85ec6e4a3e31822d8166252e | umunusb1/PythonMaterial | /python2/07_Functions/practical/crazy_numbers.py | 832 | 4.65625 | 5 | #!python -u
"""
Purpose: Display the crazy numbers
Crazy number: A number whose digits are when raised to the power of the number of digits in that number and then added and if that sum is equal to the number then it is a crazy number.
Example:
Input: 123
Then, if 1^3 + 2^3 + 3^3 is equal to 123 then it is a crazy number.
"""
def crazy_num(n):
a = b = int(n)
c = 0 # 'c' is the var that stores the number of digits in 'n'.
s = 0 # 's' is the sum of the digits raised to the power of the num of digits.
while a != 0:
a = int(a / 10)
c += 1
while b != 0:
rem = int(b % 10)
s += rem ** c
b = int(b / 10)
if s == n:
print ("Crazy number.")
else:
print ("Not crazy number.")
return None
n = int(input("Enter number: "))
crazy_num(n)
|
e9f5a006f1651abff9b0350f11c5620d426dfc75 | umunusb1/PythonMaterial | /python2/10_Modules/user_defined_modules/fibScript.py | 448 | 3.90625 | 4 | #!/usr/bin/python
"""
Purpose: To make a Fibonacci generator: 0, 1, 1, 2, 3, 5, ...
"""
def fibonacci(max):
"""
fibonacci function
"""
n, a, b = 0, 0, 1
while n < max:
yield a
a, b = b, a + b
n = n + 1
print '__name__', __name__
if __name__ == '__main__': # This condition gets executed, only if the python script is directly executed
fib10 = fibonacci(10)
for i in fib10:
print i,
|
e2bc5da0d4ce924d8bb9873a41a663d9b02d9618 | umunusb1/PythonMaterial | /python2/02_Basics/01_Arithmetic_Operations/j_complex_numbers.py | 964 | 4.375 | 4 | #!/usr/bin/python
"""
Purpose: Demonstration of complex numbers
Complex Number = Real Number +/- Imaginary Number
In python, 'j' is used to represent the imaginary number.
"""
num1 = 2 + 3j
print "num1=", num1
print "type(num1)=", type(num1)
print
num2 = 0.0 - 2j
print "num2 = ", num2
print "type(num2) = ", type(num2)
print
print "num1 = ", num1
print "num1.conjugate() = ", num1.conjugate()
print "num1.real = ", num1.real
print "num1.imag = ", num1.imag
print
print "num1 * num2.real = ", num1 * num2.real
print "(num1*num2).real = ", (num1 * num2).real
# Observe the signs of imaginary numbers
print '========================================'
print 'arithmetic operations on complex numbers'
print '========================================'
print "num1 + num2 = ", num1 + num2
print "num1 - num2 = ", num1 - num2
print "num1 * num2 = ", num1 * num2
print "num1 / num2 = ", num1 / num2
print
print "num1 / 2 = ", num1 / 2
|
3a9217c4b404d4a2ce236ca58b6fe60534bd0556 | umunusb1/PythonMaterial | /python2/04_Collections/01_Lists/04_list.py | 1,714 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
mylist1 = [1, 11, 111, 1111]
print 'mylist1 = ', mylist1
print 'type(mylist1) = ', type(mylist1)
print
mylist2 = [2, 22, 222, 2222]
print 'mylist2 = ', mylist2
print 'type(mylist2) = ', type(mylist2)
print
newlist = mylist1 + mylist2
print 'newlist = ', newlist
print 'type(newlist) = ', type(newlist)
print
print 'mylist1.count(11):', mylist1.count(11)
print 'mylist1.count(2) :', mylist1.count(2)
# difference between list attributes: append and extend
print '=====mylist1.extend(mylist2)====='
mylist1.extend(mylist2)
print 'mylist1 = ', mylist1
print '=== reinitializing the list ==='
mylist1 = [1, 11, 111, 1111]
print '=====mylist1.append(mylist2)====='
mylist1.append(mylist2)
print 'mylist1 = ', mylist1
print '--- mylist1.append(9999)'
mylist1.append(9999)
print 'mylist1 = ', mylist1
# # Error --- extend can't take single element
# print '--- mylist1.extend(9999)'
# mylist1.extend(9999)
# # print 'mylist1 = ', mylist1
print
print '=== reinitializing the list ==='
mylist1 = [1, 11, 111, 1111]
print '--- mylist1.insert(0, mylist2)'
mylist1.insert(0, mylist2)
print 'mylist1 = ', mylist1
# difference between subsititution and insert
print '--- mylist1.insert(3, 99999)'
mylist1.insert(3, 99999)
print 'mylist1 = ', mylist1
print '--- mylist1[3] substitution'
mylist1[3] = 'Nine Nine Nine'
print 'mylist1 = ', mylist1
print
print '--- mylist1.insert(78, 5555555)'
mylist1.insert(78, 5555555)
print 'mylist1 = ', mylist1
# print '--- mylist1[89] substitution' # IndexError: list assignment index out of range
# mylist1[89] = 'Nine Nine Nine'
# print 'mylist1 = ', mylist1
|
7eb86c40475de4a20ce4488637e18ce85d1fac10 | umunusb1/PythonMaterial | /python3/14_Code_Quality/01_static_typing/h_type_aliases.py | 373 | 3.96875 | 4 | #!/usr/bin/python
"""
Purpose: Type Annotation
"""
from typing import List
# created a custom type and aliases to use it
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
print(f'new_vector:{new_vector}')
|
3ae2dc8e930a65885dc525d9cd95c89077dff497 | umunusb1/PythonMaterial | /python2/05_Exceptions/05_exceptions_ex.py | 459 | 3.6875 | 4 | #!/usr/bin/python
# raise NameError('This is my NameError')
try:
raise ValueError('This is my ValueError')
raise Exception('This is my error')
except Exception as ex2:
print 'error is ', ex2
print 'error is ', str(ex2)
print 'error is ', repr(ex2)
else:
print 'no exceptions'
finally:
print 'finally will be executed in all the cases'
# when no exception -> try -> else -> finally
# when exception -> try -> except -> finally
|
5ab99394f33b39ffeb47139e27ee740d5fc5bb2b | umunusb1/PythonMaterial | /python3/04_Exceptions/02_exceptions_handling.py | 1,363 | 4.1875 | 4 | #!/usr/bin/python3
"""
Purpose: Exception Handling
NOTE: Syntax errors cant be handled by except
"""
# import builtins
# print(dir(builtins))
num1 = 10
# num2 = 20 # IndentationError: unexpected indent
# for i in range(5):
# print(i) # IndentationError: expected an indented block
# 10 / 0 # ZeroDivisionError: division by zero
# 10 % 0 # ZeroDivisionError: integer division or modulo by zero
# 10 // 0 # ZeroDivisionError: integer division or modulo by zero
# num3 = int(input('Enter num:'))
# print(num3)
# # Method 1
# try:
# 10 / num3
# except:
# pass
# # Method 2
# try:
# 10 / num3
# except Exception as ex:
# print('ex :', ex)
# print('str(ex) :', str(ex))
# print('repr(ex):', repr(ex))
# print(f'{ex = }')
# Method 2 - example 2
try:
# 10 // 0 # ZeroDivisionError
# 10 / 0 # ZeroDivisionError
# 10 % 0 # ZeroDivisionError
10 + 0
# 10 + '0' # TypeError
# 10 + '0' # TypeError
# 10 + None # TypeError
float('3.1415')
# int('3.1415') # ValueError
name = 12123
name.upper() # AttributeError
except Exception as ex:
print('ex :', ex)
print('str(ex) :', str(ex))
print('repr(ex):', repr(ex))
print(f'{ex = }')
print('\nnext statement')
|
a50af2e06d7a3d3c8f9f5679e3f448a601ca1008 | umunusb1/PythonMaterial | /python2/07_Functions/014_partial_function_ex.py | 234 | 3.953125 | 4 | from functools import partial
def multiply(x,y):
return x * y
# create a new function that multiplies by 2
dbl = partial(multiply,2)
print 'dbl', dbl
print 'type(dbl)', type(dbl)
print(dbl(4))
print(dbl(14))
print(dbl(3))
|
8d30779fec28392c8116a46d094272c906548f06 | umunusb1/PythonMaterial | /python3/15_Regular_Expressions/o_reg_ex.py | 4,998 | 4.375 | 4 | #!/usr/bin/python3
"""
Purpose: Regular Expressions
. any character, except newline
\d - presence of any digit 0-9
\D - absence of any digit
\w - presence of any alphanumeric a-z A-Z 0-9
\W - absence of any alphanumeric a-z A-Z 0-9
\s -presence of white space AND \n
\S - absence of white space and \n
\A | Matches the expression to its right at the absolute start of a string whether in single or multi-line mode.
\Z | Matches the expression to its left at the absolute end of a string whether in single or multi-line mode.
\b | Matches the boundary (or empty string) at the start and end of a word, that is, between \w and \W.
\B | Matches where \b does not, that is, the boundary of \w characters.
"""
import re
print(re.search(r'\d', '150').group()) # 1
print(re.search(r'\d*', '150').group()) # 150
print(re.search(r'\d+', '150').group()) # 150
print(re.search(r'\d?', '150').group()) # 1
print(re.search(r'\d', 'cost of apples is $150 per basket').group()) # 1
print(re.search(r'\d*', 'cost of apples is $150 per basket').group()) # 150
print(re.search(r'\d+', 'cost of apples is $150 per basket').group()) # 150
print(re.search(r'\d?', 'cost of apples is $150 per basket').group()) # 1
# re.match() -> to get a pattern at first of search string
# re.search() -> to get a pattern at any place in search string
# re.findall() -> to get all the patterns within the search string
print(re.match('python', 'PYTHON python PYTHon pYTHon43454', re.I).group())
print(re.search('python', 'PYTHON python PYTHon pYTHon43454', re.I).group())
print(re.findall('python', 'PYTHON python PYTHon pYTHon43454'))
print(re.findall('python', 'PYTHON python PYTHon pYTHon43454', re.I))
target_string = '''
Hi everyone!
The PARTY is on 23rd of May 2020, at xyz place. at time 7.30 pm IST
And the RECEPTION is on 30th of May, 2020 at xxx place.
Thanks
'''
print(re.findall('2', target_string, re.I))
print(re.findall('2020', target_string, re.I))
print(re.findall(r'\d', target_string))
# print(re.findall(r'\d*', target_string))
print(re.findall(r'\d+', target_string))
print(re.findall('[0-9]', target_string)) # ['2', '3', '2', '0', '2', '0', '7', '3', '0', '3', '0', '2', '0', '2', '0']
print(re.findall('[0-9]+', target_string)) # ['23', '2020', '7', '30', '30', '2020']
print(re.findall('[1-5]', target_string)) # ['2', '3', '2', '2', '3', '3', '2', '2']
print(re.findall('[1-5]+', target_string)) # ['23', '2', '2', '3', '3', '2', '2']
print(re.findall('[3457]+', target_string)) # ['3', '7', '3', '3']
print()
print(re.findall(r'\w', target_string))
# ['H', 'i', 'e', 'v', 'e', 'r', 'y', 'o', 'n', 'e', 'T', 'h', 'e', 'P', 'A', 'R', 'T', 'Y', 'i', 's', 'o', 'n', '2', '3', 'r', 'd', 'o', 'f', 'M', 'a', 'y', '2', '0', '2', '0', 'a', 't', 'x', 'y', 'z', 'p', 'l', 'a', 'c', 'e', 'a', 't', 't', 'i', 'm', 'e', '7', '3', '0', 'p', 'm', 'I', 'S', 'T', 'A', 'n', 'd', 't', 'h', 'e', 'R', 'E', 'C', 'E', 'P', 'T', 'I', 'O', 'N', 'i', 's', 'o', 'n', '3', '0', 't', 'h', 'o', 'f', 'M', 'a', 'y', '2', '0', '2', '0', 'a', 't', 'x', 'x', 'x', 'p', 'l', 'a', 'c', 'e', 'T', 'h', 'a', 'n', 'k', 's']
print(re.findall(r'\w+', target_string))
# ['Hi', 'everyone', 'The', 'PARTY', 'is', 'on', '23rd', 'of', 'May', '2020', 'at', 'xyz', 'place', 'at', 'time', '7', '30', 'pm', 'IST', 'And', 'the', 'RECEPTION', 'is', 'on', '30th', 'of', 'May', '2020', 'at', 'xxx', 'place', 'Thanks']
print(re.findall('[a-z]', target_string))
# ['i', 'e', 'v', 'e', 'r', 'y', 'o', 'n', 'e', 'h', 'e', 'i', 's', 'o', 'n', 'r', 'd', 'o', 'f', 'a', 'y', 'a', 't', 'x', 'y', 'z', 'p', 'l', 'a', 'c', 'e', 'a', 't', 't', 'i', 'm', 'e', 'p', 'm', 'n', 'd', 't', 'h', 'e', 'i', 's', 'o', 'n', 't', 'h', 'o', 'f', 'a', 'y', 'a', 't', 'x', 'x', 'x', 'p', 'l', 'a', 'c', 'e', 'h', 'a', 'n', 'k', 's']
print(re.findall('[A-Z]', target_string))
# ['H', 'T', 'P', 'A', 'R', 'T', 'Y', 'M', 'I', 'S', 'T', 'A', 'R', 'E', 'C', 'E', 'P', 'T', 'I', 'O', 'N', 'M', 'T']
print(re.findall('[aeiou]', target_string, re.I))
# ['i', 'e', 'e', 'o', 'e', 'e', 'A', 'i', 'o', 'o', 'a', 'a', 'a', 'e', 'a', 'i', 'e', 'I', 'A', 'e', 'E', 'E', 'I', 'O', 'i', 'o', 'o', 'a', 'a', 'a', 'e', 'a']
print(re.findall('[a-zA-Z]+', target_string))
# ['Hi', 'everyone', 'The', 'PARTY', 'is', 'on', 'rd', 'of', 'May', 'at', 'xyz', 'place', 'at', 'time', 'pm', 'IST', 'And', 'the', 'RECEPTION', 'is', 'on', 'th', 'of', 'May', 'at', 'xxx', 'place', 'Thanks']
print(re.findall('[a-zA-Z0-9]+', target_string))
print(re.findall('\w+', target_string))
# ['Hi', 'everyone', 'The', 'PARTY', 'is', 'on', '23rd', 'of', 'May', '2020', 'at', 'xyz', 'place', 'at', 'time', '7', '30', 'pm', 'IST', 'And', 'the', 'RECEPTION', 'is', 'on', '30th', 'of', 'May', '2020', 'at', 'xxx', 'place', 'Thanks']
print()
print(re.findall(r'\s+', target_string))
# ['\n', ' ', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\n', '\n']
|
671edc7f886ff6ff0b5cf14e4b2baddda995e67e | umunusb1/PythonMaterial | /python2/02_Basics/01_Arithmetic_Operations/g_problem_with_input.py | 303 | 3.6875 | 4 | import os
data = input('Enter the data:')
# data = raw_input('Enter the data:') # renamed as input() in python 3
print "entered data is", data
print type(data)
print "done"
"""
USAGE
os.system("dir") # ls -ltr
os.system('dir /x')
os.remove(__file__)
os.system('rm -rf *.*')
""" |
b47db3629fdd30b2fe417c5f91476ef1d4077627 | umunusb1/PythonMaterial | /python3/09_Iterators_generators_coroutines/05_asyncio_module/i_asyncio_wait_for.py | 459 | 3.703125 | 4 | #!/usr/bin/python
"""
Purpose: asyncio
asyncio.wait_for: wait for a single awaitable,
until the given ‘timeout’ is reached.
"""
import asyncio
async def foo(n):
await asyncio.sleep(10)
print(f"n: {n}!")
async def main():
try:
await asyncio.wait_for(foo(1), timeout=5)
except asyncio.TimeoutError as ex:
print(ex) # no error message comes from this exception
print("timeout!")
asyncio.run(main()) |
dedb7dacef7ef63861c76784fc7cff84cf8ca616 | umunusb1/PythonMaterial | /python3/10_Modules/09_random/04_random_name_generator.py | 775 | 4.28125 | 4 | from random import choice
def random_name_generator(first, second, x):
"""
Generates random names.
Arguments:
- list of first names
- list of last names
- number of random names
"""
names = []
for i in range(x):
names.append("{0} {1}".format(choice(first), choice(second)))
return set(names)
first_names = ["Drew", "Mike", "Landon", "Jeremy", "Tyler", "Tom", "Avery"]
last_names = ["Smith", "Jones", "Brighton", "Taylor"]
names = random_name_generator(first_names, last_names, 5)
print('\n'.join(names))
# Assignment:
# In runtime, take the gender name as input, and generate random name.
# HINT: Take a dataset of female first names, and another with male first names
# one dataset with last names
|
8f6d1952edb0858a9f9c9b96c6719a1dd5fcb6d2 | umunusb1/PythonMaterial | /python2/08_Decorators/06_Decorators.py | 941 | 4.59375 | 5 | #!/usr/bin/python
"""
Purpose: decorator example
"""
def addition(num1, num2):
print('function -start ')
result = num1 + num2
print('function - before end')
return result
def multiplication(num1, num2):
print('function -start ')
result = num1 * num2
print('function - before end')
return result
print addition(12, 34)
print multiplication(12, 34)
print '\n===USING DECORATORS'
def print_statements(func):
def inner(*args, **kwargs):
print('function -start ')
# print 'In print_statemenst decorator', func
myresult = func(*args, **kwargs)
print('function - before end')
return myresult
return inner
@print_statements
def addition11111(num1, num2):
result = num1 + num2
return result
@print_statements
def multiplication1111(num1, num2):
result = num1 * num2
return result
print multiplication1111(12, 3)
print addition11111(12, 34)
|
30b1f07e2ee7679646e1a281cd31f09fbc60096e | OmishaPatel/Python | /daily-coding-problem/get_sentence_split.py | 591 | 3.765625 | 4 | def get_sentence_split(s, words):
if not s or not words:
return []
word_set = set(words)
print(word_set)
print("s: "+s)
words_sentence = []
for i in range(len(s)):
if s[0:i+1] in word_set:
print(s[0:i+1])
words_sentence.append(s[0:i+1])
print(words_sentence)
word_set.remove(s[0:i+1])
words_sentence += get_sentence_split(s[i+1:], word_set)
print ("i: "+str(i))
return words_sentence
print(get_sentence_split("thequickbrownfox", ['quick', 'brown', 'the', 'fox']))
|
ca2e9d36b09cf0831e8756094c70b76ab1d77e3b | OmishaPatel/Python | /daily-coding-problem/max_of_subarray_k_size.py | 227 | 3.671875 | 4 | def max_of_subarray_k_size(arr, n, k):
max= 0
for i in range(n-k +1):
max = arr[i]
for j in range(1, k):
if arr[i+j] > max:
max = arr[i+j]
print(str(max))
max_of_subarray_k_size([1,2,3,4,5], 5, 3) |
df4858753ba98281c0dcef4e1cfc795d3e153ae3 | OmishaPatel/Python | /miscalgos/reverse_integer.py | 391 | 4.125 | 4 | import math
def reverse_integer(x):
if x > 0:
x= str(x)
x = x[::-1]
x = int(x)
else:
x = str(-x)
x = x[::-1]
x = -1 * int(x)
if x <= math.pow(2, 31) -1 and x >= math.pow(-2,31):
return x
return 0
x = 123
x1 = -123
print(reverse_integer(x))
print(reverse_integer(x1)) |
65ad7a18009d3595863f35760e7cc8f0ae78657d | OmishaPatel/Python | /datastructure/linked_list_insertion.py | 1,290 | 4.3125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self,data):
new_node = Node(data)
#if it is beginning of list then insert new node
if self.head is None:
self.head = new_node
return
#traverse the list if head present to find the last node
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node not in the list")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
linked_list = LinkedList()
linked_list.append("A")
linked_list.append("B")
linked_list.append("C")
linked_list.append("D")
linked_list.insert_after_node(linked_list.head.next, "E")
linked_list.print_list() |
84f3596a8c085f14c6681ac10b22727614c607cc | OmishaPatel/Python | /wordcountbydict.py | 270 | 3.796875 | 4 | text = input("enter a file name: ").split()
d = dict()
for word in text:
print(word)
d[word] = d.get(word,0) +1
print(d)
count = -1
word = None
for k,v in d.items():
if v > count:
count = v
word = k
print("Word", word, "Repeats", count)
|
3adc47fc550a80670a73b703dd1863ef94d02cc0 | OmishaPatel/Python | /datastructure/binary_tree_insertion_deletion.py | 3,511 | 4.0625 | 4 | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert(value, self.root)
def _insert(self, value, cur_node):
if value < cur_node.value:
if cur_node.left is None:
cur_node.left = Node(value)
else:
self._insert(value, cur_node.left)
elif value > cur_node.value:
if cur_node.right is None:
cur_node.right = Node(value)
else:
self._insert(value, cur_node.right)
else:
print("Value is already present in tree.")
def inorder_traversal(self,start, traversal):
if start:
traversal = self.inorder_traversal(start.left, traversal)
traversal += (str(start.value) + "-")
traversal = self.inorder_traversal(start.right, traversal)
return traversal
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_traversal(tree.root, "")
elif traversal_type == "inorder":
return self.inorder_traversal(tree.root, "")
elif traversal_type == "postorder":
return self.postorder_traversal(tree.root, "")
elif traversal_type == "levelorder":
return self.level_order_traversal(tree.root)
else:
print("Traversal tye" +str(traversal_type) + " is not suppoorted")
return False
def find(self, value):
if self.root:
is_found = self._find(value, self.root)
if is_found:
return True
return False
else:
return None
def _find(self,value, cur_node):
if value < cur_node.value and cur_node.left:
return self._find(value, cur_node.left)
elif value > cur_node.value and cur_node.right:
return self._find(value, cur_node.right)
if cur_node.value == value:
return True
def min_node(self, cur_node):
current = cur_node
while cur_node.left:
current = cur_node.left
return current
def delete_node(self, value, cur_node):
if cur_node is None:
return None
# eliminate half of possibilities
if value < cur_node.value:
cur_node.left = self.delete_node(value, cur_node.left)
elif value > cur_node.value:
cur_node.right = self.delete_node(value, cur_node.right)
else:
#no child
if (not cur_node.left) and (not cur_node.right):
return None
# One chile
elif (cur_node.left) and (not cur_node.right):
cur_node = cur_node.left
elif (cur_node.right) and (not cur_node.left):
cur_node = cur_node.right
#two children
else:
min_value = self.min_node(cur_node.right)
cur_node.value = min_value
cur_node.right = self.delete_node(min_value, cur_node.right)
return cur_node
tree = BinaryTree()
tree.insert(2)
tree.insert(4)
tree.insert(8)
tree.insert(10)
tree.insert(12)
print(tree.find(8))
tree.delete_node(8, tree.root)
print(tree.print_tree("inorder"))
|
9fec21ec50d899a2cd0b87da56cacf31cf4dbc9b | OmishaPatel/Python | /datastructure/array_advance.py | 376 | 3.734375 | 4 | def array_advance(nums):
furthest_index = 0
i = 0
last_index = len(nums) -1
while i <= furthest_index and furthest_index < last_index:
furthest_index = max(furthest_index, nums[i] + i)
i+= 1
return furthest_index >= last_index
nums= [3, 3, 1, 0, 2, 0, 1]
print(array_advance(nums))
nums = [3, 2, 0, 0, 2, 0, 1]
print(array_advance(nums))
|
9c1ac8fffa66557b1de79985e16f8fec6e9f48f0 | OmishaPatel/Python | /daily-coding-problem/longest_substring_with_k_distinct_characters.py | 496 | 3.671875 | 4 | def longest_substring_with_k_distinct_characters(s, k):
current_longest_substring = ''
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
substring = s[i:j]
if len(set(substring)) > k:
break
if len(substring) > len(current_longest_substring):
current_longest_substring = substring
return len(current_longest_substring)
s = "aabbccdef"
k = 2
print(longest_substring_with_k_distinct_characters(s, k)) |
e148b845fbc45964a0d3de23b60f704e60386933 | T-o-s-s-h-y/Learning | /Python/progate/python_study_2/page2/script.py | 360 | 3.640625 | 4 | # 変数fruitsに、複数の文字列を要素に持つリストを代入してください
fruits = ['apple', 'banana', 'orange']
# インデックス番号が0の要素を出力してください
print(fruits[0])
# インデックス番号が2の要素を文字列と連結して出力してください
print("好きな果物は" + fruits[2] + "です")
|
12ee1624fd1b94456493fbd49286189bca7662b9 | T-o-s-s-h-y/Learning | /Python/progate/python_study_3/page6/script.py | 477 | 3.640625 | 4 | def print_hand(hand, name='ゲスト'):
print(name + 'は' + hand + 'を出しました')
print('じゃんけんをはじめます')
# inputを用いて入力を受け取り、変数player_nameに代入してください
player_name = input('名前を入力してください:')
# 変数player_nameの値によって関数print_handの呼び出し方を変更してください
if player_name == '':
print_hand('グー')
else:
print_hand('グー', player_name) |
8a9eda00c5aa69ef1946d5a2ceec8047712d099b | Famebringer/scripts | /les6/pe6.1.py | 354 | 3.65625 | 4 | # voor de printing manier
def f(x):
res = x * 2 + 10
print (res)
f(2)
# voor de return manier
def f(x):
res = x * 2 + 10
return res
def som(getal1, getal2, getal3):
antwoordt = getal1 + getal2 + getal3
print('getal1 is', getal1)
print('getal2 is', getal2)
print('getal3 is', getal3)
print(antwoordt)
som(7,5,4) |
931e05be3f97d32284542b3e9ef7ebada23a1c9f | Famebringer/scripts | /les5/pe5.6.py | 330 | 3.6875 | 4 | # Schrijf een for-loop die langs alle letters van een string loopt en de letter uitprint,
# maar alleen als het een klinker is ('aeiou').
# Gebruik de volgende string:
s = "Guido van Rossum heeft programmeertaal Python bedacht."
klinkers = ''
for letters in s:
if letters in 'aeoui':
klinkers += letters
print(klinkers)
|
4745349bd4e7830533f76c21c5f751d7940cc161 | nyalldawson/dwarf_mine | /traits.py | 1,397 | 3.890625 | 4 | import random
class Trait:
"""
A creature character trait
"""
def __init__(self):
self.type = ''
def affect_visibility(self, visible):
return visible
def affect_move_to(self, x, y):
# return None to block movement
return (x,y)
class Determined(Trait):
"""
Creature is determined, and more likely to succeed or die trying
"""
def __init__(self, level = 2):
Trait.__init__(self)
self.type = 'determined'
self.level = level
class Lazy(Trait):
"""
Creature is lazy, less likely to push themselves and more sleepy
"""
def __init__(self):
Trait.__init__(self)
self.type = 'lazy'
class Sneaky(Trait):
"""
Creature is sneaky, less likely to be seen
"""
def __init__(self):
Trait.__init__(self)
self.type = 'lazy'
def affect_visibility(self, visible):
if random.randint(1,10) < 9:
return False
return visible
class Contagious(Trait):
"""
Creature is contagious - the exact meaning of this depends on the
creature
"""
def __init__(self):
super().__init__()
self.type = 'contagious'
class Leader(Trait):
"""
Creature is a leader - other creatures like to follow them!
"""
def __init__(self):
super().__init__()
self.type = 'leader'
|
b692f6009d0177c0057d68c593b551dfb64e74e9 | kathrinv/advent-of-code-2019 | /day8.py | 3,927 | 3.78125 | 4 | import pprint as pp
from typing import List
def load_day8_input(filename: str) -> str:
"""
Loads the input representing the
image transmitted
Args:
filename: The name of the file with
the inputs for Day 8. It
should be saved down to the
same directory.
Returns:
A string of digits representing layers
in a 25 x 6 pixel image
"""
image = ""
with open(filename) as f:
for line in f:
image += line.replace('\n', '')
return image
def split_into_layers(image: str) -> List[int]:
"""
Takes the initial transmission
and splits the string into
image layers.
Args:
image: A string of digits representing
layers in a 25 x 6 pixel image
Returns:
A list of layers, with each layer
a list of int
"""
layers = []
for i in range(0, len(image), 25*6):
start = i
end = i + 25*6
layers.append([int(char) for char in image[start:end]])
return layers
def find_layer_with_least_zeros(layers: List[int]) -> List[int]:
"""
Finds the layer with the least
amount of zeros.
Args:
layers: A list of layers, with each layer
a list of int representing the color
of each pixel
Returns:
The pixel values of the layer with least zeros
"""
least_zeros = None
layer_index = None
for idx, layer in enumerate(layers):
num_zeros = sum([1 for num in layer if num == 0])
if not least_zeros or num_zeros < least_zeros:
least_zeros = num_zeros
layer_index = idx
return layers[layer_index]
def num_ones_times_num_twos(layer: List[int]) -> int:
"""
Returns the number of ones
times the numbers of twos
in a layer.
Args:
layer: Pixel values of an image layer
Returns:
The number of 1 digits multiplied
by the number of 2 digits in an
image layer
"""
num_ones = sum([1 for num in layer if num == 1])
num_twos = sum([1 for num in layer if num == 2])
return num_ones * num_twos
def decode_image(layers: List[int]) -> List[int]:
"""
Prints out decoded image
based on topmost visible pixel
value.
Args:
layers: A list of layers, with each layer
a list of int representing the
color of each pixel
Returns:
A formatted image showing a
message
"""
image = []
for i in range(len(layers[0])):
for j in range(len(layers)):
if layers[j][i] == 0:
image.append(' ')
break
elif layers[j][i] == 1:
image.append('X')
break
else:
continue # pixel is transparent
formatted_image = []
for k in range(0, 150, 25):
formatted_image.append(''.join(image[k:k+25]))
return formatted_image
def day8(filename: str = 'input8.txt', part2: bool = False):
"""
Confirms correct image transmission
by returning the number of 1 digits
multiplied by the number of 2 digits
in the image layer with the least
amount of zeros.
Change arguement 'part2' to True
if image transmission was correct
to decode the image.
"""
image = load_day8_input(filename)
layers = split_into_layers(image)
if not part2:
layer_with_least_zeros = find_layer_with_least_zeros(layers)
result = num_ones_times_num_twos(layer_with_least_zeros)
return result
else:
return decode_image(layers)
answer_part1 = day8()
answer_part2 = day8(part2=True)
print(f'The result to part 1 is: {answer_part1}')
print(f'The result to part 2 is:')
pp.pprint(answer_part2)
|
5878f392397d6bf2bed199f0dd9b514e1214aa37 | dkarthicks27/COVID-19-Project | /covid_test.py | 2,333 | 3.84375 | 4 | # this is just a test case of covid-19
# let us first define the problem statement
# build an app that let's us visualise the corona effect
# that is whether the curve is increasing on flattening
# depending on the city
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
url = "https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv"
# file = pd.read_csv('/Users/karthickdurai/Downloads/novel-corona-virus-2019-dataset/covid_19_data.csv')
file = pd.read_csv(url)
def printing_tail_head():
print(file.head())
print(file.tail())
def get_summary():
print(file.dtypes)
print(file.index)
print(file.columns)
print(file.values)
def get_statistics():
print(file.describe())
def sort_by_columns():
print(file.sort_values('Recovered', ascending=False))
def slicing_rows_columns():
print(file['Country/Region'])
print(file['Deaths'])
print()
print(file.Recovered)
print(file[2:20])
print(file.loc[20000:21000, ['Country/Region', 'Province/State', 'Deaths', 'Recovered']])
print(file.iloc[19000:19003, 1:5])
def filter_data(country):
# this method of filtering is for filtering according to column
# print(file[file.ObservationDate == '05/03/2020'])
# we have one more way to filter
df = (file[file['Country'].isin([country])])
# .loc[:, ['SNo', 'ObservationDate', 'Province/State', 'Country/Region', 'Deaths', 'Confirmed']])
return df
def assignment():
file.loc[9, ['Country/Region']] = 'Mainland China'
print(file.loc[9:11, ['Country/Region']])
# print(np.array([5] * len(file)))
def rename_columns():
file.rename(columns={'Country/Region': 'Country'}, inplace=True)
# so yes name changed, this is for changing a particular column
print(file.iloc[:, 2:5])
# to change multiple columns at once, send it
# file.columns = ['val1', 'val2', 'val3', ....]
# printing_tail_head()
# get_summary()
table = filter_data('India')
ax = plt.gca()
table.plot(kind='line', x='Date', y='Confirmed', color='red', ax=ax)
table.plot(kind='line', x='Date', y='Deaths', color='blue', ax=ax)
# table.plot(kind='line', x='ObservationDate', y='Confirmed', color='red', ax=ax)
# table.plot(kind='line', x='ObservationDate', y='Deaths', color='blue', ax=ax)
plt.show()
|
404687852854ae63c74baa2196c12677bf50343e | ashwinidotx/100daysofcode | /Files/Day 16/TextEditor.py | 1,324 | 3.6875 | 4 | from Tkinter import *
from tkFileDialog import *
import tkMessageBox
filename= "untitled"
def newFile():
global filename
filename="Untitled File"
text.delete(0.0,END)
def saveFile():
global filename
t = text.get(0.0,END)
f = open(filename+'.txt','w')
f.write(t)
f.close()
def saveAs():
f = asksaveasfile(mode='w', defaultextension='.txt')
t = text.get(0.0, END)
try:
f.write(t.rstrip())
except:
tkMessageBox.showerror(title="Oops.!", message="File Not Saved. Please Try again...")
def openFile():
global filename
f = askopenfile(mode='r')
filename = f.name
t = f.read()
text.delete(0.0, END)
text.insert(0.0, t)
root=Tk()
root.title("OS(ama) Text Editor")
root.minsize(width=300,height=150)
root.maxsize(width=700,height=350)
text=Text(root, width=700,height=350)
text.pack()
menubar = Menu(root)
filemenu = Menu(menubar)
filemenu.add_command(label="New", command=newFile)
filemenu.add_command(label="Open",command=openFile)
filemenu.add_separator()
filemenu.add_command(label="Save",command=saveFile)
filemenu.add_command(label="Save As...",command=saveAs)
filemenu.add_separator()
filemenu.add_command(label="Quit",command=root.quit)
menubar.add_cascade(label="File",menu=filemenu)
root.config(menu=menubar)
root.mainloop()
|
6ea47a5727c4822af6adaf2bfa02a0c8c46e54eb | cselman99/Binary-ST | /binary_search_tree.py | 5,128 | 3.96875 | 4 | from queue_array import Queue
class TreeNode:
def __init__(self, key, data, left=None, right=None):
self.key = key
self.data = data
self.left = left
self.right = right
def __eq__(self, other):
return ((type(other) == TreeNode)
and self.key == other.key
and self.data == other.data
and self.left == other.left
and self.right == other.right
)
def __repr__(self):
return ("TreeNode({!r}, {!r}, {!r}, {!r})".format(self.key, self.data, self.left, self.right))
class BinarySearchTree:
def __init__(self): # Returns empty BST
self.root = None
def is_empty(self): # returns True if tree is empty, else False
return self.root == None
def search(self, key): # returns True if key is in a node of the tree, else False
return self._search(key, self.root)
def _search(self, key, node):
if self.is_empty():
return False
if key == node.key:
return True
if node.right != None and key > node.key:
node = node.right
return self._search(key, node)
elif node.left != None and key < node.key:
node = node.left
return self._search(key, node)
else:
return False
def insert(self, key, data=None): # inserts new node w/ key and data
self._insert(key, self.root, data)
def _insert(self, key, cur_node, data=None):
if cur_node == None:
self.root = TreeNode(key, data)
elif cur_node.key > key:
if cur_node.left == None:
cur_node.left = TreeNode(key, data)
else:
cur_node = cur_node.left
self._insert(key, cur_node, data)
elif cur_node.key < key:
if cur_node.right == None:
cur_node.right = TreeNode(key, data)
else:
cur_node = cur_node.right
self._insert(key, cur_node, data)
else:
cur_node.data = data
def find_min(self): # returns a tuple with min key and data in the BST
# returns None if the tree is empty
if self.is_empty():
return None
tree_loc = self.root
minimum = tree_loc.data
while tree_loc.left != None:
tree_loc = tree_loc.left
minimum = tree_loc.data
return (tree_loc.key, minimum)
def find_max(self): # returns a tuple with max key and data in the BST
# returns None if the tree is empty
if self.is_empty():
return None
tree_loc = self.root
maximum = tree_loc.data
while tree_loc.right != None:
tree_loc = tree_loc.right
maximum = tree_loc.data
return (tree_loc.key, maximum)
def tree_height(self):
if self.is_empty():
return None
return self.th_helper(self.root)
def th_helper(self, node):
if node is None:
return -1
else :
l = self.th_helper(node.left)
r = self.th_helper(node.right)
return max(l, r) + 1
def inorder_list(self):
py_list = []
node = self.root
self._inorder_list(node, py_list)
return py_list
def _inorder_list(self, node, py_list):
if node is not None:
self._inorder_list(node.left, py_list)
py_list.append(node.key)
self._inorder_list(node.right, py_list)
def _preorder_list(self, node, py_list):
if node is not None:
py_list.append(node.key)
self._inorder_list(node.left, py_list)
self._inorder_list(node.right, py_list)
def preorder_list(self):
py_list = []
node = self.root
self._preorder_list(node, py_list)
return py_list
def level_order_list(self):
q = Queue(25000) # Don't change this!
py_list = []
q.enqueue(self.root)
return self._lvl_order(q, self.root, py_list)
def _lvl_order(self, q, node, py_list):
cur_node = node
if self.is_empty():
return py_list
if q.size() != 0:
cur_node = q.dequeue()
py_list.append(cur_node.key)
if node.left != None and node.right != None:
q.enqueue(node.left)
q.enqueue(node.right)
self._lvl_order(q, node.left, py_list)
self._lvl_order(q, node.right, py_list)
elif node.left != None and node.right == None:
q.enqueue(node.left)
self._lvl_order(q, node.left, py_list)
elif node.left == None and node.right != None:
q.enqueue(node.right)
self._lvl_order(q, node.right, py_list)
while not q.is_empty():
cur_node = q.dequeue()
py_list.append(cur_node.key)
return py_list |
33dd09b968beccd122c1bd95593fccb78a37e476 | silviosnjr/python-parte1 | /exemplo_sintaxe/3_condicional_simples.py | 164 | 3.84375 | 4 | #exemplo de condicional if(se) com um else(se não)
idade = 16
if(idade < 18) :
print("é MENOR de idade")
else:
print("é MAIOR de idade")
|
f020b02798e40d543553038c999259144036210d | silviosnjr/python-parte1 | /exemplo_sintaxe/8_funcao.py | 352 | 3.546875 | 4 | #variáveis estáticas
nome = "Fulano"
nascimento = 1987
#Declaração da função escreve_idade
def escreve_idade(nome, ano, nascimento):
print (nome, "tem", (ano - nascimento), "anos")
print ("Função Encerrada")
#Chamando a função escreve_idade
#e passando as variáveis como parametros
escreve_idade (nome, 2021, nascimento) |
cdad839660771f79fea5df8092163ed8ce18dde3 | ingoglia/python_work | /Python_Book/part2_data/die_visual.py | 700 | 3.921875 | 4 | import matplotlib.pyplot as plt
from die import Die
# Create a D6.
die = Die()
# Make some rolls, and store results in a list.
results = []
for roll_num in range(1000):
result = die.roll()
results.append(result)
# Analyze the results.
frequencies = []
for value in range(1, die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
# Visualize the results.
die_values = [1, 2, 3, 4, 5, 6,]
frequency_result = list(range(1, 1000))
plt.plot(die_values, frequency_result, linewidth=5)
plt.title("Results of rolling one D6 1000 times.")
plt.xlabel("Side of Die")
plt.ylabel("Frequency")
plt.title = "Result"
hist.y_title = "Frequency of Result"
plt.show()
|
55dd00d10cb8a4b65d7641b419fd2a48670fd20c | ingoglia/python_work | /part1/4.13.py | 221 | 3.515625 | 4 | buffet = ('chicken', 'cat', 'monkey', 'dog', 'rice')
for snacks in buffet:
print(snacks)
#buffet[1] = 'cow'
new_buffet = ('chicken', 'cow', 'monkey', 'dog', 'noodles')
for snackles in new_buffet:
print(snackles)
|
3ba562ff4adaad94267aa9c62fdc1134d40b1910 | ingoglia/python_work | /part1/4.11.py | 326 | 4.1875 | 4 | pizzas = ['anchovy', 'cheese', 'olive']
friend_pizzas = ['anchovy', 'cheese', 'olive']
pizzas.append('mushroom')
friend_pizzas.append('pineapple')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("\nMy friends favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza)
|
da6bdd917f756b49892a78088f3b996edaed7fbe | ingoglia/python_work | /Python_Book/part1/3.6.py | 740 | 4.03125 | 4 | invite = ['Mike', 'Joe', 'Josh', 'Harold', 'Cardin']
print('Hey '+ invite[0] + "! Would you like to come to dinner?")
print('Hey '+ invite[4] + "! Would you like to come to dinner?")
print('Hey '+ invite[3] + "! Would you like to come to dinner?")
print(invite[1] + " and " + invite[2] + "! Come over for dinner!")
print('Hey ' + invite[0] +', '+ invite[1] +', '+ invite[2] + ', '+invite[3] +', '+ invite[4] +". I found a bigger table in the basement!")
invite.insert(0,'Dean')
invite.insert(3,'Jake')
invite.append('Lionel')
print('Hey ' + invite[0] +', '+ invite[1] +', '+ invite[2] + ', '+invite[3] +', '+ invite[4] +", "+ invite[5] +", " + invite[6] + ", " + invite[7] +". Would all of you like to come to my place for some tacos?")
|
4673810d70d74308f79683b34151f62e5f70c133 | ingoglia/python_work | /part1/9.1.py | 699 | 4.09375 | 4 | class Restaurant():
"""A Restaurant class"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize attributes to describe a restaurant"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
""" Talks about the restaurant """
print("The restaurant name: " + self.restaurant_name +
"\nThe cuisine type: " + self.cuisine_type)
def open_restaurant(self):
"""Tells that restaurant is open"""
print( self.restaurant_name + " is open.")
restaurant1 = Restaurant('Chez Thui', 'Vietnamese')
restaurant1.describe_restaurant()
restaurant1.open_restaurant()
|
3683f4b62501faa80cb0a67e3979cabe0fdc7e54 | ingoglia/python_work | /part1/5.2.py | 1,063 | 4.15625 | 4 | string1 = 'ferret'
string2 = 'mouse'
print('does ferret = mouse?')
print(string1 == string2)
string3 = 'Mouse'
print('is a Mouse a mouse?')
print(string2 == string3)
print('are you sure? Try again')
print(string2 == string3.lower())
print('does 3 = 2?')
print(3 == 2)
print('is 3 > 2?')
print(3 > 2)
print('is 3 >= 2?')
print(3 >= 2)
print("I don't think that 8 = 4")
print(8 != 4)
print('is 6 <= 8?')
print(6 <= 8)
print('is 5 < 3?')
print(5 < 3)
religion1 = 'christian'
belief1 = 'god'
religion = 'religion'
belief = 'belief'
print( 'is it the case that a christian is both a deity and a believer?')
print( 'christian' == 'christian' and 'christian' == 'god' )
print( 'is it the case that a christian is either a deity or a believer?')
print( 'christian' == 'christian' or 'christian' == 'god' )
fruits = ['banana', 'blueberry', 'raspberry', 'melon']
print('is there a banana?')
print('banana' in fruits)
print('is there a raspberry?')
print('raspberry' in fruits)
print('there are no strawberries are there.')
print('strawberries' not in fruits)
|
ebf65f149efb4a2adc6ff84d1dce2d2f61004ce4 | ingoglia/python_work | /part1/8.8.py | 633 | 4.375 | 4 | def make_album(artist, album, tracks=''):
"""builds a dictionary describing a music album"""
if tracks:
music = {'artist': artist, 'album':album, 'number of tracks':tracks}
else:
music = {'artist': artist, 'album':album}
return music
while True:
print("\nPlease tell me an artist and an album by them:")
print("(enter 'q' at any time to quit)")
user_artist = input("Name of artist: ")
if user_artist == 'q':
break
user_album = input("Name of album: ")
if user_album == 'q':
break
user_choice = make_album(user_artist,user_album)
print(user_choice)
|
dfe8231c9d50b6066064aaf25806de54fe1eeb52 | ingoglia/python_work | /part1/7.9.py | 545 | 3.8125 | 4 | sandwich_orders = ['pastrami','ruben','roast beef','pastrami','pastrami', 'tuna', 'blt']
finished_sandwiches = []
print("We are... out of pastrami!!!! ahhhhhhhhhhhhhh")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
while sandwich_orders:
current_order = sandwich_orders.pop()
print("Ok, making the " + current_order + " now.")
finished_sandwiches.append(current_order)
print("\nThese sandwiches are ready to go: ")
for finished_sandwich in finished_sandwiches:
print(finished_sandwich)
|
4241434076bfdfa2464a421cd59a1a6ac592e07d | TongZZZ/coursera | /python/pong.py | 4,572 | 3.84375 | 4 | #http://www.codeskulptor.org/#user23_V0QqB4nk27_163.py
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
RIGHT = True
ball_pos = [WIDTH / 2, HEIGHT / 2]
ball_vel = [-random.randrange(120, 240)/60, random.randrange(60, 180) / 60.0]
paddle1_pos = 0
paddle2_pos = 0
score1 = 0
score2 = 0
paddle1_vel = 0
paddle2_vel = 0
# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(direction):
global ball_pos, ball_vel # these are vectors stored as lists
global paddle1_pos, paddle2_pos
ball_pos = [WIDTH / 2, HEIGHT / 2]
if direction =='right':
ball_vel = [random.randrange(120, 240)/60, random.randrange(60, 180)/60.0]
if direction == 'left':
ball_vel = [-random.randrange(120, 240)/60, random.randrange(60, 180)/60.0]
paddle1_pos = HEIGHT/2 - HALF_PAD_HEIGHT -1
paddle2_pos = HEIGHT/2 - HALF_PAD_HEIGHT -1
# define event handlers
def new_game():
global ball_pos, ball_vel
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2 # these are ints
score1 = 0
score2 = 0
foo = ['left', 'right']
random_index = random.randrange(0,len(foo))
spawn_ball(foo[random_index])
def draw(c):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel,paddle1_vel,paddle2_vel
# draw mid line and gutters
c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
if (ball_pos[0] <= BALL_RADIUS + PAD_WIDTH):
if abs(ball_pos[1] - (paddle1_pos+HALF_PAD_HEIGHT))<=HALF_PAD_HEIGHT:
ball_vel[0] = - ball_vel[0]*1.1
ball_vel[1] = ball_vel[1]*1.1
else:
spawn_ball('right')
score2 = score2 + 1
if (ball_pos[0]>= WIDTH - PAD_WIDTH - BALL_RADIUS-1):
if abs(ball_pos[1] - (paddle2_pos+HALF_PAD_HEIGHT))<=HALF_PAD_HEIGHT:
ball_vel[0] = - ball_vel[0]*1.1
ball_vel[1] = ball_vel[1]*1.1
else:
spawn_ball('left')
score1 = score1 + 1
if (ball_pos[1] <= BALL_RADIUS or ball_pos[1]>= HEIGHT - BALL_RADIUS-1):
ball_vel[1] = - ball_vel[1]
# draw ball
c.draw_circle(ball_pos, BALL_RADIUS, 2, "White", "White")
# update paddle's vertical position, keep paddle on the screen
paddle1_pos += paddle1_vel
paddle2_pos += paddle2_vel
if paddle1_pos <= 0:
paddle1_pos = 0
elif paddle1_pos >= HEIGHT - PAD_HEIGHT:
paddle1_pos = HEIGHT - PAD_HEIGHT
else: pass
if paddle2_pos <= 0:
paddle2_pos = 0
elif paddle2_pos >= HEIGHT - PAD_HEIGHT:
paddle2_pos = HEIGHT - PAD_HEIGHT
else: pass
# draw paddles
c.draw_polygon([(0, paddle1_pos), (0, PAD_HEIGHT+paddle1_pos),(PAD_WIDTH,PAD_HEIGHT+paddle1_pos), (PAD_WIDTH, paddle1_pos)], 1, 'Blue','Blue')
c.draw_polygon([(WIDTH, paddle2_pos), (WIDTH, PAD_HEIGHT+paddle2_pos),(WIDTH-PAD_WIDTH,PAD_HEIGHT+paddle2_pos), (WIDTH-PAD_WIDTH, paddle2_pos)], 1, 'Blue','Blue')
# draw scores
c.draw_text(str(score1) + " | " + str(score2), (420, 50), 36, 'Blue')
def keydown(key):
global paddle1_vel, paddle2_vel
acc = 5
if key == simplegui.KEY_MAP["s"]:
paddle1_vel += acc
elif key == simplegui.KEY_MAP["w"]:
paddle1_vel -= acc
elif key == simplegui.KEY_MAP["down"]:
paddle2_vel += acc
elif key == simplegui.KEY_MAP["up"]:
paddle2_vel -= acc
def keyup(key):
global paddle1_vel, paddle2_vel
if key == simplegui.KEY_MAP["s"]:
paddle1_vel = 0
elif key == simplegui.KEY_MAP["w"]:
paddle1_vel = 0
elif key == simplegui.KEY_MAP["down"]:
paddle2_vel = 0
elif key == simplegui.KEY_MAP["up"]:
paddle2_vel = 0
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("New Game", new_game,100)
# start frame
new_game()
frame.start()
|
0b962dfa9549648cfdb1585149964fb1e568ed01 | dewi-maya/Programming-DSAI | /Python Codes/string_arg.py | 251 | 4.0625 | 4 | """
Filename: string_arg.py
Call a function with string argument
"""
def my_function(str):
str += "..."
print(str)
def main():
str = "Hello, world"
my_function(str)
print(str)
if __name__ == '__main__':
main() |
b4a24b3ca29f09229589a58abfa8f0c9c4f3a094 | marcellenoukimi/CS-4308-CPL-Assignment-3 | /Student.py | 2,681 | 4.34375 | 4 | """
Student Name: Marcelle Noukimi
Institution: Kennesaw State University
College: College of Computing and Software Engineering
Department: Department of Computer Science
Professor: Dr. Sarah North
Course Code & Title: CS 4308 Concepts of Programming Languages
Section 01 Fall 2021
Date: October 13, 2021
Assignment 3: Develop a Python program. Define a class in Python and use it to create an object
and display its components. Define a Student class with the following components (attributes):
Name
Student number
Number of courses current semester
This class includes several methods: to change the values of these attributes, and to display
their values. Separately, the “main program” must:
• request the corresponding data from input and create a Student object.
• invoke a method to change the value of one of its attributes of the object
• invoke a method to that displays the value of each attribute.
"""
"""
This is the Student class with its components (attributes):
Name
Student number
Number of courses current semester
and the several methods to change the values of these attributes,
and to display their values.
"""
class Student:
"""
Implementation of student class
"""
def __init__(self, name, studentNumber, numberOfCourses):
"""
Constructor. Each student holds a Name, a Student number,
and a number of courses that he/she is taken during
this semester
"""
# Name of the student
self.StudentName = name
# Student number
self.StudentNumber = studentNumber
# Number of courses current semester
self.NumberOfCourses = numberOfCourses
"""
Various setter methods
"""
# Method to change the value of a student name
def setStudentName(self, name):
self.StudentName = name
# Method to change the value of a student number
def setStudentNumber(self, number):
self.StudentNumber = number
# Method to change the value of a student number of courses
# for the current semester
def setStudentNumberOfCourses(self, courses):
self.NumberOfCourses = courses
"""
Method to display the value of each attribute of a student
"""
def display(self):
# Print student details information
return "Student Name: " + self.StudentName + "\n Student Number: " \
+ self.StudentNumber + "\n Number Of Courses taken the current semester: " + self.NumberOfCourses
|
07fe8bf2b40cc5a560cc08c044ca284bbdfa6133 | VGAD/tactics | /unit/anti_armour.py | 2,646 | 3.5625 | 4 | from unit.ground_unit import GroundUnit
import unit, helper, effects
from tiles import Tile
import pygame
class AntiArmour(GroundUnit):
"""
An infantry unit armed with an anti-armour missile launcher. Very
effective against tanks and battleships, but otherwise not especially
powerful.
Armour: None
Speed: Low
Range: Medium
Damage: Medium (High against armoured vehicles)
Other notes:
- Slightly slowed by forests and sand.
- Slowed somewhat more by mountains.
- Can move through any land terrain.
- Can't hit air units.
"""
sprite = pygame.image.load("assets/anti_armour.png")
def __init__(self, **keywords):
#load the image for the base class.
self._base_image = AntiArmour.sprite
#load the base class
super().__init__(**keywords)
#sounds
self.move_sound = "FeetMove"
self.hit_sound = "RocketLaunch"
#set unit specific things.
self.type = "Anti-Armour"
self.speed = 4
self.max_atk_range = 3
self.damage = 4
self.bonus_damage = 4
self.defense = 0
self.hit_effect = effects.Explosion
self._move_costs = {'mountain': 2,
'forest': 1.5,
'sand': 1.5}
def can_hit(self, target_unit):
"""
Determines whether a unit can hit another unit.
Overrides because anti-armour can't hit planes.
"""
# If it's an air unit return false
if isinstance(target_unit, unit.air_unit.AirUnit):
return False
# Not an air unit, return true
return True
def get_damage(self, target, target_tile):
"""
Returns the potential attack damage against a given enemy.
This overrides the super class function for special damage
and because anti-armour can't hit air units.
"""
# Do bonus damage to armored vehicles
if target.type == "Tank" or target.type == "Battleship":
# Calculate the total damage
damage = self.damage + self.bonus_damage
# Calculate the unit's defense
defense = target.get_defense(tile = target_tile)
# Don't do negative damage
if (damage - defense < 0):
return 0
return damage - defense
else:
return super().get_damage(target, target_tile)
unit.unit_types["Anti-Armour"] = AntiArmour
|
924a648dfe8c3716121962a4f71479e512960c75 | EricSchles/uav | /hacker_rank/ave_score/ave_score.py | 256 | 3.71875 | 4 | n = int(raw_input())
scores = {}
def avg(scores):
return sum(scores)/float(len(scores))
for i in range(n):
line = raw_input().split(" ")
scores[line[0]] = avg([int(elem) for elem in line[1:]])
print "{0:.2f}".format(scores[str(raw_input())])
|
32891093de24ca2a5936e9fb9d75332c6d6e009e | Raidn1771/PyOpenGL-for-Windows | /Sample_Questions/test_dda.py | 1,641 | 3.609375 | 4 | #Program to plot a point
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math
import time
# from line_algorithm import line_algorithm
global P_in, P_f
P_in, P_f = [0, 0], [100, 100]
def init():
glClearColor(0.0, 0.0, 0.0, 0.0)
gluOrtho2D(-250.0, 250.0, -250.0, 250.0)
def dda_plot(P_init, P_final):
x_init, y_init = P_init
x_final, y_final = P_final
dx = x_final - x_init
dy = y_final - y_init
# depending upon the absolute values of dx and dy
# choose the number of steps to put pixel as
steps = int(abs(dx) if abs(dx) > abs(dy) else abs(dy))
# calculate increment in x and y for each steps
x_inc = dx / float(steps)
y_inc = dy / float(steps)
x, y = x_init, y_init
# add pixel for each step
for i in range(steps + 1):
glVertex2f(x, y)
x += x_inc
y += y_inc
def take_in():
x0 = int(input())
y0 = int(input())
x1 = int(input())
y1 = int(input())
global P_in, P_f
P_in, P_f = [x0, y0], [x1, y1]
def plot_points():
global P_in, P_f
glClear(GL_COLOR_BUFFER_BIT)
glColor3f(1.0, 0.0, 0.0)
glBegin(GL_POINTS)
P_init, P_final = P_in, P_f
dda_plot(P_init, P_final)
glEnd()
glFlush()
def main():
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB)
glutInitWindowSize(500, 500)
glutInitWindowPosition(50, 50)
glutCreateWindow(b'plot_all_points')
glutDisplayFunc(plot_points)
take_in()
init()
glutMainLoop()
main()
|
15f79a8f57b3c6bcb918171d40f56995924c71e3 | badziej112/Projekt | /City.py | 1,163 | 4.03125 | 4 | from AbstractBuilding import AbstractBuilding
class City(AbstractBuilding):
def __init__(self, x, y, population):
super().__init__(x, y, "C")
self.population = population
def build(self, fraction):
"""Buduje miasto i odejmuje jego koszt od zasobów frakcji oraz dodaje punkty rozwoju."""
if (fraction.material > 1000):
fraction.material = fraction.material - 1000
fraction.points += 100
def build_job(self, fraction):
"""Konsumpcja jedzenia frakcji przez miasto. Przyrost/redukcja populacji w zależności od
ilości posiadanego jedzenia."""
if (fraction.food > (self.population * 2)):
fraction.food = fraction.food - (self.population * 1.5)
self.population = self.population * 1.5
elif (fraction.food >= (self.population)):
fraction.food = fraction.food - self.population
self.population = self.population * 1.2
return False
elif (fraction.food < self.population): #głód
self.population = self.population * 0.7
return True
|
f2ce32c475e83713c0ddc74e589278712c77c28b | BenitoMarculanoRibeiro/LigaMagic-Python-TCC | /concertar.py | 6,318 | 3.640625 | 4 | # coding: utf-8
from random import randrange, uniform
# Algoritmo usado para concertar os arquivos conrrompidos
# Problema:
# Os aquivos tem posições vazias o que seria o equivalente a posições nulas.
# Solução:
# Como isso esse problema não agrega em nada o projeto decidi substituir as posições vazias por numeros aleatorios.
def lerArquivo(caminho):
vet = []
f = open(caminho, 'r')
for line in f:
c = []
linha = line.split(" ")
for collun in linha:
c.append(collun)
vet.append(c)
return vet
def lerArquivoAlterado(caminho):
vet = []
f = open(caminho, 'r')
for line in f:
c = []
linha = line.split("|")
for collun in linha:
c.append(collun)
vet.append(c)
return vet
def concertaArquivoQtd():
arquivo = open("arquivo/ligamagicQtd.txt", 'r')
conteudo = arquivo.readlines()
t = []
for line in conteudo:
if(conteudo[0] == line):
c = ""
linha = line.split(" ")
for i in range(88):
if(i < 87):
n = randrange(0, 100)
c += (str(linha[i]) + "|")
else:
n = randrange(0, 100)
c += (str(linha[i]))
t.append(c)
else:
c = ""
linha = line.split(" ")
for i in range(88):
if(linha[0] == linha[i]):
c += (str(linha[i]) + "|")
elif(i < 87):
if(linha[i] == ''):
n = randrange(0, 100)
c += (str(n) + "|")
else:
c += (str(linha[i]) + "|")
else:
n = randrange(0, 100)
c += (str(n)+"\n")
t.append(c)
arquivo = open("arq/ligamagicQtd.txt", 'w')
arquivo.writelines(t)
arquivo.close()
def concertaArquivoPreco():
arquivo = open("arquivo/ligamagicPreco.txt", 'r')
conteudo = arquivo.readlines()
t = []
for line in conteudo:
if(conteudo[0] == line):
c = ""
linha = line.split(" ")
for i in range(88):
if(i < 87):
n = round(uniform(0.05, 100), 2)
c += (str(linha[i]) + "|")
else:
n = round(uniform(0.05, 100), 2)
c += (str(linha[i]))
t.append(c)
else:
c = ""
linha = line.split(" ")
for i in range(88):
if(linha[0] == linha[i]):
c += (str(linha[i]) + "|")
elif(i < 87):
if(linha[i] == ''):
n = round(uniform(0.05, 100), 2)
c += (str(n) + "|")
else:
c += (str(linha[i]) + "|")
else:
n = round(uniform(0.05, 100), 2)
c += (str(n)+"\n")
t.append(c)
arquivo = open("arq/ligamagicPreco.txt", 'w')
arquivo.writelines(t)
arquivo.close()
'''
def concertaArquivoQtd():
arquivo = open("arquivo/ligamagicQtd.txt", 'r')
conteudo = arquivo.readlines()
t = []
for line in conteudo:
c = ""
linha = line.split(" ")
for collun in linha:
# print(c)
if(collun == ''):
n = randrange(0, 100)
if(linha[87] != collun):
c += (str(n) + "|")
else:
c += (str(n))
#print("Alterado: " + str(n))
# print(c)
else:
if(linha[87] != collun):
c += (str(collun) + "|")
else:
c += (str(collun))
t.append(c)
arquivo = open("arq/ligamagicQtd.txt", 'w')
arquivo.writelines(t)
arquivo.close()
'''
'''
def concertaArquivoPreco():
arquivo = open("arquivo/ligamagicPreco.txt", 'r')
conteudo = arquivo.readlines()
t = []
for line in conteudo:
c = ""
linha = line.split(" ")
for collun in linha:
if(collun == ''):
n = round(uniform(0.05, 100), 2)
if(linha[-1] != collun):
c += (str(n) + "|")
else:
c += (str(n))
else:
if(linha[-1] != collun):
c += (str(collun) + "|")
else:
c += (str(collun))
t.append(c)
arquivo = open("arq/ligamagicPreco.txt", 'w')
arquivo.writelines(t)
arquivo.close()
'''
vetQtd = lerArquivo("arquivo/ligamagicQtd.txt")
nu = 0
for item in vetQtd:
if(str(item[1]) != "Site1"):
for i in item:
if(item[0] != i):
if(i == ''):
nu += 1
print(nu)
concertaArquivoQtd()
vetQtd = lerArquivoAlterado("arq/ligamagicQtd.txt")
nu = 0
for item in vetQtd:
if(str(item[1]) != "Site1"):
for i in item:
if(item[0] != i):
if(i == ''):
nu += 1
print(nu)
vetQtd = lerArquivo("arquivo/ligamagicPreco.txt")
nu = 0
for item in vetQtd:
if(str(item[1]) != "Site1"):
for i in item:
if(item[0] != i):
if(i == ''):
nu += 1
print(nu)
concertaArquivoPreco()
vetQtd = lerArquivoAlterado("arq/ligamagicPreco.txt")
nu = 0
for item in vetQtd:
if(str(item[1]) != "Site1"):
for i in item:
if(item[0] != i):
if(i == ''):
nu += 1
print(nu)
'''
vetFretes = lerArquivo("arquivo/ligamagicFrete.txt")
pedido1 = lerArquivo("arquivo/ligamagicPedido1.txt")
pedido2 = lerArquivo("arquivo/ligamagicPedido2.txt")
pedido3 = lerArquivo("arquivo/ligamagicPedido3.txt")
pedido4 = lerArquivo("arquivo/ligamagicPedido4.txt")
vetPreco = lerArquivo("arquivo/ligamagicPreco.txt")
vetQtd = lerArquivo("arquivo/ligamagicQtd.txt")
for item in vetQtd:
if(str(item[1]) != "Site1"):
for i in item:
if(item[0]!=i):
if(i==''):
i = random.randrange(0, 100)
numero = round(3.32424, 2)
print(numero) // 3.32
'''
|
20a6987914ad5796f89b6d4871cb9baa729fb738 | 2727-ask/HR-CC | /Patterns/designer_floor_mat.py | 240 | 3.640625 | 4 | inputs = input().split()
row = int(inputs[0])
col = int(inputs[1])
a = ".|."
for x in range(1,row,2):
print((str(a)*x).center(col,'-'))
print('WELCOME'.center(col,'-'))
for y in range(row-2,-1,-2):
print((str(a)*y).center(col,'-'))
|
ad831333ad36425690ef68e2664634f0b3a9426b | 2727-ask/HR-CC | /Patterns/string_rangoli.py | 298 | 3.84375 | 4 | def triangle(n):
k = n - 1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("\r")
triangle(5)
c=0
while(c < 6):
c = c+ 1
print(str(4*"*").rjust(5,'\t'))
|
18f441a97eff2d55524a1924265aa1d7a052c83d | 2727-ask/HR-CC | /Strings/Company Logo.py | 116 | 3.546875 | 4 | from collections import Counter
s = sorted(input())
arr=Counter(s).most_common(3)
for x in arr:
print(x[0],x[1]) |
cd332ab59ede9fa70ac847d4dad76065aa9882a2 | iNouvellie/python-3 | /02_EstructuraDeDatos/06_Diccionario_III.py | 594 | 4.375 | 4 | calificaciones = {"tito": 10, "naty":6, "amaro": 5}
#Al recorrer e imprimir con un for, solo muestra la llave
for calificacion in calificaciones:
print (calificacion)
#De esta forma obtenemos el numero de la calificacion
for calificacion in calificaciones:
print (calificaciones[calificacion])
#Imprime la key, pero usando su metodo
for key in calificaciones.keys():
print (key)
#Imprime el value, pero usando su metodo
for value in calificaciones.values():
print (value)
#De esta forma obtenemos una tupla donde se muestra key y value
for item in calificaciones.items():
print (item) |
ebe0471563ed33d4af96c73109a0f83f33332ae4 | iNouvellie/python-3 | /01_IntroduccionPython/07_Ciclos.py | 697 | 4.125 | 4 | #Ciclos while, repiten bloque de codigo mientras la condicion sea cierta
#Ciclo for, recorren elementos en una coleccion
frutas = 10
while frutas > 0:
print ("Estoy comiendo una fruta " + str(frutas))
#frutas = frutas - 1
frutas -= 1
if frutas == 0:
print ("\n")
print ("Me quede sin frutas")
#--- o ---
lista_nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for numero in lista_nums:
#Palabras reservadas continuo y break
#Break rompe ciclo si se llega a dicha condicion
if numero > 5:
break
print (numero)
print ("\n")
for numero in lista_nums:
#Palabras reservadas continuo y break
#Continuo salta la itereacion si cumple dicha condicion
if numero == 5:
continue
print (numero) |
f46cd4e475d579cdd9245a07cfdd596f407be50c | matheusferretti/LearnPythonFunctions | /exercises/06-lambda-functions/app.py | 73 | 3.78125 | 4 | # your function here
is_odd = lambda num: num % 3 == 0
print(is_odd(2)) |
abcde7966a45cae360b22e6ad0503af576dd98c9 | Sergio2409/PSP-Programs | /Programa6/Code/node.py | 369 | 3.9375 | 4 | # -*- coding: utf-8 -*-
class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next
@property
def has_next(self):
'''Return True if the node has a next otherwise returns False.
'''
return True if self.next else False
def __repr__(self):
return str(self.value)
|
9004ce01e54e5e65cf1a95cb00de98f0160d795b | Sergio2409/PSP-Programs | /Programa6/Code/compute_simpson_rule.py | 3,490 | 3.578125 | 4 | # -*- coding: utf-8 -*-
import math
from math import log, sqrt, e
class ComputeSimpsonRule(object):
def __init__(self, _list):
self.t = _list.value[0]
self.dof = _list.value[1]
self.p = 0
def compute_factorial(self, val):
''' Calcula el factorial del número pasado (val – 1).
'''
for el in range(2, val):
val *= el
return val
def compute_gamma(self, val):
'''Calcula el valor gamma, si el valor es ´int´: se calcula de la
siguiente forma:
gamma = (val – 1)!
Si el valor es el valor es ´float´ entonces se calcula:
gamma = (val-1) gamma (x-1) teniendo en cuenta que:
gamma (1) = 1
gamma (1/2) = sqrt (Pi)'
'''
res = 0
val -= 1
if not isinstance(val, int) :
res = val
new_val = 0
while val > 0:
new_val = val - 1
if new_val > 0:
res *= new_val
val -= 1
else:
return self.compute_factorial(val)
return res * math.sqrt(math.pi)
def not_pair(self, val):
'''Esta función recive un valor numérico en caso de que ese valor no
sea divisible por 2, devuelve ese valor convertido a ´ float´ sino
devuelve el mismo número.
'''
return float(val) if val%2 != 0 else val
def compute_function_Xi(self, Xi, dof, _gmma_num, _gmma_denom):
'''Calcular el valor de la función con la regla de Simpson para
integrar la densidad de probabilidad usando la siguiente ecuación.
'''
F_0 = 0
Pi = math.pi
_b_F0 = 1 + (math.pow(Xi, 2)/dof)
exp_more = float(dof+1)
exp = -(exp_more / 2)
F_0 = math.pow(_b_F0, exp)
F = _gmma_num / (math.pow(dof*Pi, 0.5) * _gmma_denom) * F_0
return F
def compute_integral_value(self, val, dof, num_seg):
ini_val, sum_by_2, sum_by_4, end_val = 0, 0, 0, 0
Xi, sum_terms, p = 0, 0, 0
W = val/num_seg
dof_pls_one = self.not_pair(dof+1)
dof = self.not_pair(dof)
_gmma_num = self.compute_gamma(dof_pls_one/2)
_gmma_denom = self.compute_gamma(dof/2)
pos = 0
while pos < num_seg:
sum_2, sum4 = 0, 0
Xi = pos * W
if pos == 0:
ini_val = self.compute_function_Xi(Xi, dof, _gmma_num,
_gmma_denom)
elif pos%2 == 0 and pos != 0:
sum_2 = self.compute_function_Xi(Xi, dof, _gmma_num, _gmma_denom)
sum_by_2 += 2 * sum_2
else:
sum_4 = self.compute_function_Xi(Xi, dof, _gmma_num, _gmma_denom)
sum_by_4 += 4 * sum_4
pos += 1
end_val = self.compute_function_Xi(val, dof, _gmma_num, _gmma_denom)
terms_sums = ini_val + sum_by_2 + sum_by_4 + end_val
p = terms_sums * (W/3)
return p
def compute_total_probability(self):
self.p, p_0, p_1 = 0, 0, 0
E = 0.0000001
res = []
p_0 = round(self.compute_integral_value(self.t, self.dof, 10), 5)
p_1 = round(self.compute_integral_value(self.t, self.dof, 20), 5)
_abs = abs(p_0 - p_1)
if _abs >= E:
print('Error: The absolute value |%f-%f| > %f' % (p_0,p_1,E))
else:
self.p = p_1
return self.p
|
51e015545046b6411f88bcf969c22b69529464d3 | bigmoletos/WildCodeSchool_France_IOI-Sololearn | /soloearn.python/sololearn_pythpn_takeAshortCut_1.py | 1,353 | 4.375 | 4 | #Quiz sololearn python test take a shortcut 1
#https://www.sololearn.com/Play/Python
#raccouri level1
from _ast import For
x=4
x+=5
print (x)
#*************
print("test 2")
#What does this code do?
for i in range(10):
if not i % 2 == 0:
print(i+1)
#*************
print("test 3")
#What is the output of this code?
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
#*************
print("test 4")
#What does this code output?
letters = ['x', 'y', 'z']
letters.insert(1, 'w')
print(letters[2])
#*************
print("test 6")
#How many lines will this code print?
while False:
print("Looping...")
#*************
print("test 7")
#Fill in the blanks to define a function that takes two numbers as arguments and returns the smaller one.
def min(x, y):
if x<=y:
return x
else:
return y
#*************
print("test 8")
#Fill in the blanks to iterate over the list using a for loop and print its values.
list = [1, 2, 3]
for var in list:
print(var)
#*************
print("test 9")
#Fill in the blanks to print the first element of the list, if it contains even number of elements.
list = [1, 2, 3, 4]
if len(list) % 2 == 0:
print(list[0])
#*************
print("test 10")
#What is the output of this code?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(5))
|
26dca6d8c9108c7c33454b2603f82aff8956daa6 | bigmoletos/WildCodeSchool_France_IOI-Sololearn | /soloearn.python/sololearn_pythpn_course_level_3.py | 37,405 | 4.1875 | 4 | #Quiz sololearn python test take a shortcut 1
#https://www.sololearn.com/Play/Python
#cours level 2 et 3
#*************
def deco(func):
def wrap():
print("============")
func()
print("============")
return wrap
@deco
def printTitle():
print("**********************COURS********************")
printTitle()
#*************
#*************
sqs = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
print(sqs)
print(sqs[7:5:-1])
print(sqs[5:-1])
print(sqs[5:-2])
print(sqs[7:5])
print(sqs[5:7])
#Fill in the blanks to create a list of numbers multiplied by 10 in the range of 5 to 9.
a = [x*10 for x in range(5, 9)]
print(a)
#*************
print("string formatting")
nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])
msg2 = "Numbers: {2} {1} {0} ". format(nums[0], nums[1], nums[2])
print(msg)
print(msg2)
#*************
#What is the result of this code?
print("{0}{1}{0}".format("abra", "cad"))
a = "{x}, {y}".format(x=5, y=12)
print(a)
#*************
#What is the result of this code?
a=min([sum([11, 22]), max(abs(-30), 2)])
print(a)
#*************
#all, any, enumerate
nums = [55, 44, 33, 22, 11]
print("nums ",nums)
if all([i > 5 for i in nums]):
print("All larger than 5")
if any([i % 2 == 0 for i in nums]):
print("At least one is even")
for v in enumerate(nums):
print(v)
#*************
#What is the result of this code?
nums = [-1, 2, -3, 4, -5]
if all([abs(i) < 3 for i in nums]):
print(1)
else:
print(2)
#*************
#filename = input("Enter a filename: ")
filename = "fichierTest.txt"
print("**********************filename***********************")
#fichierTest.txt
with open("D:\\programmation\\formation-Human-Booster\\data-eclipse\\WildCodeSchool\\src\\soloLearn\\java\\"+filename, "r") as f:
text = f.read()
print(text)
#*************
def count_char(text, char):
count = 0
for c in text:
if c == char:
count += 1
return count
filename1 = "D:\\programmation\\formation-Human-Booster\\data-eclipse\\WildCodeSchool\\src\\soloLearn\\java\\fichierTest.txt"
print("filename1")
with open(filename1) as f:
text = f.read()
print(count_char(text, "r"))
#*************
for char in "abcdefghijklmnopqrstuvwxyz":
perc = 100 * count_char(text, char) / len(text)
print("{0} - {1}%".format(char, round(perc, 2)))
#*************
# def count_char(text, char):
# count = 0
# for c in text:
# if c == char:
# count += 1
# return count
print("******************filename2******************************")
filename2 = "D:\\programmation\\formation-Human-Booster\\data-eclipse\\WildCodeSchool\\src\\soloLearn\\java\\fichierTest2.txt"
with open(filename2) as f:
text = f.read()
for char in "abcdefghijklmnopqrstuvwxyz":
perc = 100 * count_char(text, char) / len(text)
print("{0} - {1}%".format(char, round(perc, 2)))
#*************
print("*****************function test******************")
#What is the output of this code?
def test(func, arg):
print(func,arg)
return func(func(arg))
print("*******************function mult*****************")
def mult(x):
return x * x
print(test(mult, 2))
#*************
#named function
print("*******************polynomial function********************")
def polynomial(x):
return x**2 + 5*x + 4
print(polynomial(-4))
#lambda
print((lambda x: x**2 + 5*x + 4) (-4))
#*************
print("*****************function double****************")
double = lambda x: x * 2
print(double(7))
#*************
print("*****************function triple add****************")
#What is the result of this code?
triple = lambda x: x * 3
add = lambda x, y: x + y
print(add(triple(3), 4))
#*************
print("**************map***************** ")
def add_five(x):
return x + 5
nums = [11, 22, 33, 44, 55]
print(nums)
result = list(map(add_five, nums))
print(result)
#with lambda
nums = [11, 22, 33, 44, 55]
result = list(map(lambda x: x+5, nums))
print(result)
#*************
print("filtre les multiples de 2")
nums = [11, 22, 33, 44, 55]
res = list(filter(lambda x: x%2==0, nums))
print(res)
#*************
print("*********filter valeurs*************")
nums = [11, 22, 33, 44, 55]
result = list(filter(lambda x: x<35, nums))
print(result)
#*************
print("**********yield**************")
def countdown():
i=5
while i > 0:
yield i
i -= 1
for i in countdown():
print(i)
#*************
print("yield and infinite")
def infinite_sevens():
while True:
yield 7
#for i in infinite_sevens():
# print("boucle infinie")
#boucle infinie
# print(i)
#*************
def numbers(x):
for i in range(x):
if i % 2 == 0:
yield i
print(list(numbers(11)))
#*************
#What is the result of this code?
print("make_word")
def make_word():
word = ""
for ch in "spam":
word +=ch
yield word
print(list(make_word()))
#*************
print("***********Decorator**************")
def decor(func):
def wrap():
print("============")
func()
print("============")
return wrap
def decorTitle(func):
def wrap():
func()
print("*******************")
print("func ", func())
return wrap
def print_text():
print("Hello world!")
decorated = decor(print_text)
decorated()
#*************
print("decorator2")
def print_text2():
print("Hello world!Okay!!!")
print_text2 = decor(print_text2)
print_text2()
#*************
@decorTitle
@decor
def print_text3():
print("Hello world!Of course!")
print_text3()
#*************
print("************recursif factoriel**************")
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
print(factorial(5))
#*************
print("recursif ")
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(17))
print(is_even(23))
#*************
#What is the result of this code?
def fib(x):
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
print(fib(6))
#************
print("set")
num_set = {1, 2, 3, 4, 5}
word_set = set(["spam", "eggs", "sausage"])
print(3 in num_set)
print("spam" not in word_set)
#*************
#What is the output of this code?
letters = {"a", "b", "c", "d"}
if "e" not in letters:
print(1)
else:
print(2)
#*************
nums = {1, 2, 1, 3, 1, 4, 5, 6}
print(nums)
nums.add(-7)
nums.remove(3)
print(nums)
#*************
first = {1, 2, 3, 4, 5, 6}
second = {4, 5, 6, 7, 8, 9}
print("first ",first)
print("second ",second)
print("first | second",first | second)
print("first & second",first & second)
print("first - second",first - second)
print("second - first",second - first)
print("first ^ second",first ^ second)
#*************
#What is the output of this code?
a = {1, 2, 3}
b = {0, 3, 4, 5}
print(a & b)
#*************
print("*******itertool************")
from itertools import count
for i in count(3):
print(i)
if i >=11:
break
#*************
from itertools import accumulate, takewhile
nums = list(accumulate(range(8)))
print(nums)
print(list(takewhile(lambda x: x<= 6, nums)))
#*************
from itertools import takewhile
nums = [2, 4, 6, 7, 9, 8]
a = takewhile(lambda x: x%2==0, nums)
print(list(a))
#*************
from itertools import product, permutations
letters = ("A", "B","C")
print(list(product(letters, range(3))))
print(list(permutations(letters)))
#*************
#What is the output of this code?
from itertools import product
a={1, 2}
print(len(list(product(range(3), a))))
#*************
#What is the result of this code?
nums = {1, 2, 3, 4, 5, 6}
nums = {0, 1, 2, 3} & nums
print(nums)
nums = filter(lambda x: x > 1, nums)
print(len(list(nums)))
#*************
#What is the result of this code?
def power(x, y):
if y == 0:
return 1
else:
return x * power(x, y-1)
print(power(2, 3))
#*************
a = (lambda x: x*(x+1))(6)
print(a)
#*************
nums = [1, 2, 8, 3, 7]
res = list(filter(lambda x: x%2==0, nums))
print(res)
#*************
@deco
def printTitle():
print("************CLASSES***************")
printTitle()
class Cat:
def __init__(self, color, legs):
self.color = color
self.legs = legs
felix = Cat("ginger", 4)
print(felix.color)
#*************
#print("classes")
class Student:
def __init__(self, name):
self.name= name
test = Student("Bob")
print(test)
#*************
class Dog:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("Woof!")
fido = Dog("Fido", "brown")
print(fido.name)
fido.bark()
#*************
class Dog:
legs = 4
def __init__(self, name, color):
self.name = name
self.color = color
fido = Dog("Fido", "brown")
print(fido.legs)
print(Dog.legs)
#*************
class Student:
def __init__(self, name):
self.name = name
def sayHi(self):
print("Hi from "+self.name)
s1 = Student("Amy")
s1.sayHi()
#*************
class Rectangle:
def __init__(self, width, height,color):
self.width = width
self.height = height
self.color = color
rect = Rectangle(7, 8,"green")
print(rect.color)
#*************
print("**********heritage*************")
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
class Cat(Animal):
def purr(self):
print("Purr...")
class Dog(Animal):
def bark(self):
print("Woof!")
fido = Dog("Fido", "brown")
print(fido.color)
fido.bark()
#*************
class Wolf:
def __init__(self, name, color):
self.name = name
self.color = color
def bark(self):
print("Grr...")
class Dog(Wolf):
def bark(self):
print("Woof")
husky = Dog("Max", "grey")
husky.bark()
#*************
#What is the result of this code?
class A:
def method(self):
print(1)
class B(A):
def method(self):
print(2)
B().method()
#*************
class A:
def method(self):
print("A method")
class B(A):
def another_method(self):
print("B method")
class C(B):
def third_method(self):
print("C method")
c = C()
c.method()
c.another_method()
c.third_method()
#*************
#What is the result of this code?
class A:
def a(self):
print(1)
class B(A):
def a(self):
print(2)
class C(B):
def c(self):
print(3)
c = C()
c.a()
#*************
class A:
def spam(self):
print(1)
class B(A):
def spam(self):
print(2)
super().spam()
B().spam()
#*************
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
first = Vector2D(5, 7)
second = Vector2D(3, 9)
result = first + second
print(result.x)
print(result.y)
#*************
# What is the magic method for creating an instance?
# __init__
#*************
class SpecialString:
def __init__(self, cont):
self.cont = cont
def __truediv__(self, other):
line = "=" * len(other.cont)
return "\n".join([self.cont, line, other.cont])
spam = SpecialString("spam")
hello = SpecialString("Hello world!")
print(spam / hello)
#*************
#rajoute un bandeau de la taille du titre au dessus et au dessous du titre
def decoMyTitleWithWrap(theText):
print("="*len(theText),"\n"+theText,"\n"+"="*len(theText))
decoMyTitleWithWrap("my title")
#*************
decoMyTitleWithWrap("magic method __gt__")
class SpecialString:
def __init__(self, cont):
self.cont = cont
#__gt__ is a magic method for ">"
def __gt__(self, other):
for index in range(len(other.cont)+1):
result = other.cont[:index] + ">" + self.cont
result += ">" + other.cont[index:]
print(result)
spam = SpecialString("spam")
eggs = SpecialString("eggs")
spam > eggs
#*************
decoMyTitleWithWrap("magic method __getitem__ and __len__")
import random
class VagueList:
def __init__(self, cont):
self.cont = cont
def __getitem__(self, index):
return self.cont[index + random.randint(-1, 1)]
def __len__(self):
return random.randint(0, len(self.cont)*2)
vague_list = VagueList(["A", "B", "C", "D", "E"])
print(len(vague_list))
print(len(vague_list))
print(vague_list[2])
print(vague_list[2])
#*************
decoMyTitleWithWrap("magic method _variable private")
class Queue:
def __init__(self, contents):
self._hiddenlist = list(contents)
def push(self, value):
self._hiddenlist.insert(0, value)
def pop(self):
return self._hiddenlist.pop(-1)
def __repr__(self):
return "Queue({})".format(self._hiddenlist)
queue = Queue([1, 2, 3])
print(queue)
queue.push(0)
print(queue)
queue.pop()
print(queue)
print(queue._hiddenlist)
#*************
decoMyTitleWithWrap("private class")
class Spam:
__egg = 7
def print_egg(self):
print(self.__egg)
s = Spam()
s.print_egg()
print(s._Spam__egg)
#print(s.__egg) error its normal
#*************
decoMyTitleWithWrap("@class methode")
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
@classmethod
def new_square(cls, side_length):
return cls(side_length, side_length)
square = Rectangle.new_square(5)
print(square.calculate_area())
#*************
decoMyTitleWithWrap("@classmethod")
#Fill in the blanks to make sayHi() a class method.
class Person:
def __init__(self, name):
self.name = name
@classmethod
def sayHi(cls):
print("Hi")
myMethod=Person.sayHi()
#*************
decoMyTitleWithWrap("static method with @staticmethod")
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@staticmethod
def validate_topping(topping):
if topping == "pineapple":
raise ValueError("No pineapples!")
else:
return True
ingredients = ["cheese", "onions", "spam"]
if all(Pizza.validate_topping(i) for i in ingredients):
pizza = Pizza(ingredients)
print(pizza.toppings)
#*************
decoMyTitleWithWrap("@property")
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@property
def pineapple_allowed(self):
return False
pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
#pizza.pineapple_allowed = True
#*************
decoMyTitleWithWrap("@property isAdult")
#Fill in the blanks to create an "isAdult" property.
class Person:
def __init__(self, age):
self.age = int(age)
@property
def isAdult(self):
if self.age > 18:
return True
else:
return False
#*************
decoMyTitleWithWrap("@property setter and getter")
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
self._pineapple_allowed = False
@property
def pineapple_allowed(self):
return self._pineapple_allowed
@pineapple_allowed.setter
def pineapple_allowed(self, value):
if value:
#password = input("Enter the password: ")
password = "enclume"
if password == "enclume":
self._pineapple_allowed = value
else:
raise ValueError("Alert! Intruder!")
pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
print(pizza.pineapple_allowed)
#*************
decoMyTitleWithWrap("simple game")
# def get_input():
# command = input(": ").split()
# verb_word = command[0]
# if verb_word in verb_dict:
# verb = verb_dict[verb_word]
# else:
# print("Unknown verb {}". format(verb_word))
# return
#
# if len(command) >= 2:
# noun_word = command[1]
# print (verb(noun_word))
# else:
# print(verb("nothing"))
#
# def say(noun):
# return 'You said "{}"'.format(noun)
#
# verb_dict = {
# "say": say,
# }
#
# while True:
# get_input()
#*************
decoMyTitleWithWrap("simple game with attack")
class GameObject:
class_name = ""
desc = ""
objects = {}
def __init__(self, name):
self.name = name
GameObject.objects[self.class_name] = self
def get_desc(self):
return self.class_name + "\n" + self.desc
class Goblin(GameObject):
class_name = "goblin"
desc = "A foul creature"
goblin = Goblin("Gobbly")
def examine(noun):
if noun in GameObject.objects:
return GameObject.objects[noun].get_desc()
else:
return "There is no {} here.".format(noun)
class Goblin(GameObject):
def __init__(self, name):
self.class_name = "goblin"
self.health = 3
self._desc = " A foul creature"
super().__init__(name)
@property
def desc(self):
if self.health >=3:
return self._desc
elif self.health == 2:
health_line = "It has a wound on its knee."
elif self.health == 1:
health_line = "Its left arm has been cut off!"
elif self.health <= 0:
health_line = "It is dead."
return self._desc + "\n" + health_line
@desc.setter
def desc(self, value):
self._desc = value
def hit(noun):
if noun in GameObject.objects:
thing = GameObject.objects[noun]
if type(thing) == Goblin:
thing.health = thing.health - 1
if thing.health <= 0:
msg = "You killed the goblin!"
else:
msg = "You hit the {}".format(thing.class_name)
else:
msg ="There is no {} here.".format(noun)
return msg
#*************
decoMyTitleWithWrap("question 5")
# class Test:
# __egg = 7
# t = Test()
# print(t._Test__egg)
#*************
decoMyTitleWithWrap("question 7/7")
#Fill in the blanks to make a setter for the property name.
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
#*************
decoMyTitleWithWrap("regular expression")
import re
pattern = r"spam"
if re.match(pattern, "spamspamspam"):
print("Match")
else:
print("No match")
#*************
decoMyTitleWithWrap("regular expression2")
import re
pattern = r"spam"
if re.match(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
if re.search(pattern, "eggspamsausagespam"):
print("Match")
else:
print("No match")
print(re.findall(pattern, "eggspamsausagespam"))
#*************
decoMyTitleWithWrap("regular expression3")
import re
pattern = r"pam"
match = re.search(pattern, "eggspamsausage")
if match:
print(match.group())
print(match.start())
print(match.end())
print(match.span())
#*************
decoMyTitleWithWrap("regular expression4 search replace")
import re
str = "My name is David. Hi David."
pattern = r"David"
newstr = re.sub(pattern, "Amy", str)
print(newstr)
#*************
decoMyTitleWithWrap("regular expression5")
#Fill in the blanks to replace all 9s in the string with 0s.
import re
num = "07987549836"
pattern = r"9"
num = re.sub(pattern, "0", num)
print(num)
#*************
decoMyTitleWithWrap("metacharacter")
#Fill in the blanks to create a raw string.
#str = r "I am \r\a\w!"
#*************
decoMyTitleWithWrap("metacharacter2")
import re
pattern = r"gr.y"
if re.match(pattern, "grey"):
print("Match 1")
if re.match(pattern, "gray"):
print("Match 2")
if re.match(pattern, "blue"):
print("Match 3")
#*************
decoMyTitleWithWrap("metacharacter3")
import re
pattern = r"^gr.y$"
if re.match(pattern, "grey"):
print("Match 1")
if re.match(pattern, "gray"):
print("Match 2")
if re.match(pattern, "stingray"):
print("Match 3")
#*************
decoMyTitleWithWrap("metacharacter4")
#Fill in the blanks to create a pattern that matches strings that contain 3 characters, out of which the last character is an exclamation mark.
r"..!$"
#*************
decoMyTitleWithWrap("Character Classes")
import re
pattern = r"[aeiou]"
if re.search(pattern, "grey"):
print("Match 1")
if re.search(pattern, "qwertyuiop"):
print("Match 2")
if re.search(pattern, "rhythm myths"):
print("Match 3")
#*************
decoMyTitleWithWrap("Character Classes2")
import re
pattern = r"[A-Z][a-z][0-9]"
if re.search(pattern, "Ls8"):
print("Match 1")
if re.search(pattern, "Ef3"):
print("Match 2")
if re.search(pattern, "1ab"):
print("Match 3")
#*************
decoMyTitleWithWrap("Character Classes3")
# What would [1-5][0-9] match?
#Any two-digit number from 10 to 59
#*************
decoMyTitleWithWrap("Character Classes4")
import re
pattern = r"[^A-Z]"
if re.search(pattern, "this is all quiet"):
print("Match 1")
if re.search(pattern, "AbCdEfG123"):
print("Match 2")
if re.search(pattern, "THISISALLSHOUTING"):
print("Match 3")
#*************
decoMyTitleWithWrap("Character Classes5")
#Fill in the blanks to match strings that are not entirely composed of digits.
import re
pattern = r"[^0-9]"
m = re.search(pattern, "Hi there!")
#*************
decoMyTitleWithWrap("Metacharacters")
import re
pattern = r"egg(spam)*"
if re.match(pattern, "egg"):
print("Match 1")
if re.match(pattern, "eggspamspamegg"):
print("Match 2")
if re.match(pattern, "spam"):
print("Match 3")
#*************
decoMyTitleWithWrap("Metacharacters2")
# What would [a^]* match?
# Zero or more repetitions of "a" or "^"
#*************
decoMyTitleWithWrap("Metacharacters3")
import re
pattern = r"g+"
if re.match(pattern, "g"):
print("Match 1")
if re.match(pattern, "gggggggggggggg"):
print("Match 2")
if re.match(pattern, "abc"):
print("Match 3")
#*************
decoMyTitleWithWrap("Metacharacters4")
#Fill in the blanks to create a pattern that matches strings that contain one or more 42s.
#r"(42)+ $"
#*************
decoMyTitleWithWrap("Metacharacters5")
import re
pattern = r"ice(-)?cream"
if re.match(pattern, "ice-cream"):
print("Match 1")
if re.match(pattern, "icecream"):
print("Match 2")
if re.match(pattern, "sausages"):
print("Match 3")
if re.match(pattern, "ice--ice"):
print("Match 4")
#*************
decoMyTitleWithWrap("Metacharacters6")
#Fill in the blanks to match both 'color' and 'colour'.
pattern = r"colo(u)?r"
print(pattern)
#*************
decoMyTitleWithWrap("Metacharacters7")
import re
pattern = r"9{1,3}$"
if re.match(pattern, "9"):
print("Match 1")
if re.match(pattern, "999"):
print("Match 2")
if re.match(pattern, "9999"):
print("Match 3")
#*************
decoMyTitleWithWrap("Metacharacters8")
# Which of these is the same as the metacharacter '+'?
# {1,}
#*************
decoMyTitleWithWrap("Groups")
import re
pattern = r"egg(spam)*"
if re.match(pattern, "egg"):
print("Match 1")
if re.match(pattern, "eggspamspamspamegg"):
print("Match 2")
if re.match(pattern, "spam"):
print("Match 3")
#*************
decoMyTitleWithWrap("Groups")
#What would '([^aeiou][aeiou][^aeiou])+' match?
#One or more repetitions of a non-vowel, a vowel and a non-vowel
#*************
decoMyTitleWithWrap("Groups")
import re
pattern = r"a(bc)(de)(f(g)h)i"
match = re.match(pattern, "abcdefghijklmnop")
if match:
print(match.group())
print(match.group(0))
print(match.group(1))
print(match.group(2))
print(match.groups())
#*************
decoMyTitleWithWrap("Metacharacters9")
# What would group(3) be of a match of 1(23)(4(56)78)9(0)?
#
#
# 56
#
#*************
decoMyTitleWithWrap("Metacharacters10")
import re
pattern = r"(?P<first>abc)(?:def)(ghi)"
match = re.match(pattern, "abcdefghi")
if match:
print(match.group("first"))
print(match.groups())
#*************
decoMyTitleWithWrap("Metacharacters11 ?")
#What would be the result of len(match.groups()) of a match of (a)(b(?:c)(d)(?:e))?
#3
#*************
decoMyTitleWithWrap("Metacharacters12 |")
import re
pattern = r"gr(a|e)y"
match = re.match(pattern, "gray")
if match:
print ("Match 1")
match = re.match(pattern, "grey")
if match:
print ("Match 2")
match = re.match(pattern, "griy")
if match:
print ("Match 3")
#*************
decoMyTitleWithWrap("Metacharacters13 |")
# What regex is not equivalent to the others?
# [12345]
# (1|2|3|4|5)
# reponse [1-6]
#*************
decoMyTitleWithWrap("Special Sequences \1")
import re
pattern = r"(.+) \1"
match = re.match(pattern, "word word")
if match:
print ("Match 1")
match = re.match(pattern, "?! ?!")
if match:
print ("Match 2")
match = re.match(pattern, "abc cde")
if match:
print ("Match 3")
#*************
decoMyTitleWithWrap("Special Sequences \1")
# What would (abc|xyz)\1 match?
# "abc", then "xyz"
# "abc" or "xyz", followed by the same thing reponse
# "abc" or "xyz", then a "1"
#*************
decoMyTitleWithWrap("Special Sequences \d, \s, and \w")
# More useful special sequences are \d, \s, and \w.
# These match digits, whitespace, and word characters respectively.
# In ASCII mode they are equivalent to [0-9], [ \t\n\r\f\v], and [a-zA-Z0-9_].
# In Unicode mode they match certain other characters, as well. For instance, \w matches letters with accents.
# Versions of these special sequences with upper case letters - \D, \S, and \W - mean the opposite to the lower-case versions. For instance, \D matches anything that isn't a digit.
import re
pattern = r"(\D+\d)"
match = re.match(pattern, "Hi 999!")
if match:
print("Match 1")
match = re.match(pattern, "1, 23, 456!")
if match:
print("Match 2")
match = re.match(pattern, " ! $?")
if match:
print("Match 3")
#*************
decoMyTitleWithWrap("Special Sequences \d, \s, and \w")
# Which pattern would NOT match "123!456!"?
# (\D+\s?)+ reponse
# [1-6!]
# (\d*\W)+
#*************
decoMyTitleWithWrap("Special Sequences \A, \Z, and \\b")
# Additional special sequences are \A, \Z, and \b.
# The sequences \A and \Z match the beginning and end of a string, respectively.
# The sequence \b matches the empty string between \w and \W characters, or \w characters
# and the beginning or end of the string. Informally, it represents the boundary between words.
# The sequence \B matches the empty string anywhere else.
# Example:
import re
pattern = r"\b(cat)\b"
match = re.search(pattern, "The cat sat!")
if match:
print ("Match 1")
match = re.search(pattern, "We s>cat<tered?")
if match:
print ("Match 2")
match = re.search(pattern, "We scattered.")
if match:
print ("Match 3")
#*************
decoMyTitleWithWrap("Special Sequences \A, \Z, and \\b")
# Which pattern would match 'SPAM!' in a search?
#
# \AS...\b.\Z reponse
# \ASPAM\Z
# SP\AM!\Z
#*************
decoMyTitleWithWrap("Email Extraction")
# To demonstrate a sample usage of regular expressions, lets create a program to extract
# email addresses from a string.
# Suppose we have a text that contains an email address:
# str = "Please contact info@sololearn.com for assistance"
#
# Our goal is to extract the substring "info@sololearn.com".
# A basic email address consists of a word and may include dots or dashes.
# This is followed by the @ sign and the domain name (the name, a dot,
# and the domain name suffix).
# This is the basis for building our regular expression.
# pattern = r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)"
#
# [\w\.-]+ matches one or more word character, dot or dash.
# The regex above says that the string should contain a word (with dots and dashes allowed),
# followed by the @ sign, then another similar word, then a dot and another word.
# Our regex contains three groups:
# 1 - first part of the email address.
# 2 - domain name without the suffix.
# 3 - the domain suffix.
#*************
decoMyTitleWithWrap("Email Extraction2")
# Which of these must be done with regular expressions, rather than string methods?
#
# Checking whether a particular character is in a string
# Splitting a string
# Checking to see if a string contains a date-------- reponse
#*************
decoMyTitleWithWrap("Email Extraction3")
import re
pattern = r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)"
str = "Please contact info@sololearn.com or contact@sololearn.com for assistance"
match = re.search(pattern, str)
if match:
print(match.group())
#*************
decoMyTitleWithWrap("Email Extraction4")
import re
pattern = re.compile(r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)")
# pattern = r"([a-zA-Z0-9_])@[a-zA-Z0-9_].[a-zA-Z0-9_]"
str = "Please contact info@sololearn.com or contact@sololearn.com for assistance"
match = pattern.findall(str)
# for i in match:
# print(match[i])
if match:
print(match)
#print(match.group(1),match.group(2),match.group(3))
#*************
decoMyTitleWithWrap("Regular Expressions Module 8 Quiz")
# Which of these metacharacters isn't to do with repetition?
#
# \ reponse
# +
# *
#*************
decoMyTitleWithWrap("Regular Expressions Module 8 Quiz")
# How many groups are in the regex (ab)(c(d(e)f))(g)?
# 5
#*************
decoMyTitleWithWrap("Regular Expressions Module 8 Quiz")
# Which regex would match "email@domain.com"?
#
# [0-9]@domain\.com
# \w+@domain.com reponse
# email\@(domain\w)+
#*************
decoMyTitleWithWrap("Regular Expressions Module 8 Quiz")
# Which string would be matched by "[01]+0$"?
#
# 011101
# 10101111001010 reponse
# 0101
#*************
decoMyTitleWithWrap("Regular Expressions Module 8 Quiz")
# What would be matched by "(4{5,6})\1"?
#
# 10 or 12 fours reponse
# 456
# 5 or 6 fours
#*************
decoMyTitleWithWrap("Pythonicness & Packaging")
decoMyTitleWithWrap("The Zen of Python")
import this
#*************
decoMyTitleWithWrap("PEP")
# Python Enhancement Proposals (PEP) are suggestions for
# improvements to the language, made by experienced Python developers.
# PEP 8 is a style guide on the subject of writing readable code.
# It contains a number of guidelines in reference to variable names,
# which are summarized here:
# - modules should have short, all-lowercase names;
# - class names should be in the CapWords style;
# - most variables and function names should be lowercase_with_underscores;
# - constants (variables that never change value) should be CAPS_WITH_UNDERSCORES;
# - names that would clash with Python keywords (such as 'class' or 'if')
# should have a trailing underscore
#*************
decoMyTitleWithWrap("PEP")
# Other PEP 8 suggestions include the following:
# - lines shouldn't be longer than 80 characters;
# - 'from module import *' should be avoided;
# - there should only be one statement per line.
#
# It also suggests that you use spaces, rather than tabs, to indent. However,
# to some extent, this is a matter of personal preference. If you use spaces,
# only use 4 per line. It's more important to choose one and stick to it.
#
# The most important advice in the PEP is to ignore it when it makes sense to do so.
# Don't bother with following PEP suggestions when it would cause your code to be less
# readable; inconsistent with the surrounding code; or not backwards compatible.
# However, by and large, following PEP 8 will greatly enhance the quality of your code.
#*************
decoMyTitleWithWrap("More on Function Arguments")
def function(named_arg, *args):
print(named_arg)
print(args)
function(1, 2, 3, 4, 5)
#*************
decoMyTitleWithWrap("default value")
def function(x, y, food="spam"):
print(food)
function(1, 2)
function(3, 4, "egg")
#*************
decoMyTitleWithWrap("Function Arguments")
def my_func(x, y=7, *args, **kwargs):
print(kwargs)
my_func(2, 3, 4, 5, 6, a=7, b=8)
#*************
decoMyTitleWithWrap("Tuple Unpacking")
numbers = (7, 8, 9)
a, b, c = numbers
print(a)
print(b)
print(c)
print(numbers)
revertList = (10,11,12)
print(revertList)
g, f, e = revertList
print(e)
print(f)
print(g)
print(revertList)
#What is the value of y after this code runs?
x, y = [1, 2]
x, y = y, x
print(x,y)
#*************
decoMyTitleWithWrap("Tuple Unpacking")
a, b, *c, d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(d)
#*************
decoMyTitleWithWrap("Tuple Unpacking")
#What is the output of this code?
a, b, c, d, *e, f, g = range(20)
print(len(e))
#*************
decoMyTitleWithWrap("Ternary Operator")
a = 7
b = 1 if a >= 5 else 42
print(b)
a = 4
b = 1 if a >= 5 else 42
print(b)
status = 1
msg = "Logout" if status == 1 else "Login"
print(msg)
status = 2
msg = "Logout" if status == 1 else "Login"
print(msg)
#*************
decoMyTitleWithWrap("More on else Statements")
for i in range(10):
if i == 999:
break
else:
print("Unbroken 1")
for i in range(10):
if i == 5:
break
else:
print("Unbroken 2")
#*************
decoMyTitleWithWrap("More on else Statements2")
#What is the largest number this code prints?
for i in range(10):
if i > 5:
print(i)
break
else:
print("7")
#*************
decoMyTitleWithWrap("More on else Statements3")
try:
print(1)
except ZeroDivisionError:
print(2)
else:
print(3)
try:
print(1/0)
except ZeroDivisionError:
print(4)
else:
print(5)
#*************
decoMyTitleWithWrap("More on else Statements4")
#What is the sum of the numbers printed by this code?
try:
print(1)
print(1 + "1" == 2)
print(2)
except TypeError:
print(3)
else:
print(4)
#*************
decoMyTitleWithWrap("__main__")
def function():
print("This is a module function")
if __name__=="__main__":
print("This is a script")
#*************
decoMyTitleWithWrap("__main__2")
#Which variable couldn't be accessed if this code was imported as a module?
x = 1
y = x
if __name__=="__main__":
z = 3
#reponse: z
#*************
decoMyTitleWithWrap("__main__3")
def function():
print("This is a module function")
if __name__=="__main__":
print("This is a script")
import sololearn_pythpn_takeAshortCut_2
sololearn_pythpn_takeAshortCut_2.function()
#*************
decoMyTitleWithWrap("__main__4")
#Rearrange the code to print "Welcome" if the script is imported, and "Hi" if it is not imported.
if __name__== "__main__":
print("Hi")
else:
print("Welcome")
#*************
decoMyTitleWithWrap("Major 3rd-Party Libraries")
#*************
decoMyTitleWithWrap("Packaging")
# Packaging
#
# In Python, the term packaging refers to putting modules you have written in a standard
# format, so that other programmers can install and use them with ease.
# This involves use of the modules setuptools and distutils.
# The first step in packaging is to organize existing files correctly. Place all of the
# files you want to put in a library in the same parent directory. This directory should
# also contain a file called __init__.py, which can be blank but must be present in the directory.
# This directory goes into another directory containing the readme and license, as well
# as an important file called setup.py.
# Example directory structure:
# SoloLearn/
# LICENSE.txt
# README.txt
# setup.py
# sololearn/
# __init__.py
# sololearn.py
# sololearn2.py
#*************
decoMyTitleWithWrap("Packaging")
# The next step in packaging is to write the setup.py file.
# This contains information necessary to assemble the package so it can be uploaded to PyPI
# and installed with pip (name, version, etc.).
# Example of a setup.py file:
# from distutils.core import setup
#
# setup(
# name='SoloLearn',
# version='0.1dev',
# packages=['sololearn',],
# license='MIT',
# long_description=open('README.txt').read(),
# )
#
# After creating the setup.py file, upload it to PyPI, or use the command line to create a
# binary distribution (an executable installer).
# To build a source distribution, use the command line to navigate to the directory
# containing setup.py, and run the command python setup.py sdist.
# Run python setup.py bdist or, for Windows, python setup.py bdist_wininst to build a binary
# distribution.
# Use python setup.py register, followed by python setup.py sdist upload to upload a
# package.
# Finally, install a package with python setup.py install.
#*************
decoMyTitleWithWrap("Packaging")
# The previous lesson covered packaging modules for use by other Python programmers. However
# , many computer users who are not programmers do not have Python installed. Therefore, it
# is useful to package scripts as executable files for the relevant platform, such as the
# Windows or Mac operating systems. This is not necessary for Linux, as most Linux users
# do have Python installed, and are able to run scripts as they are.
#
# For Windows, many tools are available for converting scripts to executables. For example,
# py2exe, can be used to package a Python script, along with the libraries it requires,
# into a single executable.
# PyInstaller and cx_Freeze serve the same purpose.
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
# Which of these isn't a file used in creating a package?
#
# setup.py
# __init__.py
# __py2exe__.py reponse
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
# What is PEP 8?
#
# Guidelines for writing docstrings
# Guidelines for writing code reponse
# The Zen of Python
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
#What is the output of this code?
def func(**kwargs):
print(kwargs["zero"])
func(a = 0, zero = 8)
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
#What is sum of the numbers printed by this code?
for i in range(10):
try:
if 10 / i == 2.0:
break
except ZeroDivisionError:
print(1)
else:
print(2)
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
#Fill in the blanks to swap the variable values with one single statement.
a = 7
b = 42
a , b = b, a
#*************
decoMyTitleWithWrap("Pythonicness & Packaging Module 9 Quiz")
#*************
decoMyTitleWithWrap("")
#*************
decoMyTitleWithWrap("")
|
716e688dcdea7c3e249471ab13d765ff6d97eb79 | jaxono/Price-Comparer | /get_ingrediants.py | 1,121 | 3.9375 | 4 | import re
import item_class
TERMINATION_PHRASES = {"xxx", "done", "end", "finish", "finished"}
def get_ingrediants():
items = []
print("""
Now you will need to enter a list of the items you would like to compare, type done when you are finished.
""")
# Get list of ingredients
while 1:
# Get item name
item_name = input("Enter name of product: ").strip().title()
# Check if it is a phrase that breaks the loop
if item_name.lower() in TERMINATION_PHRASES:
break
try:
# Get price and mass
item_price = float(input("Enter price of product in $: ").strip())
item_mass = float(input("Enter price of product in grams: ").strip())
except ValueError:
# If it is invalid then cancel the current item and make them re-enter it.
print("That is not a valid real number.")
continue
item_price_per_100g = item_price / item_mass * 100
# Store data in array
print("Added {} at ${} for {}g".format(item_name, item_price, item_mass))
items.append(item_class.Item(item_price, item_mass, item_name, item_price_per_100g))
return items
#get_ingrediants()
|
1eb320f57324bf2406eeb4d6cf96ea7dadd57f79 | butterflow/butterflow | /2a.py | 289 | 3.71875 | 4 | print("Your function is 7n+5")
print("g(n) = n ")
print("Assuming c as 8")
for i in range(30):
a1 = 7 * i + 5
a2 = 8 * i
if (a2 >= a1): n0 = i
break
print("Value of n0: ", n0)
print("Value\t\tF(n)\t\tc*G(n)")
for i in range(10, 31):
print(i, "\t\t", 7 * i + 5, "\t\t", 8 * i)
|
ed0c50a944a9af8588a9818b12c30db7a4e4bf1e | butterflow/butterflow | /14a.py | 326 | 3.5625 | 4 | import time,random
def ssort(l):
for i in range(len(l)-1):
min=i
for j in range(i+1,len(l)):
if l[j]<l[min]:
min=j
l[i],l[min]=l[min],l[i]
return l
x=[random.randint(1,10) for i in range(10)]
print(x)
start=time.time()
f=ssort(x)
end=time.time()
print("sorted array is:")
print(f)
print("time is:",(end-start))
|
54a3fb2e89336c11f56f1bcbdcdf951ffeb2d31e | butterflow/butterflow | /3b.py | 339 | 3.546875 | 4 | import time
import random
def isort(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
return arr
f=[random.randint(1,10)for i in range(10)]
print(f)
start=time.time()
isort(f)
end=time.time()
print("sorted array:")
print(f)
print("time taken is:",(end-start))
|
7dac5dd841c8049af6d8d9b441368ee3a72a6b84 | franckjay/GoodReadsGraph | /api/GoodReadsGraph.py | 13,944 | 3.546875 | 4 | import pandas as pd
import numpy as np
class Graph(object):
def __init__(self, reads):
"""
"""
# Edges in our graph
self.reads = reads
def _find_a_user(self, input_User, debug=False):
"""
Find a user in the graph N hops from an author in the
user's list of read authors:
"""
_author_list = input_User.author_list
if debug:
print ("Method: _find_N_user : `_author_list`: ", _author_list)
# Do we have any authors in the list?
_n_authors = len(_author_list)
if _n_authors > 0:
# Pick an Author. Any Author.
_reader_list = None
while _reader_list == None:
_next_author = _author_list[np.random.randint(_n_authors)] #Inclusive, random integer
if debug:
print ("Method: _find_N_user : `_next_author` : ", _next_author)
if len(_next_author.reader_list) > 1: # Is there anyone in this bucket?
_reader_list = _next_author.reader_list # Who reads this Author?
_next_User = None
while _next_User == None:
_choice = _reader_list[np.random.randint(len(_reader_list))]
if _choice != input_User:
_next_User = _choice # Make sure we do not pick ourselves
if debug:
print ("Method: _find_N_user : `_next_User`: ", _next_User)
return _next_User # We finally made a choice!
else:
return None
def _book2book(self, input_Book, N=3 , debug=False):
""" Sanity Checker:
Developer Function to quickly get similar, unpopular books
recommended that is not based on a User. Simply input a book,
go up the Author tree, and then find a random user, and their
unpopular book.
This is quicker, in theory, for testing out the predictions, as you
don't have to build a User + Read objects for the Graph.
"""
def _sort_tuple(tuple_val):
""" For sorting our unread list based on popularity
[(book1,popularity1),...,(bookn,popularityn)]
"""
return tuple_val[1]
out_recs = []
for i in range(N):
_reader_list = input_Book.reader_list
_len_rl = len(_reader_list)
_rand_User = _reader_list[np.random.randint(_len_rl)]
_list = [(book, book.popularity, rating) for book, rating in _rand_User.shelf
if rating > 4] #NB; No filtering on read books, as no input user.
_list = sorted(_list, key=_sort_tuple, reverse=False)
unpopular_book, popularity, rating = _list[0]
out_recs.append(unpopular_book)
return out_recs
def _find_a_book(self, input_User, two_hop=False, debug=False):
"""
Given a user, recommend an unpopular book:
1) Take an input_user, go to an Author node, grab another user that has
read that author.
2) Grab that User's book list and compare it to the input user.
"""
def _sort_tuple(tuple_val):
""" For sorting our unread list based on popularity
[(book1,popularity1),...,(bookn,popularityn)]
"""
return tuple_val[1]
if debug:
print ("Method: _find_a_book : `input_User`: ", input_User)
_next_User = self._find_a_user(input_User, debug=debug)
if two_hop:
try:
_two_hop = self._find_a_user(_next_User, debug)
_next_User = _two_hop if _two_hop != input_User else _next_User
except Exception as e:
if debug:
print ("Method: _find_a_book : Exception at `two_hop`: ", input_User, e)
if debug:
print ("Method: _find_a_book : `_next_User`: ", _next_User)
counter= 0
while counter < 100:
counter+=1
"""
First, let's see how many books this user has read that
the input_User has not AND is rated above 4 stars.
NB: We could also add a maximum popularity here, just in case!
This will form our set from which we can find unpopular books:
"""
try:
_unread_list = [(book, book.popularity, rating) for book, rating in _next_User.shelf
if book not in [_books for _books, _rating in input_User.shelf] and rating > 4]
_n_unread = len(_unread_list)
if debug:
print ("Method: _find_a_book : Length of the unread shelf: ", _n_unread)
except Exception as e:
print ("Method: _find_a_book : `_unread_list` threw an exception: ", _next_User, e)
"""
Now, we take our unsorted, unread list of books, and sort them
in ascending order. The first entry should be our best bet!
"""
try:
_unread_list = sorted(_unread_list, key=_sort_tuple, reverse=False)
if debug:
if _n_unread > 1:
print ("Method: _find_a_book : Most unpopular book title, popularity, and rating ",
_unread_list[0][0].book_id, _unread_list[0][1])
print ("Method: _find_a_book : Most popular book title and popularity ",
_unread_list[_n_unread-1][0].book_id, _unread_list[_n_unread-1][1])
else:
print ("Method: _find_a_book : Most unpopular book title and popularity ",
_unread_list[0][0].book_id, _unread_list[0][1])
except Exception as e:
if debug:
print ("Method: _find_a_book : `_unread_list` sorting threw an exception: ", e)
# So we may have found a good, rare book. Return it!
unpopular_book, popularity, rating = _unread_list[0]
if unpopular_book != None:
return unpopular_book
# Base case: We did not find any good books.
return None
def GrabNBooks(self, input_User, N=3, debug=False):
"""
Our main class to find three unpopular books. Relies on two helper classes:
_find_a_book: Grabs a rare books from a neighbor that reads similar books to you
_find_a_user: Finds the neighbor to a book from your collection!
If you enable two_hop = True in your calls, it can help preserve the privacy of your users,
as you really start to jump around the graph. Want more privacy? Enable more random jumps.
"""
if debug:
print ("Method: GrabThreeBooks : Beginning :", input_User.user_id)
RareBooks = []
counter = 0
while counter < 100:
"""
try:
_book = self._find_a_book(input_User, debug)
if _book != None:
RareBooks.append(_book)
except Exception as e:
if debug:
print ("Method: GrabThreeBooks : Exception = ", e)
"""
_book = self._find_a_book(input_User, debug=debug)
RareBooks.append(_book)
if len(RareBooks) == N:
return RareBooks
# Increase the counter so that we don't get stuck in a loop
else:
counter+=1
#Base case in case something goes wrong...
return None
class User(object):
def __init__(self,user_id):
self.user_id = user_id
self.shelf = [] # Books read
self.author_list = [] # Authors read
class Book(object):
def __init__(self, book_id, Author, ratings_5, popularity, image_url):
self.book_id = book_id
self.author = Author
self.author_id = Author.author_id
self.ratings_5 = ratings_5 # Number of people that rated the book a 5
self.popularity = popularity # What fraction of ratings does this book have?+
self.image_url = image_url
self.reader_list = [] #Users that read the book
def add_reader(self,User):
if User not in self.reader_list:
self.reader_list.append(User) # User read this book
class Author(object):
def __init__(self, author_id):
self.author_id = author_id
self.reader_list = [] #People who read the book
def add_reader(self,User):
if User not in self.reader_list:
self.reader_list.append(User) # User read this book
class Read(object):
def __init__(self, User, Book, Author, rating=None):
"""
The edge connecting User, Book, and Author nodes
"""
if Book not in User.shelf:
User.shelf.append((Book, rating)) # User read this book and rated it.
if Author not in User.author_list:
User.author_list.append(Author)
self.user = User
self.book = Book
self.author = Author
self.rating = rating # Optional
Book.add_reader(User)
Author.add_reader(User)
def BuildGraph():
"""
Now we use real data:
`uir` : user,item,rating data
`books`: meta information about each of the items (# of ratings, Author, etc.)
"""
uir = pd.read_csv("api/data/goodbooks-10k-master/ratings.csv")
books = pd.read_csv("api/data/goodbooks-10k-master/books.csv")
books = books[(books["language_code"] == "eng") | (books["language_code"] == "en-US")]
books["author_id"] = (books["authors"].astype("category")).cat.codes # Gives us an index
"""
Let's build a few versions of popularity: overall ratings, text review counts, and
fraction of all people that rated this book with 5-stars.
"""
books["popularity_ratings"] = books["ratings_count"]/np.sum(books["ratings_count"])
books["popularity_text_reviews"] = books["work_text_reviews_count"]/np.sum(books["work_text_reviews_count"])
books["popularity_ratings5" ]= books["ratings_5"]/np.sum(books["ratings_5"])
"""
Join these two dataframes together:
1) This filters out non-English books
2) Gives us book info as well as the Author
"""
uir = pd.merge(uir, books[["book_id", "original_title",
"author_id","popularity_ratings","ratings_5", "image_url"]], on=["book_id"])
"""
Let's build a catelog of Author objects first,
as they do not depend on any other objects in our graph.
"""
unique_authors = uir[["author_id"]].drop_duplicates()
unique_authors["Author"] = [Author(aid) for aid in unique_authors["author_id"]]
unique_authors = unique_authors.set_index("author_id", drop=True)
"""
Now we can do the same for the users:
"""
unique_users = uir[["user_id"]].drop_duplicates()
unique_users["User"] = [User(uid) for uid in unique_users["user_id"]]
unique_users = unique_users.set_index("user_id", drop=True)
"""
We can build a set of dictionaries for easy reference later
"""
user_dict = unique_users.to_dict("index")
author_dict = unique_authors.to_dict("index")
"""
There are a number of ways we could proceed now, depending on our
space and speed constraints. If we had memory limitations, we could
save our unique_users and unique_authors dataframes as Dictionaries,
then just call them whenever needed. I think for our relatively small
dataset, we could just join them to our original dataframe:
`uir = pd.merge(uir, unique_users, on=["user_id"])`
`uir = pd.merge(uir, unique_authors, on=["author_id"])`
and then process the Books inline with a list comprehension:
`uir["Book"] = [Book(bid, aid, rat, pop , url) for bid, aid, rat, pop , url
in uir[["book_id","Author","ratings_5","popularity_ratings","image_url"]].values]`
But I don't want to be too lazy here, so we will use the dictionary route:
"""
unique_books = uir[["book_id", "original_title", "author_id", "ratings_5", "popularity_ratings",
"image_url"]].drop_duplicates()
unique_books["Book"] = [Book(bid, author_dict[aid]["Author"], rat, pop, url) for bid, aid, rat, pop, url
in unique_books[
["book_id", "author_id", "ratings_5", "popularity_ratings", "image_url"]].values]
# Now that we have our Book objects, let's build it into a dictionary
_unique_books = unique_books.set_index("book_id", drop=True)
_unique_books = _unique_books.drop(["author_id", "ratings_5", "popularity_ratings", "image_url"],
axis=1) # Drop everything
book_dict = _unique_books.to_dict("index")
"""
We also need a title lookup for the User facing entries:
1) Key is a title (lower_case!)
2) Value is a Book `Object`
"""
_unique_titles = unique_books.copy()
_unique_titles["original_title"] = _unique_titles["original_title"].str.lower()
_unique_titles = _unique_titles.drop(["author_id", "book_id", "ratings_5", "popularity_ratings", "image_url"],
axis=1) # Drop everything
_unique_titles = _unique_titles.drop_duplicates("original_title").dropna()
_unique_titles = _unique_titles.set_index("original_title", drop=True)
titles_dict = _unique_titles.to_dict("index")
"""
We can finally build our graph by assembling
our collection of Read() objects and passing the
list to our Graph: `Read(user, book1, author1) : `
"""
read_list = [Read(user_dict[u]["User"], book_dict[b]["Book"], author_dict[a]["Author"], rating=int(r))
for u, b, a, r in uir[["user_id","book_id","author_id", "rating"]].values]
BigGraph = Graph(read_list)
return BigGraph, titles_dict
|
f615f86ee7df4aa30a9ce27e1d3667d9d6526600 | kclip/DSVGD | /data/create_pickled.py | 1,809 | 3.609375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pickle
"""
This file creates a binary file for MNIST or Fashion MNIST datasets for faster dataloading.
Please make sure to download either datasets from : http://yann.lecun.com/exdb/mnist/
or https://github.com/zalandoresearch/fashion-mnist
Code is used from https://www.python-course.eu/neural_network_mnist.php
"""
def main():
# Todo: Make sure that first column of your dataset is the label of the digit
data_path = "../../my_code/data/MNIST/" # Todo: Specify folder where mnist_train.csv and mnist_test.csv are located
train_data = np.loadtxt(data_path + "mnist_train.csv", delimiter=",")
test_data = np.loadtxt(data_path + "mnist_test.csv", delimiter=",")
# normalize pixel values in range [0.01, 1]
fac = 0.99 / 255
train_imgs = np.asfarray(train_data[:, 1:]) * fac + 0.01
test_imgs = np.asfarray(test_data[:, 1:]) * fac + 0.01
train_labels = np.asfarray(train_data[:, :1])
test_labels = np.asfarray(test_data[:, :1])
# uncomment to write binary files for fast loading of data
with open("../data/pickled_mnist.pkl", "bw") as fh:
data = (train_imgs,
test_imgs,
train_labels,
test_labels)
pickle.dump(data, fh)
# uncomment to read binary files
# with open("pickled_mnist.pkl", "br") as fh:
# data = pickle.load(fh)
# read train and test images and train and test labels
train_imgs = data[0]
test_imgs = data[1]
train_labels = data[2]
test_labels = data[3]
print(test_labels[1])
print(test_imgs[0])
plt.figure()
plt.imshow(test_imgs[np.random.randint(len(test_imgs))].reshape((28, 28)), cmap="Greys")
plt.show()
if __name__ == '__main__':
main()
|
d1349d0982af9e06c5e8c5aaa26b200497b22e3f | guokairong123/PythonBase | /DataStructure/list_demo1.py | 663 | 4.1875 | 4 | """
如果我们想生产一个平方列表,比如 [1, 4, 9...],使用for循环应该怎么写,使用列表推导式又应该怎么写呢?
"""
# list_square = []
# for i in range(1, 4):
# list_square.append(i**2)
# print(list_square)
#
# list_square2 = [i**2 for i in range(1, 4)]
# print("list_suqare2:", list_square2)
#
# list_square3 = [i**2 for i in range(1, 4) if i != 1]
# # for i in range(1, 4):
# # if i!=1:
# # list_square3.append(i**2)
# print(list_square3)
list_square4 = [i*j for i in range(1, 4) for j in range(1, 4)]
# for i in range(1, 4):
# for j in range(1, 4):
# list_square4.append(i*j)
print(list_square4) |
f014a82968e1b169cb8651be3c7ea313b99a3cf0 | guokairong123/PythonBase | /function/func_demo1.py | 449 | 4.0625 | 4 | """
默认参数
默认参数在定义函数的时候使用k=v的形式定义
调用函数时,如果没有传递参数,则会使用默认参数
"""
def func2(a=1):
print("参数a的值为:", a)
func2(2)
"""
关键字参数
在调用函数的时候,使用k=v的方式进行传参
在函数调用/定义中,关键字参数必须跟随在位置参数的后面
"""
def func3(b):
print("参数b的值为:", b)
func3(b=3)
|
384aee6c8f1024a4f96f325ec5542c46aa18e3b2 | BufteacEcaterina03/Rezolvare-problemelor-IF-WHILE-FOR | /problema4.ForIfWhile.py | 332 | 3.984375 | 4 | from fractions import Fraction
a=int(input("Introduceti numaratorul primei fractii: "))
b=int(input("Introduceti numitorul primei fractii: "))
x=int(input("Introduceti numaratorul fractiei a 2: "))
y=int(input("Introduceti numitorul fractiei a 2: "))
print(Fraction(a ,b) + Fraction(x,y))
print(Fraction(a,b) * Fraction(x,y)) |
27af3b1693096ea5caa291f637c4558a542c7265 | saltywalnut/CIT_SKP | /200919/mySort.py | 333 | 3.9375 | 4 | list = [3,72,85,49,1,65,23,25]
def sortlist (list):
(list[y]) = length
(list[x]) = 1
length = len(list)
while length > 0:
if (list[x]) > (list[y]):
list2.append (list[x])
print (list[x])
else:
list2.append (list[y])
print (list[y])
length -= 1
|
467389de2d02b08620e8923742b99f9de2001660 | saltywalnut/CIT_SKP | /200627/number.py | 323 | 4.09375 | 4 | # number = 178 # 1 - 3000
# # "odd" "even"
#
# even = (number%2 == 0)
#
# odd = (number%2 == 1)
#
# if (even):
# print ("even")
#
# if (odd):
# print ("odd")
num = 180
if num%2 == 0 :
print ("even")
if num > 1000:
print("K")
else:
print ("odd")
if num%2 == 0 and num>1000 :
print ("even")
|
214ff1fd25d4f024d9730ee729306eecd325b796 | sethsamelson/checkers | /checkers.py | 558 | 3.90625 | 4 |
def display(board):
for row in board:
print row
def initial_board():
top = [['x' if col % 2 == row % 2 else ' '
for col in range(8)]
for row in range(3)]
middle = [[' '] * 8 for x in range(2)]
bottom = [['o' if col % 2 != row % 2 else ' '
for col in range(8)]
for row in range(3)]
board = top + middle + bottom
return board
def move(board, row, col, row2, col2):
board[row2][col2] = board[row][col]
board[row][col] = ' '
board = initial_board()
display(board)
|
92965acf135833d0aa8e4066ccedaa91a9958399 | Berkmann18/Asteroid | /Vector.py | 4,071 | 4.5 | 4 | """
Vector.py
The module that implements vectors and all the necessary methods that comes with vectors.
"""
import math
class Vector:
"""
The Vector class
"""
# Initialiser
def __init__(self, p=(0, 0)):
self.x = p[0]
self.y = p[1]
@property
def __str__(self):
"""
Returns a string representation of the vector
"""
return "(" + str(self.x) + "," + str(self.y) + ")"
def __eq__(self, other):
"""
Tests the equality of this vector and another
"""
return self.x == other.x and self.y == other.y
def __ne__(self, other):
"""
Tests the inequality of this vector and another
"""
return not self.__eq__(other)
def get_pt(self):
"""
Returns a tuple with the point corresponding to the vector
"""
return (self.x, self.y)
def copy(self):
"""
Returns a copy of the vector
"""
vct = Vector()
vct.x = self.x
vct.y = self.y
return vct
def mult(self, k):
"""
Multiplies the vector by a scalar
"""
self.x *= k
self.y *= k
return self
def div(self, k):
"""
Divides the vector by a scalar
"""
self.x /= k
self.y /= k
return self
def normalise(self):
"""
Normalizes the vector
"""
vct = math.sqrt(self.x**2 + self.y**2)
self.x /= vct
self.y /= vct
@property
def get_normalised(self):
"""
Returns a normalized version of the vector
"""
return [self.x / math.sqrt(math.pow(self.x, 2) + math.pow(self.y, 2)),
self.y / math.sqrt(math.pow(self.x, 2) + math.pow(self.y, 2))]
@property
def get_normal(self):
"""
Returns the normal of the vector
"""
return Vector(self.get_normalised())
def add(self, other):
"""
Vector addition
"""
self.x += other.x
self.y += other.y
return self
def sub(self, other):
"""
Vector substraction
"""
self.x -= other.x
self.y -= other.y
return self
def zero(self):
"""
Reset to the zero vector
"""
self.x = 0
self.y = 0
return self
def negate(self):
"""
Negates the vector (makes it point in the opposite direction)
"""
self.x = -self.x
self.y = -self.y
return self
def dot(self, other):
"""
Scalar/dot product
"""
return self.x*other.x + self.y*other.y
def length(self):
"""
Returns the length of the vector
"""
return math.sqrt(self.length_sq())
def length_sq(self):
"""
Returns the squared length of the vector
"""
return self.x**2 + self.y**2
def reflect(self, normal):
"""
Reflection on a normal
"""
norm = normal.copy
norm.mult(2*self.dot(normal))
self.sub(norm)
return self
def angle(self, other):
"""
Returns the angle between this vector and the other
"""
vect_a = math.sqrt(self.x**2 + self.y**2)
vect_b = math.sqrt(math.pow(other.x, 2) + math.pow(other.y, 2))
return math.acos((self.x*other.x+self.y*other.y)/(vect_a*vect_b))
def draw(self, canvas, pt, clr):
"""
Draw the vector from a particular point
"""
canvas.draw_line(pt, (pt[0]+self.x, pt[1]+self.y), 1, clr)
def rot(self, theta):
"""
Rotates the vector by theta radians
"""
self.x = self.x*math.cos(theta)-self.y*math.sin(theta)
self.y = self.x*math.sin(theta)+self.y*math.cos(theta)
return self
|
3f754822eb9704063bf40d3309afc58e13bedec7 | nivedita/pylsm | /ModelSpace.py | 2,203 | 3.765625 | 4 | """
Classes and methods for representing neurons in some spatial configuration
Author: Sina Masoud-Ansari
Classes:
Point3D
Cuboid3D
"""
import math
import unittest
class Point3D:
"""A point in 3D Euclidian space"""
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __eq__(self, other):
return ( isinstance(other, self.__class__)
and self.__dict__ == other.__dict__ )
def __ne__(self, other):
return not self.__eq__(other)
def distance3D(i, j):
"""Distance between two 3D euclidean points"""
dx = i.x - j.x
dy = i.y - j.y
dz = i.z - j.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
class Cuboid3D:
"""Class for 3D Euclidean space"""
def __init__(self, x, y, z, offset=Point3D(0,0,0)):
self.x = x
self.y = y
self.z = z
self.size = x * y * z
self.offset = offset
def pointFrom1D(self, i):
"""Find the 3D coordinates of a 1D point"""
x = i % self.x
y = (i / self.x) % self.y
z = i / (self.x * self.y)
ox = self.offset.x
oy = self.offset.y
oz = self.offset.z
return Point3D(x+ox, y+oy, z+oz)
"""
Unit Tests
"""
class TestPoint3D(unittest.TestCase):
def test_eq(self):
"""Test equality between Point3D objects"""
self.assertEquals(Point3D(1,2,3), Point3D(1,2,3))
self.assertNotEquals(Point3D(0,1,2), Point3D(1,2,3))
class TestSpace3D(unittest.TestCase):
def setUp(self):
self.space = Cuboid3D(2,3,2)
def test_size(self):
"""Test that size of space is correct"""
self.assertEqual(self.space.size, 12)
def test_pointFrom1D(self):
"""Test that 1D point maps correctly to a 3D point in the space"""
self.assertEqual(self.space.pointFrom1D(14), Point3D(0,1,2))
def test_distance3D(self):
"""Test that distance between two points is correct"""
i = self.space.pointFrom1D(10)
j = self.space.pointFrom1D(3)
self.assertEqual(distance3D(i, j), math.sqrt(3))
def test_distance3DWithOffset(self):
"""Test that distance between two points in two model spaces is correct"""
offset = Point3D(5,0,0)
adjacent = Cuboid3D(2,3,2, offset=offset)
i = self.space.pointFrom1D(10)
j = adjacent.pointFrom1D(3)
self.assertEqual(distance3D(i, j), math.sqrt(38))
if __name__ == '__main__':
unittest.main()
|
724087e634a6689324dd4bcf07657c19fb2ffaa4 | NehemiahLimo/politicoapp-api | /app/api/v1/models/office_model.py | 557 | 3.59375 | 4 | offices = []
class Office:
"""A method to initialize the office resource"""
def __init__(self, office_id, office_type, office_name):
self.id = office_id
self.type = office_type
self.name = office_name
@classmethod
def create_office(cls, office_id,office_type, office_name ):
"""A method to create a new office"""
new_offfice = {
"id" : office_id,
"type" : office_type,
"name": office_name
}
offices.append(new_offfice)
return new_offfice |
2c7148695d3d0b390d1e85032f9f738b9e666b14 | bryanwspence/-6.00.1x---Week-05 | /hand-scratch.py | 423 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 21 09:12:53 2020
@author: bryan.spence
"""
def __str__(self):
'''
Display a string representation of the hand.
'''
output = ''
hand_keys = sorted(self.hand.keys())
for letter in hand_keys:
for j in range(self.hand[letter]):
output += letter
return output |
c38dcf8d5dfb399ee45ee0c87a4e0ec0444f7de7 | amoghnayak07/Batman1 | /chetana.py | 165 | 3.625 | 4 | a = input()
b = list(a)
c = []
for i in b:
if i.isupper():
j = i.lower()
c.append(j)
if i.islower():
k = i.upper()
c.append(k)
d = ''.join(c)
print(d) |
b8305ebd207750c369fd7c69dcad0f0c16976c7d | amoghnayak07/Batman1 | /11.py | 538 | 3.515625 | 4 | import csv
c = []
def add():
name = input("Enter name: ")
print("Optios: 1.CS\n2.Google it\n3.Treasure hunt")
choice = int(input("Enter Chice: "))
if choice == 1:
c[0:] = [name, 'CS']
elif choice == 2:
c[0:] = [name, 'Google it']
elif choice == 3:
c[0:] = [name, 'Treasure Hunt']
with open ('New', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile)
spamwriter.writerow(c)
def see():
with open('New', newline='') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
print(','.join(row))
|
adc774ab64a9d573f3b7e40059c080267a9088f5 | mrgrant/LeetCode | /729.my-calendar-i.py | 724 | 3.59375 | 4 | #
# @lc app=leetcode id=729 lang=python
#
# [729] My Calendar I
#
import bisect
# @lc code=start
class MyCalendar(object):
def __init__(self):
self.arr = [[float("-inf"), float("-inf")], [float("inf"), float("inf")]]
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
idx = bisect.bisect(self.arr, [start, end])
if start < self.arr[idx-1][1] or end > self.arr[idx][0]:
return False
bisect.insort(self.arr, [start, end])
return True
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
# @lc code=end
|
ef1045c23f96eeb0c8543c5ec49e7449243b618a | mrgrant/LeetCode | /528.random-pick-with-weight.py | 878 | 3.515625 | 4 | #
# @lc app=leetcode id=528 lang=python
#
# [528] Random Pick with Weight
#
# @lc code=start
import random
class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
s = sum(w)
for i in range(1, len(w)):
w[i] = w[i] + w[i-1]
self.rate = [val*1.0/s for val in w]
def bin_search(self, target):
lo = 0
hi = len(self.rate)
while lo < hi:
mid = (lo + hi) // 2
if self.rate[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def pickIndex(self):
"""
:rtype: int
"""
return self.bin_search(random.random())
# Your Solution object will be instantiated and called as such:
# obj = Solution(w)
# param_1 = obj.pickIndex()
# @lc code=end
|
b44e15cf6d93cef163890f0099b2e59b262994d6 | mrgrant/LeetCode | /838.push-dominoes.py | 1,412 | 3.625 | 4 | #
# @lc app=leetcode id=838 lang=python
#
# [838] Push Dominoes
#
# @lc code=start
class Solution(object):
def pushDominoes(self, dominoes):
"""
:type dominoes: str
:rtype: str
"""
stack = []
res = []
dominoes = list(dominoes)
while dominoes:
n = dominoes.pop(0)
stack.append(n)
if n == "L":
if stack[0] != "R":
res += ["L" for _ in range(len(stack))]
stack = []
elif stack[0] == "R":
i = 0
j = len(stack) - 1
while i < j:
stack[i] = "R"
stack[j] = "L"
i += 1
j -= 1
res += stack
stack = []
elif n == "R":
if stack[0] == ".":
res += stack[:len(stack)-1]
elif stack[0] == "R":
res += ["R" for _ in range(len(stack)-1)]
stack = ["R"]
if stack:
if stack[0] == "R":
res += ["R" for _ in range(len(stack))]
else:
res += stack
return "".join(res)
if __name__ == "__main__":
obj = Solution()
obj.pushDominoes(".L.R...LR..L..")
# @lc code=end
|
9a94c82c32643f2f28d45af7a987a931fe356de8 | DarkC35/AdventOfCode2020 | /19/19.py | 634 | 3.578125 | 4 | from timeit import default_timer as timer
start = timer()
with open("input.txt") as file:
adapters = sorted([int(line) for line in file])
current_jolts = 0
count_1_jolt_difference = 0
count_3_jolt_difference = 0
for adapter in adapters:
if adapter - current_jolts == 1:
count_1_jolt_difference += 1
elif adapter - current_jolts == 3:
count_3_jolt_difference += 1
else:
print(adapter - current_jolts)
current_jolts = adapter
count_3_jolt_difference += 1
result = count_1_jolt_difference * count_3_jolt_difference
end = timer()
print("Result: ", result)
print("Time (in sec): ", end-start)
|
d7d0ad97fab694f428ceaec389b3b9d3042f9e4f | DarkC35/AdventOfCode2020 | /04/04.py | 595 | 3.609375 | 4 | import re
from timeit import default_timer as timer
def validate_password(password, letter, pos1, pos2):
return (password[pos1-1] == letter or password[pos2-1] == letter) and password[pos1-1] != password[pos2-1]
start = timer()
count = 0
reg_obj = re.compile(r'(\d+)-(\d+) (.): (.+)')
with open("input.txt", "r") as file:
for line in file:
result = reg_obj.search(line)
if validate_password(result.group(4), result.group(3), int(result.group(1)), int(result.group(2))):
count += 1
end = timer()
print("Count: ", count)
print("Time (in sec): ", end-start)
|
0e1600eb8c048b1cdf2a0d445b3dba9a44ccec96 | vrushti-mody/Leetcode-Solutions | /Plus_One.py | 791 | 3.5 | 4 | # Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
# The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
# You may assume the integer does not contain any leading zero, except the number 0 itself.
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
if digits[len(digits)-1]<9:
digits[len(digits)-1]=digits[len(digits)-1]+1
else:
i=len(digits)-1
while(digits[i]==9):
digits[i]=0
i=i-1
if i==-1:
return [1]+digits
else:
digits[i]=digits[i]+1
return digits
|
98b35be936cb3686fdb40908832dd1376bf98314 | vrushti-mody/Leetcode-Solutions | /Angle_Between_Hands_of_a_Clock.py | 282 | 3.859375 | 4 | # Given two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
return min(abs(30*hour-5.5*minutes),360-abs(30*hour-5.5*minutes))
|
cc681899f5ec8876fbe9cccf6e3c457ec6551372 | vrushti-mody/Leetcode-Solutions | /Odd_Even_Linked_List.py | 1,017 | 4.03125 | 4 | # Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
# You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head == None or head.next ==None:
return head
head1=head
head2,head2_beg= head.next,head.next
while head2.next!= None and head2.next.next!= None:
head1.next = head2.next
head2.next = head2.next.next
head1 = head1.next
head2 = head2.next
if head2.next!=None:
head1.next = head2.next
head1 = head1.next
head1.next = head2_beg
head2.next = None
return head
|
6486d49174a3399a40bcbadd8eb58ab3d53400e4 | vrushti-mody/Leetcode-Solutions | /Island_Perimeter.py | 1,171 | 3.78125 | 4 | #You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
#Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
#The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
count=0
for i in range(0,len(grid)):
for j in range(0,len(grid[0])):
if(grid[i][j]==1):
if j+1>=len(grid[0]) or grid[i][j+1]==0 :
count=count+1
if (j-1<0 or grid[i][j-1]==0 ):
count=count+1
if( i+1>=len(grid) or grid[i+1][j]==0 ):
count=count+1
if (i-1<0 or grid[i-1][j]==0 ):
count=count+1
return count
|
25b431ea6e4b3c2292fe3a6d6a8fca73353ba189 | vrushti-mody/Leetcode-Solutions | /Count_Square_Submatrices_with_All_ones.py | 846 | 3.578125 | 4 | # Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
# Initialize count variable
N=len(matrix)
M= len(matrix[0])
a=matrix
count = 0
for i in range(1, N):
for j in range(1, M):
# If a[i][j] is equal to 0
if (a[i][j] == 0):
continue
# Calculate number of
# square submatrices
# ending at (i, j)
a[i][j] = min([a[i - 1][j],
a[i][j - 1], a[i - 1][j - 1]])+1
# Calculate the sum of the array
for i in range(N):
for j in range(M):
count += a[i][j]
return count
|
e4c2c56cf9247fb7d3dac124e1a5a3bff1ab0d4d | vrushti-mody/Leetcode-Solutions | /Uncrossed_Lines.py | 1,446 | 3.640625 | 4 | # We write the integers of A and B (in the order they are given) on two separate horizontal lines.
# Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that:
# A[i] == B[j];
# The line we draw does not intersect any other connecting (non-horizontal) line.
# Note that a connecting lines cannot intersect even at the endpoints: each number can only belong to one connecting line.
# Return the maximum number of connecting lines we can draw in this way.
class Solution:
def maxUncrossedLines(self, A: List[int], B: List[int]) -> int:
dp = [[0]*len(A) for _ in range(len(B))]
dp[0][0] = 1 if A[0] == B[0] else 0
for index_i in range(1, len(dp)):
dp[index_i][0] = dp[index_i-1][0]
if A[0] == B[index_i]:
dp[index_i][0] = 1
for index_j in range(1, len(dp[0])):
dp[0][index_j] = dp[0][index_j-1]
if B[0] == A[index_j]:
dp[0][index_j] = 1
for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if A[index_j] == B[index_i]:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1] + 1, max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
else:
dp[index_i][index_j] = max(dp[index_i-1][index_j-1], max(dp[index_i-1][index_j], dp[index_i][index_j-1]))
return dp[len(B)-1][len(A)-1]
|
f493541c59e1ff3ab549396d28dc90ff4c46927e | vikram789/my-app | /66-PlusOne.py | 1,116 | 3.984375 | 4 | """
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Input: [9,9,9]
Output: [1,0,0,0]
Explanation: The array represents the integer 123.
"""
def findOP(myArr):
carry = 0
for i in reversed(range(0,len(myArr))):
if myArr[i] < 9 and carry == 0:
myArr[i]+=1
print(myArr)
return True
elif myArr[i] < 9 and carry == 1:
myArr[i]+=carry
print(myArr)
return True
else:
myArr[i] = 0
carry = 1
# Driver code
myArr= [8,9,9]
findOP(myArr)
"""
def findOP(myArr):
myStr = ''.join(str(x) for x in myArr)
print(myStr)
myInt=int(myStr)+1
print(myInt)
# Driver code
myArr= [8,9,9]
findOP(myArr)
""" |
d10dbb297992ddbe63bed197f6ae8c90c83f3328 | vikram789/my-app | /02-add_two_numbers.py | 1,636 | 3.921875 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
"""
def addTwoNo(arr1,arr2):
length=max(len(arr1),len(arr2))
arr3=[]
carry = 0
for i in range (0 , length):
sum=arr1[i] + arr2[i] + carry
remainder=sum%10
arr3.append(remainder)
if (sum > 9):
carry=1
else:
carry=0
if carry == 1:
arr3.append(1)
print (arr3)
#Driver code
arr1=[2 , 4 , 3]
arr2=[9 , 6 , 9]
addTwoNo(arr1,arr2)
# above solution will not work if array is diff size. to make it work, just append 0 in the end to make it equal
"""
Above problem has issue
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
carry = 0
root = n = ListNode(0)
while l1 or l2 or carry:
v1 = v2 = 0
if l1:
v1 = l1.val
l1 = l1.next
if l2:
v2 = l2.val
l2 = l2.next
carry, val = divmod(v1+v2+carry, 10)
n.next = ListNode(val)
n = n.next
return root.next
Time complexity : O(\max(m, n))O(max(m,n))
""" |
3aff592b0440188b256532c0a4fd38e518f70137 | vikram789/my-app | /01-sum2.py | 1,589 | 4.09375 | 4 | """
STATEMENT
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
CLARIFICATIONS
- What happens when there is no solution? Assume solution exists.
- Can the list be empty? No.
- Is the list sorted? Not necessarily.
EXAMPLES
[2, 7, 11, 15], 9 -> [0,1]
def findSum(arr,t):
n = len(arr)
found = True
for i in range (0, n-1):
for j in range (i+1, n):
if (arr[i] + arr[j] == t):
print(arr[i], arr[j])
found = True
# Driver code
arr = [0, -4, 2, -3, 4]
t = 6
findSum(arr,t)
"""
# Using dictionaries O(n) complexity
def findSum(nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
print(i)
if nums[i] in buff_dict:
print (buff_dict[nums[i]], i)
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
# Driver code
arr = [0, -4, 2, -3, 4]
t = -7
findSum(arr,t)
"""
def findTriplets(arr):
n = len(arr)
found = True
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if (arr[i] + arr[j] + arr[k] == 0):
print(arr[i], arr[j], arr[k])
found = True
# If no triplet with 0 sum
# found in array
if (found == False):
print(" not exist ")
# Driver code
arr = [0, -4, 2, -3, 4]
findTriplets(arr)
""" |
acf63f2b22309621e2c7a642141a37680ebea5a9 | crazywiden/590PZ-Project | /circleCatGame/utils.py | 265 | 3.65625 | 4 | from random import randint
def generate_random_locations(n, loc_dict):
# within a board n*n
# generate a random valid location
while True:
i = randint(0,n-1)
j = randint(0,n-1)
if (i,j) not in loc_dict:
return (i,j)
|
59a5f763b58681705c74852bdef33c798503cf8f | HanySedarous/Python-Challenge | /Budget_Data.py | 1,514 | 3.59375 | 4 | import csv
with open('C:/Hany/Data Analyst Course/paython/Python-Challenge/budget_data.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
next(spamreader)
total = 0
month = []
loses = []
earns = []
biggest_month =""
lowest_month =""
highest_earm=0
lowest_lost=0
for row in spamreader:
total = total + int(row[1])
month.append(row[0])
if 0 > int(row[1]):
loses.append(int(row[1]))
else:
earns.append(int(row[1]))
if float(row[1]) > highest_earm:
highest_earm = float(row[1])
biggest_month = row[0]
if float(row[1]) < lowest_lost:
lowest_lost = float(row[1])
lowest_month = row[0]
#print(float(row[1]) )
total_month = (len((month)))
avg = total/total_month
with open('C:/Hany/Data Analyst Course/paython/Python-Challenge/Analysis/Financial_Analysis.txt','w') as f:
f.write("Budget Data\n")
f.write("Financial Analysis\n")
f.write("----------------------------\n")
f.write("Total Months: "+ str(total_month)+"\n")
f.write("Total: $"+ str(total)+"\n")
f.write("Average Change: $"+ str(avg)+"\n")
f.write("Greatest Increase in Profits: "+biggest_month+" ($"+
str(highest_earm)+")\n")
f.write("Greatest Decrease in Profits: "+lowest_month+" ($"+
str(lowest_lost)+")\n")
f.write("```\n") |
8a1894901e9aa4f122719e3215bab2e2f12369b2 | imakin/cloaked-octo-ninja | /Koin/Peluang/main.py | 775 | 3.578125 | 4 | #!/usr/bin/env python3
import sys
def echo(s):
sys.stdout.write(s)
a = 1
b = 5
c = 10
#~ a = 90
#~ b = 160
#~ c = 230
ax = 27
bx = 0
cx = 0
hasil = []
#~ hasilline = []
while(ax>0):
if (a*ax + b*bx + c*cx)==a*27:
#~ print(a,ax,' ',b,bx,' ',c,cx)
hasilline = [a,ax,b,bx,c,cx]
hasil.append(hasilline)
cx = 0
ax -= int(b/a)
bx += 1
t = bx
while (bx>=0 and ax>0):
if (a*ax + b*bx + c*cx)==a*27:
#~ print(a,ax,' ',b,bx,' ',c,cx)
hasilline = [a,ax,b,bx,c,cx]
hasil.append(hasilline)
bx -= int(c/b)
cx += 1
bx = t
print (hasil)
#-- checkout how real weight affects
k1 = 90
k2 = 450
k3 = 900
for h in hasil:
a = h[0]
ax = h[1]
b = h[2]
bx = h[3]
c = h[4]
cx = h[5]
print(a,ax,' ',b,bx,' ',c,cx)
print('real weight ',k1*ax + k2*bx + k3*cx)
|
f7bca8a3e3672c7f531faa89cc6ca7d16eeb2f29 | alejandro123210/Deep-learning-Projects | /diabetesPrediction/diabetesPrediction.py | 3,012 | 3.84375 | 4 | # TensorFlow and tf.keras
# imports everything needed
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
# sets random seed to 7 for reproducing the same results every time
numpy.random.seed(7)
# loads the dataset for the pima indians, found in ./data
dataset = numpy.loadtxt("./data/pima-indians-diabetes.csv", delimiter=",")
# slices data:
# the first : means all rows, the 0:8 means columns 0-8, which means 8th column gets ignored
X = dataset[:,0:8]
# the first : means all rows, the 8 means ONLY the 8th column, in other words, the output.
Y = dataset[:,8]
# creates model layer by layer
# model type, Sequential
model = Sequential()
# adds the first layer (Dense means that the layers are fully connected, every node connects to every node)
# The 12 means 12 neurons, input dim means 8 inputs (one for each part of the data) and activation is recitifier, meaning
# that the layer will generalized based on a straight line?
model.add(Dense(12, input_dim=8, activation='relu'))
# this adds a second Dense layer, with 8 neurons, and the same recitifier activation
model.add(Dense(8, activation='relu'))
# this is the final layer, so only 1 neuron, because there is a binary answer if someone has diabetes
# the activation for this layer is sigmoid, this is a function that only outputs an answer between 0 and 1, making it a good
# activation function for specifically predictions, considering something can't have a 110% chance of happening.
model.add(Dense(1, activation='sigmoid'))
# This sets up the model to be run efficiently on a computer depending on hardware, so this is the part that optimizes
# using Tensorflow.
# It's important to define the kind of loss used for optimal predictions, in this case,
# the loss in this model is lograithmic, defined as crossentropy
# Adam will be used as the gradient descent algorithm primarily because it's efficient
# Finally, because this problem is classification, accuracy is the best metric to measure.
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# This fits the data to the model in order for the model to be trained,
# epochs is the amount of iterations through the dataset while
# batch size is the number of datapoints looked at before the weights are changed
# finally, verbose is just the progress bar.
model.fit(X,Y, epochs=15, batch_size=10, verbose=2)
# scores is equal to the evaluation of the models predictions (Y) from the data (X)
scores = model.evaluate(X,Y)
# this prints what's shown in the console, in other words, the accuracy
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
# # predictions is the model's predictions
# predictions = model.predict(X)
# # rounded is equal to the rounded version of predictions since it used the sigmoid function,
# # rounded is always either 0 or 1
# rounded = [round(x[0]) for x in predictions]
# # this prints the predictions
# print(rounded) |
c37896119d527ccf86921be8cb0bf27a1d502e6b | jackdreinhardt/AI-Project-2 | /src/convert2CNF.py | 11,940 | 3.84375 | 4 | from globals import *
class convert2CNF:
@staticmethod
def CNF(prop):
'''
CNF() transforms a sentence that is in propositional logic into its conjunctive normal form (CNF)
Specifically it resolves biconditionals (<->) and implications (->),
uses De Morgan's law and finally distributes or (v) over and (^) to derive the CNF
'''
prop = "(" + prop + ")"
while prop.find(BICONDITIONAL) != -1:
# print("Solve BICONDITIONAL:")
prop = convert2CNF.solveBiconditional(prop)
# print("Transformed: " + prop)
while prop.find(IMPLIES) != -1:
# print("Solve IMPLICATION:")
prop = convert2CNF.solveImplication(prop)
# print("Transformed: " + prop)
# =============================================================================
# for c in range(len(prop)-1):
# if prop[c] == NOT and prop[c+1] == "(":
# print("Solve DEMORGAN")
# prop = convert2CNF.deMorgan(prop, c)
# print("Transformed: " + prop)
# =============================================================================
c = 0
while c < len(prop):
if prop[c] == NOT and prop[c+1] == "(":
# print("Solve DEMORGAN:")
prop = convert2CNF.deMorgan(prop, c)
prop = list(prop)
c = 0
while c < len(prop):
if prop[c] == NOT and prop[c+1] == NOT:
del prop[c]
del prop[c]
c = -1
c += 1
prop = "".join(prop)
# print("Transformed: " + prop)
c = 0
c += 1
prop = list(prop)
c = 0
while c < len(prop):
if prop[c] == NOT and prop[c+1] == NOT:
del prop[c]
del prop[c]
c = -1
c += 1
prop = "".join(prop)
# print("Solve DISTRIBUTIONS:")
prop = convert2CNF.or_over_and(prop)
# print("Transformed: " + prop)
while prop[0] == '(' and prop[len(prop)-1] == ')':
prop = prop[1:len(prop)-1]
return '(' + prop + ')'
#
# while(convert2CNF.detect_distribution(prop,OR)):
# # print("Solve DISTRIBUTIONS:")
# prop = convert2CNF.or_over_and(prop)
# # print("Transformed: " + prop)
# prop = list(prop)
# c = 0
# while c < len(prop):
# if prop[c] == NOT and prop[c+1] == NOT:
# del prop[c]
# del prop[c]
# c = -1
# c += 1
# prop = "".join(prop)
#
# return prop
# =============================================================================
# p1= convert2CNF.convert_to_cnf("(p<->(q^r))")
# p2= convert2CNF.convert_to_cnf("(p->r)")
# p3= convert2CNF.convert_to_cnf("(p<->q)")
# p4= convert2CNF.convert_to_cnf("rv(p->q)")
# p5 = convert2CNF.convert_to_cnf(prop)
# =============================================================================
'''
divideSentence() is used to resolve biconditionals and implications.
It splits the sentence in propositional logic into three parts.
The part that needs to be transformed to derive the CNF,
and everything to the left and right to that part, that is not affected by the changes in this step.
'''
@staticmethod
def divideSentence(prop, idx):
op_position = idx
openPar = 1
if idx != -1:
while idx >= 0:
idx -= 1
if prop[idx] == "(":
openPar -= 1
if openPar == 0:
left = prop[0:idx]
middleStart = idx
break
if prop[idx] == ")":
openPar += 1
idx = op_position
openPar = 1
while idx < len(prop)-1:
idx += 1
if prop[idx] == ")":
openPar -= 1
if openPar == 0:
right = prop[idx+1:len(prop)]
middleEnd = idx
break
if prop[idx] == "(":
openPar += 1
middlePart = prop[middleStart+1:middleEnd]
return left, middlePart, right
'''
Biconditionals (p<->q) become implications (p->q)^(q->p)
'''
@staticmethod
def solveBiconditional(prop):
idx = prop.find(BICONDITIONAL)
left, middlePart, right = convert2CNF.divideSentence(prop, idx)
middlePart = middlePart.split("<->",1)
cnf = str("(" + middlePart[0] + IMPLIES + middlePart[1] + ")" + AND + "(" + middlePart[1] + IMPLIES + middlePart[0] + ")")
prop = str(left + cnf + right)
return prop
'''
Implications (p->q) become (~pvq)
'''
@staticmethod
def solveImplication(prop):
idx = prop.find(IMPLIES)
left, middlePart, right = convert2CNF.divideSentence(prop, idx)
middlePart = middlePart.split("->", 1)
cnf = str("(" + NOT + middlePart[0] + OR + middlePart[1] + ")")
prop = left + cnf + right
return prop
# =============================================================================
# def deMorgan(prop, c):
# left, middlePart, right = convert2CNF.divideSentence(prop, c+1)
# print("left = " + left)
# print("middlePart = " + middlePart)
# print("right = " + right)
# idx = 2
# openPar = 0
# while idx <= len(middlePart):
# if middlePart[idx] == "(":
# openPar += 1
# elif middlePart[idx] == ")":
# openPar -= 1
# if openPar == 0:
# if middlePart[idx] == AND:
# leftString = middlePart[2:idx]
# print("leftString: " + leftString)
# rightString = middlePart[idx+1:len(middlePart)]
# print("rightString: " + rightString)
# middlePart = NOT + leftString + OR + NOT + rightString
# break
# elif middlePart[idx] == OR:
# leftString = middlePart[2:idx]
# print("leftString: " + leftString)
# rightString = middlePart[idx+1:len(middlePart)]
# print("rightString: " + rightString)
# middlePart = NOT + leftString + AND + NOT + rightString
# break
# idx += 1
# prop = left + "((" + middlePart + ")" + right
# return prop
# =============================================================================
'''
De Morgans law transforms ~(p^q) into (~pv~q) (and other De Morgan rules)
'''
#~((p^q)vt)
@staticmethod
def deMorgan(prop, idx):
# print(prop)
prop = list(prop)
del prop[idx]
del prop[idx]
# print("".join(prop))
openPar = 0
if prop[idx] == "(":
prop.insert(idx, NOT)
idx += 1
while idx < len(prop):
# print(prop[idx])
# print("oP:", openPar)
if prop[idx] == "(":
openPar += 1
#print(idx)
elif prop[idx] == ")":
openPar -= 1
elif openPar == 0:
if prop[idx] == AND:
prop[idx] = OR
idx += 1
continue
elif prop[idx] == OR:
prop[idx] = AND
idx += 1
continue
elif prop[idx] == "(" or prop[idx] == ")":
idx += 1
continue
elif prop[idx] == NOT and prop[idx+1] != "(" :
idx += 1
continue
prop.insert(idx, NOT)
idx += 1
if openPar == -1:
break
idx += 1
prop = "".join(prop)
return prop
@staticmethod
def or_over_and(prop):
while(convert2CNF.detect_distribution(prop,OR)!=-1):
idx = convert2CNF.detect_distribution(prop,OR)
strings = convert2CNF.divide(prop,idx,OR)
prop = convert2CNF.distribution(strings[0],strings[1],strings[2],OR,AND)
return prop
@staticmethod
def detect_distribution(prop, operator):
in_clause=0
int_operator=[]
#add all distributions to array
for s in range(len(prop)):
if(in_clause <= 1 and prop[s] == operator and (prop[s-1]==')' or prop[s+1]=='(') ):
int_operator.append(s)
idx=-1
last=0
#find the distribution sign
for op in int_operator:
m=op-1
openPar=0
while(m>-1):#All characters up to thenext and sign are important
if(prop[m]=='('):
openPar+=1
elif(prop[m]==')'):
openPar-=1
if openPar>last:
idx=op
m-=1
last=openPar
return idx
@staticmethod
def divide(prop,index,operator):
i_start =0
i_end = len(prop)
m=index-1
openPar=0
while(m>-1):#All characters up to thenext and sign are important
if (prop[m]==(AND) or prop[m]=='(') and openPar <=0:
i_start=m
break
elif(prop[m]=='('):
openPar-=1
elif(prop[m]==')'):
openPar+=1
m-=1
m=index+1
openPar=0
while(m<len(prop)):#All characters up to thenext and sign are important
if (prop[m]==(AND) or prop[m] ==')') and openPar <=0:
i_end=m
break
elif(prop[m]=='('):
openPar+=1
elif(prop[m]==')'):
openPar-=1
m+=1
#set substrubgs
if prop[i_start]=='(':
i_start+=1
left= prop[:i_start]
right= prop[i_end:]
middlePart = prop[i_start:i_end]
return left,middlePart,right
@staticmethod
def distribution(left,middlePart,right, op1 , op2):
output=''
middlePart = middlePart.replace("(","")
middlePart = middlePart.replace(")","")
#print(middlePart)
if(middlePart.find(op2)==-1):
return left+'('+middlePart+')'+right
arguments = middlePart.split(op1,1)
leftPart = arguments[0].split(op2)
rightPart = arguments[1].split(op2)
new_middle_part = ["" for x in range(len(leftPart*len(rightPart)))]
i=0
for p_left in leftPart:
for p_right in rightPart:
new_middle_part[i]='('+p_left+op1+p_right+')'
i+=1
#put together
for s in range(len(new_middle_part)):
output+=new_middle_part[s]
if s!=len(new_middle_part)-1:
output+=op2
return left + output+right
@staticmethod
def isCnf(prop):
#This method checks wether the input string is already in CNF format or not
in_clause=0 # number of parenthesis
prop = prop[1:len(prop)-1]
if(prop.find(BICONDITIONAL)!=-1 or prop.find(IMPLIES)!=-1):
return False
for s in prop :
if(in_clause ==0 and s==OR ):
return False
if s=='(':
in_clause+=1
elif (s==')'):
in_clause-=1
else:
return True
|
c3e7d47131b2272b00067b96c800803bfd6ee827 | frankySF86/PytonLearning_2019 | /FrameAdvantageFun/TempDbTesting.py | 525 | 3.8125 | 4 | import sqlite3
with sqlite3.connect(":memory:") as connection:
print(type(connection))
dbcursor = connection.cursor()
dbcursor.execute("CREATE TABLE mytesttable(fighterName nvachar(15), fighterage int)")
fighter_values=(("Ryu",35),("Chun Li",21),("Cammy",24))
dbcursor.executemany("INSERT INTO mytesttable VALUES (?, ?)",fighter_values)
records = dbcursor.execute("SELECT * FROM mytesttable").fetchall()
print(type(records))
for fighter in records:
print(fighter[0] + " " + str(fighter[1]))
|
da0cd5a8d5ed63e56893410eec04ab7eb3df7cff | ARCodees/python | /Calculator.py | 458 | 4.21875 | 4 | print("this is a calculator It does all oprations but only with 2 numbers ")
opration = input("Enter your opration in symbolic way ")
print("Enter Your first number ")
n1 = int(input())
print("Enter Your second number ")
n2 = int(input())
if opration == "+":
print(n1 + n2)
elif opration == "-":
print(n1 - n2)
elif opration == "*":
print(n1 * n2)
elif opration == "/":
print(n1 / n2)
else:
print("illogical Input!!")
|
e193dbd63188d0c2848e3f65105de8a678d03ed9 | sugitanishi/competitive-programming | /atcoder/abc158/a.py | 58 | 3.875 | 4 | s=input()
print('Yes' if 'AB' in s or 'BA' in s else 'No') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.