blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
6bd5297aaa64794dc4be44a39a1867b21d6f1b2c | aucan/LeetCode-problems | /468.ValidateIPAddress.py | 2,968 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 15:27:26 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/validate-ip-address/
Problem description:
Validate IP Address
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid.
IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases).
However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address.
Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.
Note: You may assume there is no extra space or special characters in the input string.
Example 1:
Input: "172.16.254.1"
Output: "IPv4"
Explanation: This is a valid IPv4 address, return "IPv4".
Example 2:
Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
Output: "IPv6"
Explanation: This is a valid IPv6 address, return "IPv6".
Example 3:
Input: "256.256.256.256"
Output: "Neither"
Explanation: This is neither a IPv4 address nor a IPv6 address.
"""
class Solution:
def validIPAddress(self, IP: str) -> str:
IP = IP.lower()
ipParts = IP.split(".")
if len(ipParts) == 4:
return "IPv4" if all([not (len(part) > 1 and part[0] == "0") and("0" <= part <= "255" and len(part) <= 3)
for part in ipParts]) else "Neither"
ipParts = IP.split(":")
if len(ipParts) ==8:
return "IPv6" if all([
"0" <= part <= "ffff" and len(part) <= 4
for part in ipParts]) else "Neither"
return "Neither"
sol = Solution()
# Test 1
ip = "172.16.254.1"
print(sol.validIPAddress(ip))
# Test 2
ip = "2001:0db8:85a3:0:0:8A2E:0370:7334"
print(sol.validIPAddress(ip))
# Test 3
ip = "256.256.256.256"
print(sol.validIPAddress(ip))
# Test 4
ip = "2001:0db8:85a3:00000:0:8A2E:0370:7334"
print(sol.validIPAddress(ip))
# Test 5
ip = "1111111"
print(sol.validIPAddress(ip))
# Test 6
ip = "192.01.01.0"
print(sol.validIPAddress(ip))
# Test 7
ip = "1.0.1"
print(sol.validIPAddress(ip)) | true |
487d989df874130d886b3ab2071441b1787cc628 | aucan/LeetCode-problems | /328.OddEvenLinkedList.py | 2,136 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 19:53:13 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/odd-even-linked-list/
Problem description:
Odd Even Linked List
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.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# Time: O(n), space: O(1)
# we move node two times in every iteration - we append the first node to odd list, and the other one to even list
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if head is None:
return head
oddHead = odd = head
evenHead = even = head.next
if not even:
return oddHead
node = even.next
while node:
odd.next = node
odd = odd.next
node = node.next
if not node:
break
even.next = node
even = even.next
node = node.next
# disconnect tail of even list
even.next = None
# connect odd list and even list - tail of odd list and head of even list
odd.next = evenHead
return oddHead
def printList(head):
while head:
print(head.val, end=" ")
head = head.next
print()
sol = Solution()
# Test 1
n1 = ListNode(1)
node = n1
for i in range(2, 6):
node.next = ListNode(i)
node = node.next
head = sol.oddEvenList(n1)
printList(head)
| true |
fa1100db45a4e6619d5c20a9b6e874e458745e2f | joojie/python01 | /Assignments/Assignment_5.2_Massawa_Lawson.py | 460 | 4.125 | 4 | smallest = None
largest = None
while True:
num = raw_input('Enter two or more different numbers: ')
if num == 'done':
break
print num
try:
num = float(num)
except:
print 'Invalid input'
continue
if smallest == None or num < smallest:
smallest = num
if largest == None or num > largest:
largest = num
print 'Maximum:', largest
print 'Minimum:', smallest
| true |
7144be8bbec754f78a5f312c677659c92a1c951e | YodaFace/Python-Lists-Loops-Programming | /exercises/12.2-Map_function_inside_variable/app.py | 539 | 4.125 | 4 | names = ['Alice','Bob','Marry','Joe','Hilary','Stevia','Dylan']
prepended_names = []
def prepender(name):
prepended_names = []
#Your code go here:
return "My name is: " + name
result = list(map(prepender, names))
print(result)
## ======== CODE FROM PREVIOUS EXERCISE ========= ##
# def fahrenheit_values(Celsius_values):
# # the magic go here:
# fahrenheit_values = []
# # print(fahrenheit_values)
# return (Celsius_values * 1.8) + 32
# result = list(map(fahrenheit_values, Celsius_values))
# print(result)
| false |
d9de99c457ade5eb394b0e606235ba9ba27accfd | sockduct/Presentations | /Concurrency Talk/fibonacci.py | 744 | 4.1875 | 4 | #
# Simple non-recursive Fibonacci
#
# Created for Concurrent Python presentation
#
# Based on examples/code from a blog/YouTube video
# * Apologies but I don't remember which one...
#
def fibonacci(n, verbose=False):
values = []
count = 0
#
if n < 0:
sys.exit('Error: Fibonacci term must be >= 0')
#
while count <= n:
if count == 0:
values = [0, 0]
loop = False
elif count == 1:
values = [0, 1]
loop = False
else:
values = [values[-1], values[-1] + values[-2]]
#
count += 1
#
if verbose:
print('values = {}'.format(values))
print('Fibonacci term {} = {}'.format(n, values[1]))
| true |
876709d0d1af697eb7309aa23cff5a67184e739b | barbaramchd/one_coding_challenge_a_day | /202104 - April_2021/20210422.py | 1,256 | 4.15625 | 4 | digits = '123456789'
rows = 'ABCDEFGHI'
columns = digits
def cross(X, Y):
""""
Creates cross product of elements in X and in Y.
"""
# stores the cross products
combinations = []
for x in X:
for y in Y:
combinations.append(x + y)
# return a list of all the cross products
return combinations
# list with all coordinates for each square
squares = cross(rows, columns)
row_units = [cross(row, columns) for row in rows]
column_units = [cross(rows, column) for column in columns]
block_units = [cross(rs, columns) for rs in ('ABC', 'DEF', 'GHI') for columns in ('123', '456', '789')]
unit_list = (row_units + column_units + block_units)
def map_square_units(squares, unit_list):
"""
Creates a dict that maps each square to the list of units that contain
that square. Note that each square has 3 units: its rown, its column,
and its block.
"""
unit_dict = {}
for square in squares:
for unit in unit_list:
if square in unit:
if square not in unit_dict:
unit_dict[square] = []
unit_dict[square].append(unit)
return unit_dict
square_units = map_square_units(squares, unit_list)
square_units | true |
4f2d6357482199e751897ac0c642c6bb5def8f8a | pshobbit/ejerciciosPython | /UMDC/02/02.py | 1,009 | 4.15625 | 4 | # Usando las funciones del ejercicio anterior, escribir un programa que lea de
# teclado dos tiempos expresados en horas, minutos y segundos; las sume y
# muestre el resultado en horas, minutos y segundos por pantalla.
def hms_seg(h, m, s):
return ((h * 60) + m) * 60 + s
def seg_hms(s):
horas = s//3600
s = s % 3600
minutos = s//60
segundos = s % 60
return (horas, minutos, segundos)
leyendo = True
while leyendo:
try:
h1 = int(input("Introduce la 1º hora: "))
m1 = int(input("Introduce los 1º minutos: "))
s1 = int(input("Introduce los 1º segundos: "))
h2 = int(input("Introduce la 2º hora: "))
m2 = int(input("Introduce los 2º minutos: "))
s2 = int(input("Introduce los 2º segundos: "))
leyendo = False
except ValueError:
print("Error en la introducción de datos\n")
(h,m,s) = seg_hms(hms_seg(h1, m1, s1) + hms_seg(h2, m2, s2))
print("La suma es: ", h, "horas", m, "minutos y ", s, "segundos")
| false |
3ff0e624f77eff4aca821d06d9106dffb14a649f | RuwangiAbeysinghe/COHDCBIS182F-004 | /01_caesar.py | 227 | 4.125 | 4 | plaintext =input("Enter Message")
alph="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key=3
cipher=''
for x in plaintext:
if x in alph:
cipher+=alph[(alph.index(x)+key)%len(alph)]
print("Encrypted Message is: " + cipher) | false |
8415d2b95538e4f4c47cdae53e58ed0bbdd5b90c | kargamant/education | /Algorithms and data stractures in python/lesson1/les_1_task_3.py | 1,394 | 4.34375 | 4 | #3. Написать программу, которая генерирует в указанных пользователем границах:
#a. случайное целое число,
#b. случайное вещественное число,
#c. случайный символ.
#Для каждого из трех случаев пользователь задает свои границы диапазона. Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы. Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно.
from random import uniform, randint
print('Введите диапазон случайного целого числа:')
b_int = int(input())
e_int = int(input())
print('Введите диапазон случайного вещественного числа:')
b_f = float(input())
e_f = float(input())
print('Введите диапазон случайного символа:')
b_l = input()
e_l = input()
print(f'Случайное целое число: {randint(b_int, e_int)}\n'
f'Случайное вещественное число: {uniform(b_f, e_f)}\n'
f'Случайный символ: {chr(randint(ord(b_l), ord(e_l)))}')
| false |
cc7b41374a4f07719d5c1c912a9496d851ccb1d3 | hachihung/DSE-ICT-Paper-2D | /DSE 2020 Q1.py | 1,482 | 4.375 | 4 | # DSE 2020 ICT Paper 2D Q1
# Written by Ha sir 😁
import turtle
import time
car = turtle.Turtle()
car.setheading(90)
car.color('blue')
car.pensize(5)
# shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”.
car.shape('turtle')
car.shapesize(1)
time.sleep(1)
steps = 20
def P(N):
while N > 0:
for i in range(1, N+1):
car.forward(N*steps)
car.right(90)
for i in range(1, N+1):
car.forward(N*steps)
car.right(90)
N = N - 1
# Actually, passing parameters in the following functions will be much better. However, since we are
# going to simulate the public exam question as much as possible, we use global for the variable dir 😅
def TE():
global dir
for i in range(1, (5 - dir + 1) % 4):
car.right(90)
dir = 1
def TW():
global dir
for i in range(1, 3 - dir + 1):
car.right(90)
dir = 3
def TN():
global dir
for i in range(1, 4 - dir + 1):
car.right(90)
dir = 0
def TS():
global dir
for i in range(1, (6 - dir + 1) % 4):
car.right(90)
dir = 2
def MOVE(X, Y, NX, NY):
if NX > X:
TE()
else:
TW()
for i in range(1, NX - X + 1):
car.forward(steps)
if NY > Y:
TN()
else:
TS()
for i in range(1, NY - Y + 1):
car.forward(steps)
# P(5)
dir = 0
# dir = TS(dir)
# print(dir)
MOVE(0, 0, 10, 1)
print(dir)
time.sleep(3)
| false |
6c14fc629cda546a15bdf8772f47df6b7f53eb9f | slambert67/techAndTools | /python/finalHangman.py | 1,332 | 4.21875 | 4 | # declare and initialise variables
choice = ''
print ('You are about to play some games of Hangman!\n')
while (1 == 1): # infinite loop. 1 always = 1
# show user menu
print('New Game: 1')
print('Exit : 2')
choice = input('Enter your selection: ')
# exit program if user selects choice 2
if choice == str(2):
print('Leaving game ...')
break # exit outer menu loop
# otherwise play a new game of hangman
phrase = list('great white shark')
progress = list('----- ----- -----')
lives = 3
print('\nPlaying hangman ...\n')
print(''.join(progress))
while (1 == 1):
correctGuess = 'n'
guess = input('\nGuess a letter: ')
# search for instances of this letter in the original phrase
index = 0
for letter in phrase:
if letter == guess:
correctGuess = 'y'
progress[index] = guess
index = index + 1
print('\nprogress = ' + ''.join(progress) )
if correctGuess == 'y':
print('\nCorrect guess - well done. You do not lose a life')
if ''.join(progress) == ''.join(phrase):
print('\nCongratulations - you have won!!!\n')
break
else:
print('\nIncorrect guess - lose a life!')
lives = lives - 1
if lives == 0:
print('\nYou have run out of lives\n')
break
| true |
ac06083d77c5f001d0b47d5c1b2c4bffd25e463a | softscienceprojects/python-algorithms | /is_even.py | 224 | 4.25 | 4 | """that will take a number x as input.
If x is even, then return True.
Otherwise, return False
"""
def is_even(x):
if x %2 == 0:
return True
else:
return False
print is_even(900)
| true |
1d54c945db6c7666fe0fb10acb27f3ec8c60f828 | softscienceprojects/python-algorithms | /digit_sum.py | 358 | 4.3125 | 4 | """takes a positive integer n as input and returns
the sum of all that number’s digits. For example:
digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.
(Assume that the number you are given will always be positive.)
"""
def digit_sum(x):
total = 0
while x > 0:
total += x % 10
x = x // 10
print x
return total
| true |
408078f6a7e255bc0bdada68e4e9f515e1fe4d9a | SamuelLearn/EjerciciosPython | /calculadora_funciones.py | 1,593 | 4.21875 | 4 | # funciones matemátcas
def suma (num1 , num2):
resultado = str(num1 + num2)
print("");print("La suma es: " + resultado);print("")
def resta (num1 , num2):
resultado = str(num1 - num2)
print("");print("La resta es: " + resultado);print("")
def multi (num1 , num2):
resultado = str(num1 * num2)
print("");print("La multiplicación es: " + resultado);print("")
def divi (num1 , num2):
resultado = str(num1 / num2)
print("");print("La división es: " + resultado);print("")
def menu():
print("...:::Opciones:::...")
print("1)para sumar esciba la palabra 'suma'")
print("2)para restar escriba la palabra 'resta'")
print("3)para multiplicar escriba la palabra 'multiplicar'")
print("4)para dividir escriba la palabra 'dividir'")
print("5)para salir escriba la palabra 'salir'")
#calculadora
while True:
menu()
user_input=input(":")
if user_input == "salir":
print ("Gracias por usar este programa :3")
break
elif user_input == "suma":
num1 = float(input("Ingrese un número: "))
num2 = float(input("Ingrese un número: "))
suma(num1 , num2)
elif user_input == "resta":
num1 = float(input("Ingrese un número: "))
num2 = float(input("Ingrese un número: "))
resta(num1 , num2)
elif user_input == "multiplicar":
num1 = float(input("Ingrese un número: "))
num2 = float(input("Ingrese un número: "))
multi(num1 , num2)
elif user_input == "dividir":
num1 = float(input("Ingrese un número: "))
num2 = float(input("Ingrese un número: "))
divi(num1 , num2)
else:
print("");print("Error no existe ese comando");print("") | false |
6c9d8085731fd3f65051f5efa40cc14d60e092e6 | Dhivyabarathi3/code-kata | /largest.py | 231 | 4.1875 | 4 | n1 = int(input(""))
n2 = int(input(""))
n3 = int(input(""))
l = n1
if l < n2:
if n2 > n3:
l = n2
else:
l = n3
elif l < n3:
if n3 > n2:
l = n3
else:
l = n2
else:
l = n1
print("Largest of given three numbers is",l,"\n")
| false |
2e77e40e8bc32a8a979d034a802c21c8c2ba67e8 | radekBednarik/this-and-that | /sum_up_integers.py | 934 | 4.25 | 4 | '''
Sum up integers up to provided integer,
see https://realpython.com/python\
-practice-problems/#python-practice\
-problem-1-sum-of-a-range-of-integers
if no integer provided, return 0
'''
TEST_VALUES = [0, 1, 2, 5, 9, 22, 100, 55, 1.5, None, "hello"]
def add_it_up(input_: int) -> int:
"""Adds up integers up to input number, inclusive.
If inputs is not type of integers ,return 0.
Args:
input_ (int): value to sum up integers from zero to this value
inclusive.
Returns:
int: sum of the integers. or 0, if `input` is not integer
"""
if not isinstance(input_, int):
return 0
summation: int = 0
for i in range(input_ + 1):
summation += i
return summation
if __name__ == "__main__":
print("test values: ", TEST_VALUES)
_ = [
print(f"cummulative sum up to {item} is: ", add_it_up(item))
for item in TEST_VALUES
]
| true |
aaef36d1dbeff212de9769d8f427048e4eb1c64d | matthannan1/pynet | /wk6-ex1.py | 453 | 4.34375 | 4 | def multiply(x,y,z=1):
product = float(x) * float(y) * float(z)
return product
print
print "Part A: Three values"
print "3.124, 22.5, 6"
print multiply(3.124, 22.5, 6)
print
print "Part B: Three named arguments"
x = 3.124
y = 22.5
z= 6
print multiply(x,y,z)
print
print "Part C: A mix of three named and positional values"
print "z = 12"
print multiply(x,y,z=12)
print
print "Part D: Two arguments and use default z (1)"
print multiply(x,y)
| true |
03f86b27ea4d84184b8fed37d746c6d7c29b501b | bavalia/scripts | /python/rollDiceN.py | 900 | 4.1875 | 4 | #! /usr/bin/python3
'''
Gives the rolling of a dice with N face, default is N=6
usage: ./rollDiceN [N]
'''
import argparse
import random
class NotAnInteger(Exception):
pass
def rollDiceN (N=6):
'''
returns a tuple with 1st value as rolled dice and 2nd value as total face of dice
'''
if (isinstance(N, int) and (N>0)):
return random.randint(1,N), N
else:
raise NotAnInteger("Number of sides of dice is not a positive integer, received N = " + str(N))
return 0
if __name__=='__main__':
parser=argparse.ArgumentParser(description='rolls a dice with N face, default N=6')
parser.add_argument("N", default=6, type=int, nargs='?' , help="number of faces of a dice ")
args=parser.parse_args()
diceN = args.N
#print (args)
roll = rollDiceN(diceN)
print ("Rolling dice of face N = %d ... result = %d" % (roll[1],roll[0]))
# -- end --
| true |
45c4f4e3f3d5b680e785a45b24f1fde6d08987d5 | szabo137/pySnippets | /pyClassTest/inheri.py | 680 | 4.15625 | 4 | """
tests the inheritance of classes in python
"""
class A(object):
def __init__(self,data):
self.__data = data
self.data=data
def setData(self,data):
self.__data = data
def getData(self):
return self.__data
class B(A):
def __init__(self,data):
A.__init__(self,data)
print"test: %s"%self.data
def transformData(self):
self._A__data = self._A__data*2
if __name__=='__main__':
testA = A("bla")
print "data: %s"%(testA.getData())
test = B("bla")
print "data: %s"%(test.getData())
test.transformData()
print "transformed data: %s"%test.getData()
print testA.getData()
| false |
264633e3a07f7422f30dfb5ef619d71d0642c021 | sumanamoothedath/hello-world | /Calc check.py | 1,048 | 4.21875 | 4 | #!/usr/bin/env python
def add(a, b):
"""Adds a and b and returns the sum."""
return(a + b)
def subtract(a, b):
"""Subtracts a and b and returns the difference."""
return a - b
def multiply(a, b):
"""Multiplies a and b and returns the product."""
return a * b
def divide(a, b):
"""Divides a and b and returns the quotient."""
return a / b
if __name__ == "__main__":
print("Select 1 for Add,2 for Subtract,3 for Multiply and 4 for Divide")
choice = input("Enter choice(1,2,3 or 4):")
num1 = int(input("Enter num1: "))
num2 = int(input("Enter num2: "))
if choice == '1':
print('{} + {} = '.format(num1, num2))
print(add(num1, num2))
elif choice == '2':
print('{} - {} = '.format(num1, num2))
print(subtract(num1, num2))
elif choice == '3':
print('{} * {} = '.format(num1, num2))
print(multiply(num1, num2))
elif choice == '4':
print('{} / {} = '.format(num1, num2))
print(divide(num1, num2))
else:
print("Invalid input")
| true |
84925c7d4baf3b12014919abe9bd6b8031e90b16 | sam-d007/python | /functions/args.py | 304 | 4.3125 | 4 | def sum(*args):
'''The *args parameter is a special parameter that can take multiple arguments and store it in a tuple'''
print(args)
sum=0
for num in args:
sum+=num
return sum
sum1 = sum(5,10,15,20)
print(sum1)
#unpacking tuple
v = (10,20,30,40,50)
s2 = sum(*v)
print(s2) | true |
679ca2c5368136b076009a98e1a9ade5d6a3c37a | JulCesWhat/problems_vs_algorithms | /problem_1.py | 515 | 4.40625 | 4 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
if number < 0:
return None
x_num = number
y_num = (x_num + 1) // 2
while y_num < x_num:
x_num = y_num
y_num = (x_num + number // x_num) // 2
return x_num
print(sqrt(100))
# 10
print(sqrt(0))
# 0
print(sqrt(5))
# 2
print(sqrt(-1))
# None
print(sqrt(-100))
# None
| true |
b1737104fb917260b5cb2069b2f0e82e87a12597 | strehlmatthew/workspace | /arrays from class.py | 573 | 4.15625 | 4 | # Array without Numpy
matrix = [[1,2,3],[4,5,6],[7,8,9]]
#print the item in row 2 column 2
print(matrix)
print(matrix[2][2])
for row in matrix:
for item in row:
pass
print(item)
import numpy as np
arrayn = np.array([[1,2,3],[4,5,6] ,[8,9,10]])
print(arrayn)
print (arrayn.shape)
for row in arrayn:
for item in row:
print(item)
#print the item in row 1 column 1
print(arrayn[1][1])
#sum and then print the sum of axis 1, column 2
summer = np.sum([[1,2,3],[4,5,6] ,[8,9,10]],axis = 0)
print(summer[2])
| true |
2259524cfc484d2d7fcfd12c30af1f6a27eb20eb | bitpit/CS112-Spring2012 | /classcode/day06--code_formating/broken1.py | 616 | 4.3125 | 4 | #!/usr/bin/env python
input_list=[] ##inits list to store all inputs,
input_number=None #and place to immediately store entry
while input_number != "": #while input isnt not a number
input_number=raw_input() #get input
if input_number.isdigit(): #if input is a number
input_list.append(float(input_number))#append to list
total = 0 #inits place to store sum of all inputs
for num in input_list:
total+=num #accumulates sum of all numbers in list
#to 'total'
print total/len(input_list) #divides total by length of list
#to find average | true |
69f1422059462a1a39ecf129e03edc6e1c9242cc | bitpit/CS112-Spring2012 | /hw04/sect2_while.py | 758 | 4.53125 | 5 | #!/usr/bin/env python
from hwtools import *
print "Section 2: Loops"
print "-----------------------------"
# 1. Keep getting a number from the input (num) until it is a multiple of 3.
num = int(raw_input("Please enter a multiple of 3: "))
while (num%3!=0):
print "That's not a multiple of 3! Try again!"
num = int(raw_input("Please enter a multiple of 3: "))
#print "1.", num
while (num!=0):
print num
num = num-3
print "0"
#print "we have liftoff"
#print "2. Countdown from", num
# 3. [ADVANCED] Get another num. If num is a multiple of 3, countdown
# by threes. If it is not a multiple of 3 but is even, countdown by
# twos. Otherwise, just countdown by ones.
# num = int(raw_input("3. Countdown from: "))
| true |
6756b063a1aeb7079dab45ff5b913a2fc6481b41 | bitpit/CS112-Spring2012 | /hw10/rects.py | 1,646 | 4.3125 | 4 | #!/usr/bin/env python
"""
rects.py
Pygame Rectangles
=========================================================
The following section will test your knowledge of how to
use pygame Rect, arguably pygame's best feature. Define
the following functions and test to make sure they
work with `python run_tests.py`
Make sure to use the documentation
http://www.pygame.org/docs/ref/rect.html
Terms:
---------------------------------------------------------
Point: an x,y value
ex: pt = 3,4
Polygon: a shape defined by a list of points
ex: poly = [ (1,2), (4,8), (0,3) ]
Rectangle: pygame.Rect
"""
from pygame import Rect
import math
def poly_in_rect(poly, rect):
count = 0
for i in range(len(poly)):
x,y = poly[i]
if rect.collidepoint(x,y):
count += 1
if count == len(poly):
return True
else:
return False
def surround_poly(poly):
#make x & y list
xes = []
yes = []
for x in range (0,len(poly)):
xes.append(poly[x][0])
yes.append(poly[x][1])
#sort em
for x in range(0, len(xes)):
min=x
for i in range(x+1, len(xes)):
if xes[i]<xes[min]:
min = i
xes[x],xes[min]=xes[min],xes[x]
for x in range(0, len(yes)):
min=x
for i in range(x+1, len(yes)):
if yes[i]<yes[min]:
min = i
yes[x],yes[min]=yes[min],yes[x]
#return a rect based on the sorted lists
w = math.fabs(xes[0]) + xes[len(xes)-1] - 1
h = math.fabs(yes[0]) + yes[len(yes)-1] + 1
return Rect((xes[0],yes[0]), (w,h))
| true |
de92cd990ab9adac8afb59a36cea506b36917f3d | bitpit/CS112-Spring2012 | /hw03/prissybot.py | 1,862 | 4.15625 | 4 | #!/usr/bin/env python
"""
prissybot.py
Evan Ricketts
for CS112
ps - if i forgot some requirement, i apologize. simply let me know
and i will add it posthaste.
"""
name=raw_input("Enter your name: ") #assigns input to variable 'name'
print ""
print "Prissybot: Hello there, "+name+"."
print "(you can respond if you'd like..)"
say1=raw_input(name+": ")
print "Prissybot: You mean '"+say1+", sir!'"
#print "(dare you respond?)"
say2=raw_input(name+": ")
print "Prissybot: Brilliant! '"+say2+".' I'm surprised NASA let you leave..."
say3=raw_input(name+": ")
print "Prissybot: '"+say3+"?' Really? That's the best you can do?"
say4=raw_input(name+": ")
print "Prissybot: you type like a drunk. I mean who even says '"+say4+"'?"
say5=raw_input(name+": ")
print "Prissybot: Well if you're not going to even try I'm done with this game"
print "I am now... AN ADDING MACHINE!"
print "Addbot: Give me 3 whole numbers to sum!"
v1=raw_input("Variable 1: ")
v2=raw_input("Variable 2: ")
v3=raw_input("Variable 3: ")
i1=int(v1)
i2=int(v2)
i3=int(v3)
sum=i1+i2+i3
sum1=str(sum)
print "Addbot: The sum of your variables is "+sum1+"."
print "Addbot: Now lets do some subtraction. Enter in order three numbers"
print "to be subtracted from the other."
n1=raw_input("Number 1: ")
n2=raw_input("Number 2: ")
n3=raw_input("Number 3: ")
a1=int(n1)
a2=int(n2)
a3=int(n3)
bum=a1-a2-a3
bum1=str(bum)
print "Addbot: The difference of your variables is "+bum1+"."
print "Addbot: Now for the grand finale, I will divide!"
print "Addbot: Remember, in A/B, A is the dividend and B is the divisor."
d=raw_input("Dividend: ")
v=raw_input("Divisor: ")
d1=float(d)
v1=float(v)
q=d1/v1
q1=str(q)
print "Addbot: The quotient of your equation is (roughly) "+q1+"."
print "I grow weary. Goodnight!"
say6=raw_input(name+": ")
print "Addbot: I'm out of the sass game now, don't you get it kid?!"
| true |
fe94626c7b67a0c27a8cf7c2c8c80c1a4325360b | anton1k/mfti-homework | /lesson_8/test_8.py | 894 | 4.3125 | 4 | # Нарисуйте Канторово множество. Канторово множество нулевого порядка - горизонтальный отрезок. Удалив среднюю треть получим множество первого порядка. Повторяя данную процедуру получим остальные множества.
import turtle
turtle.shape('turtle')
def cantor_set(x, y, l, n):
if n == 0:
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(l)
return
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.forward(l)
cantor_set(x, y-30, l/3, n-1)
cantor_set(x + l*2/3, y-30, l/3, n-1)
L = 600
N = 3
X = -L/2
Y = 15 * N
turtle.penup()
turtle.goto(X, Y)
turtle.pendown()
cantor_set(X, Y, L, N)
turtle.exitonclick() # click to exit | false |
fea565f05a291ce98ab6140986cdc77200f45331 | adstr123/ds-a-in-python-goodrich | /chapter-1/c15_is_distinct.py | 691 | 4.21875 | 4 | def is_distinct(integer_list):
"""Takes a list and determines if all elements are unique
:param list integer_list: list of integers
:return boolean: conditional on evaluation of the input
"""
index = 0
for i in integer_list:
for j in integer_list:
if i != index and i == j:
return False
index += 1
return True
print(is_distinct(list(range(10))))
print(is_distinct(list([0, 1, 2, 3, 4, 5, 5, 6])))
"""
Time: O(n^2)
- n calculations per element in input (nested loops)
Space: O(n)
- 1 unit for external index, 2 units for loop indexing, 1 for return value
- Units required for integer_list grow with input size
- Both loops operate on the same list
"""
| true |
4e1e4110fb9a9a8a0dd8a988299bb598ff512f81 | adstr123/ds-a-in-python-goodrich | /chapter-1/r4_cumulative_square.py | 575 | 4.15625 | 4 | def cumulative_square(limit):
"""Sums the square of all integers up to the given limit
:param int limit: exclusive limit of the cumulative squares
:return int: accumulation of the square of all integers up to limit
"""
accumulation = 0
for i in range(limit):
accumulation += i ** 2
return accumulation
print(cumulative_square(100))
"""
Time: O(n)
- One calculation per increment up to input
Space: O(1)
- One unit of space to track sum, one for loop index, one for return value
- One unit which is constantly increased, no matter the size of limit
"""
| true |
8373e0bce23ce312f67b473b32fb789ed6f93464 | bipintatkare2/PythonTutorial | /Files/file_basic_command.py | 436 | 4.34375 | 4 | # Program to demonstrate files and their functions in python .
# To open a file in a particular mode , Here is the command :-
open_file = open("sample.txt", "r")
# To get the name of file , Here is the command :-
print(open_file.name)
# To get the mode of file is be , Here is the command :-
print(open_file.mode)
# To get the status of file is been closed or not in the bool format , Here is the command :-
print(open_file.closed)
| true |
f35b655babab3219127783c5c6596ca4f9758c2c | leejongcheal/algorithm_python | /파이썬 알고리즘 인터뷰/ch9 스택, 큐/23. 큐를 이용한 스택구현.py | 609 | 4.125 | 4 | # 굳이 deque 에 popleft를 사용해서 풀생각 안함 귀찮아
# 구조체 선언과 사용방법만 눈여겨 보기
class MyStack:
def __init__(self):
self.q = []
def push(self, x: int) -> None:
self.q.append(x)
def pop(self) -> int:
return self.q.pop()
def top(self) -> int:
return self.q[-1]
def empty(self) -> bool:
return len(self.q) == 0
myStack = MyStack()
myStack.push(1)
myStack.push(2)
print(myStack.top()) # return 2
print(myStack.pop()) # return 2
print(myStack.pop()) # return 1
print(myStack.empty()) # return True
| false |
4260b175d6757c1b064173f9787acb838e24dd3a | BhagyashreeKarale/if-else | /ques5.py | 725 | 4.4375 | 4 | # Take user input in a variable named varx.
# Convert it to an integer.
# Check if this number is divisible by 2.
# You can achieve this by using the modulus operator``.
# Remember, modulus operator returns the remainder of the division of first operand by the second operand.
# Example:
# 6 % 2 returns 0 as the output because 2 completely divides 6 and the remainder is 0.
# But 9 % 2 returns 1 as the output since 2 does not completely divide 9. The remainder is 1.
# To conclude, 6 is divisible by 2 but 9 is not divisible by 2.
# If the number is divisible by 2, print Divisible else print Not Divisible
varx=int(input("Enter a number"))
if varx % 2 == 0:
print("Divisible by 2")
else:
print("Not divisible")
| true |
ce0832075f90560db3586e536b3d7305266b9260 | BhagyashreeKarale/if-else | /ques9.py | 1,438 | 4.375 | 4 | # Question 9
# Consider the following rules:
# People 5 years and above in age can go to school.
# People 18 years and above in age can vote in elections.
# People 21 years and above in age can drive a car.
# People 24 years and above in age can marry.
# People 25 years and above in age can legally drink.
# Create a flowchart that takes the age of the user as input.
# Print what all activities the user can do from the list above.
# For example, if user enters age as 20, the code should print:
# You can go to school
# You can vote in elections
# If user enters age as 24, the code will print:
# You can go to school
# You can vote in elections
# You can drive a car
# You can marry
# Submit the flowchart as well as the code.
age=int(input("Enter your age:\n"))
if age>=5:
if age>=18:
if age>=21:
if age>=24:
if age>=25:
print("You can go to school\nYou can vote in elections\nYou can drive a car\nYou can marry\nyou can drink legally")
else:
print("You can go to school\nYou can vote in elections\nYou can drive a car\nYou can marry")
else:
print("You can go to school\nYou can vote in elections\nYou can drive a car")
else:
print("You can go to school\nYou can vote in elections")
else:
print("You can go to school")
else:
print("Come back when you grow up child!")
| true |
786bbb10f994d9ac7365d33750a37e6bbe3d83c8 | shreyansh-sh1/twoc-python-assingment4 | /question1.py | 275 | 4.1875 | 4 | a=[]
n=int(input("Enter number of elements of tuple: "))
print("Enter elements of tuple: ")
for i in range(n):
b=input()
a.append(b)
tuple(a)
c=input("Enter element whose occurrence you want to know: ")
print(c,"occurs",c.count(c),"times")
# Code by shreyansh sharma | false |
f7338151697bef111a36199e1dff7dcc8116f6e7 | Sujan0rijal/PythonLab | /main.py | 323 | 4.3125 | 4 | '''1. write a program that takes three numbers and prints their sum.
Every number is given on separate lines. '''
num1 = int(input("enter the first number;"))
num2 = int(input("enter the second number;"))
num3 = int(input("enter the third number;"))
sum = num1+num2+num3
print(sum)
print(f"the value of sum is {sum}")10 10 | true |
71b85955cab76e63cd13c937502feb879941047c | spoonsandhangers/ALevel_GUIBook | /3.1 labels.py | 2,383 | 4.3125 | 4 | """
Label widgets added to Frames.
padx and pady are parameters that set the interior distance from text in a label to the edge of the label.
when used in a frame it sets the distance from the edges of the frame to the internal widgets.
"""
import tkinter as tk
class ExampleFrame(tk.Frame):
def __init__(self, the_window):
super().__init__() # this invokes the constructor of the super class Frame
self["width"] = 300 # sets the width of the greenFrame instance to 300
self["height"] = 300 # sets the height of the greenframe instance to 300
self["relief"] = "sunken" # sets the relief of the greenframe instance to sunken
self["border"] = 8
self["bg"] = "green"
self["padx"] = 80
self["pady"] = 100 # changing the value of the padx and pady will change the label position.
self.addLabel()
# this method creates labels and adds to them the frame self.
def addLabel(self):
# here labels are created. the first parameter passed to them is self.
# this is the exampleFrame object that they will be added to.
lbl_one = tk.Label(self,
text="This is label one",
font=("comic sans",10,"bold"),
fg="white",
bg="black",
padx=5,
pady=5) # self is passed to the label as the window it will be added to
lbl_two = tk.Label(self,
text="This is label two",
fg="purple",
bg="white",
font=("helvetica",20,"italic"), # name a font, size and type
padx=5,
pady=5)
lbl_three = tk.Label(self,
text="This is label three",
fg="blue",
bg="yellow",
font=("ariel",15),
padx=5,
pady=5)
# labels are only visible when placed onto the exampleframe using a layout manager
# here grid is used.
lbl_one.grid(row=0, column=0)
lbl_two.grid(row=1, column=0)
lbl_three.grid(row=2, column=0)
window = tk.Tk() # creates new base window.
window.title("My window")
#window.geometry("300x300") # width x height
# creates an instance of the ExampleFrame class
a_frame = ExampleFrame(window)
# adds the frame to the base window
a_frame.grid(row=0, column=0)
window.mainloop()
| true |
492945d52ff99ce673b666781a6472e6d3536dba | mahinsagotra/Python | /Itertools/product.py | 251 | 4.1875 | 4 | # itertools: product, permutations, combinations, accumulate, groupby,
# and iterators
from itertools import product
a = [1, 2]
b = [3, 4]
prod = product(a, b) # cartesian product
print(list(prod))
prod = product(a, b, repeat=2)
print(list(prod))
| true |
db7e6ae7cdcf986f2d70188bb08b31c0cc72f34d | SunayChinni/Pythonpractice | /pythonsamples/prac/collections.py | 1,332 | 4.125 | 4 | l1 = [10,20,30,40,50]
print(l1)
print(l1[0])
print(l1[-1])
l1[2] = 90
print(l1)
l1 = [10,20,30]
# l2 = l1+3 Error
# TypeError: can only concatenate list (not "int")
# print(l2)
l2 = [40,50,60]
l3 = l1+l2
print(l1)
print(l2)
print(l3)
print("-------------------------")
l1 = [10,20,30]
l2 = [1,2,3]
# l3 = l1*l2 # Error
# TypeError: can't multiply sequence by non-int of type 'list'
# print(l3)
l3 = l1*3
print(l3)
l1 = [10,20,30,40,50,60,70,80,90,100]
print(l1[0:3])
print(l1[0:5:2])
print(l1[0:10:3])
print(l1[-1:-11:-2])
l1 = [] # Empty List
print(l1)
s1 = int(input("Enter 1sub Marks"))
l1.append(s1)
s2 = int(input("Enter 2sub Marks"))
l1.append(s2)
s3 = int(input("Enter 3sub Marks"))
l1.append(s3)
print("Marks = ",l1)
print("Total marks = ",sum(l1))
first = [11,12,13,14,15,16,17]
second = [10,20,30,40,50]
# adding second list elements to first list
first.extend(second)
print(first)
print(second)
l1 = [10,20,30]
print(l1)
val = l1.pop(0)
print("Removed value = ",val)
print(l1)
l1 = [10,20,30,40,50,10,50,60,30]
no = l1.index(30)
print(no)
t1 = (10,"Ravi",10.25,False)
t2 = (20,"Kumar",20.25,True)
t3 = t1+t2
print(t3)
t4 = t1*2
print(t4)
t1 = (10,"Ravi",10.25,False)
print(t1[0:2])
print(t1[0:5:2])
t1 = (10,20,"Ravi",40.85,10,30,20,10)
coun = t1.count(10)
print(coun)
ind = t1.index("Ravi")
print(ind) | false |
326e583f3999886edca90c916a7727ec9c1b560f | ankitkumarbrur/information_security_assignment | /3. ceaserCipher.py | 1,830 | 4.21875 | 4 | from collections import defaultdict
def frequencyAttack(S):
# calculating the length of string & converting the string to uppercase to avoid any snag in frequency attack
N, S = (len(S), S.upper())
# List to store the top plain texts
plaintext = []
# storing the english letters in their decreasing order of frequency
english_letter_frequency = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
# dictionary to store frequency of the letters in cipher text
frequency = defaultdict(int)
# calculating the frequency of the letters in cipher text
for c in S: frequency[c] += 1
# In python 3.7+ dictionary preserves the insertion order (NOTE: program may not work as expected if we use dictionary and run on python version < 3.7)
# sorted_frequency = dict(sorted(fr.items(), key = lambda i: i[1], reverse=True))
# Sorting frequency and storing it in a tuple
sorted_frequency = tuple(sorted(frequency.items(), key = lambda i: i[1], reverse=True))
for i in range(26):
# calculating the key
key = (26 + ord(sorted_frequency[0][0]) - ord(english_letter_frequency[i])) % 26
txt = ""
# time complexity : O(26 * N)
for j in range(len(S)):
# traversing on string and decoding it
if(S[j] >= 'A' and S[j] <= 'Z'):
txt += chr(65 + (ord(S[j]) - 65 + key) % 26)
else:
txt += S[j]
plaintext.append(txt)
return plaintext
S = input("Enter encoded string: ")
pt = int(input("Enter how many plain texts you want (max: 26): "))
# calling the function to get plaintexts
plaintext = frequencyAttack(S)
print("\n\nDECODED PLAIN TEXTS:\n")
# printing the plaintexts
for i in range(pt % 26):
print( i + 1, end = ": ")
print( plaintext[i], end = "\n\n") | true |
1a09925dc5cd1400ece9e0427f3bc7be796a3750 | majurski/Softuni_Fundamentals | /Functions - Exercise/6-Password-generator.py | 632 | 4.1875 | 4 | def pass_check(text):
digits = 0
letter = 0
val_pass = True
if len(text) < 6 or len(text) > 10:
print(f"Password must be between 6 and 10 characters")
val_pass = False
for i in text:
if i.isdigit():
digits += 1
if i.isalpha():
letter += 1
if digits + letter != len(text):
print(f"Password must consist only of letters and digits")
val_pass = False
if digits < 2:
print(f"Password must have at least 2 digits")
val_pass = False
if val_pass:
print(f"Password is valid")
word = input()
pass_check(word)
| true |
0b23a79d3ca6126b1063364ad0c7b6b64291c75f | Yihhao/python-1000-day | /Day-19/Day-19-start/main.py | 1,079 | 4.1875 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title='Make your bet', prompt='Which turtle will win the race? Enter a color: ')
color = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
y_position = [-70, -40, -10, 20, 50, 80]
all_turtle = []
for turtle_index in range(6):
tim = Turtle(shape='turtle')
tim.color(color[turtle_index])
tim.penup()
tim.goto(x=-230, y=y_position[turtle_index])
all_turtle.append(tim)
# print(all_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() >= 210:
is_race_on = False
wining_color = turtle.pencolor()
if user_bet == wining_color:
print(f"You've won! The {wining_color} turtle is the winner.")
else:
print(f"You've lose! The {wining_color} turtle is the winner.")
rand_distance = random.randint(0, 10)
turtle.forward(rand_distance)
screen.exitonclick()
| true |
f241f12a331822445db8151ecb397adccee239e2 | MichaelBlackwell/SortingAlgoritms | /quickSort.py | 973 | 4.125 | 4 | # Quick Sort
# Complexity O(nlogn) for best cases
# O(n^2) for average and worst cases
def quickSort(inputList):
less = []
pivotList = []
more = []
if len(inputList) <= 1:
return inputList
else:
pivot = inputList[0]
for i in inputList:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivotList.append(i)
print("input list: ")
print(inputList)
print("less list: ")
print(less)
print("pivot list: ")
print(pivot)
print("more list: ")
print(more)
less = quickSort(less)
more = quickSort(more)
r = less + pivotList + more
print("returned list: ")
print(r)
print()
return r
A = [1,5,8,3,0,9,2,7,4,6]
print("unsorted list: ")
print(A)
B = quickSort(A)
print("sorted list: ")
print(B)
| true |
5b622a7474cf14a82e340e32ee70a7f385ca2b6c | natepaxton/DiscreteMath | /project_7.py | 2,241 | 4.4375 | 4 | """
The purpose of this program is to perform a binary search within a
randomly generated list of integers between 0 and 200.
The program will first generate a list of integers using the random
generator from project 5, and will sort the list using the insert
sort from project 6. Binary searches can only be performed on sorted
lists.
The program will return the position of the integer being searched
for if it is present, and will return a message if not found.
"""
import random
class projectSeven:
def __init__(self):
#Generate the random number list
ints = self.irand(100, 200)
print("\nThe random list:\n" + str(ints))
#Sort the list
ints = self.insSort(ints)
print("\nThe sorted list:\n" + str(ints))
#Search for the index
c = int(input("\nEnter an integer to search for: "))
print(self.binSearch(ints, c))
def binSearch(self, nums, c):
#Variables to represent the start and end point, control logic
a = 0
b = len(nums) - 1
found = False
#Iterate over the values if not found
while a <= b and not found:
#Determine the midpoint for the search
mid = int((a + b) // 2)
#If the number matches, found == true
if nums[mid] == c:
found = True
#Increment or decrement the upper and lower bounds depending
#on comparison
else:
if c < nums[mid]:
b = mid - 1
else:
a = mid + 1
if found:
return "\n" + str(c) + " found at position " + str(mid + 1)
else:
return "\n " + str(c) + " is not in the sequence"
def irand(self, n, m):
b = list(range(n))
b = random.sample(range(m), n)
return b
#Sort the list using an insertion sort
def insSort(self, nums):
#Compare the positions in the array
for i in range(1, len(nums)):
#The value to be compared
currentvalue = nums[i]
#Assign the iterator to a new variable to avoid index errors
position = i
#Position must be greater than zero so the index can't be -1
while position > 0 and nums[position - 1] > currentvalue:
#Assign the value to a new position
nums[position] = nums[position - 1]
position = position - 1
#Assign the value to a new position
nums[position] = currentvalue
#Return the sorted array
return nums
p = projectSeven() | true |
ba06aeed3043b065a80bd3a4cd219a45325a04c9 | djschor/2-SI206Assignments | /sample_db_example.py | 2,220 | 4.3125 | 4 |
import sqlite3
conn = sqlite3.connect('music2.db') #makes a connection to the database stored in the
#file music.sqlite3 in the current directory, if file doesn't exist, it's created
cur = conn.cursor() #cursor is like a file handle that we can se to perform operations on the data stored in the datanase/ calling cursor() is smilar to calling open() for text files
# Make sure we can run this over and over
cur.execute('DROP TABLE IF EXISTS Tracks')
table_spec = 'CREATE TABLE IF NOT EXISTS '
table_spec += 'Tracks (id INTEGER PRIMARY KEY, '
table_spec += 'title TEXT, artist INTEGER, album TEXT, plays INTEGER)'
cur.execute(table_spec)
table_spec = 'CREATE TABLE IF NOT EXISTS '
table_spec += 'Artists (id INTEGER PRIMARY KEY, '
table_spec += 'name TEXT)'
cur.execute(table_spec)
statement = 'DELETE FROM Tracks'
cur.execute(statement)
statement = 'DELETE FROM Artists'
cur.execute(statement)
conn.commit()
artists = [
(None, 'The Clash'),
(None, 'The Sex Pistols'),
(None, 'The Ramones'),
(None, 'Lcur.execute(statement, t)')
]
statement = 'INSERT INTO Artists VALUES (?, ?)'
for a in artists:
cur.execute(statement, a)
conn.commit()
tracks = [
(None,'London Calling', 'The Clash', 'London Calling', 235),
(None,'Anarchy in the UK', 'The Sex Pistols', 'Never Mind the Bollocks', 144),
(None,'Blitzkrieg Bop', 'The Ramones', 'The Ramones', 89),
(None, 'Stairway to Heaven', 'Led Zeppelin', 'Led Zeppelin IV', 74),
]
statement = 'INSERT INTO Tracks VALUES (?, ?, ?, ?, ?)'
for t in tracks:
cur.execute(statement, t)
conn.commit()
# Write a query to get some data out and then fetch it all into a list...
query = "SELECT artist from Tracks"
cur.execute(query)
print("\nBelow, results of a query:\n")
query = "SELECT title FROM Tracks WHERE artist='Led Zeppelin'"
# execute the query...
cur.execute(query)
# Fetch it all:
result_one = cur.fetchone()
print(result_one)
print("\nBelow, results of another query:\n")
# Another query:
q2 = "SELECT * from Tracks WHERE instr(artist, 'The')"
cur.execute(q2)
result = cur.fetchall()
for tup in result:
print(tup)
conn.close() # Close connection to the database, we're done for now | true |
460e1a5d8e42b78611f4f8d4cc7c7f1fb0ee9404 | dipen7520/Internship-Akash-Technolabs | /Day-3_Task-3_15 basic_tasks/pract_09_less_100.py | 354 | 4.28125 | 4 | for i in range(3):
number = int(input(f'Enetr the number: '))
if number > 100:
print(f'Number is greater than 100.')
elif number == 100:
print(f'Number is a 100.')
else:
if number % 2 == 0:
print(f'Number is less than 100 and even.')
else:
print(f'Number is less than 100 and odd.') | false |
de19cdc9f55ca301d7e2326e5061e75790ef2cfd | dipen7520/Internship-Akash-Technolabs | /Day-3_Task-3_15 basic_tasks/pract_08_smallest_num.py | 314 | 4.15625 | 4 | number = []
for i in range(1, 3):
number.append(int(input(f'Enter the number{i}: ')))
if number[0] == number[1]:
print(f'{number[0]} and {number[1]} are equal.')
elif number[0] > number[1]:
print(f'{number[1]} is smaller than {number[0]}.')
else:
print(f'{number[0]} is smaller than {number[1]}.') | true |
a2786297357e1b2bc2461352cffdf735b9c4cc07 | gjwei/leetcode-python | /medium/Construct BinaryTreefromInorderandPostorderTraversal.py | 1,443 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
created by gjwei on 3/25/17
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
#
# self.right = None
from TreeNode import TreeNode
class Solution(object):
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: TreeNode
"""
return self.buildTreeRecursive(inorder, 0, len(inorder) - 1, postorder, 0, len(postorder) - 1)
def buildTreeRecursive(self, inorder, in_left, in_right, postorder, post_left, post_right):
if in_left > in_right or post_left > post_right:
return None
root = TreeNode(postorder[post_right])
root_index_inorder = self.find_root_position_in_inorder(inorder, root)
left_part_length = root_index_inorder - in_left
root.left = self.buildTreeRecursive(inorder, in_left, root_index_inorder - 1, postorder, post_left, post_left + left_part_length - 1)
root.right = self.buildTreeRecursive(inorder, root_index_inorder + 1, in_right, postorder, post_left + left_part_length, post_right - 1)
return root
def find_root_position_in_inorder(self, inorder, root):
for i in xrange(len(inorder)):
if root.val == inorder[i]:
return i
return -1
| true |
88377d4777541d8dba8154fa9baf30dfa02f2a94 | gjwei/leetcode-python | /easy/Multiply Strings.py | 1,082 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
created by gjwei on 6/1/17
"""
"""
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Subscribe to see which companies asked this question.
Show Tags
Show Similar Problems
"""
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result_len = len(num1) + len(num2) + 1
result = [0 for _ in xrange(result_len)]
def multiply_single(self, num, n):
result, charge = [], 0
for c in num[::-1]:
t = int(c) * int(n) + charge
charge = t / 10
result.append(t % 10)
if charge:
result.append(charge)
return ''.join(result[::-1])
| true |
8d8be21db87436ddd8c5fa86c2bda740b006d415 | miguelcoria94/AA-Week-17-Python | /range.py | 1,223 | 4.21875 | 4 | print('THREE CASES FOR RANGE')
print('A) End Value')
# STEP 1: Change the zero in the range to 10
# Notice how "10" is not included in the output
for i in range(10):
print(i)
print('B) Start & End Values')
# STEP 2: Code a `for` loop to print numbers 5 through 9
for i in range(5,10):
print(i)
print('C) Only Even Values')
# STEP 3: Print 0, 2, 4, 6 and 8 using a for loop
# Hint - range can take a 3rd parameter for the step distance
for i in range(0,9,2):
print(i)
# Write your function, here.
def get_sum_of_elements(list):
total = 0
for i in list:
total += i
return total
print(get_sum_of_elements([2, 7, 4])) # > 13
print(get_sum_of_elements([45, 3, 0])) # > 48
print(get_sum_of_elements([-2, 84, 23])) # > 105
# Write your function, here.
def get_indices(list, val):
indicies = []
for i in range(0, len(list)):
if val == list[i]:
indicies.append(i)
return indicies
print(get_indices(["a", "a", "b", "a", "b", "a"], "a"))
# Prints [0, 1, 3, 5]
print(get_indices([1, 5, 5, 2, 7], 7))
# Prints [4]
print(get_indices([1, 5, 5, 2, 7], 5))
# Prints [1, 2]
print(get_indices([1, 5, 5, 2, 7], 8))
# Prints []
| true |
a0a3cd3a3df86b006eb591bb8a2342274c47e5e3 | Felipepereiralima/Python | /Tabuada 3.0.py | 493 | 4.125 | 4 | #Exercício Python 67: Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo.
while True:
n = int(input('Quer ver a tabuada de qual valor? '))
if n < 0:
break
print('='*36)
for c in range (1, 11):
tabuada = n * c
print(f'{n} X {c} = {tabuada}')
print('=' * 36)
print('Programa tabuada encerrado. Obrigado por usar.') | false |
5bd15e45e2299ff7aa3c6a770dca00680200fad9 | KevinKupervaser/path_to_glory | /sumseriesavg.py | 370 | 4.1875 | 4 | import math
def sumseriesavg():
n = eval(input("How many numbers you want to enter: "))
x = 0
sum = 0
for i in range(n):
num = eval(input("Please enter a number: "))
sum += num
print("The sum of the amount of numbers is: ", sum)
print("The average of this series of numbers is:", sum / n)
sumseriesavg()
| true |
e02c106139f8e5a4aafe0d14d069d1e547e793f6 | csi013/CodingInterview | /1-2.py | 362 | 4.15625 | 4 | #check Permutation 2017 09 04 CSI#
def CheckPermutation(Str1,Str2):
if len(Str1) == len(Str2):
Str1 = sorted(Str1)
Str2 = sorted(Str2)
if Str1 == Str2:
print('True')
else:
print('False')
else:
print('False')
Str1 = input("string1: ")
Str2 = input("string2: ")
CheckPermutation(Str1,Str2)
| false |
fc743b487be49e660e07bae6b1f702d694425d25 | dplyakin/likbez | /algorithms/search.py | 652 | 4.1875 | 4 | """Search algorithms examples"""
def binary_search(source, target):
"""Binary Search."""
head = 0
tail = len(source) - 1
while head <= tail:
mid = (head + tail) // 2
print(f"check {mid} element")
value = source[mid]
if value > target:
tail = mid - 1
print(f"value is greater then target, search in head: [{head}:{tail}]")
elif value < target:
head = mid + 1
print(f"value is lower then target, search in tail: [{head}:{tail}]")
else:
print("target found")
return mid
print("target not found")
return -1
| true |
b698c3bb1fa9abba959086083aca6c1ebff6ce0e | pdiallo/Tutoriel-python | /exo.py | 1,152 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#print "Hello World"
def somme2(a, b):
"""
Fait la somme de deux entiers
"""
c = a + b
return c
p = somme2(1, 2)
print(p)
def somme4(m, n, h, f):
"""
Fait la somme de quatre entiers en se basant sur la fonction somm2()
"""
d = somme2(somme2(m,n), somme2(h,f))
return d
def somme3(w, x, r):
d = somme2(somme2(w, x), r)
return d
v = somme4(1,4, 3, 2)
print(v)
#estPaire = lambda x : (True if (x%2 == 0) else False)
estPaire = lambda x :(x%2 == 0)
# Fonction lambda qui retourne si un nombre est paire ou impaire
def sommeGeneral(*arg):
"""
Fait la somme de n nombres donnees en parametre (n etant variable)
"""
s = 0
for i in arg:
s = s + i
return s
s = sommeGeneral(10, 20, 30)
print(s)
x = (2, 4)
y = (3, 4)
import math
def distance(a, b):
"""
Calcule la distance entre deux points. Le deuxieme point doit etre un parametre facultatif, par defaut il vaut (0,0)
"""
q = math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)
return q
x = (3, 4)
y = (3, 4)
q = distance(x, y)
print(q)
| false |
be896faae1b4f8eedfec5913c2bcf2f645a8f8bc | bpbpublications/Natural-Computing-with--Python | /Chapter_01/perceptron_logic_gates.py | 1,110 | 4.25 | 4 | #Natural Computing with Python
#Chapter 1 - Neural Networks
#Perceptron logic gates
import numpy as np
#Define the AND logic gate
def And(x1, x2):
x = np.array([1, x1, x2])
w = np.array([-1.5, 1, 1])
y = np.sum(w*x)
if y <= 0:
return 0
else:
return 1
#Define the OR logic gate
def Or(x1, x2):
x = np.array([1, x1, x2])
w = np.array([-0.5, 1, 1])
y = np.sum(w*x)
if y <= 0:
return 0
else:
return 1
#Define the NAND logic gate
def Nand(x1, x2):
x = np.array([1, x1, x2])
w = np.array([1.5, -1, -1])
y = np.sum(w*x)
if y <= 0:
return 0
else:
return 1
#MAIN function
if __name__ == '__main__':
#input array
input = [(0, 0), (1, 0), (0, 1), (1, 1)]
#start evaluation
print("AND")
for x in input:
y = And(x[0], x[1])
print(str(x) + " -> " + str(y))
print("OR")
for x in input:
y = Or(x[0], x[1])
print(str(x) + " -> " + str(y))
print("NAND")
for x in input:
y = Nand(x[0], x[1])
print(str(x) + " -> " + str(y))
| false |
3220865845138d69ec007418c8fe5f8e4a6dfdf3 | Preethikoneti/pychallenges | /InterviewCake/02question.py | 1,679 | 4.125 | 4 | # You have a list of integers, and for each index you want to find the product of every integer except the integer at that index.
# Write a function get_products_of_all_ints_except_at_index() that takes a list of integers and returns a list of the products.
#
# For example, given:
#
# [1, 7, 3, 4]
#
# your function would return:
#
# [84, 12, 28, 21]
#
# by calculating:
#
# [7*3*4, 1*3*4, 1*7*4, 1*7*3]
#
# Do not use division in your solution.
# Will return an empty list if provided with an empty list, or a list with only one element
def get_products_of_all_ints_except_at_index(list_of_ints):
if len(list_of_ints) <= 1:
return []
product = 1
list = []
# This is a solution but not the one they wanted.
# for index, num in enumerate(list_of_ints, start=0):
# product = product * num
# for index, num in enumerate(list_of_ints, start=0):
# list.append(product/num)
for index, num in enumerate(list_of_ints, start=0):
for index2, num2 in enumerate(list_of_ints, start=0):
if index != index2:
product = product * num2
list.append(product)
product = 1
return list
def test_cases():
result1 = get_products_of_all_ints_except_at_index([])
if result1 != []:
print "Expect a list to be empty when empty list is passed to function."
result2 = get_products_of_all_ints_except_at_index([5])
if result2 != []:
print "Expect a list to have at least two elements."
result3 = get_products_of_all_ints_except_at_index([1,7])
if result3 != [7,1]:
print "Expect result to be [7,1]"
result4 = get_products_of_all_ints_except_at_index([1,6,9,5])
if result4 != [270,45,30,54]:
print "Expect result to be [270,45,30,54]"
test_cases() | true |
58a713308555a9e588a06ed87bed6d13e54b2b57 | osamudio/python-scripts | /fibonacci_2.py | 303 | 4.1875 | 4 | def fib(n: int) -> None:
"""
prints the Fibonacci sequence of the first n numbers
"""
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a+b
print()
return
if __name__ == "__main__":
n = int(input("please, enter a number: "))
fib(n)
| true |
5cb0ebf439bd62bb46158e3e94f8be78b8694eb2 | mftoy/early_python_studies | /assignment7_1.py | 250 | 4.21875 | 4 | # Use words.txt as the file name
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print('Error! Worng file name:',fname)
quit()
for line in fh:
line = line.rstrip()
line = line.upper()
print(line)
| true |
d306a558ab925c29b497f0cc981b70f3d0060650 | naz-rin/CyberRSA-Project | /rsa.py | 667 | 4.25 | 4 | terminate = 0
while terminate != 1:
print("Encrypt, Decrypt, or Terminate?")
answer=input("----->")
if answer == "Terminate":
terminate += 1
print ("Exiting...")
elif answer == "Encrypt":
n=
e=input("What is your ")
elif answer == "Decrypt":
print ("What is ")
def encryption(e,n):
print ("what is the message?")
message = input="Message:"
encrypted_message=""
for c in message:
numerize = ord(c)
encrypt = pow(numerize, e, n)
denumerize = chr(encrypt)
encrypted_message += denumerize
print (encrypted_message)
def decryption(d,n):
for u in encrypted_message:
numerize = ord(u)
decrypt = pow(numerize, d, n)
print (decrypt)
| false |
df4ec99e18a72b9b81e7c963eb0403df57a17a15 | hirara20701/Python | /practice 7.py | 247 | 4.15625 | 4 | '''Create a program that computes for the BMI of a person'''
'''Input -> weight, height
bmi = 703 * weight/(height * height)'''
w = eval(input("Enter weight(kg): "))
h = eval(input("Enter height(m): "))
bmi =(w / (h * h))
print (bmi) | true |
b6289a07191051f1ceaa87a387622ad52422ce86 | abcs-ab/Algorithms | /selection_sort.py | 796 | 4.15625 | 4 | #!/usr/bin/env python3
def selection_sort(seq):
"""Returns a tuple if got a tuple. Otherwise returns a list.
>>> t = (3, 1, 1, 4, -1, 6, 2, 9, 8, 2)
>>> selection_sort(t)
(-1, 1, 1, 2, 2, 3, 4, 6, 8, 9)
>>> l = [9, 9, 3, -1, 14, 67, 1]
>>> selection_sort(l)
[-1, 1, 3, 9, 9, 14, 67]
"""
alist = list(seq)
for idx, i in enumerate(alist):
minvalue_idx = idx
minvalue = i
for idx2, y in enumerate(alist[idx:]):
if y < minvalue:
minvalue_idx = idx + idx2
minvalue = y
alist[idx] = alist[minvalue_idx]
alist[minvalue_idx] = i
if isinstance(seq, tuple):
return tuple(alist)
return alist
if __name__ == "__main__":
import doctest
doctest.testmod()
| false |
a792cb50555f6c54e794c52be11069df9a77bfa5 | abcs-ab/Algorithms | /quick_sort.py | 2,386 | 4.3125 | 4 | #!/usr/bin/env python3
"""Python quick sort implementation with a comparisons counter.
Sorts in place, returns comparisons number.
Pivot selection can be done in 4 ways:
Always take the first element.
Always take the last element.
Choose median of 3 elements (first, last and the middle one).
Random choice.
First 2 methods can give you O(n**2) when an array is already sorted.
"""
import random
def quick_sort(alist, sidx, eidx, pivot_method=None):
"""Quick sort inplace implementation with comparisons counter. 4 methods to choose pivot:
:param alist: A list.
:param sidx: Start index for inplace list manipulation.
:param eidx: End index for inplace list manipulation.
:param pivot_method: None for default pivot selection: randomized. Other methods:
'f' (first), 'l' (last), 'm3' (median of 3 elements: first, last and the middle one).
:return: Comparisons number.
>>> a = [9, 3, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> b = [0, 3, 8, 1, 6, 8, 4]
>>> c = [9, 3, 8, 4, 0, 2, 1, 9, 2, 2, 10]
>>> quick_sort(a, 0, len(a), 'f')
37
>>> a
[0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9]
>>> quick_sort(b, 0, len(b), 'l')
10
>>> b
[0, 1, 3, 4, 6, 8, 8]
>>> quick_sort(c, 0, len(c), 'm3')
27
>>> c
[0, 1, 2, 2, 2, 3, 4, 8, 9, 9, 10]
"""
comps = 0
if eidx - sidx < 2:
return 0
if pivot_method == 'f': # First element
piv_idx = sidx
elif pivot_method == 'l': # Last element
piv_idx = eidx - 1
elif pivot_method == 'm3': # Median of 3 values (first, last and the middle one).
midx = (sidx + eidx - 1) // 2
med_of_three = [(alist[sidx], sidx), (alist[midx], midx), (alist[eidx - 1], eidx - 1)]
piv_idx = sorted(med_of_three)[1][1]
else:
piv_idx = random.randint(sidx, eidx-1) # Random pivot
alist[sidx], alist[piv_idx] = alist[piv_idx], alist[sidx]
pivot = alist[sidx]
i = sidx + 1
for j in range(sidx+1, eidx):
comps += 1 # adds each comparison.
if alist[j] < pivot:
alist[i], alist[j] = alist[j], alist[i]
i += 1
alist[i - 1], alist[sidx] = alist[sidx], alist[i - 1]
comps += quick_sort(alist, sidx, i - 1, pivot_method)
comps += quick_sort(alist, i, eidx, pivot_method)
return comps
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
de087ccadf474dab0b67377d9d9177c477e18752 | abcs-ab/Algorithms | /merge_sort.py | 2,478 | 4.1875 | 4 | #!/usr/bin/env python3
"""Merge sort implementation with inversions counter.
Max inversions number can be defined as n(n-1)/2
where n is a n-element array.
"""
def merge_sort(alist, inplace=False, print_inv=True, inversions=[0], reset_inv=True):
"""Merge sort implementation with inversions counter.
:param alist: list
:param inplace: bool. If True, list is sorted in place, otherwise a new list is returned.
:param print_inv: bool. If True prints out total inversions number.
:param inversions: mutable default argument to avoid globals (educational goal only).
:param reset_inv: bool. Inversions parameter is set to [0] when sorting is done.
>>> merge_sort([4, 3, 2, 1])
Inversions: [6]
[1, 2, 3, 4]
>>> merge_sort([5, 4, 3, 2, 1])
Inversions: [10]
[1, 2, 3, 4, 5]
>>> merge_sort([5, 4, 3, 2, 1, 5])
Inversions: [10]
[1, 2, 3, 4, 5, 5]
>>> merge_sort([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], True)
Inversions: [45]
"""
if inplace:
combined = alist
else:
combined = alist[:]
list_len = len(combined)
if list_len > 1:
middle = list_len // 2
left = combined[:middle]
right = combined[middle:]
merge_sort(left, True, False, inversions, False)
merge_sort(right, True, False, inversions, False)
left_idx = 0
right_idx = 0
for k in range(list_len):
if left_idx == len(left):
combined[k] = right[right_idx]
right_idx += 1
elif right_idx == len(right):
combined[k] = left[left_idx]
left_idx += 1
elif left[left_idx] <= right[right_idx]:
combined[k] = left[left_idx]
left_idx += 1
elif left[left_idx] > right[right_idx]:
combined[k] = right[right_idx]
right_idx += 1
# When this term is met. Count inversions by adding
# a number of remaining elements in a left sublist.
# Sublists are sorted, so when left element is greater
# than the right one, all next left elements are greater too.
inversions[0] += len(left[left_idx:])
if print_inv:
print("Inversions:", inversions)
if reset_inv:
inversions[0] = 0
if not inplace:
return combined
return None
if __name__ == "__main__":
import doctest
doctest.testmod()
| true |
a033d6d2d492e64b1d3b14fc0699ca0ace8c7819 | Santigio/Daily_Coding | /Calculator/calculator.py | 1,139 | 4.1875 | 4 |
Run = True
Exit = False
while Run:
button = int(input("Press 1(add), 2(subtract), 3(divide), 4(multiply)"))
User_input = int(input("Enter a number "))
User_input1 = int(input("Enter another number "))
def Addition(user1, user2):
return user1 + user2
def Subtration(user1, user2):
return user1 - user2
def Division(user1, user2):
return user1 / user2
def Multiplication(user1, user2):
return user1 * user2
if button == 1:
print(User_input, "+", User_input1, "=",
Addition(User_input, User_input1))
elif button == 2:
print(User_input, "-", User_input1, "=",
Subtration(User_input, User_input1))
elif button == 3:
print(User_input, "/", User_input1, "=",
Division(User_input, User_input1))
elif button == 4:
print(User_input, "*", User_input1, "=",
Multiplication(User_input, User_input1))
Question = input("Do you still want to continue? ")
if Question == "n" or "no":
quit()
else:
if Question == "yes" or "y":
continue
| true |
59a53b37d97a76d2ba66023e4218bc529233092c | tuvshinot/algorithm-sorting-DS | /leetcode/python/problems/recursion.py | 1,049 | 4.34375 | 4 | def power_num(base, expo):
""" recursively calculates power """
if expo == 0:
return 1
return base * power_num(base, expo - 1)
print(f'Power : {power_num(2, 2)}')
def factorial(num):
""" finding recursively factorial """
if num == 1:
return 1
return num * factorial(num - 1)
print(f'Factorial : {factorial(5)}')
def product_arr(arr):
""" Returns product of array """
if len(arr) == 0:
return 1
return arr[0] * product_arr(arr[1:])
print(f'Product of arr : {product_arr([1,2,3,4,5])}')
def reverse_str(str):
""" Returns reversed str """
if len(str) == 1:
return str
return str[-1] + reverse_str(str[:-1])
print(f'Reversed str : {reverse_str("abcd")}')
def is_palindrome(str):
""" Returns is str palindrome or not """
if len(str) == 1:
return True
if len(str) == 2:
return str[0] == str[1]
if str[0] == str[-1]:
return is_palindrome(str[1:-1])
return False
print(f'Is Palindrome : {is_palindrome("cabac")}')
| false |
6c02e785a307f4cfc4afe19b6aeb2e7ed4de52ff | conor1982/Python_Module | /plot.py | 2,216 | 4.3125 | 4 | #Conor O'Riordan
#Task 8
#Program that displays the plot of functions f(x) = x, g(x) = x^2, h(x) = x^3
#in the range of [0,4] on one set of axes
#Matplotlib for plotting
#Numpy for arrays
import matplotlib.pyplot as plt
import numpy as np
#variable using Numpy to create an array
#Similar to list, last value not included, at values are increasing by 1 step
#Ref: Lecture Video
#Ref: https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html
x = np.arange(0,4,1)
#Ref https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html
#Variable to smooth out X [0:4] over 500 evenly spaced steps
x_smooth = np.linspace(x.min(),x.max(),500)
#Variables for functions to be plotted E.G g(x) = 0,4,9
#https://www.khanacademy.org/math/algebra-home/alg-radical-eq-func/alg-graphs-of-radical-functions/v/graphs-of-square-root-functions
#f(x)
fx = x_smooth
#g(x)
gx = x_smooth**2
#h(x)
hx = x_smooth**3
#Ref https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html
#Ref https://matplotlib.org/2.1.2/api/_as_gen/matplotlib.pyplot.plot.html (details on plot line colours, legends and other features)
#plot of each function
#black coloured dash line, line width 2 label is f(x)
plt.plot(x_smooth,fx,'--k',label = "f(x) = x",linewidth = 2)
#blue coloured dotted line, line width 3, label is g(x)
plt.plot(x_smooth,gx,':b', label = "g(x) = x^2", linewidth = 3)
#navy coloured solid line, line width 4, label = h(x)
plt.plot(x_smooth,hx, 'navy', label = 'h(x) = x^3', linewidth = 4)
#display legend - from plt.plot label function
plt.legend()
#display plot title
plt.title('Weekly Task 8')
#display x axis label
plt.xlabel('Range')
#display y axis label
plt.ylabel('Function Value')
#start x axis at 0
plt.xlim(xmin = 0)
#start y axis at 0
plt.ylim(ymin = 0)
#https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib
#x axis tick frequency at 1
plt.xticks(np.arange(min(x), max(x)+1,1))
#Ref https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib
#y axis tik frequency every 2, to a value of 2 past the max value of the plot
plt.yticks(np.arange(min(hx), max(hx)+2,2))
#save plt
plt.savefig("Task 8")
| true |
64eb18cb3920698601e94b3426cc97af161c335a | rams4automation/SeleniumPython | /Collections/Set.py | 428 | 4.25 | 4 |
thisset = {"apple", "banana", "cherry"}
print(thisset)
for x in thisset:
print(x)
# ***************** Access Items
if "banana" in thisset:
print("banana" in thisset)
# ************** Add Items
adset= {"apple", "banana", "cherry"}
adset.add("Test")
print(adset)
# ***************** Update Items
upset= {"apple", "banana", "cherry"}
upset.update(["orange", "mango", "grapes"])
print(upset)
print(len(upset))
| true |
8f06c4da36c95a94ad302cf43b8002a190df4a80 | SlickChris95/practicePython | /exercise15.py | 604 | 4.25 | 4 | """
Write a program (using functions!) that asks the
user for a long string containing multiple words.
Print back to the user the same string, except
with the words in backwards order. For example,
say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.
"""
def reverseString(str):
#split String
newStr = str.split(' ')
#reverse list
newStr.reverse()
#join list
newStr = ' '.join(newStr)
#return
return newStr
print(reverseString('done are we dude'))
print(reverseString('! here of out get let\'s scoob like'))
| true |
b13cd873690bedf24ded93eb674a1105d5badcea | secgithub/python100Days | /day9/day9_002.py | 1,082 | 4.125 | 4 | # _*_ coding: utf-8 _*_
"""
__slots__魔法
限定自定义类型的对象,只能绑定某些属性
限定之后,对象就不能创建其他的属性了
"""
class Person(object):
# 限定Person的对象只能绑定下面几个属性
__slots__ = ('__name', '__age__', '__gender__')
def __init__(self, name, age):
self.__name = name
self.__age__ = age
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age__
@name.setter
def name(self, name):
self.__name = name
@age.setter
def age(self, age):
self.__age__ = age
def play(self):
if self.__age__ <= 18:
print('%s正在玩泥巴' % self.__name)
else:
print('%s正在玩电脑' % self.__name)
if __name__ == '__main__':
person = Person('小明', 19)
person.play()
person.name = '王重阳'
person.age = 10
person.play()
person.__gender__ = '1111'
person.__wtf = '2222'# AttributeError: 'Person' object has no attribute '__wtf'
| false |
0ed4fabdc713bfe8004c4f0da3966a4abe383852 | abhibalani/data-structures-python | /data_structures/stack.py | 1,469 | 4.375 | 4 | """Stack implementation in Python"""
class Stack:
"""Class for stack and its methods"""
def __init__(self):
"""Initialize the top of stack to none"""
self.top = None
def push(self, node):
"""
Method to push a node into a stack
:param node: Node to be pushed
:return: None
"""
if not self.top:
self.top = node
else:
node.next = self.top
self.top = node
return
def pop(self):
"""
Method to pop the value from top of the stack
:return: return the value which is popped
"""
if not self.top:
print('Stack is empty')
return
value = self.top.data
self.top = self.top.next
print('Value popped is: ', value)
return value
def print_stack(self):
"""Method to print the stack"""
current = self.top
while current:
print(current.data)
current = current.next
return
class Node:
"""Class for Node"""
def __init__(self, data):
self.data = data
self.next = None
stack = Stack()
stack.print_stack()
stack.push(Node(1))
stack.push(Node(2))
stack.push(Node(3))
stack.push(Node(4))
stack.push(Node(5))
stack.print_stack()
stack.pop()
stack.pop()
stack.pop()
stack.print_stack()
stack.pop()
stack.pop()
stack.print_stack()
stack.pop()
stack.pop()
stack.print_stack()
| true |
ab6aa091df7630bf3799053ebce2dcaeab79b6a1 | alfozaav/Software_Engineering | /Algorithms/QuickSort.py | 470 | 4.1875 | 4 | # QuickSort in Python
def quicksort(arr):
if len(arr) < 2:
return arr #Base case arrays with 0 or 1 elements are already sorted
else:
pivot = arr[0]
less = [ i for i in arr[1:] if i <= pivot ] #Sub-array of all elementes less than pivot
greater = [ i for i in arr[1:] if i > pivot ] #Sub-array of all elements greater than pivot
return quicksort(less) + [pivot] + quicksort(greater)
print quicksort([10, 5, 2, 3]) | true |
c0184233fc4d65c73110cbe014fed13d705ebd2a | sabdj2020/CSEE-5590---Python-DeepLearning | /ICP3/Class_Emp.py | 1,531 | 4.28125 | 4 | # create class emplyee
class employee:
emp_count = 0
salary_total = 0
# create the constructor for this class and give attributes value to objects
def __init__(self, n, f, s, d):
self.name = n
self.family = f
self.salary = s
self.department = d
employee.emp_count = employee.emp_count + 1
employee.salary_total = employee.salary_total + s
# calculate the average salary
def avg_salary(self):
average_salary = self.salary_total / self.emp_count
print("the average salary is " + str(average_salary))
# method to display the emplyees created
def display(self):
print("name:" + self.name, "family_name:" + self.family, "salary:" + str(self.salary),
"department:" + self.department)
# create class fulltime_employee that inherite from the class emplyee
class fulltime_employee(employee):
def __init__(self, n, f, s, d):
employee.__init__(self, n, f, s, d)
#instanciate three objects of type emplyee
emp1 = employee("Sabrina", "Djeddi", 3000, "Developer")
emp2 = employee("Nelya", "Aliane", 5000, "Designer")
emp3 = employee("Ghania", "Salhi", 4000, "Manager")
# display these 3 objects
emp1.display()
emp2.display()
emp3.display()
# instanciate an object that inherite from class emplyee and display it
emp4 = fulltime_employee("Tom", "Jerry", 4000, "Electrical")
emp4.display()
# display the salary
print("The number of emplyees is:" + str(employee.emp_count))
employee.avg_salary(employee)
| true |
007496134f811b7a3f7c81fa7b94c687ff02c751 | immortal3/Matrix_Inversion | /Main.py | 1,273 | 4.28125 | 4 | """
Program : program gets input of dynamic matrix from user and first it checks for matrix is invertible or not.
If matrix is invertible and then it try's to find inverse with RREF algorithms
Name : Patel Dipkumar p.
Roll No. : 201501070
for LA_Code_Submission_1
Warning : In some cases,when Value of Matrix gets very very small....it creates overflow and inverse of matrix
will not get correct.btw,It's not error of algorithms!!!!
"""
import RREF as rref
import Determinant as DM
print ("Enter a row of matrix(row = column):")
row = input(">>>")
col = row
list = []
for x in range(int(row)):
list.append([])
for y in range(2*int(col)):
list[x].append(0)
print ('\n\n')
for x in range(int(row)):
for y in range(int(col)):
print ("Row %d Col %d"%(x+1,y+1))
temp = input(">>>")
list[x][y] = float(temp)
for x in range(int(row)):
list[x][x+int(row)] = 1
print ("\n\nGiven Matrix:\n")
for i in range(len(list)):
for j in range(0,int(len(list[i])/2)):
print (list[i][j],end="\t")
print ("\n")
print ("\n\n")
inverseflag = DM.finddeterminant(list)
if(inverseflag != 0):
rref.findRREF(list)
else:
print ("Inverse of Given Matrix is not possible!!")
| true |
064e7c48380aa4bb6aa985a1187ef762787430ae | alexandersuarez96/python-tarea | /ejerciciosiete.py | 401 | 4.28125 | 4 | """Diseña un programa que, a partir del valor de la base y de la altura de
un triángulo (3 y 5 metros, respectivamente), muestre el valor de su área
(en metros cuadrados).Recuerda que el área A de un triángulo se puede
calcular a partir de la base y la altura como A = Base * Altura / 2 ."""
base=3
altura=5
area=(base*altura/2)
print("El area del triangulo es igual a:{} metros".format (area)) | false |
b6996db5a5225c1ae09af9c65faff0b7f160ae15 | Diego0103/EjPractica | /assignments/CuentaNumeros/src/exercise.py | 541 | 4.15625 | 4 | #Cuenta números
#Escribe un programa que lea un número positivo n, e imprima todos los números en orden desde el 1 hasta n. Cada uno de los números debe ser impreso en una linea por separado.
#Entrada
#Un número entero positivo n
#Salida
#Los números enteros desde 1 hasta n, uno en cada renglón
#Ejemplo de ejecución del programa:
#>>>5
#1
#2
#3
#4
#5
def main():
#escribe tu código abajo de esta línea
n=int(input("Cuál es el número? "))
for x in range(1,n+1):
print(x)
if __name__=='__main__':
main()
| false |
e424bc5b6522bfae9daa47e960f60e419519c22b | steveyttt/python | /flow/if-else-elif/if-elif-else.py | 352 | 4.1875 | 4 | print("enter a name")
name = input()
#If runs ONCE to check a condition and then performs an action
if name == "alice":
print('Hi ' + str(name))
elif name == "bobby":
print('Hi Bobby, not Hi Alice')
elif name == "jimmy":
print('Hi jimmy, not Hi Alice')
else:
print("I dont like you, you are not Alice")
print("if statement complete")
| true |
09baf9ff03008b7d6c859b4b337cc95e50a22e41 | marios1400/Ta-sphlaia-Dhrou | /thema 12.py | 798 | 4.125 | 4 | import math
a = input ("Give the first number : ")
b = input ("Give the second number : ")
c = input ("Give the third number : ")
if (math.fabs(c-b)<a and a<b+c):
if (a>b and a >c):
if (a*a==b*b+c*c):
print ("3")
elif (a*a>b*b+c*c):
print("2")
elif (a*a<b*b+c*c):
print ("1")
elif (b>a and b>c):
if (b*b==a*a+c*c):
print ("3")
elif (b*b>a*a+c*c):
print("2")
elif (b*b<a*a+c*c):
print ("1")
elif (c>a and c>b):
if (c*c==b*b+a*a):
print ("3")
elif (c*c>b*b+a*a):
print("2")
elif (c*c<b*b+a*a):
print ("1")
elif (a==b and a==c):
print ("1")
else:
print ("-1")
| false |
78459a630f5ee5cc394337519767513df3ef6242 | Meenal-goel/assignment_13 | /excp.py | 2,343 | 4.375 | 4 | #1.- Name and handle the exception occured in the following program:
a=3
try:
if a<4:
a=a/(a-3)
print(a)
except Exception as er :
print("Name of exception occured is :",er)
print("\n")
print("*"*25)
print("\n")
#2- Name and handle the exception occurred in the following program:
l=[1,2,3]
try:
print(l[3])
except Exception as er :
print("Name of exception occured is :",er)
print("\n")
print("*"*25)
print("\n")
#3- What will be the output of the following code:
'''# Program to depict Raising Exception
try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not'''
'''OUTPUT:
An exception
Traceback (most recent call last):
File "C:\Git\assignment_13\excp.py", line 31, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there'''
#4- What will be the output of the following code:
''' # Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
OUTPUT:
-5.0
a/b result in 0'''
#5.Write a program to show and handle following exceptions:
#1. Import Error
#2. Value Error
#3. Index Error
try :
from math import minus
except ImportError as er1:
print("EXCEPTION OCCURED")
print(er1)
print("\n")
try:
li = [0,1,3,str]
print(li[5])
except IndexError as er2:
print("EXCEPTION OCCURED")
print(er2)
print("\n")
try:
val = int("meenal")
except ValueError as er3:
print("EXCEPTION OCCURED")
print(er3)
print("\n")
print("\n")
print("*"*25)
print("\n")
#6- Create a user-defined exception AgeTooSmallError() that warns the user when they have entered age less than 18. The code must keep taking input till the user enters the appropriate age number(less than 18).
class AgeTooSmallError(Exception):
"Raised when age is less than 18"
age = 18
while True:
try:
ip_age = int(input("enter the age:"))
if (ip_age<age):
raise AgeTooSmallError
break
except AgeTooSmallError:
print("WARNING : Age must not be less than 18")
print()
print("YEAH,it's perfect")
| true |
c0e46b9f2ee0b2fc24d9225a4f41350660153187 | dhruvbaid/Project-Euler | /055 - lychrelNumbers.py | 1,432 | 4.1875 | 4 | """
Lychrel Numbers: if we take a number, reverse it, and add the two, we obtian a
new number. If we do this repeatedly, sometimes, we end up with a palindrome. If
we can never obtain a palindrome, however, the original number is called a
Lychrel Number. How many Lychrel Numbers are there below 10,000?
Assumptions:
1. It will not take more than 50 iterations to obtain a palindrome IF the
number is not Lychrel.
2. Palindromic numbers are not automatically non-Lychrel; they have to be
iterated as well.
"""
# isPalindrome : checks if a number is palindromic
def isPalindrome(x: int) -> bool:
xStr = str(x)
for i in range(int(len(xStr)/2)):
if xStr[i] != xStr[len(xStr) - 1 - i]:
return False
return True
# reverse : reverses a given number and returns the new integer
def reverse(x: int) -> int:
xStr = str(x)
rev = int(xStr[::-1])
return rev
# main : returns the number of Lychrel Numbers from 1 to maxNum (inclusive)
def main(maxNum: int) -> int:
lychrel = []
for num in range(1, maxNum + 1):
iterated = num + reverse(num)
for iteration in range(50):
if isPalindrome(iterated):
break
elif iteration == 49:
lychrel.append(num)
break
else:
iterated += reverse(iterated)
return len(lychrel)
| true |
2e3da8863fa91f2061d3289f9e8685ffcf182272 | tqsclass/edX | /6001x/ps6/finger-exercise.py | 2,742 | 4.125 | 4 | class Queue(object):
def __init__(self):
self.queue = []
def insert(self,e):
self.queue.append(e)
#print self.queue
def remove(self):
if len(self.queue) > 0:
e = self.queue[0]
del self.queue[0]
#print self.queue
return e
else:
raise ValueError()
q = Queue()
q.insert(3)
q.insert(7)
q.insert(6)
q.insert(8)
q.remove()
print q.insert(22)
print q
print q.remove()
print q.remove()
print q.remove()
print q.remove()
print q.remove()
print q.remove()
print q.remove()
print q.remove()
class intSet(object):
"""An intSet is a set of integers
The value is represented by a list of ints, self.vals.
Each int in the set occurs in self.vals exactly once."""
def __init__(self):
"""Create an empty set of integers"""
self.vals = []
def insert(self, e):
"""Assumes e is an integer and inserts e into self"""
if not e in self.vals:
self.vals.append(e)
def member(self, e):
"""Assumes e is an integer
Returns True if e is in self, and False otherwise"""
return e in self.vals
def remove(self, e):
"""Assumes e is an integer and removes e from self
Raises ValueError if e is not in self"""
try:
self.vals.remove(e)
except:
raise ValueError(str(e) + ' not found')
def __str__(self):
"""Returns a string representation of self"""
self.vals.sort()
return '{' + ','.join([str(e) for e in self.vals]) + '}'
def intersect(self,s2):
assert type(s2) == type(self)
iset = intSet()
for val in self.vals:
if s2.member(val):
iset.insert(val)
return iset
return self.intersection(s2)
def __len__(self):
#assert type(self) == type(s)
return len(self.vals)
class Coordinate(object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __str__(self):
return '<' + str(self.getX()) + ',' + str(self.getY()) + '>'
def __eq__(self,o):
assert type(other) == type(self)
if (self.x == o.x) and (self.y == o.y):
return True
else:
return False
def __repr__(self):
return 'Coordinate(' + str(self.getX()) + ', '+str(self.getY()) + ')'
| true |
39741e221c1cda5a85fcfbb5b7990e98b40790c2 | acviana/coding-practice | /fibonacci.py | 1,219 | 4.46875 | 4 | '''
A function that generates the nth Fibonacci number.
A function that generates the Fibonacci sequence through the nth term.
'''
def fibonacci_number(n):
'''
A naive recursive implementation that returns the nth Fibonacci
number.
'''
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_number(n - 1) + fibonacci_number(n - 2)
def test_fibonacci_number():
assert fibonacci_number(7) == 8, fibonacci_number(8)
def fibonacci_sequence(n):
'''
A naive implementation that returns 1st n values in the Fibonacci
series.
'''
if n == 0:
return [0]
elif n == 1:
return [0, 1]
else:
temp = fibonacci_sequence(n - 1)
return temp + [temp[-1] + temp[-2]]
def test_fibonacci_sequence():
assert fibonacci_sequence(7) == [0, 1, 1, 2, 3, 5, 8], fibonacci_sequence(7)
if __name__ == '__main__':
# test_fibonacci_number()
# test_fibonacci_sequence()
# import timeit
# for n in range(0, 51, 5):
# trial = timeit.timeit(f'fibonacci_sequence(n)', globals=globals())
# print(f'N = {n}: {trial} s')
# import cProfile
# cProfile.run('fibonacci_sequence(5)')
| false |
5f4cae53855dd30b896a52ac7f60d5e3bef30105 | Anoop-myplace/sample | /RPS_mini_project.py | 1,954 | 4.15625 | 4 | import random
print("<===== It's a Rock Paper Scissor Game =====>")
ucount,ccount = 0,0
while True:
while True:
print("\n1. Rock\n2. Paper\n3. Scissor\n")
user_choice = input("Please Enter your Choice : ")
user_choice = user_choice.lower()
if user_choice not in ['rock','paper','scissor']:
print("Please enter a valid choice")
else: break
print("Your choice is : {}".format(user_choice))
cmp_choice = random.choice(['rock','paper','scissor'])
print("\nComputer's choice is : {}".format(cmp_choice))
print("\t"+user_choice+"\n (V/S)\n\t"+cmp_choice+"\n")
result = None
if ((user_choice=='rock' and cmp_choice=='scissor') or
(cmp_choice=='scissor' and user_choice=='rock')):
result = 'rock'
elif ((user_choice=='paper' and cmp_choice=='rock') or
(cmp_choice=='rock' and user_choice=='paper')):
result = 'paper'
elif ((user_choice=='scissor' and cmp_choice=='rock') or
(cmp_choice=='rock' and user_choice=='paper')):
result = 'rock'
elif ((user_choice=='rock' and cmp_choice=='paper') or
(cmp_choice=='paper' and user_choice=='rock')):
result = 'paper'
else:
result = 'scissor'
if (user_choice == cmp_choice):
print("<===== Draw =====>")
elif (user_choice == result):
print("<===== You Win =====>")
ucount += 1
else :
print("<===== Computer win's =====>")
ccount += 1
ans = input("Do you want to play again? Y/N : ")
if(ans == 'n' or ans == 'N'):
break
if(ucount > ccount):
print("****** Congradualtion You have won this Game with {} points ******".format(ucount))
else:
print("****** You lost this game by {} points ******".format(ccount-ucount))
print("****** Better Luck Next Time ******")
print("\nThanks for Playing this Game")
| false |
57d354ad199b829b0d1131d59c35f32d05e37eac | raj-savaj/MCA | /Python/FinadAll_Ex.py | 254 | 4.21875 | 4 | import re
str="The rain in Spain"
##x = re.findall("ai",str)
##
##print(x)
#return the List if not match return empty
# ~ The Search() Function
x = re.search("S",str,re.I);
if x :
print("Pattern Found")
else:
print("Not Found")
| true |
b47b9ab39f79a8e3299c25ef62cf5757839c962e | wardmike/Data-Structures | /Trees/Binary Tree/check_symmetry.py | 920 | 4.28125 | 4 | from tree_node import TreeNode
class BinaryTree:
# takes two nodes (one for each side of the tree) & recursively calls opposite sides on each
# the tree is symmetric if each left from node1 equals a right from node2 and vice versa
def isSymmetricRecursive(self, node1: TreeNode, node2: TreeNode) -> bool:
if node1 != None and node2 != None and node1.val == node2.val:
path1Symmetric = self.isSymmetricRecursive(node1.left, node2.right)
path2Symmetric = self.isSymmetricRecursive(node1.right, node2.left)
return (path1Symmetric and path2Symmetric)
elif node1 == None and node2 == None:
return True
else:
return False
# checks if a binary tree is symmetric
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
return self.isSymmetricRecursive(root.left, root.right)
| true |
9c8cadb138f01f2983c3bb65936e7cafd2b6b648 | CrazyYong/pythonProject | /直接赋值深浅拷贝.py | 1,347 | 4.21875 | 4 | #直接赋值
#字符串
# str1='Python'
# str2=str1
# print(id(str1))
# print(id(str2))
# str2='123'
# print(id(str1))
# print(id(str2))
# print(str2)
#列表
list1=[1,2,3,['问','Python']]
list2=list1
# print(list2)
list2[0]='AI'
print(list1)
print(list2)
#深浅拷贝
#原始对象
import copy
list0=[1,2,3,['we','haha','Python']]
#浅拷贝
list1=list0[:]
list2=list(list0)
list3=list0.copy()
list4=copy.copy(list0)
#深拷贝
# list0=[1,2,3,['we','haha','Python']]
listd=copy.deepcopy(list0)
# print(id(list0))
# print(id(list1))
# print(id(list2))
# print(id(list3))
# print(id(list4))
# print(id(list0[0]))
# print(id(list1[0]))
# print(id(list2[0]))
# print(id(list3[0]))
# print(id(list4[0]))
# print(id(listd[0]))
# list1[0]='A1'
# list2[0]='A2'
# list3[0]='A3'
# list4[0]='A4'
# listd[0]='A5'
# print(list0)
# print(list1)
# print(list2)
# print(list3)
# print(list4)
# print(listd)
# print(id(list0[0]))
# print(id(list1[0]))
# print(id(list2[0]))
# print(id(list3[0]))
# print(id(list4[0]))
# print(id(listd[0]))
list0=[1,2,3,['we','haha','Python']]
list1[3][0]='11'
list2[3][0]='12'
list3[3][0]='13'
list4[3][0]='14'
listd[3][0]='15'
print(id(list0[3]))
print(id(list1[3]))
print(id(list2[3]))
print(id(list3[3]))
print(id(list4[3]))
print(id(listd[3]))
print(list0)
print(list1)
print(list2)
print(list3)
print(list4)
print(listd) | false |
e1a33f2edd30d9fde36f3167f19b05fbea94e8ca | CrazyYong/pythonProject | /globalExample.py | 1,155 | 4.28125 | 4 | #!/usr/bin/python3
#coding=utf-8
#global全局变量
#用global之后就可以修改外面的变量
a='6'
def fun():
global a
a = '7'
print (a)
fun()
print (a)
#如果不用,那么修改的只是内部的变量跟外部的变量没关系
def func_local(x):
print ('x is', x)
x = 2
print ('Chanaged local x to',x)
x = 50
func_local(x)
print ('x is still', x)
#函数参数若是list、set、dict可变参数,在函数内改变参数,会导致该参数发生变化,例如:
#(1)
def func_local(x):
print ('x is', x)
x.append(10)
print ('Chanaged local x to',x)
x = range(6)
func_local(x)
print ('x is', x)
#(2)
def func_local(x):
print ('x is', x)
x.add(10)
print ('Chanaged local x to',x)
x = set(range(6))
func_local(x)
print ('x is', x)
#(3)
def func_local(x):
print ('x is', x)
x.add(10)
print ('Chanaged local x to',x)
x = set(range(6))
func_local(x)
print ('x is', x)
#如果是元组的话,就不行了,改变不了外面的
def func_local(x):
print ('x is', x)
x = (4, 5, 6)
print ('Chanaged local x to',x)
x = (1,2,3,)
func_local(x)
print ('x is', x)
| false |
c708b2ce06476d82c88dc6c694ccca497920e6f6 | jingweiwu26/Practice_code | /recursive.py | 451 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 30 15:12:49 2017
@author: Wu Jingwei
"""
arr=[1,2,[3,4,[5,6]]]
ar=[]
def unlist(arr_):
# a list contain the unlist
for i in arr_:
if type(i)!= list:
ar.append(i)
else:
for j in i:
if type(j)!=list:
ar.append(j)
else:
unlist(j)
return ar
print unlist(arr) | false |
1ec84c448a4f0c10619c9fe031791de5dfc0cda1 | karthika-onebill/python_basics_assignments | /Day1_Assignments/qn11.py | 436 | 4.375 | 4 | # program to print characters at the odd positions first followed by even position characters Input: SOFTWARE Output:OTAESFWR (with and without slice operator)
s = "SOFTWARE"
# with using slice operator
print(s[1:len(s):2]+s[0:len(s):2])
res_odd = ""
res_even = ""
# without using slice operator
for i in range(0, len(s)):
if(i % 2 == 1):
res_odd += s[i]
else:
res_even += s[i]
print(res_odd+res_even)
| true |
05dc40f5ef44af0ac34da86d47212157d097c78f | karthika-onebill/python_basics_assignments | /Day2_Assignments/qn1.py | 1,132 | 4.25 | 4 | '''
1) Given an integer,n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 10 , print Weird
If n is even and greater than 20 , print Not Weird
Input Format : A single line containing a positive integer,n .
Constraints : 1≤n≤100
Output Format : Print Weird if the number is weird; otherwise, print Not Weird. '''
# way1 (using ternery operator)
n = int(input("Enter n : "))
if(n >= 1 and n <= 100):
print("Weird" if(n % 2 == 1) else "Not Weird" if (n % 2 == 0 and (n in range(2, 6))) else "Weird" if ((n %
2 == 0) and (n in range(6, 11))) else "Not Weird" if (n % 2 == 0 and n > 20) else "")
# way2 (using nested if)
if(n >= 1 and n <= 100):
if(n % 2 == 1):
print("weird")
if(n % 2 == 0 and (n in range(2, 6))):
print("Not Weird")
if(n % 2 == 0 and (n in range(6, 11))):
print("Weird")
if(n % 2 == 0 and n > 20):
print("Not Weird")
| true |
24b06cf8b6cd014652e3bd3437a34a337388b2de | Ajuwon-Mormon-Love/CS2041 | /check04a.py | 1,055 | 4.125 | 4 | class Person():
"""Person class contains a name and birth year"""
def __init__(self):
self.name = "anonymous"
self.birthyear = "unknown"
def __str__(self):
return self.name + " (b. " + self.birthyear + ")"
class Book():
"""Book class contains a title and an author (Person class), and a publisher"""
def __init__(self):
self.title = "untitled"
self.author = Person()
self.publisher = "unpublished"
def __str__(self):
authStr = str(self.author)
return self.title + "\nPublisher:\n" + self.publisher + "\nAuthor:\n" + authStr
def setBook(self):
print("")
print("Please enter the following:")
self.author.name = input("Name: ")
self.author.birthyear = input("Year: ")
self.title = input("Title: ")
self.publisher = input("Publisher: ")
print("")
def main():
book = Book()
print(book)
book.setBook()
print(book)
if __name__ == "__main__":
main() | false |
c78b0feac93531a61de28148a078c2d3cbddcade | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/7 - Guessing Game Mini Project/v2_guessing_game.py | 556 | 4.28125 | 4 | '''
starter code
'''
import random
random_number = random.randint(1,10) # numbers 1-10
# handle user guesses
# if the guess correct, tell them they won
# otherwise tell them if they are too high or too low
# BONUS - let them play again if they want!
'''
my code
'''
guess = ''
while guess != random_number:
guess = input("Choose a number between 1 and 10: ")
guess = int(guess)
if guess == random_number:
print("You chose correctly!")
elif guess < random_number:
print("Too low!")
else:
print("Too high!") | true |
8fbbb4f84e5776ed71c2d1a5ef1824766112772a | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/4 - Boolean and Conditional Logic/getting_user_input.py | 562 | 4.40625 | 4 | # there is a built-in function in Python called "input" that will prompt the user and store the result to a variable
name = input("Enter your name here: ")
print(name)
# you can combine the variable that an end user input something to with a string
data = input("What's your favorite color?")
print("You said " + data)
# preferred to do a print statement first, then declare the variable and print the variable later -- this also puts the input on a separate line
print("What's your favorite color?")
data = input()
print("You said " + data)
| true |
f8597697abb74520f782cf91ed5ad66f109bcfc1 | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/6 - Loops/for_loops_quizzes.py | 641 | 4.34375 | 4 | # what numbers does the following range generate?
# range(5,10)
print(5,6,7,8,9)
# what numbers does the following range generate?
# range(3)
print(0,1,2)
# what is printed out after the following code?
# nums = range(1,5)
# print(nums)
range(1,5)
# what numbers does the following range generate?
# range(8,0,-2)
print(8,6,4,2)
# Use a loop to add up every odd number from 10-20 (inclusive) and store the result in the variable x
# Add up all odd numbers between 10 and 20
# Store the result in x:
# x = 0
# Your Code Goes here
x = 0
for y in range(10,21):
if (y % 2) != 0:
x = x + y | true |
66468308d722571298827e4be8077a6b44e803a3 | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/2 - Numbers and Math/math_quizzes.py | 1,405 | 4.5 | 4 | # How can we add parenthesis to the following expression to make it equal 100?
# 1 + 9 * 10
print((1+9)*10) # putting the parenthesis around the 1+9 equations equals 10, which when multiplied by 10 = 100
# What is the result of the following expression?
# 2 + 10 * 5 + 3 * 2
print(58) # multiplications occur first in order of operation which changes the equation to 2 + 50 + 6, adding them together equals 58
# What is the result of the following expression?
# 6 * 8 / 2**3 - 2 * 2
print(2) # the exponentiation occurs first, 2**3=8, then multiplication - 6*8=48 and 2*2=4, changing the equation to 48 / 8 - 4. Division occurs, 48/8=6. Subtraction occurs, 6-4=2.
# What is the result of running the following code?
# 1/2 * 2 # + 1
print(1.0) # the comment prevents the latter half of the line from running, so we only see 1/2 * 2 which is 1.0. 1/2=0.5, which when multiplied by 2 equals 1
# Which of the following result in integers in Python?
# A. 6/2
# B. 5//2
# C. 6.5*2
print("B") # A will return a float since all equations using / return floats, C will return a float since a float is part of the equation (6.5)
# What is the result of 16 //6?
print(2) # 6 is only divisble by 16 twice
# What is the result of 111 % 7?
print(6) # This equation will return 6 - because there is a remainder of 6 after 111 is divided by 7 (15 times - 7*15=105, 111-105=6) | true |
6deace0a5fe8fc79db596281577960d1b9ced540 | Jacobo-Arias/Ordenamiento | /counting_sort.py | 1,292 | 4.125 | 4 | # Counting sort in Python programming
def countingSort(array):
size = len(array)
output = [0] * size
# Initialize count array
count = [0] * size*2
# Store the count of each elements in count array
for i in range(0, size):
count[array[i]] += 1
# Store the cummulative count
for i in range(1, size*2):
count[i] += count[i - 1]
# Find the index of each element of the original array in count array
# place the elements in output array
i = size - 1
while i >= 0:
output[count[array[i]] - 1] = array[i]
count[array[i]] -= 1
i -= 1
# Copy the sorted elements into original array
for i in range(0, size):
array[i] = output[i]
data = [97, 139, 195, 85, 105, 79, 162, 129, 25, 148, 63, 118, 35, 0, 16, 77, 174, 42, 110, 51, 72, 141, 108, 182, 54, 140, 24, 92, 119, 27, 165, 185, 5, 37, 19, 196, 107, 14, 153, 144, 187, 17, 149, 50, 64, 179, 104, 13, 62, 115, 159, 143, 32, 70, 93, 132, 109, 29, 106, 96, 122, 20, 94, 36, 114, 145, 111, 1, 180, 88, 7, 126, 74, 39, 53, 147, 116, 173, 30, 46, 183, 191, 4, 198, 134, 193, 18, 59, 76, 164, 136, 33, 199, 160, 48, 178, 154, 103, 158, 138]
# data = [4, 2, 2, 8, 3, 3, 1]
countingSort(data)
print("Sorted Array in Ascending Order: ")
print(data) | true |
b71c3d01b15bc273140abdb805d60062562da99d | bitsapien/anuvaad | /public/phase-2-20160620022203/PYTHON/skyscraper.py | 398 | 4.125 | 4 | #!/usr/bin/python
# Name : Skyscraper
# input:
# n : number of skyscrapers
# k : number of stories to move
# h : each row has height of each skyscraper
elements = raw_input().strip().split(' ')
n = int(elements[0])
k = int(elements[1])
h_elements = raw_input().strip().split(' ')
h = map(int, h_elements)
# write your code here
# store your results in `j`
# output
# Dummy Data
j = 3
print(j)
| false |
a793ee88d44635868f823faa3153e703f71daf05 | Inkozi/School | /AI/HelloWorld.py | 882 | 4.1875 | 4 | ##
##HOMEWORK # 1
##
## NAME = CHARLES STEVENSON
## DATE = AUGUST 25, 2016
## CLASS = Artificial Intelligence TR 8 - 9:20
##
##
## Description:
## This is the first homework assignment
## where I read a file into a priority queue
## and then outputed to the console by sorting
## the integers using the priority queue
##
##
from Queue import PriorityQueue
def readLines(f, q):
#Extract name
name = f.readline()
name = name[:-1]#get rid of /n character
for line in f:
num = int (line[:-1])
q.put(num)#put number into priority queue
return name
def main():
#get && open file
fileName = "priority.txt"
f = open(fileName, 'r+')
#create queue
q = PriorityQueue()
#Load Queue
name = readLines(f, q)
#Output Queue && Name
print("Hello " + name + "!")
while not q.empty():
print(q.get())
#execute
main()
| true |
652603e6c06ecf9f05d507a0d4607d701fdd4fb9 | ruben-lou/design-patterns | /behavioural-patterns/strategy.py | 976 | 4.125 | 4 | import types
class Strategy:
"""The Strategy Pattern class"""
def __init__(self, function=None):
self.name = "Default Strategy"
# If a reference to a function is provided, replace the execute() method with the given function
if function:
self.execute = types.MethodType(function, self)
def execute(self):
"""Default method that prints the name of the strategy being used"""
print("{} is used.".format(self.name))
# Replacement method 1
def strategy_one(self):
print("{} is used to execute method 1".format(self.name))
# Replacement method 2
def strategy_two(self):
print("{} is used to execute method 2".format(self.name))
# Creating default strategy
s0 = Strategy()
# Executing default strategy
s0.execute()
# First variation of default strategy
s1 = Strategy(strategy_one)
s1.name = "Strategy 1"
s1.execute()
# Second variation
s2 = Strategy(strategy_two)
s2.name = "Strategy 2"
s2.execute()
| true |
528c81f911302dd6ddea96f0d7738eb967b8fbb9 | justiniansiah/10.009-Digital-Word | /Week 8/HW03_Numerical Differentiation.py | 728 | 4.21875 | 4 | from math import *
import math
#return only the derivative value without rounding
#your return value is a float, which is the approximate value of the derivative
#Tutor will compute the approximate error based on your return value
class Diff(object):
def __init__(self,f,h=1E-4):
self.f = f
self.h = h
def __call__(self,x):
return ((self.f(x+self.h))-self.f(x))/(self.h)
#
# def f(x):
# return 0.25*x**4
#
# df = Diff(f)
#
# for x in (1, 5, 10):
# df_value = df(x) # approx value of derivative of f at point x
# exact = x**3 # exact value of derivative
# print "f'(%d)=%g (error = %.2E)" %(x, df_value , exact - df_value )
df = Diff(math.log,0.1)
print df(10.0) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.