blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ea7b254cac5d2fce96496f8a6fa49d573ef83078 | seema1711/My100DaysOfCode | /Day 5/AddEleQueue.py | 984 | 4.21875 | 4 | <<<<<<< HEAD
### ADDING ELEMENTS TO A QUEUE ###
class Queue:
def __init__(self):
self.queue = list()
def add(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TQueue = Queue()
TQueue.add('Taj1')
TQueue.add('Taj2')
TQueue.add('Taj3')
TQueue.add('Taj4')
print(TQueue.size())
=======
### ADDING ELEMENTS TO A QUEUE ###
class Queue:
def __init__(self):
self.queue = list()
def add(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TQueue = Queue()
TQueue.add('Taj1')
TQueue.add('Taj2')
TQueue.add('Taj3')
TQueue.add('Taj4')
print(TQueue.size())
>>>>>>> 3ab12aa2dd515dac2d001ccb20fcb678b9842d4a
| true |
44b0f6ad8977686865b8eb3fc78b6215533715d1 | KlimentiyFrolov/-pythontutor | /Занятие 8. Функции и рекурсия/задача 2.PY | 243 | 4.1875 | 4 | #http://pythontutor.ru/lessons/functions/problems/negative_power/
def power(a, n):
b = 1
for i in range(abs(n)):
b *= a
if n >= 0:
return b
else:
return 1 / b
print(power(float(input()), int(input()))) | true |
49f4af3bb658ec31944b69a42b1745300aa849b0 | HenFaibishProjects/Python | /mine/The-Basic/If-Else.py | 485 | 4.21875 | 4 | # Simple if condition:
num1 =5
if num1 > 4:
print num1
# Using and,or,not
num2 =5
if num2 > 4 and num2 < 3:
print num2
num3 =5
if num3 > 4 or num3 < 3:
print num3
num4 =5
if not num4 == 4:
print num4
# Add Elese:
num5 = 10
if num5 > 5:
print 'Num5 is bigger then 5'
else:
print 'Num5 is smaller then 5'
# Elif:
num6 = 10
if num6 > 5:
print 'Num5 is bigger then 5'
elif num6 < 5:
print 'Num5 is smaller then 5'
else:
print 'Num5 is smaller then 5' | false |
1197b645af240babf6cefa4be8af88f32149ed3e | jthiruveedula/PythonProgramming | /Regex/patternStar.py | 512 | 4.21875 | 4 | #asterisk is used to find patterns based on left or right position from asterisk
pattern='swi*g'
import re
string = '''I am black!
I am swinging in the sky,
I am wringing worlds awry;'''
match =re.match(pattern,string)
search =re.search(pattern,string)
findall =re.findall(pattern,string)
print("Match Method: " ,match)
print("Search Method: ",search)
print("FindAll Method:",findall)
#output
# Match Method: None
# Search Method: <re.Match object; span=(17, 22), match='swing'>
# FindAll Method: ['swing'] | true |
d2382eb19ffc091fedcc333b0d3c96a010804127 | jthiruveedula/PythonProgramming | /DataEngineering/sets.py | 1,133 | 4.25 | 4 | #Branch of Mathematics applied to collection of objects
#i.e., sets
#Python has built in set datatype with accompanying methods
# instersection (all elements that are in both sides)
#difference(elements in one set but not in other set)
#symmetric_difference(all elements in exactly one set)
#union ( all elements that are in either set)
lstA= ['Horse','Lion','cheeta','deer','parrot']
lstB = ['Peacock','humming','pigeon','parrot']
setlsta=set(lstA)
setlstb=set(lstB)
intersect=setlsta.intersection(setlstb)
print("Intersection for both sets at:",intersect)
diff = setlsta.difference(setlstb)
print("Difference between seta and setb is: ",diff)
symdiff = setlsta.symmetric_difference(setlstb)
print("Symmetric Difference: ",symdiff)
unionout = setlsta.union(setlstb)
print("Union of both sets: ",unionout)
# output:
# Intersection for both sets at: {'parrot'}
# Difference between seta and setb is: {'Horse', 'cheeta', 'deer', 'Lion'}
# Symmetric Difference: {'humming', 'Horse', 'cheeta', 'pigeon', 'deer', 'Lion', 'Peacock'}
# Union of both sets: {'humming', 'Horse', 'cheeta', 'Peacock', 'pigeon', 'deer', 'parrot', 'Lion'} | true |
df5f166e5011a902893c503e8c9237a309f0e293 | HeroRacerNiko/lesson_5_hw | /count_odds_and_evens.py | 2,141 | 4.28125 | 4 | # Function check only WHOLE number
# Function doesn't check for digits duplication in the parameter number input
# For example 44411 would return 3 even digits and 2 odds
# Function does NOT skip count with duplicate digit and will count and add to list of evens or odds
def count_odds_and_evens(num):
while not num.isnumeric():
num = input('Please enter a whole number with DIGITS: ')
evens = []
odds = []
for char in num:
if int(char) % 2 == 0:
evens.append(char)
else:
odds.append(char)
print(evens)
return f'In {num} there are {len(evens)} even digits {*evens,} and {len(odds)} odd digits {*odds,}'
# print(count_odds_and_evens(input('Enter a number: ')))
# helper function
def prettify_dict(obj):
result = ""
for key_val in obj:
result += f'Number {key_val}, count: {obj[key_val]}\n'
return result
# And following is more sophisticated function that will count evens and odds without duplicating
# the numbers that already occurred. It will also calculate total count of evens and odds.
def count_evens_odds_duplicate_free(n):
while not n.isnumeric():
n = input("Enter a whole number in digits: ")
evens = {} # local scope variable within function
odds = {} # local scope variable within function
for char in n:
if int(char) % 2 == 0:
if char in evens:
evens[char] += 1
else:
evens[char] = 1
else:
if char in odds:
odds[char] += 1
else:
odds[char] = 1
return f'Number {n} has {len(evens)} duplicate free even digits: {*evens,} ' \
f'\nwith total of {sum(evens.values())} occurrences of even digits ' \
f'\nList of even digits: \n{prettify_dict(evens)}\n\n' \
f'Number {n} also has {len(odds)} duplicate free odd digits: {*odds,} ' \
f'\nwith total of {sum(odds.values())} occurrences of even digits ' \
f'\nList of even digits: \n{prettify_dict(odds)}'
print(count_evens_odds_duplicate_free(input('Enter a number: ')))
| true |
6c1456aa803cfe446a9b9df5c17d2d4c2e430fe7 | OMerkel/Fractals | /Hilbert/Howto/hilbert-howto-3.py | 1,632 | 4.375 | 4 | #!/usr/bin/env python3
"""
How to draw a Hilbert Curve - Step 3
In step 2 the turtle drew a hilbert curve in iteration n=0
"""
import turtle
COLOR = [ 'blue' ]
def hilbert( turtle, length, depth ):
"""
hilbert shall recursively call itself
The function holds a parameter depth that is decreased on each call
Reaching a negative depth value will abort the recursive calls
"""
if depth>=0:
"""
Each forward movement can be seen as a transition into a quadrant
+-------+ +---+---+
| | | | |
| 2---3 | | 2 | 3 |
| | | | | | |
| | | | +---+---+
| | | | | | |
| 1 4 | | 1 | 4 |
| | | | |
+-------+ +---+---+
Now the idea is that in one of our next 'how to' steps the
turtle shall draw the U shape again in each deeper recursive call
Per quadrant we call the recursive function
The turtle moves forward between the calls
"""
turtle.left(90)
hilbert(turtle, length, depth-1)
turtle.forward(length)
turtle.right(90)
hilbert(turtle, length, depth-1)
turtle.forward(length)
hilbert(turtle, length, depth-1)
turtle.right(90)
turtle.forward(length)
hilbert(turtle, length, depth-1)
turtle.left(90)
screen = turtle.Screen()
flitzi = turtle.Turtle()
length = 300
flitzi.penup()
offset = -length * (0.5)
flitzi.goto( offset, offset )
flitzi.pendown()
flitzi.color( COLOR[0] )
flitzi.pensize( 1 )
n = 0
hilbert(flitzi, length, depth = n)
screen.exitonclick()
| true |
0ba643609336a3ffed063e32526fc246e14e2e5c | cinthiatengan/Basic-Python | /Ex_Files_Python_EssT/Exercise Files/Chap04/conditional.py | 222 | 4.15625 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 1
if x>= 5:
print('verdadeiro porque {} >= 5'.format(x))
elif x == 3:
print('{} == 3'.format(x))
else:
print('{} é menor que 5'.format(x))
| false |
371a13b27ba338050a1e885cb53f1d426f9fede1 | pedrottoni/Studies-Python | /Cursoemvideo/Mundo2/exercise036.py | 799 | 4.375 | 4 | '''
Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
'''
house_price = float(input('Qual o valor da casa? '))
buyer_salary = float(input('Qual o salário do comprador? '))
years_paying = int(input('Quantos anos de financiamento? '))
monthly_installment = house_price / (years_paying * 12)
thirty_percent = 30 / 100 * buyer_salary
print(
f'Para pagar uma casa de R${house_price:.2f} em {int(years_paying)} anos, a prestação será de R${monthly_installment:.2f}'
)
if monthly_installment <= thirty_percent:
print('Emprestimno concedido')
else:
print(f'Emprestimno negado')
| false |
fe131b33f35efa66510e7543b46f636fe1a07eca | pedrottoni/Studies-Python | /Cursoemvideo/Mundo2/exercise059.py | 1,189 | 4.34375 | 4 | '''
Crie um programa que leia dois valores e mostre um menu na tela:
[ 1 ] somar
[ 2 ] multiplicar
[ 3 ] maior
[ 4 ] novos números
[ 5 ] sair do programa
Seu programa deverá realizar a operação solicitada em cada caso.
'''
first_value = int(input('Digite o primeiro valor: '))
second_value = int(input('Digite o segundo valor: '))
option = 0
while option != 5:
option = int(input(
f'{"-=" *5}\n[1] Somar\n[2] Multiplicar\n[3] Maior\n[4] Novos números\n[5] Sair do programa\n{"-=" *5}\nQual é a sua opção? '))
if option > 5 or option < 0:
option = int(input(
f'Opção Invalida.\n{"-=" *5}\n[1] Somar\n[2] Multiplicar\n[3] Maior\n[4] Novos números\n[5] Sair do programa\n{"-=" *5}\nQual é a sua opção? '))
if option == 1:
print(first_value + second_value)
elif option == 2:
print(first_value * second_value)
elif option == 3:
if first_value > second_value:
print(first_value)
else:
print(second_value)
elif option == 4:
first_value = int(input('Digite o primeiro valor: '))
second_value = int(input('Digite o segundo valor: '))
print('Volte sempre!')
| false |
d8515e68643e393c81df9f0c86a836cae800c0f4 | pedrottoni/Studies-Python | /Cursoemvideo/Mundo1/exercise031.py | 689 | 4.15625 | 4 | '''
Desenvolva um programa que pergunte a distância de uma viagem em Km. Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 parta viagens mais longas.
'''
distance = float(input('Qual é a distância da viagem? '))
print(f'Você está prestes a iniciar uma viagem de {distance}Km')
if distance > 200:
print(
f'Com 0 if padrão:\nO preço da passagem será de R${distance * 0.45:.2f}')
else:
print(f'O preço da passagem será de R${distance * 0.50:.2f}')
print(
f'Com o if inline:\nO preço da passagem será de R${distance * 0.45:.2f}') if distance > 200 else print(f'O preço da passagem será de R${distance * 0.50:.2f}')
| false |
0b481af4a03fe47d7e40c2647b278bb89f8a19c0 | pedrottoni/Studies-Python | /Pessoais/Jogo da Forca.py | 661 | 4.125 | 4 | '''
V Receber 3 palavras
V Agrupar as 3 palavras
V Sortear uma das 3 palavras
- Receber uma letra
- Verificar se é uma letra
- Verificar se a letra é repetida
- Verificar se a letra pertence a palávra escolhida
- Verificar quantas letras faltam
-
-
-
'''
import random
# Receber 3 palavras
first_word = str(input('Digite uma palavra para ser sorteada: '))
second_word = str(input('Digite outra palavra para ser sorteada: '))
third_word = str(input('Digite outra palavra para ser sorteada: '))
# Agrupar as 3 palavras
word_group = [first_word, second_word, third_word]
# Sortear uma das 3 palavras
drawn_word = random.choice(word_group)
print(drawn_word)
| false |
16b21fa84cb8b02f3aa8afd9ce4eafa3156520bf | OtsoValo/UTSC-Works | /CSCA08/ex0.py | 1,895 | 4.21875 | 4 | def multiply(x,y):
return x+y
def auto_email_address(x,y):
return x + "." +y + "@mail.utoronto,ca"
x = float(input("please input a number:"))
y = float(input("please input another number:"))
print(multiply(x,y))
a = input("please enter your first name:")
b = input("please enter your last name:")
address = auto_email_address(a,b)
print("Your UofT emaill may be:",address)
#--------------------------------------------------------------
#calculate fibonacci sequence
#input the range of fibonacci sequence
#calclulate fibonacci sequence untill reach the input number
#--------------------------------------------------------------
a, b = 0, 1
c = int(input("please enter the range of the fibonacci sequence:"))
while b < c:
print(a)
a, b = b, a + b
#guess the number
#save a random number
import random
number = random.randrange(1,100)
i = 1
#ask to begin the game
print("Shall we begin the game?")
answer = input()
if (answer in ["y","Y","yes","Yes","YES"]):
#10 opportunities to guess the random number
for i in range(1,11):
if(i < 10):
guess = int(input("please guess a number from 1 to 100:"))
#if the guess is correct
if (guess == number):
print("Correct!")
print("Guess Times:",i)
break
#if the guess is too big
elif (guess > number):
print("Too Big")
i += 1
#if the guess is too small
else:
print("Too Smaill")
i += 1
#10 times without right answer
else:
print("Oops,Running out of your opportunities!")
#end the game dircetly
elif (answer in ["n","N","no","No","NO"]):
print("What a pity!")
#wrong input
else:
print("I can not understand it!") | true |
5bf93ada1ebcc70d6243e0a5bf352e6526722ff0 | OtsoValo/UTSC-Works | /CSCA08/week9/week9_my_stack2.py | 1,690 | 4.125 | 4 | class Stack():
'''A last-in, first-out (LIFO) stack of items'''
def __init__(self):
'''(Stack) -> NoneType
Create a new, empty Stack.
'''
# this time, let's represent our stack with a list such that the top
# of the stack is at the 0th element of the list
self._contents = []
def push(self, new_obj):
'''(Stack, object) -> NoneType
Place new_obj on top of this stack.
'''
# putting a new element on top of the stack means putting that element
# at the beginning of our list
self._contents.insert(0, new_obj)
def pop(self):
'''(Stack) -> object
Remove and return the top item in this stack.
'''
# the top item on the stack is the 0th item in the list
# so first save it
top_item = self._contents[0]
# then remove it from the list
self._contents = self._contents[1:]
# then return it
return top_item
def is_empty(self):
'''(Stack) -> bool
Return True iff this stack is empty.
'''
# just for fun, let's try a different way of testing for an empty
# list this time (which means an empty stack)
return len(self._contents) == 0
if (__name__ == '__main__'):
# this is just some sample code that uses our stack
# if we keep our ADT the same in each of our implementations
# of our stack, then we should be confident that this code
# will work identically each time
stk = Stack()
stk.push('a')
stk.push('b')
stk.push('c')
print(stk.pop())
stk.push('d')
while(not stk.is_empty()):
print(stk.pop())
| true |
ce24642c0b9a675bc6402dfb9f00e191a86a3aa6 | kalsotra2001/practice | /ctci/linked-lists/4-partition-by-x.py | 895 | 4.125 | 4 | class LinkedList(object):
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data, self.head)
self.head = new_node
return self.head
def print_list(self):
cur = self.head
while cur:
print cur.data
cur = cur.next
class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def partition(l, x):
before = LinkedList()
after = LinkedList()
cur, mid = l.head, None
while cur:
if cur.data < x:
if not mid: mid = before.insert(cur.data)
else: before.insert(cur.data)
else: after.insert(cur.data)
cur = cur.next
mid.next = after.head
before.print_list()
l = LinkedList()
l.insert(8)
l.insert(2)
l.insert(7)
l.insert(12)
l.insert(3)
l.insert(4)
l.print_list()
partition(l, 5) | false |
9ba37e0ec412a97a1341545f89772823bbaa8ded | kalsotra2001/practice | /hackerrank/algorithms/warmups/sherlock-and-the-beast.py | 589 | 4.1875 | 4 | def get_decent(digits):
target = digits
threes = 0
fives = 0
max = 0
while digits > 0:
if digits % 3 == 0:
fives = digits
break
digits -= 5
threes = target - digits
if digits < 0 or threes % 5 != 0:
return "-1"
number = ""
while fives > 0:
number += "5"
fives -= 1
while threes > 0:
number += "3"
threes -= 1
return number
test_cases = (int)(raw_input())
for i in range(test_cases):
digits = (int)(raw_input())
answer = get_decent(digits)
print answer | true |
5b1cb7b7e1e1c695b4a0a703bf647c3ee2da5abf | Sinha123456/Simple_code_python | /factorial_while.py | 312 | 4.46875 | 4 | number = 6
product = 1
current = 1
while current<=number:
product*=current
current += 1
print(product)
#Running same thing using for loop
# calculate factorial of number with a for loop
for num in range(1, number + 1):
product *= num
# print the factorial of number
print(product)
| true |
c96ec0dd3f7be02edb2cb90ee747eb395be69792 | libus1204/bigdata2019 | /01. Jump to python/chap05/174_class_calculator.py | 652 | 4.125 | 4 | class Calculator: # 사용자 정의 클래스
def __init__(self): # 생성자(Constructor) 객체 생성시 최초로 수행되는 함수
self.result = 0 # Class 의 멤버 변수
def adder(self, num): # 멤버 함수(Member Function)
print("[%d]값을 입력 받았습니다." % num)
self.num1 = 100 # 멤버변수로 등록은 가능하나, 가독성은 떨어진다.
self.result += num
return self.result
cal1 = Calculator()
cal2 = Calculator()
cal3 = Calculator()
print(cal1.adder(3))
print(cal1.adder(4))
print(cal2.adder(3))
print(cal2.adder(3))
print(cal3.adder(3))
print(cal3.adder(7))
| false |
dc7311f672b80ddf847eac14a1ad81bee065cd66 | bala4rtraining/python_programming | /python-programming-workshop/test/namedtuple/namedtuplecreationexpone.py | 1,449 | 4.125 | 4 |
# the code below shows a simple tuple - 1st part of excercise
from math import sqrt
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
print(line_length)
# the code below shows a simple named tuple - 2nd part of our excercise
from collections import namedtuple
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
line_length = sqrt((pt1.x-pt2.x)**2 + (pt1.y-pt2.y)**2)
print(line_length)
# the code below shows a namedtuple but accessed as a tuple
# so backward compatible
# this is part 3 of our excercise
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
# use index referencing
line_length = sqrt((pt1[0]-pt2[0])**2 + (pt1[1]-pt2[1])**2)
# use tuple unpacking
x1, y1 = pt1
#However, as with tuples, attributes in named tuples are immutable:
# this is part 4 of our excercise
Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
#pt1.x = 2.0
#AttributeError: can't set attribute
#If you want to be able change the values, you need another type.
#There is a handy recipe for #mutable recordtypes which allow you
#to set new values to attributes.
# here we use a new data type called rcdtype where we can change the values
# and is used like a named tuple
# this is part 5 of our excercise
#from rcdtype import *
#Point = recordtype('Point', 'x y')
#pt1 = Point(1.0, 5.0)
#pt1 = Point(1.0, 5.0)
#pt1.x = 2.0
#print(pt1[0])
| true |
1b852fc0dd98132bc8590ca978654de519bca513 | bala4rtraining/python_programming | /python-programming-workshop/youtube_python_videos/dictionary/dictionaryfromkeysthree.py | 807 | 4.375 | 4 |
# create a dictionary from mutable object list
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]
vowels = dict.fromkeys(keys, value)
print(vowels)
# updating the value
value.append(2)
print(vowels)
#If the provided value is a mutable object (whose value can be modified) like list, dictionary, etc., when the mutable object is modified, each element of the sequence also gets updated.
#This is because, each element is assigned a reference to the same object (points to the same object in the memory).
#To avoid this issue, we use dictionary comprehension.
# vowels keys
keys = {'a', 'e', 'i', 'o', 'u' }
value = [1]
vowels = { key : list(value) for key in keys }
# you can also use { key : value[:] for key in keys }
print(vowels)
# updating the value
value.append(2)
print(vowels)
| true |
315a09868d5ccdd2c29900f3e5df8148b09f3524 | bala4rtraining/python_programming | /python-programming-workshop/string/ljust_and_rjust.py | 424 | 4.5 | 4 |
#Ljust, rjust. These pad strings. They accept one or two arguments. The first argument
#is the total length of the result string. The second is the padding character.
#Tip: If you specify a number that is too small, ljust and rjust do nothing.
#They return the original string.
#Python that uses ljust, rjust
s = "Paris"
# Justify to left, add periods.
print(s.ljust(10, ";"))
# Justify to right.
print(s.rjust(10))
| true |
40f9fbb5bfd6cdcd6c5ab29d2b109f76b3548167 | bala4rtraining/python_programming | /python-programming-workshop/interesting_programs/decimal_to_binary_in_bits.py | 206 | 4.25 | 4 |
# Python 3 implementation of above approach
# Function to convert decimal to
# binary number
def bin(n):
if (n > 1):
bin(n >> 1)
print(n&1,end=" ")
# Driver code
bin(131)
print()
bin(3)
| true |
6b99a93f0c58c2ab9ac3ded9483a65ad45e69fa6 | bala4rtraining/python_programming | /python-programming-workshop/pythondatastructures/class/issubclass.py | 758 | 4.34375 | 4 |
#Issubclass. This determines if one class is derived from another. With this
#built-in method, we pass two class names (not instances).
#Return:If the first class inherits from the second, issubclass returns true.
#Otherwise it returns false.
#Tip:This is rarely useful to know: a class is considered a subclass of itself.
#The third issubclass call below shows this.
class A:
def hello(self):
print("A says hello")
class B(A):
def hello(self):
print("B says hello")
# Use the derived class.
b = B()
b.hello()
# See if B inherits from A.
if issubclass(B, A):
print(1)
# See if A inherits from B.
if issubclass(A, B):
# Not reached.
print(2)
# See if A inherits from itself.
if issubclass(A, A):
print(3)
| true |
f06d4ab6301792efe152f6e31b879e8af446677f | bala4rtraining/python_programming | /python-programming-workshop/data_structures/named_tuple/namedtupletwo.py | 563 | 4.53125 | 5 |
#namedtuple is a factory function for making a tuple class. With that class
#we can create tuples that are callable by name also.
import collections
#Create a namedtuple class with names "a" "b" "c"
Row = collections.namedtuple("Row", ["a", "b", "c"], verbose=False, rename=False)
row = Row(a=1,b=2,c=3) #Make a namedtuple from the Row class we created
print row #Prints: Row(a=1, b=2, c=3)
print row.a #Prints: 1
print row[0] #Prints: 1
row = Row._make([2, 3, 4]) #Make a namedtuple from a list of values
print row #Prints: Row(a=2, b=3, c=4)
| true |
59e8e3a092bb160de2b3216f99f3cb7e6cde6709 | bala4rtraining/python_programming | /python-programming-workshop/pythondatastructures/regular_expression/search.py | 747 | 4.40625 | 4 |
#Search. This method is different from match. Both apply a pattern. But search attempts this
#at all possible starting points in the string. Match just tries the first starting point.
#So:Search scans through the input string and tries to match at any location. In this
#example, search succeeds but match fails.
#Python program that uses search
import re
# Input.
value = "voorheesville"
m = re.search("(vi.*)", value)
if m:
# This is reached.
print("search:", m.group(1))
m = re.match("(vi.*)", value)
if m:
# This is not reached.
print("match:", m.group(1))
#Output
#search: ville
#Pattern details
#Pattern: (vi.*)
#vi The lowercase letters v and i together.
#.* Zero or more characters of any type.
| true |
1f528a9f016ab29739e09549db415d98b11af0be | bala4rtraining/python_programming | /python-programming-workshop/test/dictionary/listto_dict.py | 230 | 4.15625 | 4 |
original = {"box": 1, "cat": 2, "apple": 5}
# Create copy of dictionary.
modified = original.copy()
# Change copy only.
modified["cat"] = 200
modified["apple"] = 9
# Original is still the same.
print(original)
print(modified)
| true |
13c4357d79ee16af405cb6a745a64e7e6b19318b | bala4rtraining/python_programming | /python-programming-workshop/test/pythondatastructures/built_in_functions/lambda/functionsinsidelist.py | 529 | 4.34375 | 4 |
#In the example above, a list of three functions was built up by embedding
#lambda expressions inside a list. A def won't work inside a list literal
#like this because it is a statement, not an expression.
#If we really want to use def for the same result, we need temporary function
#names and definitions outside:
def f1(x): return x ** 2 # here f1, f2 and f3 are the function names
def f2(x): return x ** 3
def f3(x): return x ** 4
# Reference by name
L = [f1, f2, f3]
for f in L:
print(f(3))
print(L[0](3))
| true |
6e3d3063dee1ed723883124085c093ccee478401 | bala4rtraining/python_programming | /python-programming-workshop/test/pythondatastructures/none/none_usage_in_dictionary.py | 209 | 4.1875 | 4 |
#Python program that uses dictionary, None
items = {"cat" : 1, "dog" : 2, "piranha" : 3}
# Get an element that does not exist.
v = items.get("giraffe")
# Test for it.
if v == None:
print("Not found")
| true |
83eee1932f9a1c411deaeed876fd83d788dc31ba | bala4rtraining/python_programming | /python-programming-workshop/test/pythondatastructures/file/parse_csv.py | 222 | 4.125 | 4 |
import csv
#Open CSV file.
with open("input.csv", newline="") as f:
# Specify delimiter for reader.
r = csv.reader(f, delimiter=",")
# Loop over rows and display them.
for row in r:
print(row)
| true |
6056539afef034b1d222ac3436e7c2ff6c68e55d | bala4rtraining/python_programming | /python-programming-workshop/test/pythondatastructures/fibonacci/fibonacci_two.py | 294 | 4.40625 | 4 |
#Python program that displays Fibonacci sequence
def fibonacci2(n):
a = 0
b = 1
for i in range(0, n):
# Display the current Fibonacci number.
print(a)
temp = a
a = b
b = temp + b
return a
# Directly display the numbers.
fibonacci2(15)
| true |
978adb0fd9c937fc09cd5f5d0594476f9fbab251 | bala4rtraining/python_programming | /python-programming-workshop/test/HomeWorkProblems/16.greaterandlesser-than-given-number.py | 435 | 4.3125 | 4 |
# Count the number of elements in a list that are greater
# than or equal to some minimum number and less that or equal
# to some maximum number for example, the list of numbers can
# be 12, 5, 23, 79, 63, 11, 7, 6, 115, 129
# minimum is 10 and maximum is 100]
newlist = [12, 5, 23, 79, 63, 11, 7, 6, 115, 129]
minimum = 10
maximum = 100
for number in newlist:
if(number > minimum and number < maximum):
print(number) | true |
16f0449bfb7dec9a11cb561cfa8cbaf1cabd8b60 | bala4rtraining/python_programming | /python-programming-workshop/HomeWorkProblems/8.anagrams-ofeachother.py | 464 | 4.34375 | 4 |
## python program to find whether the given words are anagrams of each other ##
# find if two strings are anagrams of each other and
# report the answer as "yes" or "no"
first_string = input(" Give first string : ")
second_string = input(" Give second string : ")
first_string = sorted(first_string)
second_string = sorted(second_string)
if(first_string == second_string):
print(" Yes They are anagrams. ")
else:
print(" No They are not anagrams. ")
| true |
89589bd79a5ee51df2033ce8dc9e7e069688cf0f | bala4rtraining/python_programming | /python-programming-workshop/solutions/new.py | 458 | 4.1875 | 4 |
# this is the basic method
number = int(input("Give a number"))
for val in range(2,number):
if number % val == 0:
print(val,end=" ")
print("\n\n")
# this is using list comprehension
factors = [val for val in range(2,number) if number % val == 0]
print(factors)
# this is using a function
def find_factors(n):
for val in range(2,number):
if number % val == 0:
print(val,end=" ")
print("\n\n")
find_factors(number)
| true |
5ee5ebe06d9c49bff31c0e598f1f44acef452cd1 | bala4rtraining/python_programming | /python-programming-workshop/HomeWorkProblems/17.tupletakeinput.py | 589 | 4.625 | 5 |
## python program to create a tuple by getting input from the user ##
# write a program create a tuple by taking input from the user
mylist = []
for count in range(5):
name=input(" Give any name : ")
mylist.append(name)
tupletwo = (mylist[0],mylist[1],mylist[2],mylist[3],mylist[4])
print(" The elements in tuple1 are : ",tupletwo)
one = input(" Give a name : ")
two = input(" Give a name : ")
three = input(" Give a name : ")
four = input(" Give a name : ")
five = input(" Give a name : ")
tupleone = (one,two,three,four,five)
print(" The elements in tuple2 are : ",tupleone)
| true |
e17c340151134585011263499a8dda6c200373f7 | bala4rtraining/python_programming | /python-programming-workshop/iterators_and_generators_new/class_03-08-2020/6.infinite_generators.py | 349 | 4.125 | 4 |
def infinite_sequence():
num = 0
while True:
yield num
num += 1
gen=infinite_sequence()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
# def infinite_sequence():
# num = 0
# while True:
# print(num)
# num = num + 1
#for i in infinite_sequence():
# print(i, end=" ")
| false |
b589cf5c1d286d01d3986160bb4c8d890791ff6c | bala4rtraining/python_programming | /python-programming-workshop/iterators_and_generators_new/12.newiteratorpattercreation.py | 317 | 4.40625 | 4 |
def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
#To use such a function, you iterate over it using a for loop or use it with some other
#function that consumes an iterable (e.g., sum(), list(), etc.). For example:
for n in frange(0, 9, 0.5):
print(n)
| true |
dccc689f10f200088286a7f8b33fe67e06afdf66 | bala4rtraining/python_programming | /database/secondone.py | 1,225 | 4.3125 | 4 | ## Connecting to the database
## importing 'mysql.connector' as mysql for convenient
import mysql.connector as mysql
## connecting to the database using 'connect()' method
## it takes 3 required parameters 'host', 'user', 'passwd'
db = mysql.connect(
host = "localhost",
user = "root",
passwd = "Superpa@99"
)
print(db) # it will print a connection object if everything is fine
## creating an instance of 'cursor' class which is used to execute the 'SQL' statements in 'Python'
cursor = db.cursor()
cursor.execute("DROP DATABASE CRICKET")
## creating a databse called 'datacamp'
## 'execute()' method is used to compile a 'SQL' statement
## below statement is used to create tha 'datacamp' database
cursor.execute("CREATE DATABASE CRICKET")
## executing the statement using 'execute()' method
cursor.execute("SHOW DATABASES")
## 'fetchall()' method fetches all the rows from the last executed statement
databases = cursor.fetchall() ## it returns a list of all databases present
## printing the list of databases
print(databases)
cursor.execute("USE CRICKET")
## creating a table called 'users' in the 'datacamp' database
cursor.execute("CREATE TABLE users (name VARCHAR(255), user_name VARCHAR(255))")
| true |
2c40f802dbf405ea79d5e792626f74011df1969e | bala4rtraining/python_programming | /python-programming-workshop/builit-in-functions/find/find_one.py | 251 | 4.25 | 4 |
#Python program that uses string find
value = "cat picture is cat picture"
# Find first index of this string.
i = value.find("picture")
print(i)
# Find first index (of this string) after previous index.
b = value.find("picture", i + 1)
print(b)
| true |
f261c999b95e455d7c5832ebeb11139aeb5a792c | ishandas387/DbsStuff | /PrgAnalytics/Problem2.py | 777 | 4.15625 | 4 | '''
Validates the user input and returns the splitted result.
If after split the list doesm't have 2 values, the input doesn't
satisfy the domain/username format.
'''
def validate_and_return(message):
while True:
user_name = input(message)
#splits with '\'
data = str(user_name).split("\\")
if(len(data) != 2):
print("Not in proper format")
print("Expected:: Domain\\username")
continue
else:
return data
#user input and result
print("###################################")
print("WELCOME TO THE DBS CONSOLE")
print("###################################")
data = validate_and_return("Please enter the username: \n")
print("Domain : ",str(data[0]))
print("Username : ",str(data[1]))
| true |
52653ebdcb26a69d87b19f6f2259ca447f1e51fd | oraloni/python-little-games | /which_hand.py | 1,371 | 4.28125 | 4 | '''Which Hand - in Pythom Basic Games Project
Or Aloni 13/06/2020 v/1/0'''
print(" Which hand?\n")
print('''RULES: Pick up a dime in one hand and a penny in the other. I'll guess which hand holds
which coin if you answer a couple of questions for me.
Multiply the value of the coin in your right hand by an even number and multiply the value
of the coin in your left hand by an odd number.\n''')
def new_game():
while True:
repeat_game = str(input("Would you like to repeat game? "))
yes = repeat_game.lower().strip("es")
no = repeat_game.lower().strip("o")
if yes == "y":
break
elif no == "n":
print("\nThank you for playing. Have a nice day")
exit()
else:
print("Please enter a yes/no answer")
while True:
user_answer = input("\nIs the sum of the two numbers you added odd or even? ").lower()
if user_answer == "even":
print("\nThe dime is in your left hand, and the penny in your right hand\n")
new_game()
elif user_answer == "odd":
print("\nThe dime is in your right hand, and the penny in your left hand\n")
new_game()
else:
print("\nPlease enter odd/even\n")
continue
| true |
a85bbe7cf2198eb26c99a1f3f60e73c463d26305 | thirdcaptain/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 355 | 4.21875 | 4 | #!/usr/bin/python3
"""
module defines number_of_lines function
"""
def number_of_lines(filename=""):
""" returns the number of lines of a text file
args:
filename (file): file to read
"""
linenumber = 0
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
linenumber += 1
return linenumber
| true |
fd5f77e150f73ee65cc191d4f8fdd666470c5394 | Hyperx837/Bits2020 | /chat bot/chatbot.py | 1,342 | 4.15625 | 4 |
ques_ans = {
'What is your name? ': 'Alpha',
'How old are you? ': '7 years',
'What is your School? ': 'I never went to school',
'What is your father\'s name? ': 'I do not have a father but I '
'was created by Anupama',
'What is your mother\'s name? ': 'I don\'t have a mother',
'Will You Be my friend? ': 'I already am',
'How do you do? ': 'I am doing good',
'Who is the Best? ': 'Obviously not you!!!',
'Do you have a meaning to live?': 'Speaking of meaning There are many '
'many meanings to live. But far as '
'I am concerned I don\'t need a meaning'
' to live because I don\'t know what'
' meaning is.',
'Who is the dumbest person that you have ever met? ': 'YOU!',
'What is the last question you can answer? ': 'The last question that '
'you can ask'
}
print('QUESTIONS THAT YOU CAN ASK')
for i, ques in enumerate(ques_ans):
print(f'{i + 1}. {ques}')
print('\ntype EXIT to exit the program\n\n')
while True:
inp_ques = input('Q: ')
if inp_ques == 'EXIT':
break
print('A:', ques_ans.get(inp_ques) or 'Question not found???', '\n')
| true |
ad6e7846181a1db91a9ed7e9d44ae373903bbf9f | Min-Guo/coursera-learn-to-program-foundamentals | /assignment-2/a2.py | 2,670 | 4.3125 | 4 | import math
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return dna1 > dna2
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide)
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(s):
'''(str) -> bool
Return True if and only if DNA sequence is valid(that is, it contains no characters other than 'A', 'T', 'C', 'G').
>>>is_valid_sequence('ATGCGAT')
True
>>>is_valid_sequence('ABCTG')
False
'''
num_dna = 0
for char in s:
if char in 'ATCG':
num_dna = num_dna + 1
else:
num_dna = num_dna
return num_dna == len(s)
def insert_sequence(s1, s2, number):
'''(str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index.
>>>insert_sequence('GTCACTG', 'AG', 3)
'GTCAGACTG'
>>>insert_sequence('TGACT', 'CT', 2)
'TGCTACT'
'''
s = s1[:number] + s2 + s1[number:]
return s
def get_complement(s):
'''(str) -> str
Return the nucleotide's complement
>>>get_complement('T')
'A'
>>>get_complement('C')
'G'
'''
if s == 'A':
return 'T'
if s == 'T':
return 'A'
if s == 'C':
return 'G'
if s == 'G':
return 'C'
def get_complementary_sequence(s):
'''(str) -> str
Return the DNA sequence that is complementary to the given DNA sequence.
>>>get_complementary_sequence('TGAGTC')
'ACTCAG'
>>>get_complementary_sequence('GCACTGT')
'CGTGACA'
'''
s1 = ''
for char in s:
if char == 'A':
s1 = s1 + 'T'
if char == 'T':
s1 = s1 + 'A'
if char == 'G':
s1 = s1 + 'C'
if char == 'C':
s1 = s1 + 'G'
else:
s1 = s1
return s1
| false |
475b3a1300525aac00cca14b41742c99d3612ea7 | Ena-Sharma/list-in-python | /newlist.py | 216 | 4.15625 | 4 | list=[1,2,3,4,5,6]
print("Initial list:")
print(list)
slicing=list[3:6]
print(slicing)
slicing_list=list[:-5]
print(slicing_list)
list.pop()
print(list)
for i in range(len(list)):
print(i, end=" ")
print("\r") | true |
62248d30fa1bd73b9d4436e03f0e42cf7e14305f | tilsies/CP1404 | /cp1404practicals/prac_02/acsii_table.py | 490 | 4.15625 | 4 | LOWER_LIMIT = 33
UPPER_LIMIT = 127
character = input("Enter a Character: ")
print("The ACSII code for {0} is {1}".format(character, ord(character)))
number = int(input("Enter a number between {0} and {1}: ".format(LOWER_LIMIT, UPPER_LIMIT)))
while number < LOWER_LIMIT or number > UPPER_LIMIT:
print("Invalid choice")
number = int(input("Enter a number between {0} and {1}: ".format(LOWER_LIMIT, UPPER_LIMIT)))
print("The character for {0} is {1}".format(number, chr(number)))
| true |
2c08dac1a7cad63382d69082c608d3fe02a75b6d | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#112 Grasshopper - Debug.py | 967 | 4.46875 | 4 | # Debug celsius converter
# Your friend is traveling abroad to the United States so he wrote a program to
# convert fahrenheit to celsius. Unfortunately his code has some bugs.
#
# Find the errors in the code to get the celsius converter working properly.
#
# To convert fahrenheit to celsius:
#
# celsius = (fahrenheit - 32) * (5/9)
# Remember that typically temperatures in the current weather conditions are
# given in whole numbers. It is possible for temperature sensors to report
# temperatures with a higher accuracy such as to the nearest tenth. Instrument
# error though makes this sort of accuracy unreliable for many types of
# temperature measuring sensors.
def weather_info(temp):
c = convert_to_celsius(temp)
if (c <= 0):
return (str(c) + " is freezing temperature")
else:
return (str(c) + " is above freezing temperature")
def convert_to_celsius(temperature):
celsius = (temperature - 32) * (5 / 9)
return celsius
| true |
d4abedb8cc12fb365e1309d49b0d8ef7e8005379 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/7 kyu/#04 Sum of odd numbers.py | 366 | 4.15625 | 4 | # Given the triangle of consecutive odd numbers:
#
# 1
# 3 5
# 7 9 11
# 13 15 17 19
# 21 23 25 27 29
# ...
# Calculate the sum of the numbers in the nth row of this triangle (starting at
# index 1) e.g.: (Input --> Output)
#
# 1 --> 1
# 2 --> 3 + 5 = 8
def row_sum_odd_numbers(n):
return n ** 3
| true |
97caf558aa471cc7bcfcab2921028f6ffa998e44 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#227 Area of a Square.py | 338 | 4.125 | 4 | # Complete the function that calculates the area of the red square, when the
# length of the circular arc A is given as the input. Return the result rounded
# to two decimals.
#
# Note: use the π value provided in your language (Math::PI, M_PI, math.pi, etc)
import math
def square_area(A):
return round((2 * A / math.pi) ** 2, 2)
| true |
d087d676cc95399719f79ce1968b9471297b7b9d | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#152 How old will I be in 2099.py | 1,442 | 4.25 | 4 | # Philip's just turned four and he wants to know how old he will be in various
# years in the future such as 2090 or 3044. His parents can't keep up
# calculating this so they've begged you to help them out by writing a programme
# that can answer Philip's endless questions.
#
# Your task is to write a function that takes two parameters: the year of birth
# and the year to count years in relation to. As Philip is getting more curious
# every day he may soon want to know how many years it was until he would be
# born, so your function needs to work with both dates in the future and in the
# past.
#
# Provide output in this format: For dates in the future: "You are ... year(s)
# old." For dates in the past: "You will be born in ... year(s)." If the year of
# birth equals the year requested return: "You were born this very year!"
#
# "..." are to be replaced by the number, followed and proceeded by a single
# space. Mind that you need to account for both "year" and "years", depending on
# the result.
#
# Good Luck!
def calculate_age(year_of_birth, current_year):
if current_year > year_of_birth:
return f"You are {current_year - year_of_birth} year{'s' * ((current_year - year_of_birth) != 1)} old."
elif current_year < year_of_birth:
return f"You will be born in {year_of_birth - current_year} year{'s' * ((year_of_birth - current_year) != 1)}."
else:
return "You were born this very year!"
| true |
a467834a82132a92cd105ef74bd73ad708a73e4c | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#122 L1 Bartender, drinks!.py | 1,206 | 4.125 | 4 | # Complete the function that receives as input a string, and produces outputs
# according to the following table:
#
# Input Output
# "Jabroni" "Patron Tequila"
# "School Counselor" "Anything with Alcohol"
# "Programmer" "Hipster Craft Beer"
# "Bike Gang Member" "Moonshine"
# "Politician" "Your tax dollars"
# "Rapper" "Cristal"
# anything else "Beer"
# Note: anything else is the default case: if the input to the function is not
# any of the values in the table, then the return value should be "Beer".
#
# Make sure you cover the cases where certain words do not show up with correct
# capitalization. For example, the input "pOLitiCIaN" should still return "Your
# tax dollars".
def get_drink_by_profession(param):
match param.lower():
case "jabroni":
return "Patron Tequila"
case "school counselor":
return "Anything with Alcohol"
case "programmer":
return "Hipster Craft Beer"
case "bike gang member":
return "Moonshine"
case "politician":
return "Your tax dollars"
case "rapper":
return "Cristal"
case _:
return "Beer"
| true |
a4f4d1ee2a78ce0ad7b827643a098a580bd07d7f | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#022 Regex count lowercase letters.py | 494 | 4.28125 | 4 | # Your task is simply to count the total number of lowercase letters in a
# string.
#
# Examples
# lowercaseCount("abc"); ===> 3
#
# lowercaseCount("abcABC123"); ===> 3
#
# lowercaseCount("abcABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~"); ===> 3
#
# lowercaseCount(""); ===> 0;
#
# lowercaseCount("ABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~"); ===> 0
#
# lowercaseCount("abcdefghijklmnopqrstuvwxyz"); ===> 26
def lowercase_count(strng):
return sum(character.islower() for character in strng)
| false |
c7be302d35c6a6ff9f9e2363219c69bc45d4b245 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#054 Add Length.py | 573 | 4.28125 | 4 | # What if we need the length of the words separated by a space to be added at
# the end of that same word and have it returned as an array?
#
# Example(Input --> Output)
#
# "apple ban" --> ["apple 5", "ban 3"]
# "you will win" -->["you 3", "will 4", "win 3"]
# Your task is to write a function that takes a String and returns an Array/list
# with the length of each word added to each element .
#
# Note: String will have at least one element; words will always be separated by
# a space.
def add_length(str_):
return [f"{word} {len(word)}" for word in str_.split()]
| true |
6acbf3dc4f5c25598f811880121a6d2cbcb72b9c | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#157 Are You Playing Banjo.py | 470 | 4.21875 | 4 | # Create a function which answers the question "Are you playing banjo?".
# If your name starts with the letter "R" or lower case "r", you are playing
# banjo!
#
# The function takes a name as its only argument, and returns one of the
# following strings:
#
# name + " plays banjo"
# name + " does not play banjo"
# Names given are always valid strings.
def are_you_playing_banjo(name):
return f"{name} {'plays banjo' if name[0] in 'Rr' else 'does not play banjo'}"
| true |
2575f9bcb23571369a0fa7cf5832fc1399a26008 | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#235 Will you make it.py | 546 | 4.125 | 4 | # You were camping with your friends far away from home, but when it's time to
# go back, you realize that your fuel is running out and the nearest pump is 50
# miles away! You know that on average, your car runs on about 25 miles per
# gallon. There are 2 gallons left.
#
# Considering these factors, write a function that tells you if it is possible
# to get to the pump or not.
#
# Function should return true if it is possible and false if not.
def zero_fuel(distance_to_pump, mpg, fuel_left):
return distance_to_pump <= mpg * fuel_left
| true |
9e38100a28ecac4ecb6a6d67e5a600371bb8658a | ChengHsinHan/myOwnPrograms | /CodeWars/Python/8 kyu/#048 Simple Fun #261 Whose Move.py | 1,022 | 4.15625 | 4 | # Task
# Two players - "black" and "white" are playing a game. The game consists of
# several rounds. If a player wins in a round, he is to move again during the
# next round. If a player loses a round, it's the other player who moves on the
# next round. Given whose turn it was on the previous round and whether he won,
# determine whose turn it is on the next round.
#
# Input/Output
# [input] string lastPlayer/$last_player
#
# "black" or "white" - whose move it was during the previous round.
#
# [input] boolean win/$win
#
# true if the player who made a move during the previous round won, false
# otherwise.
#
# [output] a string
#
# Return "white" if white is to move on the next round, and "black" otherwise.
#
# Example
# For lastPlayer = "black" and win = false, the output should be "white".
#
# For lastPlayer = "white" and win = true, the output should be "white".
def whoseMove(lastPlayer, win):
if win:
return lastPlayer
else:
return "white" if lastPlayer == "black" else "black"
| true |
6685082c37a723957d9439431f42bd51a1ef0f4a | cinker/karanProjects | /Classes/Product_Inventory.py | 1,242 | 4.15625 | 4 | #!/usr/bin/python3
# Product Inventory Project - Create an application which manages an inventory
# of products. Create a product class which has a price, id, and quantity on
# hand.
# Then create an inventory class which keeps track of various products and can
# sum up the inventory value.
class Product:
def __init__(self, prd_price, prd_id, prd_quatity):
self.prd_id = prd_id
self.prd_price = prd_price
self.prd_quatity = prd_quatity
def get_value(self, prd_id):
self.prd_value = self.prd_price*self.prd_quatity
return self.prd_value
class Inventory:
def __init__(self):
self.list_prd = []
def add_product(self, prd_id):
self.list_prd.append(prd_id)
def del_product(self, prd_id):
if prd_id in self.list_prd:
self.list_prd.remove(prd_id)
else:
print("The product is not in the inventory.")
# TODO: How to calucate this???
def get_value(self):
total_value = 0
for p in self.list_prd:
total_value += Product.get_value(p)
return total_value
def view_inventory(self):
print(self.list_prd)
p = Product(5, 4, 5)
i = Inventory()
i.add_product(4)
i.get_value()
| true |
d2cd63e30ab801cfcb2186987d069525340f6f6b | abhishekrd760/BasicPythonPrograms | /quadratic.py | 460 | 4.21875 | 4 | import cmath
a = float(input("Enter the value of a in quadratic equation"))
b =float(input("Enter the value of b in quadratic equation"))
c = float(input("Enter the value of c in quadratic equation"))
x1 = (-b + cmath.sqrt((b**2)-(4*a*c)))/(2*a)
x2 = (-b - cmath.sqrt((b**2)-(4*a*c)))/(2*a)
d = (b**2)-(4*a*c)
print("The two roots of the quadratic equation are : ",x1,x2)
if d<0:
print("The roots are complex")
else:
print("The roots are not complex") | true |
659d1521ecdd0cfd143b222364c0e8889a952263 | Mohit1299/Python | /A3Q3.py | 481 | 4.15625 | 4 | input_time = input("Enter the time : ")
time = input_time.split(":")
minute_angle = int(time[1])*6
print(minute_angle)
hour_angle = int(time[0])*30 + (minute_angle/12)
print(hour_angle)
if(hour_angle > minute_angle):
res_angle = hour_angle - minute_angle
else:
res_angle = minute_angle - hour_angle
if(res_angle > 180):
print("The Smaller angle between the clock hands is : ",360-res_angle)
else:
print("The smaller angle between the clock hands is : ",res_angle)
| true |
d8838575fd3f49c16694f11bf788ad4c7ec1cf39 | Mohit1299/Python | /A5Q9.py | 472 | 4.1875 | 4 | def is_prime(no):
if(no < 2):
print("Prime numbers are always greater than 2")
return False
count = 0
for i in range(1,no):
if(no%i==0):
count += 1
else:
continue
if(count == 1):
return True
else:
return False
user_input = int(input("Enter the Number : "))
if(is_prime(user_input) == True):
print("The number is Prime ")
else:
print("The number is Not Prime ") | true |
28d8b70dcfed4461d22dcfb7919e79c702091ff3 | permCoding/algopro20 | /part2/01-func-coding/04.py | 683 | 4.21875 | 4 | # генераторы и итераторы
# итераторы
lst = list(range(10))
print(lst) # объект-итератор
lst = [smb for smb in '012345']
print(lst) # объект-итератор
lst = (smb for smb in '012345')
print(lst) # объект-генератор
print(', '.join(lst))
print('= = = = = = = = =')
tpl = (x for x in [0, 1, 2, 3]) # из итератора в генератор
print(tpl)
# print(list(tpl))
print(next(tpl))
print(next(tpl))
print(next(tpl))
print(next(tpl))
print(tpl)
print('= = = = = = = = =')
enum = [smb for smb in enumerate([1, 4, 55, 9])]
print(enum)
for index, value in enumerate('Python'):
print(index, value)
| false |
33e073a5a1bf85fc0e4b20d7bfd9bae96adfefeb | calendij9862/CTI110 | /P1HW2_BasicMath_CalendineJoseph.py | 658 | 4.25 | 4 | # This program adds and multiplies 2 numbers
# 9/13/2020
# CTI-110 P1HW2 - Basic Math
# Joseph Calendine
#
print('Please enter your first number:')
Integer1 = int(input())
print( 'Please enter your second number:')
Integer2 = int(input())
print( 'First number entered: ' , Integer1 )
print( 'Second number entered: ' , Integer2 )
print()
print( 'Sum of both numbers: ' , Integer1 + Integer2 )
print( 'Result of Multiplying the two numbers: ' , Integer1 * Integer2 )
# print prompt to enter string 1 and convert to integer
# print prompt to enter string 2 and convert to integer
# print both inputs
# print sum of both numbers
# print product of both numbers
| true |
9c0f21efca20bb54f6f6aee834adb755f8a65e9f | HBashanaE/algorithms | /basic-concepts/binary_search/a_binary_search.py | 2,734 | 4.375 | 4 | def binary_search_recur(arr, find, start, end):
"""Recursive algorithm. Halves search"""
if start == end:
return False
mid = (start + end) // 2
if arr[mid] == find:
return True
elif arr[mid] > find:
return binary_search_recur(arr, find, start, mid)
else:
return binary_search_recur(arr, find, mid + 1, end)
def binary_search_iter(arr, find, start, end):
"""Iterative algorithm. Halves search"""
while start != end:
mid = (start + end) // 2
if arr[mid] == find:
return True
elif arr[mid] > find:
end = mid
else:
start = mid + 1
return False
def binary_search_jump(arr, find):
"""Alternative iterative algorithm. Jump forward and search"""
jump = len(arr) // 2
index = 0
while arr[index] != find:
while index + jump >= len(arr) or arr[index + jump] > find:
jump //= 2
if jump == 0:
return False
index += jump
return True
def find_changing_point(func, start, max_range):
"""
Function to find a value for which a given function changes
from False to True
max_range is not important but it is the
maximum jump length
So it has to be higher than turning point
to be efficient
"""
val = start
# Initial jump is total length
jump = max_range
# Continue until jump is a positive integer
# ..or there is something to jump
while jump != 0:
# If at value this hopes to jump,
# function takes True, then point which is searched
# is passed. So must not jump.
while not func(val + jump):
# If a jump is possible, jump
val += jump
jump //= 2
# This gives last value for which
# function is False.
# Answer is the integer after that
return val + 1
def find_maximum_point(func, start, max_range):
"""
Adds a internal function so it can be passed
Finds a maximum point when given a function
"""
# Add a converting wrapper to make this a
# True False step function
def converted_func(x):
return func(x) > func(x + 1)
# Pass to above function
return find_changing_point(converted_func, start, max_range)
def function_change_position(function, initial_jump, minimum_accuracy=1e-6):
"""
Find position where boolean function changes
function has to accept a number and return True False
F F F F F F F T T T T
Finds larget value where function is False
Time complexity O(logn)
"""
x = -1
b = initial_jump
while b>=minimum_accuracy:
while not function(x+b):
x += b
b /= 2
return x
| false |
e8e7be052d4014a42d2ad8b74ee3eeabc6f89f16 | absingh-hub/Python_practise | /iterators2.py | 280 | 4.21875 | 4 | nums = [1, 2, 3]
#for num in nums:
# print(num)
#this for loop is equivalent to following working in background
i_num = iter(nums)
while True:
try:
num = next(i_num)
print(num)
except StopIteration:
break
#Iterators can only go forward through __next__ method | true |
ce00f60549ffd503e99682e1649a94a160a7eb19 | arbonap/interview-practice | /LL.py | 1,303 | 4.125 | 4 | class Node(object):
def __init__(self):
self.value = value
self.next = None
class Linkedlist(object):
def __init__(self):
self.head = None
def append_node(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
current = self.head
while self.head is not None:
current = current.next
current.next = new_node
def print_LL(self):
current = self.head
while current.next is not None:
print current.value
current = current.next
def print_LL(self):
current = self.head
while current.next is not None:
print current.value
current = current.next
def contains_cycle(first_node):
# start both runners at the beginning
slow_runner = first_node
fast_runner = first_node
# until we hit the end of the list
while fast_runner is not None and fast_runner.next is not None:
slow_runner = slow_runner.next
fast_runner = fast_runner.next.next
# case: fast_runner is about to "lap" slow_runner
if fast_runner is slow_runner:
return True
# case: fast_runner hit the end of the list
return False
| true |
82e6e225af956d7b7d6fa0aad4d208a4f4ddb157 | arbonap/interview-practice | /remove-odds.py | 216 | 4.28125 | 4 | def remove_odd_nums(array):
""" Remove odd numbers from a given array"""
for num in array:
if num % 2 != 0:
array.remove(num)
return array
print remove_odd_nums([1, 2, 3, 4, 5, 6, 7])
| true |
39b2468242a054fdd8442ac7d348861dc391704b | arbonap/interview-practice | /pig-latin.py | 459 | 4.1875 | 4 | def pig_latin(text):
"""Create Pig Latin generator. If a word begins with a vowel, add '-ay' to the end of the word. If a word begins with a consonant, slice the first letter to the end and add '-ay' to the end of the string."""
pyg = '-ay'
text = text.lower()
if len(text) > 0 and text.isalpha():
if text[0] in 'aeiou':
print text + pyg
else:
print text[1:] + text[0] + pyg
print pig_latin('potatoes')
print pig_latin('icecream')
| true |
30e251b989128d2745451b5f34999f65ee3f1d8b | gkulk007/Hacktoberfest2021 | /Programs/Aman_Ahmed_Siddiqui/Evil Number.py | 1,539 | 4.28125 | 4 | '''
An Evil number is a positive whole number which has even number of 1's in its binary equivalent. Example: Binary equivalent of 9 is 1001, which contains even number of 1's. A few evil numbers are 3, 5, 6, 9…. Design a program to accept a positive whole number and find the binary equivalent of the number and count the number of 1's in it and display whether it is a Evil number or not with an appropriate message. Output the result in format given below:
Example 1
Input: 15
Binary Equivalent: 1111
No. of 1's: 4
Output: Evil Number
Example 2
Input: 26
Binary Equivalent: 11010
No. of 1's: 3
Output: Not an Evil Number
'''
#bin() Is A Method In Python To Convert
#Num Into Binary
#But I Will Be Using Custom Binary Function
#Custom Binary Function----------------------
def Bin(num : int)-> int:
mun_nib = ''
if num == 0:
return 0
while num > 0:
n = num % 2
mun_nib += str(n)
num //= 2 #Floor Division
bin_num = mun_nib[::-1] #Reversing String
return int(bin_num)
#Function Ends-------------------------------
#Function Starts-----------------------------
def isEvil(num : int) -> None:
bin = str(Bin(num))
print("Binary Equivalent:",bin)
ones = bin.count('1')
print("No. Of 1's:",ones,end= ' ')
if ones % 2: #0 -> False; 1 -> True
print(f"(Odd)\n{num= }, Is Not An Evil Number")
else:
print(f"(Even)\n{num= }, Is An Evil Number")
#Function Ends-----------------------------
num = int(input("Enter A Number To Check:"))
if num >= 0:
isEvil(num)
else:
print('Incorrect Input. Try Again.') | true |
12a6ad4283868e04e2913c3639fd8e7cbfdea215 | gkulk007/Hacktoberfest2021 | /Programs/Aman_Ahmed_Siddiqui/Smith Number.py | 1,513 | 4.34375 | 4 | '''
A Smith number is a composite number, whose sum of the digits is equal to the sum of its prime factors. For example:
4, 22, 27, 58, 85, 94, 121 ………. are Smith numbers.
Write a program in Python to enter a number and check whether it is a Smith number or not.
Sample Input: 666
Sum of the digits: 6 + 6 + 6 = 18
Prime factors are: 2, 3, 3, 37
Sum of the digits of the prime factors: 2 + 3 + 3 + (3 + 7) = 18
Thus, 666 is a Smith Number.
'''
#Function Starts-----------------------------
def Factors(num : int) -> list:
i = 2
facts = []
while num > 1:
if num % i == 0:
facts.append(i)
num = num // i
else:
i += 1
return facts
#Function Ends-------------------------------
#Function Starts-----------------------------
def DigitsSum(num : int) -> int:
sum = 0
while num > 0:
sum += (num % 10)
num //= 10
return sum
#Function Ends-------------------------------
#Function Starts-----------------------------
def isSmith(num : int) -> None:
factstr = ''
factors = Factors(num)
for each in factors:
factstr += str(each)
facts_sum = DigitsSum( int(factstr) )
digit_sum = DigitsSum( num )
print(f"Sum Of Digits Of {num}: {digit_sum}")
print("Prime Factors Are:",factors)
print("Sum Of Digits Of Prime Factors:",facts_sum)
if facts_sum == digit_sum:
print(f"Thus, {num} Is A Smith Number.")
else:
print(f"{num} Is Not A Smith Number.")
#Function Ends-------------------------------
num = int(input("Enter Number To Check:"))
isSmith(num)
| true |
d9fb509e83bc948c3566f0f714fa1096212f4431 | irene1811/Everything | /Shapes.py | 556 | 4.15625 | 4 | from turtle import *
import math
# Name your Turtle
t = Turtle()
#Set Up your screen and starting position
setup (500,300)
x_pos = (0)
y_pos = (0)
t.setposition(x_pos,y_pos)
for i in range (3):
forward(50)
left(120)
for i in range (5):
left (-60)
for i in range (3):
forward(50)
left (120)
for i in range (5):
forward(50)
for i in range (2):
forward(50)
left(120)
for i in range (5):
left (-60)
for i in range (3):
forward(50)
left (120)
exitonclick ()
| false |
f2c2a749c967baf45396e85dcd0d6e5cc097e374 | LayllaRodrigues/Head_First_LearntoCode | /ch6/pseudocodigo_loop.py | 1,359 | 4.15625 | 4 | # O loop externo representa cada passagem no algoritmo.
# O loop interno passa por cada item da lista e executa as comparações (e qualquer troca necessária).
# Com isso em mente, vamos dar uma olhada:
# PSEUDOCODIGO - classifica a lista em ordem crescente:
# # define a function
# def bubble_sort(list):
# # declare a variable
# swapped and set to True
# while swapped to False.
# # For variable i in range(0, len(list)- I)
# IF list[i] > list[i+I]:
# DECLARE a variable temp and set to list[i].
# SET list[i] to list[i+I]
# SET list[i + I] to temp
# SET swapped to True.
# bug:
for i in range(0, 4):
for j in range(0,4):
print(i * j)
# bug:
for word in ['ox', 'cat', 'lion', 'tiger', 'bobcat']:
for i in range(2,7):
letters = len(word)
if(letters % i) == 0:
print(i, word)
full = False
donations = []
full_load = 45
toys = ['robot', 'doll', 'ball', 'slinky']
while not full:
for toy in toys:
donations.append(toy)
size = len(donations)
if (size >= full_load):
full = True
print('Full with', len(donations), 'toys')
print(donations)
| false |
450fff7c3c0e11a77a0601387ad6c73c48a67cb3 | vijaynchakole/Python-Code | /MyParallelProgramming.py | 886 | 4.125 | 4 |
#below program which uses serial processing approach
def square(n):
return(n*n)
if __name__ == "__main__":
#input list
arr = [1,2,3,4,5]
#empty list to store result
result = []
for num in arr :
result.append(square(num))
print(result)
###########################################################################################################################
#program which uses Pooling for Parallel Programming
import multiprocessing
import os
def square(n):
print("Worker process id for {0}:{1}".format(n,os.getpid()))
return(n*n)
if __name__ == "__main__":
#input list
arr = [1,2,3,4,5]
# creating pooling object
p = multiprocessing.Pool()
#map this list to target function
result = p.map(square,arr)
print("Square of each elements:")
print(result) | true |
6d1cd1d5e5be293ca71d3b8b9f4e5e0df4b96726 | Audrey-me/CGPA-CALCULATOR | /second.py | 1,301 | 4.15625 | 4 | def degree_checker(grade):
degree = 'Pass'
y = ['first class honours', 'second class honours (upper division)', 'second class honours (lower division)',
'third class honours']
about = '''ABOUT
The function takes in strings
UOP students should include % while MAU students include gpa when entering grade.'''
if type(grade) is not str:
return about
grade = grade.replace(' ', '')
if '%' in str(grade):
grade = grade.replace('%', '')
grade = float(grade)
grade = (grade / 100) * 5.0
if 4.5 <= grade <= 5:
degree = y[0]
elif 3.5 <= grade <= 4.49:
degree = y[1]
elif 2.4 <= grade <= 3.39:
degree = y[2]
elif 1.5 <= grade <= 2.39:
degree = y[3]
elif 'gpa' in grade:
grade = grade.replace('gpa', '')
grade = float(grade)
if 4.5 <= grade <= 5:
degree = y[0]
elif 3.5 <= grade <= 4.49:
degree = y[1]
elif 2.4 <= grade <= 3.39:
degree = y[2]
elif 1.5 <= grade <= 2.39:
degree = y[3]
else:
return about
return f'Dear student your CGPA is {grade:.2f}, you are a {degree} student.'
print(degree_checker('60%'))
print(degree_checker('4.5gpa')) | false |
875605683c59e5cacd6b7cbe69c182c45318aa76 | haifeng94/Python-Algorithm | /剑指offer/面试中的各项能力/发散思维能力/Sum.py | 631 | 4.1875 | 4 | # coding=utf-8
'''
题目:求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
'''
'''
思路一:利用了python的特性, range和sum
'''
class Solution:
def Sum_Solution(self, n):
return sum(range(1, n+1))
s = Solution()
res = s.Sum_Solution(5)
print(res)
'''
思路二:其实跟思路一差不多
'''
class Solution2:
def Sum_Solution2(self, n):
from functools import reduce
return reduce(lambda x, y: x+y, range(1, n+1))
s2 = Solution2()
res = s2.Sum_Solution2(5)
print(res) | false |
ed1200ad70c5924d2b556a263be368679482b7f8 | MerhuBerahu/Python3-DnD5e-CharacterCreator- | /Races.py | 1,909 | 4.1875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Display race information and select a race
"""
#TODO stuff
import json
from Systems import check_input
with open("Jsons\\races.json", encoding="utf8") as test: #Open races.json as test
race_list = json.load(test)
def race_info():
"""Pull in race information from a Json, format it into a list for
selection and make a choice. Then print the values of that race
from the Json
"""
print("Which Race would you like to know more about?")
race_choices = {}
for index, item in enumerate(race_list, 1):
print(index, item) #Print Numbers list of items in races.json
dict1 = {index:item} #create dict with enumerate number(index) as a key and item as the value
race_choices.update(dict1)
minmax = list(race_choices.keys())[0:]
selection = check_input(minmax[0],minmax[1])
if selection in race_choices:
chosen_race = race_choices[selection]
for i in race_list[chosen_race].values():
print(i,"\n")
choice = input("Type 'back' to go back to the race menu to look at another Race 1or 'continue' if you are happy to choose a race now.\n")
if choice in ("back", "Back", "b", "B"):
race_info()
elif choice in ("continue", "continue"):
race_selection()
def race_selection():
print("Which Race would you like to be?")
race_choices = {}
for index, item in enumerate(race_list, 1):
print(index, item) #Print Numbers list of items in races.json
dict1 = {index:item} #create dict with enumerate number(index) as a key and item as the value
race_choices.update(dict1)
minmax = list(race_choices.keys())[0:]
selection = check_input(minmax[0],minmax[1])
if selection in race_choices:
chosen_race = race_choices[selection]
print(chosen_race)
return chosen_race
race_info() | true |
e4d83836f27a7cd3d1719661f6a8a963dc3b735f | byui-cs/cs241-course | /week01/ta01-solution.py | 1,168 | 4.28125 | 4 | # Team Activity 01
# Author: Br. Burton
# Part 1: Ask the user for their DNA sequence, count the number of A's
dna = input("Please enter your DNA sequence: ")
# This will keep track of our matches
match_count = 0
# Go through the string letter by letter, and count the matches
for letter in dna:
if letter == 'A':
match_count += 1
# Output the results:
print("The sequence {} has {} A's.".format(dna, match_count))
# Blank line. Just for fun...
print()
# Part 2/3: Ask for a second person's sequence, and compare them:
dna_friend = input("Please enter your friend's DNA sequence: ")
# set the match count to be 0
match_count = 0
# For part 2, we assume each sequence is 10 characters, and could use this:
#length = 10
# For part 3, we use the smaller of the two:
length = 0
if len(dna) < len(dna_friend):
length = len(dna)
else:
length = len(dna_friend)
# Go through that many letters and count the matches
for i in range(length):
if dna[i] == dna_friend[i]:
match_count += 1
# Display the results:
match_percent = match_count / length * 100
print("You and your friend had {} matches for {}%".format(match_count, match_percent)) | true |
1bbff88e227879dd98c15b0ffe6a78554378caa1 | myfriendprawin/Praveen-Kumar-Vattikunta | /Weekend Day2.py | 671 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[6]:
#Data Types:
#Numbers: Number data types are immutables.
#Integers:
A=1
B=3
A+B
# In[7]:
#Float: Declaring values in decimal is called as float.
X=1.
Y=2.0
X+Y
# In[8]:
#Advance assignment of values to variables.
K,L,M,N=5,6,9,1
print(M)
# In[19]:
#List Data Type: List is muatble. we can modify/change/append values to it.
#List is a collection of items in order
Names=['Raj', 'Vijay','akmal', 'Shuwen']
# 0 1 2 3 ==> this is called as indexing.
# in above list, the names are arranged in an order.
print(Names)
print(Names[1])
print(Names[3])
print(Names[2].upper())
| true |
023a9c620470e17c50842ee0b078960cb3b2d88d | ivyldewitt/python-review | /practice/interactive.py | 698 | 4.53125 | 5 | ### PRACTICE ###
user_prompt = input("Please enter a whole number (no decimals): ")
user_int = int(user_prompt)
## Write a program that requests a number from the user.
# Have the program print "Even" or "Odd" depending on whether
# they entered an even or odd number.
while user_int != 0:
if user_int % 2 == 0:
print(f"It looks like {user_int} is an EVEN number!")
else:
print(f"{user_int} is an ODD number.")
# I'm curious if there's a more efficient way to do this. I initially broke the loop instead of repeating this twice.
user_prompt = input("Please enter a whole number (no decimals): ")
user_int = int(user_prompt)
print("Thanks for playing!")
| true |
ae7b0936d7d7a56203adc0d7fc63db4466ab2229 | tristan-neateworks/AIArena | /AIArena/AI.py | 1,963 | 4.125 | 4 | class Player:
"""This forms an interface for a generic game "player." It is extended by the AI class and can be used to represent any kind of entity that makes moves in a given game.
:param name: The human-readable reported name for the player (ex. LilBuddy for our Connect 4 playing AI)
:param game: The specific game instance for this AI to play.
"""
def __init__(self, name, game):
"""Constructor
"""
self.name = name
self.game = game
def makeMove(self, state):
"""Returns an appropriate move given a game state. Must be overridden in implementations of the Player class.
:param state: The game state given which to make a move.
:return: An appropriate move representation depending on the game played.
"""
print("This player is missing the method 'makeMove(self, state)'")
return None
class AI(Player):
"""This is the core interface for AI development. Extending the makeMove() method allows for a hook into an AI so that it can respond to game states and inputs.
:param name: The human-readable reported name for this AI (ex. LilBuddy for our Connect 4 playing AI)
:param game: The specific game instance for this AI to play.
"""
def __init__(self, name, game):
"""Constructor. Calls superclass (Player) constructor and nothing else
"""
super().__init__(name, game)
#add AI specific code here
def makeMove(self, state):
"""Returns an appropriate move given a game state. Must be overridden in implementations of the Player class.
:param state: The game state in which to make a move.
:return: An appropriate move representation depending on the game played.
"""
print("Your AI is missing the method 'makeMove(self, state)'")
return None
class AI_Connect4(AI):
def __init__(self, name):
super().__init__(name, "Connect4")
| true |
0d8908216a9d7ce6f1419118b6f88db5f8fd1672 | natasharivers/python-exercises | /python_warmup.py | 1,984 | 4.75 | 5 | ##WARM UP EXERCISES
#write the code that takes a single string string containing the make and model of a vehicle.
#first part of te string before the space is the make
#the last part of the string after the space is a model
#we can assume that the strings will only have one space
#assume the input string is completely lowercased
#ex: truck = "toyota tacoma"
#sedan = "hyundai sonata"
#sports_car = "lambourgini diablo"
truck = "toyota tacoma"
make_and_model = truck.split()
vehicle_make = truck.split()[0]
vehicle_model = truck.split()[1]
print(make_and_model)
##Exercise #1
#Write the code to take a string and produce a dictionary out of that string.
#such that the output looks like the following:
#-you'll need a way to get the first part of the string and a way to get the second part of the string
#-feel free to make new variables/ data types in between the string and the output dictionary
#input:
#truck = "toyota tacoma"
#output
#truck = {
#"make": "Toyota"
#"model": "Tacoma"
#}
truck = dict(vehicle_make = 'toyota', vehicle_model = 'tacoma')
print(truck)
## Exercise #2
#Write the code that takes a dictionary contraining make/mode for a vehicle and capitalizess the first character of the make and the mode;
#input
#truck = {
#"make": "toyota"
#"model": "tacoma"
#}
#output
#truck = {
#"make": "Toyota"
#"model": "Tacoma"
#}
truck["make"] = truck["make"].capitalize()
truck["model"] = truck["model"].capitalize()
print(truck)
## Exercise #3
#create a list of 3 dictionaries where each dictionary represents a vehicle, as above
#write the code that operates on the list of dictionaries in order to uppercase the entire make and model values.
#input
#trucks = [{
# "make": "toyota",
# "model": "tacoma"
#},
#{
# "make": "ford",
# "model": "fusion"
#},
#{
# "make": "mazda",
# "model": "miata"
#}]
for truck in trucks:
truck["make"] = truck["make"].upper()
truck["model"] = truck["model"].upper()
trucks
| true |
2920e6e3ec24466f9e284bc5ec0bd200359c037a | jashidsany/Learning-Python | /LCodecademy Lesson 11 Function Arguments/L11.3_Default_Arguments.py | 1,015 | 4.15625 | 4 | # Function arguments are required in Python. So a standard function definition that defines two parameters requires two arguments passed into the function.
# Not all function arguments in Python need to be required. If we give a default argument to a Python function that argument won’t be required when we call the function.
import os
def make_folders(folders_list, nest=False):
if nest:
"""
Nest all the folders, like
./Music/fun/parliament
"""
path_to_new_folder = "."
for folder in folders_list:
path_to_new_folder += "/{}".format(folder)
try:
print(path_to_new_folder)
os.makedirs("./" + path_to_new_folder)
except FileExistsError:
continue
else:
"""
Makes all different folders, like
./Music/ ./fun/ and ./parliament/
"""
for folder in folders_list:
try:
os.makedirs(folder)
except FileExistsError:
continue
make_folders(['Music', 'fun', 'parliament'])
| true |
956cd4948879564ec6b2d19ade61a1bf5ef76885 | jashidsany/Learning-Python | /Codecademy Lesson 8 Dictionaries/LA8.11_Try_And_Except_To_Get_A_Key.py | 585 | 4.34375 | 4 | # We saw that we can avoid KeyErrors by checking if a key is in a dictionary first. Another method we could use is a try/except:
# key_to_check = "Landmark 81"
# try:
# print(building_heights[key_to_check])
# except KeyError:
# print("That key doesn't exist!")
# When we try to access a key that doesn’t exist, the program will go into the except block and print "That key doesn't exist!".
caffeine_level = {"espresso": 64, "chai": 40, "decaf": 0, "drip": 120, "matcha": 30}
try:
print(caffeine_level["matcha"])
except KeyError:
print("Unknown Caffeine Level")
| true |
6bb3631eed8bdebd296f4054d1c84d272f44ff1f | jashidsany/Learning-Python | /Codecademy Lesson 9 Files/L9.0_Reading_A_File.py | 1,191 | 4.5625 | 5 | # Computers use file systems to store and retrieve data.
# Each file is an individual container of related information.
# If you’ve ever saved a document, downloaded a song, or even sent an email you’ve created a file on some computer somewhere.
# Even script.py, the Python program you’re editing in the learning environment, is a file.
# So, how do we interact with files using Python?
# We’re going to learn how to read and write different kinds of files using code.
# Let’s say we had a file called real_cool_document.txt with these contents:
# real_cool_document.txt
# Wowsers!
# We could read that file like this:
# script.py
# with open('real_cool_document.txt') as cool_doc:
# cool_contents = cool_doc.read()
# print(cool_contents)
# This opens a file object called cool_doc and creates a new indented block where you can read the contents of the opened file.
# We then read the contents of the file cool_doc using cool_doc.read() and save the resulting string into the variable cool_contents.
# Then we print cool_contents, which outputs the statement Wowsers!.
with open('welcome.txt') as text_file:
text_data = text_file.read()
print(text_data)
| true |
ba45301804c28d062503ca306c6ea393b7da0394 | jashidsany/Learning-Python | /Codecademy Lesson 6 Strings/LA6.16_Joining_Strings_1.py | 511 | 4.375 | 4 | # Now that you’ve learned to break strings apart using .split(), let’s learn to put them back together using .join(). .join() is essentially the opposite of .split(), it joins a list of strings together with a given delimiter. The syntax of .join() is:
# 'delimiter'.join(list_you_want_to_join)
# Delimiters are spaces
reapers_line_one_words = ["Black", "reapers", "with", "the", "sound", "of", "steel", "on", "stones"]
reapers_line_one = (' '.join(reapers_line_one_words))
print(reapers_line_one)
| true |
022fc7d62f80194c39334f22d8e48e8826f01a07 | jashidsany/Learning-Python | /Codecademy Lesson 6 Strings/LA6.28_X_Length.py | 560 | 4.1875 | 4 | # Write your x_length_words function here:
def x_length_words(sentence, x):
words = sentence.split(" ")
# creates a variable words that stores the words split in the string sentence
for word in words:
# iterates through the words
if len(word) < x:
# if the length of the word is less than the integer x
return False
return True
# Uncomment these function calls to test your tip function:
print(x_length_words("i like apples", 2))
# should print False
print(x_length_words("he likes apples", 2))
# should print True
| true |
b93ee019f4b0714aec476258771ad849ddb70c95 | SSamiKocaaga/python-project | /Assignment 007_003.py | 693 | 4.1875 | 4 |
# Variables
armvalue = 0
condition = False
# Receives input from the user until he/she enters data in the expected format
while not condition:
number = input('Write a number: ')
if number.isdigit():
condition = True
else:
print(" It is an invalid entry. Don't use non-numeric, float, or negative values!")
list_digits_numbers = list(number)
#calculates whether it is a armstrong number or not.
for i in range(len(list_digits_numbers)):
armvalue = armvalue + int(list_digits_numbers[i])**len(list_digits_numbers)
if int(number) == armvalue:
print('{} is an armstrong number'.format(number))
else:
print('{} is not an armstrong number'.format(number))
| true |
e6385076df5131c0df3330896536fb40edbfa250 | fuston05/Computer-Architecture | /OLD_ls8/util.py | 1,512 | 4.46875 | 4 | # In general, the `.format` method is considered more modern than the printf `%`
# operator.
# num = 123
#
# # Printing a value as decimal
#
# print(num) # 123
# print("%d" % num) # 123
# print("{:d}".format(num)) # 123
#
# # Printing a value as hex
#
# print(hex(num)) # 0x7b
# print("%x" % num) # 7b
# print("%X" % num) # 7B
# print("%04X" % num) # 007B
# print(f"{num:x}") # 7b
# print(f"{num:X}") # 7B
# print(f"{num:04x}") # 007b
#
# # Printing a value as binary
#
# print("{num:b}".format(num)) # 1111011, format method
#
# # Converting a decimal number in a string to a value
#
# s = "1234"; # 1234 is 0x4d2
# x = int(s); # Convert base-10 string to value
#
# # Printing a value as decimal and hex
#
# print(num) # 1234
# print(f"{num:x}") # 4d2
#
# # Converting a binary number in a string to a value
#
# s = "100101" # 0b100101 is 37 is 0x25
# x = int(s, 2) # Convert base-2 string to value
#
# # Printing a value as decimal and hex
#
# print(num) # 37
# Conversion Python code:
# str = "10101010"
def to_decimal(num_string, base):
digit_list = list(num_string)
digit_list.reverse()
value = 0
for i in range(len(digit_list)):
print(f"+({int(digit_list[i])} * {base ** i})")
value += int(digit_list[i]) * (base ** i)
return value
# to_decimal(str, 2) | true |
81fb3be1743672abd6f93a65aa4892ed28901eaf | jcellomarcano/Willy | /myStack.py | 1,904 | 4.125 | 4 | DEBUG_MODE = True
import sys
"""
Estructura de Pila para verificacion del interprete
Primera fase del proyecto
Traductores e Interpretadores (CI-3725)
Maria Fernanda Magallanes (13-10787)
Jesus Marcano (12-10359)
E-M 2020
Simulacion de una Pila que se encarga de verificar contextos dentro de dentro del mundo y dentro de la tarea
con esta clase se puede ver si existe o no un elemento dentro de la pila y devuelve True or False, si el
elemento a insertar ya existe. De esta forma, no aseguramos si existen elementos repetidos dentro de nuestro
programa
"""
class myStack:
def __init__(self):
self.stack = []
self.level = 0
def find(self,symbol):
table = self.stack[len(self.stack) - 1]
iFoundIt = False
for element in table:
if element[0] == symbol:
iFoundIt = True
break
return iFoundIt
def insert(self, symbol, data):
if not self.find(symbol):
pair = [symbol, data]
table = self.stack[self.level - 1]
table.append(pair)
else:
print("El elemento: " + str(symbol) + "existe en la pila y no podemos volver a agregarlo")
sys.exit()
def push_empty_table(self):
table = []
self.level = 1
self.stack.append(table)
def pop(self):
if not self.empty():
self.stack.pop()
self.level = self.level - 1
else:
self.level = 0
def empty(self):
return len(self.stack)==0
def push(self,table):
if (len(self.stack) - self.level) == 1:
self.level = self.level + 1
elif (len(self.stack) - self.level) == 0:
self.stack.append(table)
self.level = self.level + 1
def __str__(self):
mystring = str(self.stack)
return mystring
| false |
8263cd6c0f37eb66061219be0d314bb12cb2564d | vvdnanilkumargoud/Python | /search.py | 548 | 4.21875 | 4 | #a is list
a = [1,2,3,4,5]
#It will search entire list whthere value is there or not
check = raw_input("Enter which you want to search in a list : ")
if check not in a:
a.append(check)
print "%s is not in the list we are adding into list" %check
print "This is the latest list : %s" %a
else:
print a
#b is dictionary
b = {'c':4,'d':5,'e':7}
key = raw_input("Enter which key you want to search in a dictionary : ")
if key in b:
print "Value of %s is %s" %(key,b[key])
else:
print "There is no %s as key in Dictionary" %key
| true |
54e81046a418fc4c8fbfa60d0ce83bdb15e4f8d3 | nvyasir/Python-Assignments | /exception_regform.py | 604 | 4.3125 | 4 | # Registration System
#
#
# You are making a registration form for a website.
# The form has a name field, which should be more than 3 characters long.
# Any name that has less than 4 characters is invalid.
# Complete the code to take the name as input, and raise an exception if the name is invalid, outputting "Invalid Name". Output "Account Created" if the name is valid.
#
# Sample Input
# abc
#
# Sample Output
# Invalid Name
try:
name = input()
if len(name)<4:
raise ValueError
else:
print("Account Created")
# your code goes here
except:
print("Invalid Name") | true |
1a1e048c7e1e5c2a367b0c5e75f5f2bef4e38506 | nvyasir/Python-Assignments | /tuples.py | 714 | 4.28125 | 4 | # Tuples
#
# You are given a list of contacts, where each contact is represented by a tuple, with the name and age of the contact.
# Complete the program to get a string as input, search for the name in the list of contacts and output the age of the contact in the format presented below:
#
# Sample Input
# John
#
# Sample Output
# John is 31
contacts = [
('James', 42),
('Amy', 24),
('John', 31),
('Amanda', 63),
('Bob', 18)
]
name = input()
index_num = 0
length = len(contacts)
for i in contacts:
if name not in i:
index_num+=1
if name in i:
print(name + " is "+ str(contacts[index_num][1]))
break
if index_num >= length:
print("Not Found")
| true |
b9f60c435d858ede41449fff6c05f4a0de3e5343 | volllyy/python_basic_HW | /HW/HW_3/Task_5.py | 1,734 | 4.1875 | 4 | # HW3 - Task № 5
def sum_func() -> int:
"""
The program asks the user for a string of numbers separated by a space.
When you press Enter, the sum of the numbers should be displayed.
The user can continue to enter numbers separated by a space and press Enter again.
The sum of the newly entered numbers will be added to the already calculated
amount. But if a special character (Stop or stop) is entered instead of a number, the program
ends. If a special character is entered after several numbers, then first you
need to add the sum of these numbers to the previously received amount and then
complete the program.
:return: Int // Return sum of all digits in all strings entered by user.
"""
data = True
next_enter = True
sum_total = 0
while next_enter and data:
sum_inter = 0
my_list = input('Enter string of digits\n').split(' ')
for itm in range(len(my_list)):
if my_list[itm] == 'stop' or my_list[itm] == 'Stop':
next_enter = False
break
elif my_list[itm].isdigit():
sum_inter = sum_inter + int(my_list[itm])
elif my_list[itm] == '': #if user in the end of the string add Space
my_list = my_list.pop(-1) #delete the last element equal to the empty element
sum_inter = sum_inter + int(my_list[itm])
else:
print('Enter correct data')
data = False
break
sum_total = sum_total + int(sum_inter)
print('Intermediate sum of 1 line is', sum_inter)
print('Final sum of all strings', sum_total)
sum_func()
| true |
b1314d7f4195ed997d446cb084b59a45f24f8623 | volllyy/python_basic_HW | /HW/HW_1/Task_1.py | 695 | 4.1875 | 4 | #HW1 - Task № 1
year = 2020
temperature = 10.5
month = 'April'
print(year,'/', temperature,'Cº /', month)
name = input('What`s your name?\n')
surname = input('What`s your surname?\n')
age = input('How old are you?\n')
number = input('What is your phone number? (Wright down without + and spaces, '
'just country code and tel.namber)\n')
if name.isdigit() or surname.isdigit():
print('Enter correct information about name and surname please!')
else:
print('Name:', name,'/ Surname:', surname)
if not age.isdigit() or not number.isdigit():
print('Enter correct information about age and phone number please!')
else:
print('Age:', age,'/ Phone number: +', number)
| true |
34328ab0d637668b489d976640218293d219691a | developeruche/python_threading_module | /demo_one/app.py | 756 | 4.1875 | 4 | import threading
""" Thread is a mean by which a program of app can excectue various function simutanously """
def thread_one_function(test_arg_one, test_arg_two):
for i in range(0, 20):
print(f'I am Tread one ----- {test_arg_one}, {test_arg_two}')
def thread_two_function(test_agr):
for i in range(0, 20):
print(f"I am thread two {test_agr}")
# Here i am initailizing the threading Tread class
thread_1 = threading.Thread(target=thread_one_function, args=("one", "two", ))
thread_2 = threading.Thread(target=thread_two_function, args=(2, ))
# Starting up the thread
thread_2.start()
thread_1.start()
# Creating a mechinsm that would make the interpreter wait till the thread is excecuted
thread_1.join()
thread_2.join() | true |
1b4c62b21246c21f184138a31135ee333ac13510 | mummyli/python_practice | /data_structure/concat_str.py | 253 | 4.125 | 4 | # join()连接可迭代对象
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print("-".join(parts))
a = 'Is Chicago'
b = 'Not Chicago?'
# format 拼接
print('{} {}'.format(a, b))
# 简单拼接两个字符串
c = "hello" "world"
print(c) | false |
3f84c7f6030299449c5513201fedc08b0fb07332 | darshanjain033/darshjain | /largest number.py | 382 | 4.40625 | 4 | # Python program to find the largest number among the three input numbers...
num_1 = float(input("Enter Number_1 :"))
num_2 = float(input("Enter Number_2 :"))
num_3 = float(input("Enter Number_3 :"))
if (num_1 >= num_2 and num_1 >= num_3):
print("Number_1 is large")
elif (num_2 >= num_1 and num_2 >= num_3):
print("Number_2 is large")
else :
print("Number_3 is large")
| true |
3956a24fe0603b39e0658763b0f8757733f018ae | ebrudalkir/Pythondersnotlar- | /ders4.py | 330 | 4.125 | 4 |
'''for i in range(1,10):
print(i*"*")'''
factoriyel=1
while True:
sayi=int(input("enter of numbers:"))
if(sayi<=0):
print("please enter positive number!!")
else :
for i in range(1,sayi+1):
factoriyel=factoriyel*i
print("factoriyel",factoriyel)
break
| false |
5c75c95c28a0e6f541d8dce1f38f5e61bf77e91f | RitRa/multi-paradigm-programming-exercises | /Week3_exercises/q8_primenumber.py | 424 | 4.1875 | 4 | # Write a program that prints all prime numbers. (Note: if your programming language does not support arbitrary size numbers, printing all primes up to the largest number you can easily represent is fine too.)
number = input("Pick a number")
#convert to a number
number = int(number)
for i in range(number):
if (number%i) == 0:
print(i)
else:
print("heelo")
print("Prime number", i)
| true |
19a4d0579ea77bd0c219ce75c467d6e650b6efae | RitRa/multi-paradigm-programming-exercises | /Week3_exercises/q3_whatisyournamemodified.py | 307 | 4.40625 | 4 | # Write a program that asks the user for their name and greets them with their name.
# Modify the previous program such that only the users Alice and Bob are greeted with their names.
name = input("what is your name?")
vip = ["Alice", "Bob"]
for i in vip:
if i == name:
print("Hello " + name) | true |
1677429d9d212b6971af7f1b7408a5aeb08b945a | xzx1kf/football_manager_project | /football_manager/elo/elo.py | 1,908 | 4.3125 | 4 | class Result(object):
"""
A Result can either be a win, lose or draw. A numerical value is
assigned to the result.
"""
WIN, LOSE, DRAW = 1, 0, 0.5
class EloFootballRating(object):
"""
A rating system based on the Elo rating system but modified to take
various football specific variables into account.
"""
def __init__(self, k_factor):
self.k_factor = k_factor
@staticmethod
def get_goal_difference_index(goal_difference):
"""
The number of goals is taken into account by use of
a goal difference index (g).
g = 1 if the game is a draw or is won by one goal.
g = 1.5 if the game is won by two goals.
g = (11 + n) / 8 if the game is won by three or more goals.
Where n is the goal difference.
"""
if goal_difference <= 1:
return 1
elif goal_difference == 2:
return 1.5
else:
return (11.0 + goal_difference) / 8.0
@staticmethod
def get_expected_result(home_rating, away_rating):
"""
Calculate the expected result based on the current ratings
of the home team and away team.
"""
rating_diff = away_rating - home_rating
rating_diff = 10 ** (rating_diff / 400.0)
return 1 / (rating_diff + 1)
def calculate(
self,
home_rating,
away_rating,
goal_difference,
result):
"""
Calculates a new elo rating based off the result of the match
between a home team and away team.
"""
goal_difference_index = self.get_goal_difference_index(goal_difference)
expected_home_result = self.get_expected_result(
home_rating,
away_rating)
chance = result - expected_home_result
return goal_difference_index * self.k_factor * chance
| true |
617b9b55c1908552d1f58451a6d9b69bd0c961cf | longhao54/leetcode | /easy/88.py | 2,191 | 4.15625 | 4 | '''
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
'''
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
if m == 0 and len(nums1) == 1:
nums1[0] = nums2[0]
elif n != 0:
nums1[m:] = nums2
nums1.sort()
return nums1
# index = 0
# check = False
# num = nums2.pop(0)
# while True:
# try:
# if num <= nums1[index]:
# if index+1 == len(nums1)-1:
# nums1[index+1:] = nums1[index:m]
# else:
# nums1[index + 1:index + m-1] = nums1[index:m]
# print(nums1)
# nums1[index] = num
# if nums2:
# check = True
# num = nums2.pop(0)
# else:
# break
#
# index += 1
# if index == len(nums1) -1 :
# break
# except:
# print(index)
# break
# if check:
# nums2.insert(0,num)
# if len(nums2) == 1:
# nums1[-1] = num
# else:
# lenth = len(nums2)
# lenth1= len(nums1)
# nums1[lenth1-lenth:] = nums2
# return nums1
a = Solution()
# print(a.merge([1],1,[],0))
# print(a.merge([0],0,[1],1))
print(a.merge([0,0,0,0,0],0,[1,2,3,4,5],5))
# print(a.merge([1,2,3,0,0,0],3,[2,5,6],3))
# print(a.merge([2,0],1,[1],1))
# print(a.merge([1,1,2,7,0,0,0,0,0],4,[2,3,6,8,8],5))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.