blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
319e95ee89071a5402aaa30aac4f77e2f34a9168 | mkuentzler/AlgorithmsCourse | /LinkedList.py | 771 | 4.1875 | 4 | class Node:
"""
Implements a linked list. Cargo is the first entry of the list,
nextelem is a linked list.
"""
def __init__(self, cargo=None, nextelem=None):
self.car = cargo
self.nxt = nextelem
def __str__(self):
return str(self.car)
def display(self):
if self.car:
print str(self)
if self.nxt:
self.nxt.display()
def next(self):
return self.nxt
def value(self):
return self.car
def reverse(unrev, rev=None):
"""
Reverses a linked list.
"""
if unrev:
return reverse(unrev.next(), Node(unrev.value(), rev))
else:
return rev
B = Node(3)
C = Node(2, B)
A = Node(1, C)
A.display()
print
D = reverse(A)
D.display() | true |
43a5d6ca3431c87af401db8ceda677bca0a1a52e | AjsonZ/E01a-Control-Structues | /main10.py | 2,365 | 4.21875 | 4 | #!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange','yellow','green','blue','violet','purple'] # make a list of color
play_again = '' # make "play again" empty
best_count = sys.maxsize # the biggest number
while (play_again != 'n' and play_again != 'no'): #start a while loop with two conditions
match_color = random.choice(colors) # using random method to select a color randomly
count = 0 # count strat with 0
color = '' # make color empty
while (color != match_color):
color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line
color = color.lower().strip() # It turns all letters on 'color' into the lower case and delete all the spaces.
count += 1 # the 'count' will plus one after finishing a loop
if (color == match_color): # if color equals to match_color, it will execute the following codes
print('Correct!') # when condition is true, it will print out 'Correct!'
else: # if false
print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) # if false, it will print out this line.
print('\nYou guessed it in {0} tries!'.format(count)) # print out this line in the next line with the number of user's tries
if (count < best_count): # if user's tries are less than best_count which is the biggest number
print('This was your best guess so far!') # it will print out this line
best_count = count # let best_count = count
play_again = input("\nWould you like to play again? ").lower().strip() # print this out on the next line and delete all spaces and turn it into lower case.
print('Thanks for playing!') # print out 'Thanks for playing.' | true |
9ebc5c4273361512bd5828dee90938820b41f097 | Andrew-2609/pythonbasico_solyd | /pythonbasico/aula11-tratamento-de-erros.py | 872 | 4.21875 | 4 | def is_a_number(number):
try:
int(number)
return True
except ValueError:
print("Only numbers are allowed. Please, try again!")
return False
print("#" * 15, "Beginning", "#" * 15)
result = 0
divisor = input("\nPlease, type an integer divisor: ")
while not is_a_number(divisor):
divisor = input("Please, type an integer divisor: ")
divisor = int(divisor)
print("\n" + "#" * 7, "Middle", "#" * 7)
dividend = input("Please, type an integer dividend: ")
while not is_a_number(dividend):
dividend = input("Type an integer dividend: ")
dividend = int(dividend)
print("\n" + "#" * 7, "Result", "#" * 7)
try:
result = divisor / dividend
print(f"The division result is {round(result, 2)}")
except ZeroDivisionError as zeroDivisionError:
print("Cannot divide by 0 :(")
print("\n" + "#" * 15, "Ending", "#" * 15)
| true |
bdc98a6f01d7d4a9663fd075ace95def2f25d35c | BipronathSaha99/GameDevelopment | /CurrencyConverter/currencyConverter.py | 608 | 4.34375 | 4 | # >>-----------CurrencyConverter-------------------<<
#To open currency list from text file .
with open("currency.txt") as file:
lines=file.readlines()
#to collect all information create a dictionary
currencyDic={}
for line in lines:
bipro=line.split("\t")
currencyDic[bipro[0]]=bipro[1]
amount=int(input("Enter your amouunt="))
print("Enter your currency name that you want. Available optiions are:")
[print(i) for i in currencyDic.keys()]
currency=input("Enter the currency name =")
print(f"{amount} BDT = {amount*float(currencyDic[bipro[0]]):0.5f} {currency}")
| true |
3e219c794ce22d0d97aaa6b45717717b337d0ca5 | 2019-fall-csc-226/a02-loopy-turtles-loopy-languages-mualcinp-a02 | /a02_mualcinp.py | 1,447 | 4.28125 | 4 | # Author: Phun Mualcin
# Username: mualcinp
# Assignment: A02: Exploring Turtles in Python
# Purpose: Draw something that brings a smile to your face using uses two turtles and one loop
import turtle
wn = turtle.Screen()
wn.bgcolor('black')
shape = turtle.Turtle()
turtle.color('blue')
turtle.pensize(20)
turtle.penup()
turtle.left(180)
turtle.forward(200)
turtle.pendown()
turtle.right(90)
turtle.forward(200)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.penup()
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(250)
turtle.pendown()
turtle.left(180)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
aturtle = turtle.Turtle()
aturtle.pensize(20)
aturtle.shape('arrow')
aturtle.penup()
aturtle.setpos(125,200)
aturtle.pencolor('blue')
aturtle.pendown()
aturtle.right(90)
aturtle.forward(100)
aturtle.left(90)
aturtle.forward(100)
aturtle.left(90)
aturtle.forward(100)
aturtle.left(180)
aturtle.forward(200)
cturtle = turtle.Turtle()
cturtle.pensize(20)
cturtle.shape('arrow')
cturtle.penup()
cturtle.pencolor('blue')
cturtle.setpos(-50,250)
cturtle.pendown()
for i in range(3):
cturtle.forward(300)
cturtle.right(90)
cturtle.forward(350)
cturtle.right(90)
cturtle.forward(200)
wn.exitonclick() | false |
44b1b2af47b75a71a5fd37f284730a0cd5b29690 | LENAYL/pysublime | /MyStack_225.py | 2,482 | 4.1875 | 4 | # 用队列实现
#
# from queue import Queue
# class MyStack(object):
#
# def __init__(self):
# """
# Initialize your data structure here.
# """
# self.q1 = Queue()
# self.q2 = Queue()
#
# def push(self, x):
# """
# Push element x onto stack.
# :type x: int
# :rtype: void
# """
# self.q1.put(x)
#
# def pop(self):
# """
# Removes the element on top of the stack and returns that element.
# :rtype: int
# """
# while self.q1.qsize() > 1:
# self.q2.put(self.q1.get())
# if self.q1.qsize() == 1:
# res = self.q1.get()
# temp = self.q2
# self.q2 = self.q1
# self.q1 = temp
# return res
#
#
# def top(self):
# """
# Get the top element.
# :rtype: int
# """
# while self.q1.qsize() > 1:
# self.q2.put(self.q1.get())
# if self.q1.qsize() == 1:
# res = self.q1.get()
# self.q2.put(res) # 将q1最后的一个元素存入q2 此时 q2 == 原来的q1
# tem = self.q2
# self.q2 = self.q1
# self.q1 = tem
# return res
#
# def empty(self):
# """
# Returns whether the stack is empty.
# :rtype: bool
# """
# return self.q1.qsize() != 0
#
# # Your MyStack object will be instantiated and called as such:
# # obj = MyStack()
# # obj.push(x)
# # param_2 = obj.pop()
# # param_3 = obj.top()
# # param_4 = obj.empty()
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self,q1 = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.q1.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
self.q1.pop()
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.q1[-1]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self.q1 != 0)
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty() | false |
163d79e904d442ee971f10f698b79a7ee7bf85fa | micahjonas/python-2048-ai | /game.py | 2,514 | 4.3125 | 4 | # -*- coding: UTF-8 -*-
import random
def merge_right(b):
"""
Merge the board right
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_right(test)
[[0, 0, 2, 8], [0, 2, 4, 8], [0, 0, 0, 4], [0, 0, 4, 4]]
"""
def reverse(x):
return list(reversed(x))
t = map(reverse, b)
return [reverse(x) for x in merge_left(t)]
def merge_up(b):
"""
Merge the board upward. Note that zip(*t) is the
transpose of b
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_up(test)
[[2, 4, 8, 4], [0, 2, 2, 8], [0, 0, 0, 4], [0, 0, 0, 2]]
"""
t = merge_left(zip(*b))
return [list(x) for x in zip(*t)]
def merge_down(b):
"""
Merge the board downward. Note that zip(*t) is the
transpose of b
Args: b (list) two dimensional board to merge
Returns: list
>>> merge_down(test)
[[0, 0, 0, 4], [0, 0, 0, 8], [0, 2, 8, 4], [2, 4, 2, 2]]
"""
t = merge_right(zip(*b))
return [list(x) for x in zip(*t)]
def merge_left(b):
"""
Merge the board left
Args: b (list) two dimensional board to merge
Returns: list
"""
def merge(row, acc):
"""
Recursive helper for merge_left. If we're finished with the list,
nothing to do; return the accumulator. Otherwise, if we have
more than one element, combine results of first from the left with right if
they match. If there's only one element, no merge exists and we can just
add it to the accumulator.
Args:
row (list) row in b we're trying to merge
acc (list) current working merged row
Returns: list
"""
if not row:
return acc
x = row[0]
if len(row) == 1:
return acc + [x]
return merge(row[2:], acc + [2*x]) if x == row[1] else merge(row[1:], acc + [x])
board = []
for row in b:
merged = merge([x for x in row if x != 0], [])
merged = merged + [0]*(len(row)-len(merged))
board.append(merged)
return board
def move_exists(b):
"""
Check whether or not a move exists on the board
Args: b (list) two dimensional board to merge
Returns: list
>>> b = [[1, 2, 3, 4], [5, 6, 7, 8]]
>>> move_exists(b)
False
>>> move_exists(test)
True
"""
for row in b:
for x, y in zip(row[:-1], row[1:]):
if x == y or x == 0 or y == 0:
return True
return False
| true |
f6422f0594441635eac2fd372428aa160ca3bbb3 | HamPUG/meetings | /2017/2017-05-08/ldo-generators-coroutines-asyncio/yield_expression | 1,190 | 4.53125 | 5 | #!/usr/bin/python3
#+
# Example of using “yield” in an expression.
#-
def generator1() :
# failed attempt to produce a generator that yields an output
# sequence one step behind its input.
print("enter generator")
value = "start"
while value != "stop" :
prev_value = value
print("about to give %s" % repr(value))
value = yield value
print("gave %s, got back %s" % (repr(prev_value), repr(value)))
#end while
#end generator1
def generator2() :
# a generator that yields the value that was sent to it on the
# previous yield, so the output sequence is one step behind the
# input sequence.
print("enter generator")
value1 = "start"
value2 = yield None # yield a dummy value from initial “send(None)”
while True :
value3 = yield value1
if value1 == "stop" :
break
value1, value2 = value2, value3
#end while
#end generator2
gen = generator2()
print("generator %s created" % gen.__name__)
for val in (None, "something", "anything", "stop", "onemore", "twomore") :
print("about to send %s" % repr(val))
print("%s => %s" % (val, gen.send(val)))
#end for
| true |
3af6228c9d8dcc735c52ae7d8375f007145ffe98 | MukundhBhushan/micro-workshop | /tectpy/if.py | 235 | 4.15625 | 4 | num=int(input("Enter the number to be tested: "))
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
| true |
f9f0e8f9212598847750967c8898eefed9e441ed | ryotokuro/hackerrank | /interviews/arrays/arrayLeft.py | 900 | 4.375 | 4 | #PROBLEM
# A left rotation operation on an array shifts each of the array's elements unit to the left.
# For example, if left rotations are performed on array , then the array would become .
# Given:
# - an array a of n integers
# - and a number, d
# perform d left rotations on the array.
# Return the updated array to be printed as a single line of space-separated integers.
import os
# Complete the rotLeft function below.
def rotLeft(a, d):
b = list(a)
for i in range(len(a)):
b[i-d] = a[i] # b is considering each element in a and shifting to position -d
return b
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().split()))
result = rotLeft(a, d)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| true |
9af20e6ee68952b2f0b61685ce406d13c770cc00 | ryotokuro/hackerrank | /w36/acidNaming.py | 828 | 4.1875 | 4 | '''
https://www.hackerrank.com/contests/w36/challenges/acid-naming
Conditions for naming an acid:
- If the given input starts with hydro and ends with ic then it is a non-metal acid.
- If the input only ends with ic then it is a polyatomic acid.
- If it does not have either case, then output not an acid.
'''
#!/bin/python3
import sys
def acidNaming(acid_name):
# print(acid_name)
classification = 'not an acid'
if acid_name[:5] == 'hydro' and acid_name[-2:] == 'ic':
classification = 'non-metal acid'
elif acid_name[-2:] == 'ic':
classification = 'polyatomic acid'
return classification
if __name__ == "__main__":
n = int(input().strip())
for a0 in range(n):
acid_name = input().strip()
result = acidNaming(acid_name)
print(result)
| true |
3a9f486d54fe15bcea60d916047e4c478ca20f85 | fillipe-felix/ExerciciosPython | /Lista02/Ex004.py | 355 | 4.3125 | 4 | """
Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
"""
letra = str(input("Digite uma letra para verificar se é vogal ou consoante: ")).upper()
if(letra == "A" or letra == "E" or letra == "I" or letra == "O" or letra == "U"):
print(f"A letra {letra} é uma vogal")
else:
print(f"A letra {letra} é uma consoante") | false |
62ad0cdecbb43d25fbae24b2514210a2cd9e56dc | amarjeet-kaloty/Data-Structures-in-Python | /linkedList.py | 1,320 | 4.125 | 4 | class node:
def __init__(self, data=None):
self.data=data
self.next=None
class linkedList:
def __init__(self):
self.head = node()
#Insert new node in the Linked-List
def append(self, data):
new_node = node(data)
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
cur_node.next = new_node
#Display the Linked-List
def display(self):
elems = []
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
#Length of the Linked-List
def length(self):
total=0
cur_node = self.head
while (cur_node.next != None):
cur_node = cur_node.next
total+=1
return total
#Delete the last node
def delete(self):
if(self.head.next == None):
return None
cur_node = self.head
while(cur_node.next.next != None):
cur_node = cur_node.next
cur_node.next = None
return cur_node
myList = linkedList()
myList.delete()
myList.display()
myList.append(40)
myList.display()
myList.delete()
myList.display()
| true |
da4e43d0cadfc4137a4f92da26d32203a9c07e54 | GilbertoSavisky/Python | /estruturas-de-dados.py | 580 | 4.15625 | 4 | pessoa_1= {'nome':'Gilberto Savisky', 'idade': 41, 'peso': 75}
pessoa_2 = {'nome':'João Arruda', 'idade': 28, 'peso': 65}
pessoa_3 = {'nome':'Reinaldo Cavalcante', 'idade': 53, 'peso': 87} # dicionario (dict)
lista_pessoas = [pessoa_1, pessoa_2, pessoa_3] # lista (list)
minha_tupla = ('Amadeu', 'Lourenço') # Tupla (tuple)
conjunto = {'pessoa_1', 'pessoa_2', 'pessoa_3'} # conjunto (set)
print(lista_pessoas[0].values())
for i in lista_pessoas:
print(i['nome'])
#perguntar se um determindao dado esta dentro da coleção
if 'pessoa_1' in conjunto:
print("pessoa esta")
print(pessoa_3['nome']) | false |
e84ebb478878b0eba4403ddca10df99dda752a82 | martinloesethjensen/python-unit-test | /star_sign.py | 960 | 4.125 | 4 | def star_sign(month: int, day: int):
if type(month) == int and month <= 12 and type(day) == int and day <= 32: # todo: test case on .isnumeric()
if month == 1:
if day <= 20:
return "Capricorn"
else:
return "Aquarius"
elif month == 5:
if day <= 21:
return "Taurus"
else:
return "Gemini"
else:
if day <= 21:
return "Sagittarius"
else:
return "Capricorn"
elif type(month) is not int or type(day) is not int: # todo: test case on typeerror
raise TypeError("Month and day must be of type int")
elif 0 <= month > 12 and 0 <= day > 32: # todo: test case on valueerror
raise ValueError("Month can't be negative and over 12.\nDay can't be negative either or over 32.")
return None
if __name__ == '__main__':
print(star_sign(1.0, 6))
| true |
2e99e7a24fa53ad663d8d62ee3b2b59d06cf9f11 | Izzle/learning-and-practice | /Misc/decorators_ex.py | 2,915 | 4.53125 | 5 | """
*************************************************
This function shows why we use decorators.
Decorators simple wrap a fucntion, modifying its behavior.
*************************************************
"""
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
print("Yes!")
else:
print("No!")
some_function()
print("Something is happening after some_function() is called.")
return wrapper
def just_some_function():
print("Whee!")
# Instead of using this syntax we can use
# the @something syntax instead as seen below
just_some_function = my_decorator(just_some_function)
just_some_function()
"""
*************************************************
The function below will do the same thing
but uses the decorator syntax.
*************************************************
"""
import time
def timing_decorator(some_function):
"""
Outputs the time a function takes
to execute.
"""
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return "Time it took to run function: " + str ((t2 - t1)) + "\n"
return wrapper
# Far cleaner than our previous examples syntax
@timing_decorator
def my_function():
num_list = []
for num in (range(0, 10000)):
num_list.append(num)
print("\nSum of all the numbers: " + str((sum(num_list))))
print(my_function())
"""
*************************************************
One more real world example of decorators
*************************************************
"""
from time import sleep
def sleep_decorator(function):
"""
Limits how fast the function is
called.
"""
def wrapper(*args, **kwargs):
sleep(2)
return function(*args, **kwargs)
return wrapper
@sleep_decorator
def print_number(num):
return num
print(print_number(222))
for num in range(1, 6):
print(print_number(num))
"""
*************************************************
Combining everything I've learned.
I want to call a decorator instead of a decorator,
but mine only take 0 or 1 parameter.
Since decorators are just wrapppers, I only had to think
about it for a minute. Here is my answer!
Decorators are awesome.
*************************************************
"""
"""
I had tried to use two decorators one after another and it didnt work.
for example:
@timing_decorator
@sleep_decorator
def foobar():
pass
Threw an error because timing_decorator only takes 1 function
as a parameter. Below is my solution.
"""
@timing_decorator # Wraps 1 function
def decorator_inception():
print("\nHello world of decorators!")
print(print_number(1337)) # @sleep_decorator is called by print_number()
# Our time will be over 2 seconds due to @sleep_decorator
# being inside @timing_decorator. Hurray!
print(decorator_inception())
| true |
9fd1d80b44dcea4693cb39f43ddc45a25e654a26 | Izzle/learning-and-practice | /theHardWay/ex6.py | 1,727 | 4.5625 | 5 | # Example 6
# Declares variable for the '2 types of people' joke
types_of_people = 10
# Saves a Format string which inputs the variable to make a joke about binary
x = f"There are {types_of_people} types of people."
# Declaring variables to show how to insert variables into strings.
binary = "binary"
do_not = "don't"
# Saves another Format string which is the punchline of the joke.
y = f"Those who know {binary} and those who {do_not}."
# Prints the joke and the punchline.
print(x)
print(y)
# Prints a format string including the previous variables that contain strings
print(f"I said: {x}")
print(f"I also said: '{y}'")
# Declares a variable 'hilarious' and sets it to the Bool value 'False'
hilarious = False
# A variable that contains a sentence with a parameter to insert a variable
joke_evaluation = "Isn't that joke so funny?! {}"
# Prints the joke and passes the value of 'hilarious' as an argument to the variable 'joke_evalution'
print(joke_evaluation.format(hilarious))
# Sets up two variables, one for the West/Left side and the other for the East/Right side
w = "This is the left side of..."
e = "a string with a right side."
# Prints two strings that form a complete sentence.
print(w + e)
#
# Study Drills
#
# 1) Added comments
# 2) There are only 4 places where a string is inside of a string:
# line 12, 19, and 20.
# 3) Yes there are only 4 places. On line 28 we are passing a 'bool' to
# the string - NOT a string inside a string.
not_a_string = type(hilarious)
print(f"Proof that line 28 is passing a bool: {not_a_string}")
# 4) Adding 'w' and 'e' creates a longer string because in python strings
# can be added together. It does so by concatenating the second string to the first. | true |
5fd329e733441ca67be649f8f604538c6697f6a3 | Izzle/learning-and-practice | /python_programming_net/sendEx05.py | 668 | 4.21875 | 4 | # Exercise 5 and 6
# While and For loops in python 3
# Basic while loop
condition = 1
while condition < 10:
print(condition)
condition += 1
# Basic For loop
exampleList = [1, 5, 6, 5, 8, 8, 6, 7, 5, 309, 23, 1]
for eachNumber in exampleList: # Iterates each item in the list and puts it into the variable 'eachNumber'
print(eachNumber)
print('continue program')
# range() is a built in Python function
# range() will go from the starting number up to the last number
# range() will use up your RAM for every slot. If you need to do range(1,10000000000000000000000)
# do not use range(), use xrange() instead
for x in range(1, 11):
print(x)
| true |
a7f7957f2f66e22f7288a077fe773fb16bab4f02 | 6188506/LearnPythonHardWay | /ex29.py | 966 | 4.125 | 4 | people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
pass
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
if people > dogs:
print "The world is dry!"
dogs += 5
if people >= dogs:
print "People are greater than or equal to dogs."
if people <= dogs:
print "People are less than or equal to dogs."
if people == dogs:
print "People are dogs."
True and True
False and True
1 == 1 and 2 == 1
"test" == "test"
1 == 1 or 2 != 1
True and 1 == 1
False and 0 != 0
True or 1 == 1
"test" == "testing"
1 != 0 and 2 == 1
"test" != "testing"
"test" == 1
not (True and False)
not (1 == 1 and 0 != 1)
not (10 == 1 or 1000 == 1000)
not (1 != 10 or 3 == 4)
not ("testing" == "testing" and "Zed" == "Cool Guy")
1 == 1 and not ("testing" == 1 or 1 == 0)
"chunky" == "bacon" and not (3 == 4 or 3 == 3)
3 == 3 and not ("testing" == "testing" or "Python" == "Fun") | false |
66dad62f348eb42e0d7196bdc87f4cfa0ef84520 | para-de-codar-alek/Respostas-Uri | /1037.py | 978 | 4.28125 | 4 | #Você deve fazer um programa que leia um valor qualquer
# e apresente uma mensagem dizendo em qual dos seguintes intervalos
# ([0,25], (25,50], (50,75], (75,100]) este valor se encontra.
# Obviamente se o valor não estiver em nenhum destes intervalos,
# deverá ser impressa a mensagem “Fora de intervalo”.
#O símbolo ( representa "maior que". Por exemplo:
#0,25] indica valores entre 0 e 25.0000, inclusive eles.
#(25,50] indica valores maiores que 25 Ex: 25.00001 até o valor 50.0000000
# num <-- número em float
# Se num >= 0 and <= 25 print intervalo [0,25
# Se num >25 and <= 50 print intervalo (25,50] e assim por diante até o (75,100]
num = float(input())
if (num >= 0 and num <= 25):
print ('Intervalo [0,25]')
elif (num> 25 and num <= 50):
print ('Intervalo (25,50]')
elif (num> 50 and num <= 75):
print('Intervalo (50,75]')
elif (num>75 and num<=100):
print('Intervalo (75,100]')
else:
print('Fora de intervalo') | false |
7c3d1f965818058958bb143b72a6f03b2824a8d6 | dimatkach11/Torno_Subito | /base_python/the_dictionary.py | 2,936 | 4.625 | 5 | #
# ! A dictionary is a set of objects which we can extract from a key
# * The keys in question are the one we used in the phase of the assignment
print('\n\t\t\t\t\t\tDICTIONARY\n')
keynote = dict()
keynote['tizio'] = '333-3333333'
keynote['caio'] = '444-4444444'
print(keynote)
# * copy() :
keynote_copy = keynote.copy()
# * keys() : showing all the keys
print('\nShowing all the keys :')
print(keynote.keys())
# * values() : showing all values
print('\nvalues() :')
print(keynote.values())
# * items() : showing all elements, keys and values
print('\nitems() :')
print(keynote.items())
# * extract a single value or raise an exception if the key dosn't exist
print('\nextract a single value : key = "caio"')
print(keynote['caio'])
# * get(key, default value) : allows us to extract a default value if the key is not present or the value of key if it is present
print('\nget("sempronio", 0) :')
print(keynote.get('sempronio', 0))
print(keynote)
print('get("tizio", 0) :')
print(keynote.get('tizio', 0))
# * setdefault(key, default value) : allows us to add the key with default value if the key specified doesn't exist
print('\nsetdefault("sempronio", "555-5555555") :')
print(keynote)
keynote.setdefault('sempronio', '555-5555555')
print(keynote)
# * if we wanna know if a key in a dictionary? we can use "in
print('\nWe wanna khow if the key sempronio is in dictionary :')
print('sempronio' in keynote)
# * del keynote['caio] to eliminate this key from dictionary, if not exist raise an exception
print('\nEliminate key = caio :')
del keynote['caio']
print(keynote)
# * clear() : cancel all the element from the dictionary
keynote.clear()
print(keynote)
# ! Comprehension
print('\ncomprehension : ')
keynote = keynote_copy
print(keynote)
# * example, we use the dictionary comprehension to switch the keys with the value
keynote_switch_keys_with_values = {key: value for value, key in keynote.items()}
print(keynote_switch_keys_with_values)
# * with the repeted values, in the final results, we will have one of the keys without establishing wich one
keynote['sempronio'] = '333-3333333'
print(keynote)
keynote_switch_keys_with_values = {key: value for value, key in keynote.items()}
print(keynote_switch_keys_with_values)
# ! Riassunto
'''
____________________________________________________________________________
keynote['tizio] = '333-3333333'
keynote = {'caio': '333-3333333'}
copy()
keys()
values()
items()
get(key, default value)
setdefault(key, default value)
'tizio' in keynote # true or false, depends if the key is exist or not
del keynote['tizio']
clear()
____________________________________________________________________________
switch the keys with the value
{key: value for value, key in keynote.items()}
with the repeted values, in the final results,
we will have one of the keys without establishing wich one
____________________________________________________________________________
''' | true |
8c802650065dec7d5744576ebb7cb08744cc8087 | dimatkach11/Torno_Subito | /base_python/the_strings.py | 2,889 | 4.4375 | 4 | h = 'hello'
print(h[2])
print(h[1:3]) # stampa da 1 a 2, l'etremo destro 3 non viene compreso, il sinistro invece si
lower = 'dima'
upper = 'TKACH'
print(lower.capitalize() + upper.lower())
print(lower.islower())
print(upper.islower())
# * join
l1 = 'egg'
l2 = '123'
print(l1.join(l2)) # egg sarà inserito in mezzo a 1, 2, 3
print(l2.join(l1)) # 123 sarà inserito in mezzo a e, g, g
# * we can return the max and the min value of a string
print(max('strringa'))
print(min('stringa'))
# * replace
frase = 'Ciao mi chiamo Dima'
newstring = frase.replace('Dima', 'Massimo')
print(newstring)
# * isdigit() : we check if string is composed only with numbers and have a boolean output
number = '140'
newstring = number.isdigit()
print(newstring)
# * isalpha() : se ci sono solo caratteri nella stringa
char = 'stringa di solo caratteri e un numero 1'
print(char.isalpha())
# * strip() : rimuove gli spazzi bianchi in eccesso a destra e a sinistra di defoult dalla stringa
stringa = ' howtobasic is a egg war '
print(stringa.strip(), 'ciao')
# * find() : cerca dopo la posizione specificata (opzionale) come secondo parametro, dove comincia la prima lettera della substringa ricercata se esiste, oppure restituisce -1 se non la trova o se si trova prima della posizione specificata, che di defoult parte da 0
stringa = 'Ciao mi chiamo Dima'
sub = 'chiamo'
print(stringa.find(sub, 5))
# * index() : idem a find() ma al posto di -1 ti restituisce l'errore se non trova la substringa
print(stringa.index(sub, 5))
# * swapcase() : inverte le maiuscole con le minuscole
stringa = 'CIAO mi chiamo DIMA'
print(stringa.swapcase())
# * title() : ritorna la prima lettera maiuscola : versione booleana istitle()
stringa = 'dima'
print(stringa.title())
# * zfill() : riempe a sinistra la stringa di zeri pari alla lunghezza specificata - la lughezza della stringa, nel nostro caso la stringa e lunga 19 e se noi specifichiamo zfill(24) allora avremmo 5 zeri a sinistra
stringa = ('ciao mi chiamo Dima')
print(stringa.zfill(10))
print(stringa.zfill(24))
# * len() : lunghezza della stringa
stringa = 'ciao mi chiamo Dima'
print(len(stringa))
# * isspace() : checks wheither the string consists of whitespace
spazzi = ' ' # stringa di soli spazzi
print(spazzi.isspace())
spazzi = '' # da notare che in questo caso darebbe False, perche non c'è niente nella stringa
print(spazzi.isspace())
# * startswith()
stringa = 'ciao mi chiamo dima ciao'
print(stringa.startswith('ciao'))
# ! maketrans() and translate() : used insieme
intab = 'camid'
outtab = '42356'
stringa = 'ciao mi chiamo dima'
print(stringa.translate(str.maketrans(intab, outtab)))
# ! riassunto :
'''
lower() / islower
upper() / isupper
join()
max()
min()
replace()
isdigit()
isalpha()
strip()
find()
index()
swapcase()
title() / istitle()
zfill()
len()
isspace()
translate() and maketrans()
''' | false |
cc0f2bc409cc9d72c792ae38c2b84b353d6bcb3d | ChakshuVerma/Python-SEM-3 | /Question 6/code.py | 1,333 | 4.46875 | 4 |
"""
Q6.Consider a tuplet1 ={1,2,5,7,9,2,4,6,8,10}.
Write a program to perform following operations :
a) Print another tuple whose values are even numbers in the given tuple .
b) Concatenate a tuplet2 = {11,13,15) with t1 .
c) Return maximum and minimum value from this tuple .
"""
ch=0
# Given
len=10
t1=(1,2,5,7,9,2,4,6,8,10)
t2=(11,13,15)
#Function to print a temp tuple with even values from t1
def even():
temp=()
print("Even Values : ")
for i in range(0,len,1):
if(t1[i]%2==0):
temp=temp + (t1[i],)
print(temp)
return
#Function to print maximum and minimum values from t1
def max_min():
Max=t1[0]
Min=t1[0]
for i in range (1,len,1):
if(t1[i]>Max):
Max=t1[i]
print("Max Element Is : ",Max)
for i in range (1,len,1):
if(t1[i]<Min):
Min=t1[i]
print("Min Element Is : ",Min)
return
#Main function
def main():
print("Press")
print("1.Print A Tuple Having Even Values From ",t1)
print("2.Concatenate ",t2," with ",t1)
print("3.Print Maximum And Minimum Values From ",t1)
ch=int(input())
if(ch==1):
even()
elif(ch==2):
temp=t1+t2 #concatenating t1 and t2
print(temp)
elif(ch==3):
max_min()
if __name__=="__main__":
main()
| true |
82af59cee878318ba259e6ca73dabbc102b4e65c | zn-zyl/Blog | /python基础高阶编程/py_01day/py04_01day_06.py | 617 | 4.125 | 4 | """
============================
Author:柠檬班-木森
Time:2020/5/6 21:32
E-mail:3247119728@qq.com
Company:湖南零檬信息技术有限公司
============================
"""
"""
数值:int float
序列:list str tuple
散列:set dict
可迭代对象:
"""
from collections import namedtuple
tu = (11, 22, 33)
# stu = ('木森', 18, 'python自动化')
# print(stu[0])
# 命名元组
student = namedtuple('Students', ('name', 'age', 'skill'))
stu = student('木森', 18, 'python自动化')
# print(type(stu))
# print(isinstance(stu, tuple))
# print(stu[1])
# print(stu.age)
| false |
8c67095e3342ea13f00743a814edd8bd25fc1b2c | AshishGoyal27/Tally-marks-using-python | /tally_marks_using_python.py | 301 | 4.25 | 4 | #Retrieve number form end-user
number = int(input("Input a positive number:"))
#how many blocks of 5 tallies: ||||- to include
quotient = number // 5
#Find out how many tallies are remaining
remainder = number % 5
tallyMarks = "||||- " * quotient + "|" * remainder
print(tallyMarks)
| true |
9858589924b5b2c4999c2cd3298a6c1697a64008 | kashyap92/python-training | /operatoroverloading2.py | 331 | 4.1875 | 4 | #!/usr/bin/python
class date():
def __init__(self):
self.dd=7;self.mm=10;self.yy=2016
def __add__(self,date1):
self.dd=self.dd+date1
return (self)
def printvalues(self):
print self.dd,self.mm,self.yy
today=date()
today+=5
today.printvalues()
| false |
c9e58aa8af5424e5b96811dd63afa86492c47c48 | lucienne1986/Python-Projects | /pythonRevision.py | 1,692 | 4.40625 | 4 | animals = ['cat', 'dog', 'monkey']
for a in animals:
print(a)
#IF you want access to the index of each element within the body of a loop use enumerate
#enums are constants
#%-style formatting: %s and %r call the Enum class’s __str__() and __repr__() respectively;
#other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type.
for index, a in enumerate(animals):
print('#%d: %s' % (index + 1, a))
#List comprehensions:
#used when we want to transform one type of data into another
nums = [0, 1, 2, 3, 4]
#option 1
print("Option 1")
squares = []
for x in nums:
squares.append(x**2)
print(squares)
#option 2
print("Option 2")
squares2 = [x ** 2 for x in nums]
print(squares2)
#List comprehensions can also contain conditions:
print("With conditionals")
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares)
#Dictionaries
#a dictionary stores the key, value pairs
d = {'cat' : ' cute', 'dog' : 'furry'}
print(d['cat'])
print('cat' in d) #checks if dictionary has a given key
d['fish'] = 'wet' #add another entry
print(d)
print(d.get('fish', 'N/A'))# Get an element with a default; prints "wet"
#Loops in dictionaries
d2 = {'person' : 2, 'cat' : 4, 'spider':8}
for animal in d2:
legs = d2[animal]
print('A %s has %d legs' % (animal, legs))
#or using items
for animal, legs in d2.items():
print('A %s has %d legs' % (animal, legs))
#Dictionary comprehensions:
#used when we want to transform one type of data into another
print("Dictionary comprehension")
nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
| true |
94ab43281970119ab3ffe8e723539c0866f5f12c | amsun10/LeetCodeOJ | /Algorithm/Python/palindrome-number-9.py | 1,068 | 4.125 | 4 | # https://leetcode.com/problems/palindrome-number/
# Determine whether an integer is a palindrome. An
# integer is a palindrome when it reads the same backward as forward.
#
# Example 1:
#
# Input: 121
# Output: true
# Example 2:
#
# Input: -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# Example 3:
#
# Input: 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Follow up:
#
# Coud you solve it without converting the integer to a string?
class Solution:
def isPalindrome(self, x: int) -> bool:
str_pal = str(x)
i = 0
j = len(str_pal) - 1
while str_pal[i] == str_pal[j]:
i += 1
j -= 1
if i >= j:
break
else:
return False
return True
if __name__ == '__main__':
solution = Solution()
print(solution.isPalindrome(1))
print(solution.isPalindrome(121))
print(solution.isPalindrome(-121))
| true |
cc7abe19bda1f613b2d070d4a2c5ec4eb722107d | oojo12/algorithms | /sort/insertion_sort.py | 612 | 4.34375 | 4 | def insertion_sort(item, least = False):
"""Implementation of insertion sort"""
"""
Parameters:
item - is assumed to be a list item
least - if true returned order is least to greatest. Else it is greatest to least
"""
__author__ = "Femi"
__version__ = "1"
__status__ = "Done"
for curr in range(len(item)):
for next in range(len(item)):
if (item[curr] <= item[next]):
pass
else:
item[curr],item[next] = item[next], item[curr]
if least:
item.reverse()
else:
pass
return item
| true |
238780e18aa4d804e2c1a07b4a7008719e4d1356 | FaezehAHassani/python_exercises | /syntax_function4.py | 781 | 4.25 | 4 | # Functions for returning something
# defining a few functions:
def add(a, b):
print(f"adding {a} + {b}")
return a + b
def subtract(a, b):
print(f"subtracting {a} - {b}")
return a - b
def multiply(a, b):
print(f"multiplying {a} * {b}")
return a * b
def divide(a, b):
print(f"dividing {a} / {b}")
return a / b
print("let's do some math with these functions!")
age = add(30, 12.5)
height = subtract(90, 190)
weight = multiply(13.4, 21.88)
iq = divide(30, 0.5)
print(f"Age: {age}, height: {height}, weight: {weight}, IQ: {iq}")
print("here is a puzzle for you:")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("that becomes:", what, "can you do it by hand?") # when not using f" " no need to use {} for the variable
| true |
9a0494e31845de5b3e38b2e1aaf8cae045185634 | vishnusak/DojoAssignments | /12-MAY-2016_Assignment/python/search.py | 1,219 | 4.28125 | 4 | # String.search
# string.search(val) - search string for val (another string). Return index position of first match ( -1 if not found).
# ---- Bonus: Implement regular expression support
def search(string, val):
val = str(val) #convert the to-be-searched string into a string type
if (len(val) == 0): #if the to-be-searched is an empty string, return 0
return 0
elif (len(val) == 1): #the to-be-searched is a single char.
for char_idx in range(len(string)):
if (string[char_idx] == val):
return char_idx
else:
return -1
else: #the to-be-searched is a string on length > 1
for char_idx in range(len(string) - len(val) + 1):
if (string[char_idx:len(val)+1] == val):
return char_idx
else:
return -1
myStr = "this is yet a34n 2other !str1ng"
mySearchStr = 1
print("\nThe string is '{}'").format(myStr)
print("The search string is '{}'\n").format(mySearchStr)
myResult = search(myStr, mySearchStr)
if (myResult == -1):
print("The '{}' is not found in '{}'\n").format(mySearchStr, myStr)
else:
print("The string '{}' is found at index {}\n").format(mySearchStr, myResult)
| true |
ea4f181fd795b69f92fb4385f7fc9ecf00abee65 | vishnusak/DojoAssignments | /3-MAY-2016_Assignment/python/reversearray.py | 956 | 4.59375 | 5 | # Reverse array
# Given a numerical array, reverse the order of the values. The reversed array should have the same length, with existing elements moved to other indices so that the order of elements is reversed. Don't use a second array - move the values around within the array that you are given.
# steps:
# 1. find length of the array
# 2. use a loop that iterates for exactly half the length (e.g., if len = 5, the iterator end condition will be < 2)
# 3. for every iteration swap a[i] with a[len-1-i]
# 4. print result
# can be done using the .reverse() built-in method
def rev_arr(arr):
l_idx = (len(arr) - 1)
for i in range((len(arr) / 2)):
arr[i], arr[l_idx - i] = arr[l_idx - i], arr[i]
my_array = [1,2,3,4,5,6,7,8,9,0]
print("\nThe original array is {}\n").format(my_array)
rev_arr(my_array)
print("The reversed array is {}").format(my_array)
# ============================================================================
| true |
0296ddc0d579edc89013f4034af9b0b0b6aec661 | vishnusak/DojoAssignments | /2-MAY-2016_Assignment/python/swap.py | 759 | 4.53125 | 5 | # Swap Array Pairs
# Swap positions of successive pairs of values of given array. If length is odd, do not change final element. For [1,2,3,4] , return [2,1,4,3] . For [false,true,42] , return [true,false,42] .
# steps:
# 1 - traverse array in for loop
# 2 - increment counter by 2 each time instead of one
# 3 - for every run of the loop, swap a[i] and a[i+1]
# 4 - run loop till counter is less than length-1
# I couldn't find any built-in function to swap variable values in python
def arrSwap(arr):
for i in range(0, (len(arr) - 1), 2):
arr[i], arr[i+1] = arr[i+1], arr[i]
my_array = [1,2,3,4,5,6,7,8,9]
print("\nThe existing array is {}\n").format(my_array)
arrSwap(my_array)
print("The array after swapping is {}").format(my_array)
| true |
f9d1fb27c3ced358419cad969dba71e8f1d56a75 | helderthh/leetcode | /medium/implement-trie-prefix-tree.py | 1,836 | 4.15625 | 4 | # 208. Implement Trie (Prefix Tree)
# https://leetcode.com/problems/implement-trie-prefix-tree/
class Trie:
def __init__(self, val=""):
"""
Initialize your data structure here.
"""
self.val = val
self.children = []
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self
for letter in word:
found = node.get(letter) # search in children
if not found:
new_node = Trie(letter)
node.children.append(new_node)
node = new_node
else:
node = found
node.children.append(Trie())
def get(self, letter):
for c in self.children:
if c.val == letter:
return c
return None
def _search(self, word: str, should_match: bool) -> bool:
"""
Returns if the word is in the trie.
"""
node = self
for letter in word:
found = node.get(letter)
if not found:
return False
node = found
if not should_match:
return True
return node.get("") is not None
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
return self._search(word, should_match=True)
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
return self._search(prefix, should_match=False)
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true |
9043e7b4e966797c20d293d674767f63b9d1af56 | oliveiralenon/Learning_python | /Mundo 2/Desafios/071.py | 836 | 4.25 | 4 | """
Crie um programa que simule o funcionamento de um caixa eletrônico.
No início, pergunte ao usuário qual será o valor a ser sacado (número
inteiro) e o programa vai informar quantas cédulas de cada valor
serão entregues.
OBS: Considere que o caixa possui cédulas de RS50, R$20, R$10 e R$1.
"""
print('-=' * 20)
print('{:^40}'.format('Banco LENON'))
print('-=' * 20)
valor = int(input('Que valor você deseja sacar? R$'))
notas50 = valor // 50
valor = valor - (notas50 * 50)
notas20 = valor // 20
valor = valor - (notas20 * 20)
notas10 = valor // 10
valor = valor - (notas10 * 10)
notas01 = valor // 1
print(f'Total de {notas50} cédulas de R$50')
print(f'Total de {notas20} cédulas de R$20')
print(f'Total de {notas10} cédulas de R$10')
print(f'Total de {notas01} cédulas de R$1')
print('-=' * 20)
print('Volte sempre!')
| false |
80964e8df8f8b7036736dbff1309f6478dedd805 | oliveiralenon/Learning_python | /Mundo 2/Desafios/036.py | 777 | 4.21875 | 4 | """
Escreva um programa para aprovar o empréstimo bancário
para a compra de uma casa. O programa vai perguntar o
valor da casa, o salário do comprador e em quantos anos
ele vai pagar.
Calcule o valor da prestação mensal, sabendo que ela não
pode exceder 30% do salário ou então o empréstimo será
negado.
"""
valor_casa = float(input('Digite o valor da casa: R$ '))
salario = float(input('Qual é o salário do comprador? R$ '))
anos = float(input('Pagará o empréstimo em quantos anos? '))
pag_mensal = valor_casa / (anos * 12)
if pag_mensal > salario * 0.3:
print('Empréstimo negado!')
else:
print('-' * 60)
print(f'Empréstimo de R$ {valor_casa:.2f} cedido. \nDeverá ser pago em mensalidades de R${pag_mensal:.2f} no período de {anos * 12} meses.')
| false |
047fb88ee80ddc5830ed77a99078812c58555e6a | oliveiralenon/Learning_python | /Mundo 1/Desafios/022.py | 568 | 4.28125 | 4 | """
Crie um progrma que leia o nome completo de uma pessoa e mostre:
- O nome com todas as letras maiúsculas
- O nome com todas minúsculos
- Quantas letras ao todo (sem considerar espaços)
= Quantas letras tem o primeiro nome.
"""
nome = str(input('Digite seu nome completo: '))
separado = nome.split()
print(f'Seu nome em maiúsculas é {nome.upper()}')
print(f'Seu nome em minúsculas é {nome.lower()}')
print('Seu nome tem ao todo {} letras'.format(len(nome.replace(' ', ''))))
print(f'Seu primeiro nome é {separado[0]} e ele tem', len(separado[0]), 'letras')
| false |
95d7346e60cb3ce345416da12bbe95cfb2bdf2ab | oliveiralenon/Learning_python | /Mundo 1/Desafios/028.py | 700 | 4.25 | 4 | """
Escreva um programa que faça o computador "pensar" em um
número inteiro entre 0 e 5 e faça para o usuário tentar
descobrir qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu
ou perdeu.
"""
from random import randint
from time import sleep
print('-=-' * 20)
print('Vou pensar em um número inteiro entre 0 e 5. Tente adivinhar...')
print('-=-' * 20)
n1 = randint(0, 5)
n2 = int(input('Digite um número: '))
print('Processando...')
sleep(2)
if n1 == n2:
print(f'Parabéns, você acertou. A máquina escolheu o número {n1} e você o número {n2}.')
else:
print(f'Ops, você errou. Eu escolhi o número {n1} e você o número {n2}')
| false |
af4caae1454e7fdb4b40d5192c45e7ca16783ff2 | juancadh/mycode | /collatz_conjecture.py | 1,118 | 4.59375 | 5 | """
======== COLLATZ CONJECTURE ========
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.
Then each term is obtained from the previous term as follows: if the previous term is even, the next term is one half the previous term.
If the previous term is odd, the next term is 3 times the previous term plus 1. The conjecture is that no matter what value of n,
the sequence will always reach 1.
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import random as rnd
import seaborn as sb
def collatz_step(n):
r = np.nan
if np.mod(n,2) == 0:
r = int(n/2)
else:
r = int(3 * n + 1)
return r
def collatz(n):
collatz_lst = []
n_steps = 0
r = n
collatz_lst.append(r)
while r != 1:
n_steps += 1
r = collatz_step(r)
collatz_lst.append(r)
return n_steps, collatz_lst
sb.set()
for i in range(2,100):
print(i)
n_steps, gr = collatz(i)
max_val = max(gr)
plt.plot(i, max_val, linestyle = '-', marker = 'o')
plt.show() | true |
4d958cd5c394fd27e09703eaf02a5193c88523fa | tanadonparosin/Project-Psit | /time-count.py | 546 | 4.125 | 4 |
# import the time module
import time
# define the countdown func.
def countdown(t):
big = 0
t += 1
while t != big:
hours = big//3600
left = big%3600
mins, secs = divmod(left, 60)
timer = '{:02d}:{:02d}:{:02d}'.format(hours, mins, secs)
print(timer, end="\r")
time.sleep(1)
big += 1
print('Time Out!')
# input time in seconds
t = input("Enter the time to stop in seconds:")
# function call
countdown(int(t))
| true |
e87191dbacfef51036b30f2fd84997367ddd5d89 | WakouTTD/learn-python | /attended/lesson11_codestype.py | 447 | 4.3125 | 4 | # pythonは1行が80文字を超えると折り返せというルール
# 長い文字列連結でバックスラッシュ
s = 'aaaaaaaaaaaaaaa' + \
'bbbbbbbbbbbbbbb'
print(s)
x = 1 + 1 + 1 + 1 + 1 + 1 + 1 + \
1 + 1 + 1 + 1 + 1 + 1
print(x)
print('------------------')
# もしくはパレンティス
s = ('aaaaaaaaaaaaaaa' +
'bbbbbbbbbbbbbbb')
print(s)
x = (1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1)
print(x)
| false |
2286bac14fa3bbfdee27a85a0f4430c31ec8a07b | mf4lsb/Algorithms | /hackerrank/python/Validating Roman Numerals.py | 345 | 4.15625 | 4 | # https://www.hackerrank.com/challenges/validate-a-roman-number/
def validateRomanNumeral(roman_numeral):
import re
return True if re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", roman_numeral) else False
if __name__ == "__main__":
roman_numeral = input()
print(validateRomanNumeral(roman_numeral)) | false |
56973aedd81e2bd1bf651ba51237d634046f3598 | amber1710/Converter | /Temperature convertor/tester.py | 1,435 | 4.3125 | 4 | from tkinter import *
#function to create a window
root = Tk()
root.geometry('550x300')
root.title("Conversions")
root.configure(background="turquoise")
#functions to create a label
label = Label(root, text="Press")
label.grid(row=0, column=0, columnspan=3)
label2 = Label(root, text="°Celsius")
label2.grid(row=0, column=0, columnspan=1)
label3 = Label(root, text="°Fahrenheit")
label3.grid(row=0, column=2, columnspan=1)
temp_celsius = Entry(root)
temp_celsius.grid(row=1, column=0)
temp_fahrenhiet = Entry(root)
temp_fahrenhiet.grid(row=1, column=2)
#numbers inserted in entry will convert
def pressed():
calculations = (int(temp_celsius.get())*9/5)+32
temp_fahrenhiet.delete(0, END)
temp_fahrenhiet.insert(0, str(round(calculations,2)) + "°F")
button = Button(root, text="Convert to °F", command=pressed)
button.grid(row=1, column=1)
def pressed2():
calculations2 = (int(temp_fahrenhiet.get())-32)*5/9
temp_celsius.delete(0, END)
temp_celsius.insert(0, str(round(calculations2,2)) + "°C")
#the function for making buttons
button2 = Button(root, text="Convert to °C", command=pressed2)
button2.grid(row=2, column=1)
def clear():
temp_celsius.delete(0, END)
temp_fahrenhiet.delete(0, END)
butoon_clear = Button(root, text="CLEAR", command=clear)
butoon_clear.grid(row=3, column=1)
butoon_exit= Button(root, text="EXIT", command=exit)
butoon_exit.grid(row=0, column=3)
root.mainloop()
| false |
c02aa901d795f6ed60a09cb3aee1ee1c3e61ced3 | AnilKOC/some-scripts | /prime-num-is-it.py | 406 | 4.125 | 4 | import math
def main():
number = int(input("Enter your number :"))
isprime = True
for x in range(2, int(math.sqrt(number) + 1)):
if number % x == 0:
isprime = False
break
if isprime:
print("Your number is an prime number : "+str(number))
else:
print("Sory dude, its not an prime number : "+str(number))
if __name__ == "__main__": main()
| true |
2e4554a4e5d00dedfdf276f950446273d40f45c0 | LyndonGingerich/hunt-mouse | /input.py | 1,224 | 4.40625 | 4 | """Helper methods for getting user input"""
def get_bool_input(message):
"""Gets boolean input from the terminal"""
values = {'y': True, 'yes': True, 'n': False, 'no': False, '': False}
return get_dict_input(message, values)
def get_dict_input(message, values):
"""Selects value from a dictionary by user input"""
input_value = validate_input_of_values(message=message, valid_values=set(values.keys()))
return values[input_value]
def get_natural_input(message):
"""Gets an integer input from the terminal"""
return int(validate_input_of_predicate(
message=message,
condition=lambda x: x.isdigit() and int(x) > 0,
failure_message='Please enter a positive integer.'
))
def validate_input_of_predicate(message, condition, failure_message):
"""Applies a condition to input to check it"""
text = input(message)
while not condition(text):
text = input(failure_message)
return text
def validate_input_of_values(message, valid_values):
"""Checks whether an input is in a set of valid inputs"""
text = input(message).lower()
while text not in valid_values:
text = input(f'Valid inputs: {valid_values}')
return text
| true |
c7a1ed5b4d9eff957d6cebf924aeeb9ab8e0da53 | codingXllama/Tkinter-with-Python | /FirstApp/app.py | 829 | 4.4375 | 4 | import tkinter as tk
# Creating the window
window = tk.Tk()
# Creating a window title
window.title("First Application")
# Creating the window size
window.geometry("400x400")
# creating the LABEL
title = tk.Label(text="Welcome to my First Tkinter APP!",
font=("Times New Roman", 20))
# Placing the title on the window you can use pack,place, or grid
# title.place(x=10, y=20)
# title.pack()
title.grid(column=0, row=0)
# Creating buttons
btn1 = tk.Button(text="click here", bg="red")
# placing the btn1 under the title so we .grid() on the btn instead of .pack
btn1.grid(column=0, row=1)
# Creating the Entry field- a blank box where user can input content inside
entryField1 = tk.Entry()
entryField1.grid(column=0, row=2)
# running the window, mainloop runs everything inside the window
window.mainloop()
| true |
3813ccf85d5136d2e028717370697c331b9c98d7 | geocarvalho/python-ds | /python-base/escola_v2_com_sets.py | 1,180 | 4.1875 | 4 | #!/usr/bin/env python3
"""Exibe relatório de crianças por atividade.
Imprimir a lista de crianças agrupadas por sala
que frequentas cada uma das atividades.
"""
__version__ = "0.1.1"
########################################################
# ATENçÃO: MODIFIQUE ESSE CÓDIGO! #
# Tente utilizar dicionários onde achar conveniente #
########################################################
# Dados
sala1 = ["Erik", "Maia", "Gustavo", "Manuel", "Sofia", "Joana"]
sala2 = ["Joao", "Antonio", "Carlos", "Maria", "Isolda"]
atividades = {
"Inglês": ["Erik", "Maia", "Joana", "Carlos", "Antonio"],
"Música": ["Erik", "Carlos", "Maria"],
"Dança": ["Gustavo", "Sofia", "Joana", "Antonio"],
}
# Listar alunos em cada atividade por sala
for nome_atividade, atividade in atividades.items():
print(f"Alunos da atividade {nome_atividade}\n")
print("-" * 40)
# sala1 que tem interseção com a atividade
atividade_sala1 = set(sala1) & set(atividade)
atividade_sala2 = set(sala2).intersection(atividade)
print("Sala1 ", atividade_sala1)
print("Sala2 ", atividade_sala2)
print()
print("#" * 40) | false |
1d6b889ec8c0d1dbff4a7e7fcb063e0f3649969a | LeleCastanheira/cursoemvideo-python | /Exercicios/ex014.py | 235 | 4.28125 | 4 | # Conversor de temperatura: escreva um programa que converta uma temperatura digitada em ºC para ºF
c = float(input('Informe a temperatura em °C: '))
f = 1.8 * c + 32
print('A temperatura de {}°C corresponde a {}°F!'.format(c, f)) | false |
337904dc2450ebaf368a58984385087c15fe2395 | ss4328/project_euler | /problem4.py | 855 | 4.25 | 4 | #The purpose of this program is to find largest 3-digit palindrome product
print("Palindrome problem starting...")
n1 = 100
n2 = 100
ans = 0;
def reverse(num):
rev = 0
while num > 0:
rev = (10 * rev) + num % 10
num //= 10
return rev
def isPalindroms(input):
if(input == reverse(input)):
return True
else:
return False
for i1 in range(100, 1000):
# print("i1 is " + str(i1))
for i2 in range(100, 1000):
# print ("i2 is " + str(i2))
temp = i1*i2
if(isPalindroms(temp) and (temp > ans)):
ans = temp
print("program finished. Largest palindrome: " + str(ans))
# This program can be modified to give a general solution for n digits.
# n can be defined by used input.
# We can change the ranges of i1 and i2 and then define them in terms of 10^n.
| true |
a58f314ff98de418dcf262957b2c336b2d5b12ea | ahsanfirdaus1/Ahsan-Personal-Project | /SimCal1.py | 2,324 | 4.15625 | 4 | print("Welcome To Ahsan Simple Calculator")
print("==================================")
print("Before The Program Starts, May I Know What's Your Name?")
UserName = input("Name: ")
i = 1
while i == 1:
print("Hello", UserName, "! Please Choose What Operator Do U Want")
print("1. + \n2. - \n3. x \n4. / \n5. (^) \n6. %")
Choose1 = int(input("Your Choice: "))
if Choose1 == 1 :
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 + Number2
print(Number1,"+",Number2,"=",Result)
i = 2
elif Choose1 == 2:
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 - Number2
print(Number1,"-",Number2,"=",Result)
i = 2
elif Choose1 == 3:
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 * Number2
print(Number1,"x",Number2,"=",Result)
i = 2
elif Choose1 == 4:
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 / Number2
print(Number1,"/",Number2,"=",Result)
i = 2
elif Choose1 == 5:
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 ** Number2
print("(",Number1,"^)",Number2,"=",Result)
i = 2
elif Choose1 == 6:
Number1 = int(input("First Number: "))
Number2 = int(input("Second Number: "))
Result = Number1 % Number2
print(Number1,"%",Number2,"=",Result)
i = 2
else:
print("The Operator is not exist yet")
i = 1
while i == 2:
fin = int(input("1 For Yes \n2 For No \n Finish? :"))
if fin == 1:
print("Thank You,",UserName,"!")
i=0
elif fin == 2:
i = 1
else:
print("Wrong Input \n Getting Restart")
i = 1
'''
i = 1
while (i<=5):
print("Hello Looping In Python")
i+=1
'''
'''
x = 1
for x in range(1,2):
print("This is for loop")
''' | false |
7692e3274550d7ef4dad4e0c3fb65d608d28f7d3 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_8.py | 1,206 | 4.28125 | 4 | # Difference of two columns in Pandas dataframe
# Difference of two columns in pandas dataframe in Python is carried out by using following methods :
# Method #1 : Using ” -” operator.
import pandas as pd
# Create a DataFrame
df1 = {'Name': ['George', 'Andrea', 'micheal',
'maggie', 'Ravi', 'Xien', 'Jalpa'],
'score1': [62, 47, 55, 74, 32, 77, 86],
'score2': [45, 78, 44, 89, 66, 49, 72]}
df1 = pd.DataFrame(df1, columns=['Name', 'score1', 'score2'])
print("Given Dataframe :\n", df1)
# getting Difference
df1['Score_diff'] = df1['score1'] - df1['score2']
print("\nDifference of score1 and score2 :\n", df1)
# Method #2 : Using sub() method of the Dataframe.
# Create a DataFrame
df = {'Name': ['George', 'Andrea', 'micheal',
'maggie', 'Ravi', 'Xien', 'Jalpa'],
'score1': [62, 47, 55, 74, 32, 77, 86],
'score2': [45, 78, 44, 89, 66, 49, 72]}
df1 = pd.DataFrame(df1, columns=['Name', 'score1', 'score2'])
print("Given Dataframe :\n", df1)
df1['Score_diff'] = df1['score1'].sub(df1['score2'], axis=0)
print("\nDifference of score1 and score2 :\n", df1)
# https://www.geeksforgeeks.org/difference-of-two-columns-in-pandas-dataframe/
| true |
c4988daadeb56b064ca9558f959a00ec031da04f | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_dictionary_1.py | 660 | 4.28125 | 4 | # Creating an empty dictionary
dictionary_1 = dict()
dictionary_2 = {}
print(f'Dictionary-1:{dictionary_1} Type:{type(dictionary_1)}')
print(f'Dictionary-2:{dictionary_2} Type:{type(dictionary_2)}')
# Creating a Dictionary with Integer Keys
dictionary_3 = {1: 'God', 2: 'is', 3: 'Great'}
print(dictionary_3)
# Creating a Dictionary with mixed Keys
dictionary_4 = {'Name': 'God', 1: [1, 2, 3, 4]}
print(dictionary_4)
# Creating a Dictionary with dict() method
dictionary_5 = dict({'Name': 'God', 1: [1, 2, 3, 4]})
print(dictionary_5)
# Creating a Dictionary with each item as pair
dictionary_6 = dict([(1, 'Jagannath'), (2, 'Krishna')])
print(dictionary_6)
| false |
fcc9c9b601411e05ff0d28f5a23f8f4502a3b139 | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_list_comprehension_assignment_1.py | 2,033 | 4.59375 | 5 | # Python List Comprehension and Slicing
# List comprehension is an elegant way to define and create list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp.
#
# A list comprehension generally consist of these parts :
# Output expression,
# input sequence,
# a variable representing member of input sequence and
# an optional predicate part.
#
# For example :
#
# lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]
#
# here, x ** 2 is output expression,
# range (1, 11) is input sequence,
# x is variable and
# if x % 2 == 1 is predicate part.
# Python program to demonstrate list comprehension in Python
# below list contains square of all odd numbers from
# range 1 to 10
odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]
print(odd_square)
print('********************************************************')
# for understanding, above generation is same as,
odd_square = []
for x in range(1, 11):
if x % 2 == 1:
odd_square.append(x ** 2)
print(odd_square)
print('********************************************************')
# below list contains power of 2 from 1 to 8
power_of_2 = [2 ** x for x in range(1, 9)]
print(power_of_2)
print('********************************************************')
# below list contains prime and non-prime in range 1 to 50
noprimes = [j for i in range(2, 8) for j in range(i * 2, 50, i)]
print(noprimes)
# Let’s understand how to use range() function with the help of a simple example.
print('\n********************************************************')
print("Python range() example to print numbers from range 0 to 6")
for i in range(6):
print(i, end=', ')
print('\n********************************************************')
for i in range(2, 8):
for j in range(i*2, 50, i):
print(j)
print('\n********************************************************')
# https://www.geeksforgeeks.org/python-list-comprehension-and-slicing/ | true |
14226708a9f5473ac80b76c4afe7bc47da5b403b | Krishnaarunangsu/ArtificialIntelligence | /src/datascience/data_exercises/python_data_assignment_2.py | 1,796 | 4.65625 | 5 | # Syntax:
# DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)
# Every parameter has some default values execept the ‘by’ parameter.
# Parameters:
# by: Single/List of column names to sort Data Frame by.
# axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column.
# ascending: Boolean value which sorts Data frame in ascending order if True.
# inplace: Boolean value. Makes the changes in passed data frame itself if True.
# kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame.
# na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’.
# Return Type:
# Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame.
# importing pandas package
import pandas as pd
# making data frame from csv file
data = pd.read_csv("../../../data/nba.csv")
# display
print(data)
print('********************************************')
data_1 = data.sort_values("Name", axis=0, ascending=True,
inplace=False, na_position='last')
print(data_1)
print('********************************************')
data.sort_values("Name", axis=0, ascending=True,
inplace=True, na_position='last')
print(data)
# sorting data frame by name
data.sort_values("Salary", axis=0, ascending=True,
inplace=True, na_position='first')
# display
print(data)
# https://www.geeksforgeeks.org/python-pandas-dataframe-sort_values-set-1/
# https://www.geeksforgeeks.org/python-pandas-dataframe-sort_values-set-2/
# https://www.geeksforgeeks.org/python-pandas-dataframe-sample/
# https://www.geeksforgeeks.org/python-pandas-series-reset_index/
| true |
7292e151d67f39b26915ecbb13b9f6389674e2b0 | tracyvierra/vigilant-pancake | /TCPM-LPFS/text-2-speech/text_2_speech_live.py | 1,175 | 4.1875 | 4 | # Author: Tracy Vierra
# Date Created: 3/11/2022
# Date Modified: 3/11/2022
# Description: Text to speech example using user input to speech and saved as a file.
# Usage:
from turtle import right
from gtts import gTTS
import os
import tkinter as tk
from tkinter import filedialog as fd
from tkinter import *
# text = open('demo.txt', 'r').read()
# gTTS(text=text, lang='en').save("hello.mp3")
# os.system("start hello.mp3")
def convert(entry, output_file):
text = entry
tts = gTTS(text=text, lang='en')
tts.save(output_file)
output_file = "output.mp3"
root = Tk()
root.title("Text 2 Speech")
canvas1 = tk.Canvas(root, width = 300, height = 100)
canvas1.pack()
entry = tk.Entry(root)
canvas1.create_window(150, 20, window=entry)
canvas1.pack()
button_convert = tk.Button(text='Convert', command= lambda:convert(entry.get(), output_file))
button_convert.configure(background='green', foreground='white')
canvas1.create_window(150, 60, window=button_convert)
canvas1.pack()
button_exit = tk.Button(root, text="Exit", command=lambda: root.destroy())
button_exit.configure(background='red', foreground='black')
button_exit.pack(padx=5, pady=5)
root.mainloop()
| true |
768c71d6e2ee67bdba5e3de87ba309be9913270a | tracyvierra/vigilant-pancake | /TCPM-LPFS/examples/multiple_inheritance_example.py | 1,324 | 4.46875 | 4 | # Author: Tracy Vierra
# Date Created: 3/1/2022
# Date Modified: 3/1/2022
# Description: Multiple inheritance example
# Usage:
# class Student: # base class
# def __init__(self, name, age):
# self.name = name
# self.age = age
# def get_data(self):
# self.name = input("Enter name: ")
# self.age = input("Enter age: ")
# def display(self):
# print(self.name)
# print(self.age)
# class ScienceStudent(Student): # derived class
# def science(self):
# print("this is a science method")
# def __init__(self, name, age):
# self.name = name
# self.age = age
# self.major = "Physics"
# def get_data(self):
# self.name = input("Enter name: ")
# self.age = input("Enter age: ")
# def display(self):
# print(self.name)
# print(self.age)
# print(self.major)
# student1 = Student("", "")
# student1.get_data()
# student1.display()
# a = ScienceStudent("", "")
# a.science()
# a.get_data()
# a.display()
class A:
def a_method(self):
print("A method")
class B:
def b_method(self):
print("B method")
class C(A,B):
def c_method(self):
print("C method")
c_object = C()
c_object.a_method()
c_object.b_method()
c_object.c_method()
| false |
e0fab44a525cc912f7f8d43c618af3fc3f9ed711 | abdulwagab/Demopygit | /Operators1.py | 531 | 4.21875 | 4 |
'''Relational Operators Example in Python'''
def operator(x, y, z): # Functions name and its arguments
a = 1 # Assign variables in Function
b = 2
c = 0
x = a or c and b # Compare variables in Logical operators but not print
y = a and c or b # Compare variables in Logical operators but not print
z = a or b and c # Compare variables in Logical operators but not print
print(x, y, z) # Indirectly Assaign values to variables
operator("x", "y", "z") # Calling the Function
| true |
93d669e04066f345afe68017ab73c30d9145e53d | Vanderscycle/lighthouse-data-notes | /prep_work/Lighthouse lab prep mod katas/.ipynb_checkpoints/ch9-linear_algebra-checkpoint.py | 1,504 | 4.15625 | 4 | import numpy as np
x = np.array([1, 2, 3, 4])
print(x)
# Matrix A
A = np.array([[1,2],[3,4],[5,6]])
print(type(A))
# in which the result is a tuple of (columns, rows)|(3x,2y) of the matrix
print(A.shape)
print(x.shape)
print(len(x)) # returns the length of the array (#in the list)
# transpose an a matrix
A_T = A.T
# this format is also acceptable
A_T = A.transpose()
print(A_T.shape)
# Note: the transpose of a matrix (At) can be obtained by reflecting the elements along its main diagonal
# https://en.wikipedia.org/wiki/Transpose
# Do not confuse transposition (flipping) with the invest of a matrix (a-1). NOTE non square matrices cannot have an inverse matrix because
B = np.array([[2, 5], [7, 4], [4, 3]])
C = A + B
print(C)
print(C + 1)
# dot product
A = np.array([[1, 2], [3, 4], [5, 6]])
B = np.array([[2], [4]])
print(A.shape,B.shape)
C = A.dot(B)
# we change the space
# C = A . B (3,2) . (2, 1) = 3d vector (3,1)
print(C)
# identity matrix
# A-1 * A = I. This provides a way to cancel the linear transformation
I = np.eye(3) # similar to np.identity(n) but you can shift the index of the diagonal
IA = I.dot(A)
print(IA)
#determinant
#area
# non square matrices should be viewed geometrically as transformations between dimensions
M = np.array([[1,2],[3,4]])
det_M = np.linalg.det(M)
print(det_M)
# inverse matrices
A = np.array([[3, 0, 2], [2, 0, -2], [0, 1, 1]])
A_inv = np.linalg.inv(A)
I = A_inv.dot(A)
print(I) | true |
dee0620a9f930628a7ea44f4d73779e76686b4c2 | melphick/pybasics | /week6/w6e2.py | 342 | 4.28125 | 4 | #!/usr/bin/python
"""
Converts a list to a dictionary where the index of the list is used as the
key to the new dictionary (the function will return the new dictionary).
"""
def list_to_dict(a_list):
a_dict = {}
for i in a_list:
print i
a_dict[i] = a_list[i]
return a_dict
a = range(10)
print list_to_dict(a)
| true |
cbd0d974b4b636760e98b1a4da159129e025be14 | patidarjp87/ROCK-PAPER-SCISSOR-GAME | /ROCK.py | 1,438 | 4.1875 | 4 | import random
print("WELCOME TO ROCK PAPER SCISSOR GAME\n")
lst = ["Rock", "Paper", "Scissor"]
computer_score = 0
player_score = 0
game = 0
chance = 6
while game < chance:
choice = random.choice(lst)
turn = input("choose(rock, paper or scissor) : ").lower()
game +=1
if turn == "rock" and choice == "Scissor":
print("Computer's point\n")
computer_score += 1
if turn == "rock" and choice == "Paper":
print("Player's point\n")
player_score += 1
if turn == "rock" and choice == "Rock":
print("No points\n")
elif turn == "paper" and choice == "Scissor":
print("Computer's point\n")
computer_score += 1
elif turn == "paper" and choice == "Rock":
print("Player's point\n")
player_score += 1
elif turn == "paper" and choice == "Paper":
print("No points\n")
elif turn == "scissor" and choice == "Rock":
print("Computer's Point\n")
computer_score += 1
elif turn == "scissor" and choice == "Paper":
print("Player's point\n")
player_score += 1
elif turn == "scissor" and choice == "Scissor":
print("No points\n")
break
print(f'Computer score: {computer_score}\n')
print(f'Player score : {player_score}\n')
if computer_score > player_score:
print("computer win")
elif computer_score < player_score:
print("you win")
else:
print("Nobody win")
input()
| true |
650074bf605a56ddb94a4a6ff9ab260cadf72467 | Souravdg/Python.Session_4.Assignment-4.1 | /Filter Long Words.py | 600 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[14]:
##############################################
# A function filter_long_words() that takes a list of words and an integer n and returns
# the list of words that are longer than n
def filter_long_words(lst,length):
newlst = []
for x in range(len(lst)):
if len(lst[x]) > length:
newlst.append(lst[x])
return newlst
#############################################
lst = ['Sam', 'John', 'Steve']
n = 3
print("Below is the new List of words that are longer than length %s " %(n))
print(filter_long_words(lst,n))
| true |
4235257b90ca960999d780a44b1f7af7607b8fc8 | cyberchaud/automateBoring | /vid04/vid04.py | 1,183 | 4.1875 | 4 | # pythontutor.com/visualize.html
# Indentation in Python indicates a block of code
# Blocks start where the indentation begins and the block stops where the indentation stops
# if block statements are conditions/expressions
# if the condition evaluates to true; then Python executes the indented code
name = 'Bob'
if name == 'Alice':
# Skips the indentation block because the condition is not True
print('Hi {}'.format(name))
print('Done')
password = 'iloveu'
# Python executes one block only
if password == 'swordfish':
print('Access granted')
elif password == 'iloveu':
print('Access granted with your terrible password')
else:
print('Try again')
# Python Truthy or Falsey
# Strings:
# Truthy is any string
# Falsey is a blank string
# Test - bool('Hello') -> True; bool('') -> False
# Integers:
# Truthy is any integer
# Falsey is 0
# Test - bool(42) -> True; bool(0) -> False
print('Enter a name')
name = input()
# Any input will print 'Thank you for entering your 'name'
# Pressing enter (blank input) prints 'You did not enter a name'
if name != '':
print('Thank you for entering your name')
else:
print('You did not enter a name')
| true |
8189b5b2488e0f5f91a999c449089c618a576196 | cyberchaud/automateBoring | /vid22/vid22.py | 1,572 | 4.28125 | 4 | #! /usr/bin/python3
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3]!= '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
print(isPhoneNumber('444-53-1234'))
# Looping through 12 char slices in a string
def checkforNumber(message):
foundNumber = False
for i in range(len(message)):
chunk = message[i:i+12]
if isPhoneNumber(chunk):
print('Phone number found: {}'.format(chunk))
foundNumber = True
return True
if not foundNumber:
print('Could find any phone numbers')
return False
print(checkforNumber('Call me at 444-555-1234 for more details'))
print(checkforNumber('Call me at 444-5234 for more details'))
# Regular expression to find a phone number within a string
# Regular expression are a mini-language for specifying text patterns
# Should use raw strings r'string' so Python doesn't try and use escape characters
# Using the re library
# Call compile function
# Call search function
# Use group() method
import re
print('Using a regular expression to see if a string has a phone number pattern')
phoneNumbRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumbRegex.search('Call me at 444-555-1234 for more details')
print(mo.group()) | true |
f407e16b8c2485680862c746d272b752b0d77eb5 | cyberchaud/automateBoring | /vid01/vid01.py | 601 | 4.28125 | 4 | # Python always evaluates down to a single value.
# Integers are whole number
# Any digits with a decimal is a floating point
# Expresssions are made from Values and Operators
print("Adding")
print(2+2)
print("Substraction")
print(5-3)
print("Multiplication")
print(3*7)
print("Division")
print(21/7)
print("PEMDAS")
print(2+3*6)
# (2+3)*6
# Python does:
# (2+3) = 5
# (5)*6
# 30
print((2+3)*6)
# String
# Strings are for text
# Concatenation for strings
print('Alice')
print('Alice' + 'Bob')
#String Replication
print('Alice'*3)
# Variables
spam = 'Hello'
print(spam)
print(spam + ' World') | true |
3b06c59a64a82f7fbaa7eeba84c04c2dc020568c | krausce/Integrify | /WEEK_1/Question_4.py | 1,954 | 4.125 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 6 01:24:18 2019
@author: chris
"""
'''
Question 4 asked us to write a function which looks through a list of int's
and returns '1' if a triplet exists and 0 if not.
My approach to this was to first sort the list using the builtin python
"list.sort()". This places all of the values in ascending order. If you
want to sort them into descending order instead, you simply call:
list_var_name.sort(reverse = True). Or if you simply want to return the
sorted list, use the method "sorted", see syntax below.
The built-in python sort methods have worst-case time complexity of
O(n log n): https://wiki.python.org/moin/TimeComplexity
Next, because the values are sorted, if any of the tests fail with the
first three values, the first value needs to simply push forward to the
position the third value was in (2 spaces) and then run the tests again.
This can be run inside of a loop or this could be done recursively. If at
any time the tests pass, return 1 and the program terminates.
'''
a = [1, 2, 3]
a.sort(reverse=True)
print(a) # Should show "[3, 2, 1]"
a.sort()
print(a)
a = sorted(a, reverse=True)
print(a) # Now they are in descending order again
a = sorted(a)
print(a) # Now the nums are back in ascending order
a = [10, 2, 5, 1, 8, 20]
b = [10, 50, 5, 1]
def tri_count(l_nums):
if len(l_nums) < 3:
return 0
for i in range(len(l_nums)):
if not isinstance(l_nums[i], int):
print(i)
return 0
l_nums.sort()
p = 0
while p in range(len(l_nums)-2):
q = p+1
r = q+1
if check_triple(l_nums[p], l_nums[q], l_nums[r]):
return 1
p += 2
return 0
def check_triple(p, q, r):
return (((p+q) > r) and ((q+r) > p) and ((p+r) > q))
print(tri_count(a)) # Should return 1
print(tri_count(b)) # Should return 0
| true |
fe22ab33e33de67fa988d00f00d58eeb0bb8cb9d | neelima-j/MITOpenCourseware6.0001 | /ps1c.py | 1,967 | 4.3125 | 4 | '''
To simplify things, assume:
1. Your semiannual raise is .07 (7%)
2. Your investments have an annual return of 0.04 (4%)
3. The down payment is 0.25 (25%) of the cost of the house
4. The cost of the house that you are saving for is $1M.
You are now going to try to find the best rate of savings to achieve a down payment on a $1M house in
36 months. Since hitting this exactly is a challenge, we simply want your savings to be within $100 of
the required down payment.
'''
#Getting inputs
annual_salary = float(input("Enter the starting salary: "))
annual_salary_original = annual_salary
#initalizing variables
semi_annual_raise = .07
r = .04
total_cost = 1000000
portion_saved = 1
i=0
max = 1
min = 0
def initialise():
global months
months = 0
global portion_down_payment
portion_down_payment = .25*total_cost
global current_savings
current_savings = 0
global annual_salary
annual_salary = annual_salary_original
initialise()
if annual_salary*3<portion_down_payment:
print("It is not possible to pay the down payment in three years.")
raise SystemExit
while True:
current_savings *= (1+r/12)
current_savings += (annual_salary/12)*portion_saved
months += 1
if months % 6 == 0:
annual_salary *= (1+semi_annual_raise)
if abs(current_savings - portion_down_payment) <=100 and months == 36:
break
elif months == 36:
if (current_savings - portion_down_payment) < 0: #saving less, increase rate
min = portion_saved
portion_saved += (max-min)/2
portion_saved = round(portion_saved ,5)
i+=1
initialise()
else: #saving too much, reduce rate
max = portion_saved
portion_saved -= (max-min)/2
portion_saved = round(portion_saved,5)
i+=1
initialise()
print("Best savings rate: ",round(portion_saved,4))
print("Steps in bisection search: ",i)
| true |
361b4561b6a87cba7a2b35a603e86f04274e94bc | skgbanga/AOC | /2020/23/solution.py | 1,899 | 4.40625 | 4 | # The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle.
# The crab selects a destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead.
# The crab places the cups it just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up.
# The crab selects a new current cup: the cup which is immediately clockwise of the current cup.
class Node:
def __init__(self, val):
self.val = val
self.next = None
circle = '963275481'
d = {}
node = Node(int(circle[0]))
d[node.val] = node
curr = node
for c in circle[1:]:
n = Node(int(c))
d[n.val] = n
node.next = n
node = n
for i in range(10, 1_000_001):
n = Node(i)
d[n.val] = n
node.next = n
node = n
node.next = curr
largest = 1_000_000
def show():
s = curr
for _ in range(9):
print(s.val, end='')
s = s.next
print()
for i in range(10_000_000):
selected = []
for _ in range(3):
selected.append(curr.next.val)
d.pop(curr.next.val)
curr.next = curr.next.next
dst = curr.val - 1
if dst == 0:
dst = largest
while dst in selected:
dst = dst - 1
if dst == 0:
dst = largest
tmp = d[dst]
for s in selected:
n = Node(s)
d[s] = n
n.next = tmp.next
tmp.next = n
tmp = n
curr = curr.next
n = d[1]
print(n.next.val * n.next.next.val)
| true |
d53d079e9e7be0e1d72e317cd090f82d7520861c | ann-ko/Python | /Lesson2_Task3.py | 1,386 | 4.21875 | 4 | while True:
month = int(input("Введите номер месяца в виде целого числа от 1 до 12: "))
if month in range(1, 13):
break
else:
print("Номер введен некорректно - повторите ввод")
# наименования времен года закодируем, чтобы в случае переименования изменяли в одном месте а не во всем коде
# например в случае изменения языка вывода на английский меняем только здесь, а не в двух вариантах решения
winter = "зима"
spring = "весна"
summer = "лето"
autumn = "осень"
# реализация решения через list
list_month = [winter, winter, spring, spring, spring, summer, summer, summer, autumn, autumn, autumn, winter]
print(f"Номер месяца: {month} - время года: {list_month[month - 1]}")
# реализация решения через dict
dict_month = {
1: winter,
2: winter,
3: spring,
4: spring,
5: spring,
6: summer,
7: summer,
8: summer,
9: autumn,
10: autumn,
11: autumn,
12: winter
}
print(f"Номер месяца: {month} - время года: {dict_month[month]}") | false |
891c4f8c7b6e238686e43e4e637f988f4c5652b5 | RavensbourneWebMedia/Ravensbourne | /mymodule.py | 1,210 | 4.625 | 5 | ## mymodule: a module containing functions to print a message, convert temperatures and find the 3rd letter of a word ##
# INSTRUCTIONS
# Write code for the three functions below:
# This function should use 'raw_input' to ask for the user's name, and then print a friendly message including
# the user's name to the command line (e.g. "Hi there Bob! Good to see you again!")
def helloMessage():
print "You need to write your own code before running this function!"
# This function should take in a temperature in Kelvin, convert it to Celsius and print the result as part of a string
# (e.g. 100 degrees Celsius is 373 Kelvin). HINT: you'll need to convert the result of the calculation to a string.
# Google is your best friend!
def Kelvin2Celsius(kelvin):
print "You need to write your own code before running this function!"
# This function should take in a word, and return the third letter of that word as part of a string to the command line
# (e.g. "The third letter of the word banana is 'n'). HINT: you can access the n^th letter of a word using square
# brackets. If you get stuck, ask me!
def thirdLetter(word):
print "You need to write your own code before running this function!"
| true |
c47d32391b8c18705ab43c0129135a3ac36f1a3b | myanir/Campus.il_python | /self.py/dateconvert.py | 213 | 4.15625 | 4 | import calendar
user_input = input("Enter a date: ")
# 01/01/2000
year = int(user_input[-4:])
month = int(user_input[3:5])
day = int(user_input[:2])
print(calendar.day_name[calendar.weekday(year, month, day)]) | true |
221a8faf61fc8d5e507718cd06c76d905ffa22d2 | jeffreybrowning/algorithm_projects | /dynamic/minimum_steps.py | 1,583 | 4.34375 | 4 | def get_min_steps (num):
"""
For any positive integer num, returns the amount of steps necessary to reduce
the number to 1 given the following possible steps:
1) Subtract 1
2) Divide by 2
3) Divide by 3
>>>get_min_steps(15)
4
"""
if num <= 0 or type(num) != int: return None
min_steps_list = [0] * (num + 1)
for i in range(2, num + 1):
print('\n')
print('i = {0}'.format(i))
print(dict(enumerate(min_steps_list)))
# We can either -1, /2 or /3 -- this is the -1 step
min_steps_list[i] = 1 + min_steps_list[i-1]
# for any number i, we either take min_steps_list[i - i] + 1, or the number of steps
# of its /2 or /3 factor (+1 because we have just added one more step)
if i % 2 == 0:
print('divisible by two')
print('''min_steps_list[{0}] = {1} \n1 + min_steps_list[{2}] = {3}'''.format(i, min_steps_list[i], i/2, 1 + min_steps_list[i/2]))
min_steps_list[i] = min( min_steps_list[i] , 1 + min_steps_list[i/2] )
if i % 3 == 0:
print('divisible by three')
print('''min_steps_list[{0}] = {1} \n1 + min_steps_list[{2}] = {3}'''.format(i, min_steps_list[i], i/3, 1 + min_steps_list[i/3]))
min_steps_list[i] = min( min_steps_list[i] , 1 + min_steps_list[i/3] )
return min_steps_list[num]
if __name__ == '__main__':
print(get_min_steps(8))
# print(get_min_steps(247))
def fib(n):
if n == 1: return 1
return fib(n-1) + fib(n-2)
def min_steps_recursive(num):
# if num == 1 return 1
return min(min_steps_recursive(n-1) + min_steps_recursive(n/2) + min_steps_recursive(n/3))
| true |
2692e538d72e8ac46ba2d2cb6db4256b2445e7b4 | henryHTH/Algo-Challenge | /Largest_prime_factor.py | 840 | 4.28125 | 4 | '''
Given a number N, the task is to find the largest prime factor of that number.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case contains an integer N.
Output:
For each test case, in a new line, print the largest prime factor of N.
Constraints:
1 <= T <= 100
2 <= N <= 1010
Example:
Input:
2
6
15
Output:
3
5
'''
def lpf(num):
while num % 2 == 0:
num = num / 2
if num == 1: return num
n = num
for i in range(3, int(math.sqrt(n)) + 1, 2):
while num % i == 0:
num = num / i
if num == 1:
return i
return num
if __name__ == '__main__':
import math
for i in range(int(input())):
num = int(input())
print(int((lpf(num)))) | true |
8fe335582eab0cb9b8ca4ccf62193d04744df241 | FirzenYogesh/DynamicProgramming | /Python/CuttingRod.py | 908 | 4.15625 | 4 | """
http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
"""
# find the maximum price that can be obtained with the given price set with Space : O(n*x)
def cutting_rod(price, n):
t = [[0 for i in range(n + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, n + 1):
if j >= i:
t[i][j] = max((t[i][j - i] + price[i - 1]), t[i - 1][j], t[i][j - 1], (t[i - 1][j - i] + price[i - 1]))
else:
t[i][j] = t[i - 1][j]
return t[n][n]
# find the maximum price that can be obtained with the given price set with Space : O(n)
def cutting_rod1(price, n):
t = [0 for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(i, n + 1):
t[j] = max(t[j], t[j - i] + price[i - 1])
return t[n]
# driver program to test the above function
print(cutting_rod([1, 4, 5, 5], 4))
| false |
eb30ff67f5f1ec9aadbf959d030da48723c85044 | FirzenYogesh/DynamicProgramming | /Python/LongestCommonSubsequence.py | 1,897 | 4.15625 | 4 | """
http://www.geeksforgeeks.org/longest-common-subsequence/
"""
# get the count of longest commom subsequence
def get_longest_common_subsequence(a, b):
r = len(a) + 1
c = len(b) + 1
# create table to store the longest common sub-sequence value
t = [[0 for i in range(c)] for i in range(r)]
# traverse on both string
for i in range(1, r):
for j in range(1, c):
# if same value update the value as value of the left diagonal + 1
if a[i - 1] == b[j - 1]:
t[i][j] = t[i - 1][j - 1] + 1
# else update maximum of previous row value or previous column value
else:
t[i][j] = max(t[i - 1][j], t[i][j - 1])
# we print the longest common sub-sequence
print(print_longest_common_subsequence(a, b, t))
# return the last value which has the maximum value
return t[r - 1][c - 1]
"""
http://www.geeksforgeeks.org/printing-longest-common-subsequence/
"""
# get the of longest commom subsequence
def print_longest_common_subsequence(a, b, t):
r = len(a)
c = len(b)
# we create an empty list to store the sub-sequence
l = []
# initialize i with r
i = r
# initialize j with c
j = c
# loop till either i or j becomes 0
while i > 0 and j > 0:
# if same append that value to the list and go to the left diagonal
if a[i - 1] == b[j - 1]:
l.append(a[i - 1])
i -= 1
j -= 1
# if value appears in previous row go to that row
elif t[i - 1][j] == t[i][j]:
i -= 1
# if the value is in previous column go to that column
else:
j -= 1
# return the reversed list to get the common sub-sequence in order
return l[::-1]
# driver program to test the above functions
s1 = "AGGTAB"
s2 = "GXTXAYB"
print(get_longest_common_subsequence(s1, s2))
| false |
0b5348cb514686eae1e95606a94c64043db7e51b | suhaylx/for-loops | /main.py | 535 | 4.34375 | 4 | for item in {1,2,3,4,6}:
for values in {'a', 'b','c'}:
print(item, values)
user = {
'name' : 'Suhaylx',
'age' : 18,
'can_swim' : False
}
for dictionary_items in user.values():
print(dictionary_items)
for dict_items in user.items():
print(dict_items)
for keys, item_s in user.items():
print(keys,item_s)
#There is still other ways to iterate
for example_value in user.items():
dict_keys, dict_values = example_value
#as example_value value is typle we assign values to another two value
print(dict_keys, dict_values) | true |
6c5dcf3f5ad4d00dca274e5fde09e3a378aac73f | ivyfangqian/python36-learning | /day1/input_output1.py | 2,218 | 4.34375 | 4 | # 我们的第一个程序
print('Hello World!')
# python2.x默认字符集为ASCII,打印中文需要设置coding为utf-8
# python3.x默认字符集为UTF-8
import sys
print(sys.getdefaultencoding())
print('你好!')
# 'print 可以同时打印多个字符串,两个字符串之间以逗号隔开
print('小明,', '你好!')
# python单行注释为#,
# 多行注释也推荐使用#
# print 'Hello World!'
# print 'Hello World!'
# print 'Hello World!'
# 多行注释用三个单引号 ''' 或者三个双引号 """ 将注释括起来\
'''
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
'''
"""
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
"""
# ''' 或者三个双引号 """ 可以作为类/函数中作为说明文档
class A(object):
'''class A desc'''
pass
print(A().__doc__)
def hello():
"""function hello desc"""
pass
print(hello.__doc__)
# Python允许用'''...''',"""..."""的格式表示多行内容,并且保留内容格式
print('''单引号,第一行
单引号,第二行''')
print("""双引号,第一行
双引号,第二行""")
# 输出数字
print(1)
# 输出运算结果
print(1 + 2)
# 输出组合结果,需要注意的是,这里1+2=是字符串
print('1+2=', 1 + 2)
# 等待用户输入input(),input()会将输入内容全部转换为字符串
# name = input("请输入你的名字:")
# print name,'你好!'
#
# result = input("请输入1+2的结果:")
# print result
# 为了让程序员有一个良好的代码习惯,python强制要求用缩进来标识一个函数或者类的范围
# java中代码块一般使用{}包裹,不需要进行缩进
# python中代码块必须要进行缩进,同一个代码块的代码缩进数量要一致
# notepad++ :一个tab=4个空格
# pycharm:一个tab=8个空格
# windows下tab的空格数与linux下tab的空格数不一致
# 解决方法:一般缩进为4个空格,pycharm在settings--》code style --》python --》use tab character 取消勾选
# 输出一个数字的绝对值
a = 1
if a >= 0:
print(a)
else:
print(-a)
| false |
35bf351112ee5abeb120a3989d17e70c095ea189 | tsunny92/LinuxAcademyScripts | /ex1.py | 301 | 4.21875 | 4 | #!/usr/bin/env python3.6
msg = input("Enter the message to echo : ")
count = int(input("Enter the number of times to display message ").strip())
def displaymsg(msg , count):
if count > 0:
for i in range(count):
print(msg)
else:
print(msg)
displaymsg(msg , count)
| true |
da643f117987410670878690fdfea9807efca07a | yiorgosk/python | /polynomials.py | 1,498 | 4.34375 | 4 | import numpy.polynomial.polynomial as poly
import numpy as np
'''The user can enter 2 polynomial functions and perform the basic math praxis of addition, subtraction, multiplication and division.
Also the user is able to discover the roots of the two function and perform for instance an addiction praxis with a polynomial and an integer, such as number 2'''
def root(a):
return poly.polyroots(a)
def add(a, b):
return np.polyadd(a, b)
def sub(a, b):
return np.polysub(a, b)
def mul(a, b):
return np.polymul(a, b)
def div(a, b):
return np.polydiv(a, b)
def main():
inpt1 = input('Enter the number of polynomial factors \n')
counter1 = 0
pol1 = []
while counter1 < int(inpt1):
factor = input('Insert your factor')
pol1.append(float(factor))
counter1 += 1
inpt2 = input('Enter the number of polynomial factors \n')
counter2 = 0
pol2 = []
while counter2 < int(inpt2):
factor = input('Insert your factor')
pol2.append(float(factor))
counter2 += 1
print('The roots of the first polynomial functions are ', root(pol1))
print('The roots of the second polynomial functions are ', root(pol2))
print('The output of the add function is ', add(pol1, pol2))
print('The output of the subtract function is ', sub(pol1, pol2))
print('The output of the mul function is ', mul(pol1, pol2))
print('The quotient and remainder of div function are ', div(pol1, pol2))
main()
| true |
ee742e94e08e5898e5369699c4d0d64e74556283 | oJacker/_python | /numpy_code/04/urn.py | 1,474 | 4.125 | 4 | '''
超几何分布(hypergeometric distribution)是一种离散概率分布,它描述的是一个罐子里有
两种物件,无放回地从中抽取指定数量的物件后,抽出指定种类物件的数量。 NumPy random模
块中的hypergeometric函数可以模拟这种分布
设想有这样一个游戏秀节目,每当参赛者回答对一个问题,他们可以从一个罐子里摸出3个
球并放回。罐子里有一个“倒霉球”,一旦这个球被摸出,参赛者会被扣去6分。而如果他们摸出
的3个球全部来自其余的25个普通球,那么可以得到1分。因此,如果一共有100道问题被正确回
答,得分情况会是怎样的呢?为了解决这个问题,请完成如下步骤
'''
import numpy as np
from matplotlib.pyplot import plot, show
'''
(1) 使用hypergeometric函数初始化游戏的结果矩阵。该函数的第一个参数为罐中普通球
的数量,第二个参数为“倒霉球”的数量,第三个参数为每次采样(摸球)的数量。
'''
points = np.zeros(100)
outcomes = np.random.hypergeometric(25, 1, 3, size=len(points))
#(2) 根据上一步产生的游戏结果计算相应的得分。
for i in range(len(points)):
if outcomes[i] == 3:
points[i] = points[i - 1] + 1
elif outcomes[i] == 2:
points[i] = points[i - 1] - 6
else:
print (outcomes[i])
# (3) 使用Matplotlib绘制points数组。
plot(np.arange(len(points)), points)
show() | false |
b496fb679a87ad1087198a2a09b5073397ee531e | Seongkyun-Yu/TIL | /algorithm-study/baekjoon/Fibonacci.py | 222 | 4.125 | 4 | wantCount = int(input())
def fibonacci(count, num1, num2):
if wantCount == count:
return num1
sum = num1 + num2
num1 = num2
num2 = sum
return fibonacci(count+1, num1, num2)
print(fibonacci(0, 0, 1))
| false |
04b818d3a8e91e3ec412d008dd23bae7ddafdedb | wenyaowu/leetcode | /algorithm/wildcardMatching/wildcardMatching.py | 1,190 | 4.1875 | 4 | # Wildcard Matching
"""
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
"""
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def isMatch(self, s, p):
s_pointer = 0
p_pointer = 0
star = -1
match = 0
while s_pointer<len(s):
if p_pointer<len(p) and (p[p_pointer]==s[s_pointer] or p[p_pointer]=='?'):
p_pointer+=1
s_pointer+=1
elif p_pointer<len(p) and p[p_pointer]=='*': #If there's a start, update
star = p_pointer
match = s_pointer
p_pointer+=1
elif star!=-1:
p_pointer = star+1
match+=1
s_pointer = match
else: return False
while p_pointer<len(p) and p[p_pointer]=='*': p_pointer+=1
return p_pointer==len(p)
| true |
bf3194d31daa0fde740f70f19ef4b502c1d82708 | wenyaowu/leetcode | /algorithm/spiralMatrix/spiralMatrix.py | 948 | 4.1875 | 4 | # Spiral Matrix
"""
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
class Solution:
# @param {integer[][]} matrix
# @return {integer[]}
def spiralOrder(self, matrix):
result = []
while matrix:
try:
result += matrix.pop(0)
except:
break
try:
for row in matrix:
result += [row.pop(-1)]
except:
break
try:
result += matrix.pop(-1)[-1::-1]
except:
break
try:
for row in matrix[-1::-1]:
result += [row.pop(0)]
except:
break
return result
| true |
bc8cab306a5c13eb063336a46464b3f29bc03e26 | wenyaowu/leetcode | /algorithm/maximumSubArray/maximumSubarray.py | 525 | 4.15625 | 4 | # Maximum Subarray
"""
Find the contiguous subarray within an array
(containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.
"""
class Solution:
# @param {integer[]} nums
# @return {integer}
def maxSubArray(self, nums):
res = [0 for x in range(len(nums))]
res[0] = nums[0]
for i in range(1, len(nums)):
res[i] = max(res[i-1]+nums[i], nums[i])
return max(res)
| true |
3bfe490ced270299d618ae3bce36dc5bf93bed6b | gonzaloquiroga/neptunescripts | /dnacalc3.py | 1,583 | 4.25 | 4 | #! /usr/bin/env python
# Ponemos env python para que lo encuentre en cualquier ordenador,
# sea donde sea que este instalado.
#DNASeq = raw_input ("Enter a DNA sequence: ") #Prompts you to write stuff
DNASeq = "ATCACGAGCTTTATTCGGGC"
DNASeq = DNASeq.upper() #Takes DNASeq and creates a new string with an uppercase version of it
print ( "Sequence " + DNASeq)
SeqLength = float (len( DNASeq )) #len cuenta las letras de una variable, es un integer
print ( "Length is " + str( SeqLength ) ) #str() dice que es un string lo que hay etre parentesis
# Si no ponemos str() el programa no funcionara pk no se pueden sumar strings e integers
NumberA = DNASeq.count('A')
NumberT = DNASeq.count("T")
NumberG = DNASeq.count("G")
NumberC = DNASeq.count("C")
print ("A: " + str( (NumberA / SeqLength) *100 ) +"%" )
print ("T: " + str( (NumberT / SeqLength) *100 ) +"%" )
print ("G: " + str( (NumberG / SeqLength) *100 ) +"%" )
print ("C: " + str( (NumberC / SeqLength) *100 ) +"%" )
print ("A: {:.5f}".format (NumberA / SeqLength))
print ("T: {}".format (NumberT / SeqLength))
print ("G: {}".format (NumberG / SeqLength))
print ("C: {}".format (NumberC / SeqLength))
TotalStrong = NumberG + NumberC
TotalWeak = NumberA + NumberT
if SeqLength <= 13:
MeltTemp = (4 *TotalStrong) + (2*TotalWeak)
#print ( "Melting Temp: {}".format(MeltTemp) )
print ("Using short formula")
else:
MeltTemp = 64.91 + 40 *(TotalStrong - 16.4) / SeqLength
#print ( "Long Melting Temp: {}".format(MeltTemp) )
print ("Using long formula")
print ( 'Melting temp: {}'.format(MeltTemp) )
print ("Done.") | false |
e02a06155c71117dd210e57c5cf0e0d3c4ff9987 | mzimecki/MyPythonRepo | /binary_tree_walk.py | 1,615 | 4.25 | 4 | class Node:
rightNode = None
leftNode = None
name = None
def __init__(self, l, r, n):
self.rightNode = r
self.leftNode = l
self.name = n
# a
# / \
# b e
# /\
# c d
#
# Reversed:
# a
# / \
# e b
# /\
# d c
#
tree = Node(Node(Node(None, None, "c"), Node(None, None, "d"), "b"), Node(None, None, "e"), "a")
def walk_depth_first(node):
print("Visiting node: " + node.name)
if node is None or (node.rightNode is None and node.leftNode is None):
return
if node.leftNode is not None:
walk_depth_first(node.leftNode)
if node.rightNode is not None:
walk_depth_first(node.rightNode)
def walk_breadth_first(node):
list = []
if node is None:
return
list.insert(0, node)
while len(list) > 0:
n = list.pop()
print("Visiting node: " + n.name)
if n.leftNode is not None:
list.insert(0, n.leftNode)
if n.rightNode is not None:
list.insert(0, n.rightNode)
def reverse_tree(node):
if node.rightNode is None and node.leftNode is None:
return
leftNode = node.leftNode
node.leftNode = node.rightNode
node.rightNode = leftNode
reverse_tree(node.leftNode)
reverse_tree(node.rightNode)
print("Walk depth: ")
walk_depth_first(tree)
print("Walk breadth: ")
walk_breadth_first(tree)
reverse_tree(tree)
print("Reversed tree walk depth: ")
walk_depth_first(tree)
print("Reversed tree walk breadth: ")
walk_breadth_first(tree)
| false |
6c1af79866f6e74500b78fbc1bae00e005ed66dc | ghydric/05-Python-Programming | /Class_Practice_Exercises/Lists/List_Functions_Review/append_list.py | 673 | 4.53125 | 5 | ## Append to list
# This function demonstrates how the append method
# can be usesd to add items to a list
def main():
# initialize empty list
name_list = []
# create a variable to control our loop
again = 'y'
# add some names to the list
while again == 'y':
# get a name from the user
name = input('Enter a name: ')
# append the name to the list
name_list.append(name)
# add another one?
print('Do you want to add another name?')
again = input('y = yes, anything else = no: ')
print()
# display the names in the name list
print(name_list)
# run the main function
main() | true |
b2c495513f454f4c992e7c6b89f0a8cb79b7ea69 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/map_func.py | 593 | 4.4375 | 4 | # map() function
# calls the specified function and applies it to each item of an iterable
def square(x):
return x*x
numbers = [1, 2, 3, 4, 5]
sqrList = map(square, numbers)
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
# print(next(sqrList))
sqrList2 = map(lambda x: x*x, numbers)
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
# print(next(sqrList2))
tens = [10,20,30,40,50]
indx = [1,2,3]
powers = list(map(pow, tens, indx))
print(powers) | true |
643dc0c7f87421eac8ee5e124dd038f9f1c6a57f | ghydric/05-Python-Programming | /Class_Practice_Exercises/Classes/Inheritance/car_truck_suv_demo.py | 1,269 | 4.25 | 4 | # This program creates a Car, Truck, and SUV object
import vehicles
def main():
# create Car object
car = vehicles.Car('Bugatti', 'Veyron', 0, 3000000, 2)
# create a Truck object
truck = vehicles.Truck('Dodge', 'Power Wagon', 0, 57000, '4WD')
# create a SUV object
suv = vehicles.SUV('Jeep', 'Wrangler', 200000, 5000, 4)
print('VEHICLE INVENTORY')
print('=================')
# display the car data
print('Make:', car.get_make())
print('Model:', car.get_model())
print('Mileage:', car.get_mileage())
print('Price', car.get_price())
print('Number of doors:', car.get_doors())
# display the truck data
print('Make:', truck.get_make())
print('Model:', truck.get_model())
print('Mileage:', truck.get_mileage())
print('Price', truck.get_price())
print('Drive Type:', truck.get_drive_type())
# display the SUV data
print('Make:', suv.get_make())
print('Model:', suv.get_model())
print('Mileage:', suv.get_mileage())
print('Price', suv.get_price())
print('Number of doors:', suv.get_pass_cap())
# Helpful functions below:
#print(help(vehicles.SUV))
#print(suv.__dict__)
#suv_dict = suv.__dict__
#print(type(suv_dict))
# call main function
main() | false |
dbbfec55fae84308c068d8b2db6f5502c6ef29a3 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Advanced_Functions/iter.py | 485 | 4.34375 | 4 | # Python iterator
#old way:
myList = [1,2,3,4]
for item in myList:
print(item)
# what is actually happening using iterators
def traverse(iterable):
it = iter(iterable)
while True:
try:
item = next(it)
print(item)
except StopIteration:
break
L1 = [1,2,3]
item = iter(L1)
print(item.__next__())
print(item.__next__())
print(item.__next__())
print(item.__next__())
print(item.__next__())
# or this method
print(next(it)) | true |
8450a626f5b9179e35e75c4a6296c036913eb583 | ghydric/05-Python-Programming | /Class_Practice_Exercises/Classes/Classes_Exercises_2.py | 2,739 | 4.75 | 5 | """
2. Car Class
Write a class named Car that has the following data attributes:
• __year_model (for the car’s year model)
• __make (for the make of the car)
• __speed (for the car’s current speed)
The Car class should have an __init__ method that accept the car’s year model and make
as arguments. These values should be assigned to the object’s __year_model and __make
data attributes. It should also assign 0 to the __speed data attribute.
The class should also have the following methods:
• accelerate
The accelerate method should add 5 to the speed data attribute each time it is
called.
• brake
The brake method should subtract 5 from the speed data attribute each time it is called.
• get_speed
The get_speed method should return the current speed.
Next, design a program that creates a Car object, and then calls the accelerate method
five times. After each call to the accelerate method, get the current speed of the car and
display it. Then call the brake method five times. After each call to the brake method, get
the current speed of the car and display it.
"""
# Car class
class Car:
# __init__ method creates a Car object with a year_model, make, and speed attributes
def __init__(self, year, make, speed = 0):
self.__year_model = year
self.__make = make
self.__speed = int(speed)
# accelerate method adds 5 to the __speed attribute each time it is called
def accelerate(self):
self.__speed += 5
# brake method subtracts 5 from the __speed attribute each time it is called
def brake(self):
self.__speed -= 5
# get_speed method returns value in the __speed attribute
def get_speed(self):
return self.__speed
# main function creates a Car object, accelerates five times, then brakes five times
# displaying the current speed after each accelerate and brake
def main():
# create the Car object using user input
my_car = Car(
input('Enter the year of your car: '),
input('Enter the make of your car: ')
)
# print the starting speed
print(f'My car\'s starting speed is: {my_car.get_speed()}')
# accelerate 5 times and display the speed after each accelerate
for i in range(1,6):
print('Accelerating now.')
my_car.accelerate()
print(f'My car is now going {my_car.get_speed()}mph.')
# brake 5 times and display the speed after each brake
for i in range(1,6):
print('Braking now.')
my_car.brake()
print(f'My car is now going {my_car.get_speed()}mph.')
# call main function
main() | true |
679154f4340225e10a6dce151354fd1a1588df40 | bhavyajain190/Guess | /un.py | 553 | 4.125 | 4 | import random
print('Hey what is your name?')
name = input()
print('Welcome ' + name + ' I am thinking of a number between 1 and 10')
Num = random.randint(1,10)
for guessesTaken in range(1,3):
print('Take a guess')
guess = int(input())
if guess < Num:
print('Your guess is a lttle low')
elif guess > Num:
print('Your guess is too high')
if guess == Num:
print('congratulations ' + name + ' you have guessed my number in ' + str(guessesTaken) + ' guesses!!')
else:
print('I am sorry number was ' + str(Num)) | true |
2018b85801fb06a3001e38c32a02978c57aaf2a8 | Jhon-G/lesson1 | /types.py | 608 | 4.28125 | 4 | '''
Практика
'''
#Float
a = 2
b = 0.5
print(a + b)
#string
name = 'Иван'
print(f'Привет, {name}!')
#Приктика числа
v = int(input('Введите число от 1 до 10: ')) #Ввод целого числа
print(v + 10)
#Строки
name = input('Введите имя: ')
name = name.capitalize() #Делаем первую букву большой
print(f'Привет, {name}! Как дела?')
#Приведение типов
print(float('1'))
print(int(2.5)) #При написании "2.5" выдаст ошибку
print(bool(1))
print(bool(''))
print(bool(0)) | false |
75df037a3564e30b1c2ed8b11598ea52bfdf2fc7 | 01FE16BME072/TensorflowBasics | /Tensor_handling3.py | 1,279 | 4.40625 | 4 | '''
TensorFlow is designed to handle tensors of all sizes and operators that can be used to
manipulate them. In this example, in order to see array manipulations, we are going to
work with a digital image. As you probably know, a color digital image that is a MxNx3
size matrix (a three order tensor), whose components correspond to the components of red,
green, and blue in the image (RGB space), means that each feature in the rectangular box for
the RGB image will be specified by three coordinates, i, j, and k.
You can see visualisation of this in this folder only just open refrence_image.png
'''
#Importing the required Libraries
import tensorflow as tf
import matplotlib.image as image #This library is used for reading and showing the image on the screen here you can even replace this with the opencv library
from matplotlib import pyplot as plt
read_img = image.imread("refrence_image.png")
plt.imshow(read_img)
plt.show()
#Now here if we want then we can even see the rank and the shape
read_tensor_img = tf.placeholder("uint8",[None,None,4])
slice_read_tensor_img = tf.slice(read_tensor_img,[100,0,0],[200,200,-1])
with tf.Session() as sess:
slicing = sess.run(slice_read_tensor_img,feed_dict = {read_tensor_img:read_img})
plt.imshow(slicing)
plt.show()
| true |
8d1d69b2606b0b5fc2e06b907271525a27ef7d6e | maniac-tech/Web-scraping-using-php-and-RSS-feeds | /testFiles/dictonaries.py | 290 | 4.40625 | 4 | dict = {
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4"
}
#iterating over keys:
# for x in dict.iterkeys():
# print (x)
#iteraing over values:
# for x in dict.itervalues():
# print(x)
#iterating over values using keys:
for x in dict.iterkeys():
print(dict[x]) | false |
176313e02cb527f58beefa6a979118618da5446e | BohanHsu/developer | /python/io/ioString.py | 1,776 | 4.78125 | 5 | #in this file we learn string in python
s = 'Hello, world.'
#what str() deal with this string
print(str(s))
#what repr() deal with this string
print(repr(s))
#repr() make a object to a string for the interpreter
print(str(1/7))
print(repr(1/7))
#deal with some transforming characters
hello = 'hello, world\n'
helloStr = str(hello)
helloRepr = repr(hello)
print(helloStr)
print(helloRepr)
#str() translate the '\n' to a new line.
#repr() ignore it
#how those two function deal with object
#this is a tuple!!!!
tuple = (32.5, 4000, ('spam', 'eggs'))
print(str(tuple))
print(repr(tuple))
#ok expect string str() is just same as repr()...
#using print and formatting string
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3),end = '...')
print(repr(x*x*x).rjust(4))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
#the rjust() function is use for right justifies a string
#similarly, there are function ljust() and center()
#those functions not truncate the string
#if you want justifies a string and truncate if the string is too long,
#user str.ljust(n)[:n] or str.rjust(n)[n:]
#hello I'm draft...
#str = '12345678'
#print(str[:5])
#print(str[-5:])
#formal way of using format()
print('{} and {}'.format('first string','second string'))
print('{0} and {1}'.format('first string','second string'))
print('{1} and {0}'.format('first string','second string'))
print('{firstPosition} and {secondPosition}'.format(firstPosition = 'first string',secondPosition = 'second string'))
#use a dictionary to format a string
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
#vars() get all the local variables
varsResult = vars()
print(varsResult)
| true |
e1be98d672f2925301e0c273a5c00a69c3d30213 | BohanHsu/developer | /nlp/assign1/hw1-files/my_regexs.py | 655 | 4.1875 | 4 | import re
import sys
# the first argument is a regular expression
# from the second argument are file path
pattern = sys.argv[1]
files = sys.argv[2:]
# reg_find : regular_expression, list_of_file_path -> list of words
# return a list of words which match the regular expression
# this method will concatenate all the lines in those given file and find patterns
#
def reg_find(pattern,files):
s = ''
for filename in files:
file = open(filename)
for line in file.xreadlines():
s = s + line
file.close()
words = set(re.findall(pattern,s))
print words
print len(words)
return words
reg_find(pattern,files)
def suffix(suff,count):
pass
| true |
4739f2dcad276d9967f2f0d36479e217db737356 | himIoT19/python3_assignments | /assignment_1/Q4.py | 328 | 4.4375 | 4 | # reverse string
def reverse(a_str: str) -> str:
"""
Function used for reversing the string
:param a_str: String
:return: String
"""
string_1 = a_str[::-1]
return string_1
# String to work on
s = "I love python"
print("Old string : {}".format(s))
print(f"New string after reversal: {reverse(s)}")
| true |
014c4247f563ba43e78dd5cc4d3f4f0e19cd41ed | seefs/Source_Insight | /node/Pythons/py_test/test_while.py | 371 | 4.15625 | 4 | #!/usr/bin/python
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
for j in range(9):
print ('The j is:', j)
#// The count is: 0
#// The count is: 1
#// The count is: 2
#// The count is: 3
#// The count is: 4
#// The count is: 5
#// The count is: 6
#// The count is: 7
#// The count is: 8
#// Good bye!
print ("Good bye!")
| true |
50fa0e9be4d7dadc0aad8eada7de2ecb362e3ba0 | seefs/Source_Insight | /node/Pythons/py_test/test_list_trans.py | 1,163 | 4.25 | 4 |
dict = {'name': 'Zara', 'age': 7, 'class': 'First'}
# 字典转为字符串,返回:<type 'str'> {'age': 7, 'name': 'Zara', 'class': 'First'}
print
type(str(dict)), str(dict)
# 字典可以转为元组,返回:('age', 'name', 'class')
print
tuple(dict)
# 字典可以转为元组,返回:(7, 'Zara', 'First')
print
tuple(dict.values())
# 字典转为列表,返回:['age', 'name', 'class']
print
list(dict)
# 字典转为列表
print
dict.values
# 2、元组
tup = (1, 2, 3, 4, 5)
# 元组转为字符串,返回:(1, 2, 3, 4, 5)
print
tup.__str__()
# 元组转为列表,返回:[1, 2, 3, 4, 5]
print
list(tup)
# 元组不可以转为字典
# 3、列表
nums = [1, 3, 5, 7, 8, 13, 20];
# 列表转为字符串,返回:[1, 3, 5, 7, 8, 13, 20]
print
str(nums)
# 列表转为元组,返回:(1, 3, 5, 7, 8, 13, 20)
print
tuple(nums)
# 列表不可以转为字典
# 4、字符串
# 字符串转为元组,返回:(1, 2, 3)
print
tuple(eval("(1,2,3)"))
# 字符串转为列表,返回:[1, 2, 3]
print
list(eval("(1,2,3)"))
# 字符串转为字典,返回:<type 'dict'>
print
type(eval("{'name':'ljq', 'age':24}"))
| false |
4bea2aa9f65dc46094022529b2666bd0ebd4a252 | chinatsui/DimondDog | /algorithm/exercise/hash_table/find_two_squares_sum.py | 943 | 4.3125 | 4 | """
Given a number 'num', find another two numbers 'a' and 'b' to make pow(a,2) + pow(b,2) = num, then return [a,b]
If there doesn't exist such a pair of numbers, return an empty array.
Example 1:
Input: 58.
Output: [3, 7]
Explanation: 3^2 + 7^2 = 58
Example 2:
Input: 12.
Output: []
Explanation: There doesn't exist a pair of numbers to make pow(a,2) + pow(b,2) == 12
"""
class Solution:
def find_two_square_nums(self, num):
if num < 0:
return []
max_sqrt = self._max_sqrt(num)
i, j = 0, max_sqrt
while i <= j:
sum = pow(i, 2) + pow(j, 2)
if sum == num:
return [i, j]
elif sum < num:
i += 1
else:
j -= 1
return []
@staticmethod
def _max_sqrt(n):
i = 0
while pow(i, 2) <= n:
i += 1
return i - 1
print(Solution().find_two_square_nums(12))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.