blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
a03d23b6929d3916abffaa0bec9933ca8cbd0ee3 | LuiMagno/Aulas-e-Exemplos | /Exemplos_Livro_Cap3/VolumeEsfera.py | 512 | 4.21875 | 4 | # Faça um algoritmo para calcular o volume de uma esfera de raio R, em que R é um dado fornecido pelo usuário. O volume de uma esfera é dado por
# V = 4/3*pi*R^3
raioEsfera = float(input('Insira o Raio da esfera: '))
PI = 3.14
volumeEsfera = (4/3) * PI * pow(raioEsfera, 3)
print('O volume da esfera é : ', volumeEsfera)
# TypeError: can't multiply sequence by non-int of type 'float'
# Origem do Erro: PI = 3,14 -> o padrão norte americano utiliza o '.' e não a ',', então temos que utilizar 3.14 | false |
71204b2224d6b2f8f47f022de9e9a9a7eb0e6e43 | LuiMagno/Aulas-e-Exemplos | /Aulas de Python/POO/Parte 1 - Objetos e Classes.py | 807 | 4.25 | 4 | # Em Python, tudo é um objeto. Lembre-se de palestras anteriores que podemos usar o type() para verificar o tipo de objeto de algo.
# Python é uma linguagem orientada á objeto
print(type(1))
print(type([]))
print(type(()))
print(type({}))
l = [1,2,3] # essa lista l é instância de uma classe de lista
print(type(l))
# Até mesmo um número o Python observa como um objeto da classe inteiro
x = 1
print(type(x))
# Agora vamos criar Classes
class Sample(object):
pass
x = Sample()
print(type(x))
class Dog(object):
especie = 'mamífero' # assim como uma função, minha classe pode ter variáveis próprias
def __init__(self, raca): #construtor
self.raca = raca
Jooj = Dog(raca='Pé duro safad')
print(Jooj.raca)
Frank = Dog('Huskie')
print(Frank.raca)
print(Frank.especie) | false |
1a9ce13740b43ace7985fdc8a8af15caaa81b954 | LuiMagno/Aulas-e-Exemplos | /Aulas de Python/14 - Declarações Aninhasdas e Escopo.py | 1,270 | 4.46875 | 4 | '''
Como Python enxerga suas variáveis?
'''
# No exemplo a seguir, vamos ver 2 tipos de escopos diferentes
x = 25 # esse é uma variável global
def printer():
x = 50 # isso é uma variável local da função
return x
print(x) # temos x na definição inicial do código
print(printer())# temos x na definição do escopo da função 'printer'
# print é uma função built in
'''
Existem 3 regras gerais para definir a ideia de escopo em Python
1. As atribuições de nomes criam ou alteram nomes locais por padrão
2. Existem 4 possíveis scopes. São eles:
1. Local
2. Enclosing functions
3. Global
4. Built-in
3. Os nomes declarados em declarações globais e não locais mapeiam nomes atribuídos para preencher módulos e escopos de função
Regra LEGB
Local
Enclosing
Global
Built-in
'''
# Agora vamos a um exemplo de acesso as variáveis de tipos de declarações diferentes
name = 'Este é um nome global' # nome global
def greet():
name = 'Sammy' #nome da segunda regra, enclosing
def hello():
#name = 'joao' isso seria procurar um nome pela regra: primeiro local, mas como não tem, ele vai pra próxima; Enclosing Functions
print('Hello ' +name)
hello()
greet()
print(name) #print, nome built-in | false |
a456576805409b2a743492994358ec394b95a0db | AADevelops/Rock-Paper-Scissors | /Rock_Paper_Scissors.py | 1,054 | 4.15625 | 4 | import random
while True:
choices = ["rock", "paper", "scissors"]
user_choice = input("Rock, Paper, or Scissors?: ").lower()
bot_choice = random.choice(choices)
if user_choice == bot_choice:
print("Tie! Onto the next round! \n")
elif user_choice == "rock" and bot_choice == "scissors":
print("The bot has chosen scissors! You win! \n")
elif user_choice == "scissors" and bot_choice == "rock":
print("The bot has chosen rock! You lose! :( \n")
elif user_choice == "paper" and bot_choice == "rock":
print("The bot has chosen rock! You win! \n")
elif user_choice == "rock" and bot_choice == "paper":
print("The bot has chosen paper! You lose! :( \n")
elif user_choice == "scissors" and bot_choice == "paper":
print("The bot has chosen paper! You win! \n")
elif user_choice == "paper" and bot_choice == "scissors":
print("The bot has chosen scissors! You lose! :( \n")
else:
print("You have not chosen rock, paper, or scissors, please retry. \n")
| true |
254c4c97cdc327a1bf561521249931e87cbcd97d | Weaam20/Problems_vs._Algorithms_Udacity | /Problem_4.py | 1,761 | 4.125 | 4 | def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
# if input_list was empty or equal to None.
if input_list is None or len(input_list) == 0:
return []
size = len(input_list)
output = [0] * size
# Initialize count array
count = [0] * 3
# Store the count of each elements in count array
for i in range(0, size):
count[input_list[i]] += 1
# Store the cumulative count
for i in range(1, len(count)):
count[i] += count[i - 1]
# Find the index of each element of the original array in count array
# place the elements in output array
i = size - 1
while i >= 0:
output[count[input_list[i]] - 1] = input_list[i]
count[input_list[i]] -= 1
i -= 1
# Copy the sorted elements into original array
for i in range(0, size):
input_list[i] = output[i]
return input_list
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
# Test case 1
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) # return pass
# Test case 2
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) # return pass
# Test case 3
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) # return pass
# ------------------------------------------------------------------------------- Invalid
# Test case 4
test_function([]) # return []
# Test case 5
test_function([]) # return []
| true |
5a34bf668e61b0dc047821c762911d60e46f86b6 | simplyade/Budget | /Budget.py | 1,435 | 4.21875 | 4 | #BudgetApp
'''
Create a Budget class that can instantiate objects based on different budget
categories like food, clothing, and entertainment. These objects should allow for
1. Depositing funds to each of the categories
2. Withdrawing funds from each category
3. Computing category balances
4. Transferring balance amounts between categories
Push your code to GitHub, and submit the repo link.
'''
class Budget: #can be any amount or integer input
def __init__(self,category,amount):
self.category=category
self.amount = amount
def deposit (self,pay):
self.pay=pay
self.amount=int((self.amount) + (self.pay))
return 'You deposited {}'.format(self.amount)
def transfer (self,transfer_amt):
self.transfer_amt=transfer_amt
if self.amount>= transfer_amt:
return 'You transfered {}'.format(self.transfer_amt)
else:
return "Invalid Transfer"
def balance(self,transfer_amt):
self.transfer_amt=transfer_amt
if self.amount>= transfer_amt:
self.amount-=transfer_amt
return "Your balance is {}:".format(int(self.amount)-(self.transfer_amt))
food = Budget("Food",40000)
print(food.deposit(300))
print(food.transfer(30000))
#print(food)
| true |
dca2ef7c3e85be6b1b6a05800eb0c725d6e7b607 | komunikator1984/Python_RTU_08_20 | /Diena_6_lists/d6_f1_u2.py | 465 | 4.28125 | 4 | ## task 2
num_1 = int(input("Ievadi sākuma skaitli "))
num_2 = int(input("Ievadi beigu skaitli "))
my_list = list(range(num_1,num_2+1))
my_list2 = [n**3 for n in my_list]
print(my_list)
print(my_list2)
# i can zip two lists side by side and the loop through both of them at once
# zip will end when one of the lists will end
for num, cube in zip(my_list, my_list2):
print(f"{num} cubed is {cube}")
# print((my_list[n], "kubā: ",my_list2[n]) for n in my_list) | false |
c90c0dd785744bd74ea3eacf0825f178f255a19a | komunikator1984/Python_RTU_08_20 | /Diena_1_4_thonny/logic_op3.py | 1,139 | 4.15625 | 4 | # Boolean algebra
# logical conjuction AND some other languages use && but not Python
print("Testing AND")
print(True and True)
print(True and False)
print(False and True)
print(False and False)
# logical disjunction OR some other languages use || but not Python
print("Testing OR")
print(True or True)
print(True or False)
print(False or True)
print(False or False)
print("Chaining logic")
# we can join our logic
print(True and True and True and 2*2 == 4)
# one bad apple ruins our cider, darvas piliens medū
print(True and 2*2 > 5 and True and True and True and 2*2 == 4)
print(True or True or True or False) # we only need one True with or
print(2*2 == 10 or 2*2 == 5 or 2*2 == 4 or 2*2 == 3) # as soon as one True is reached we get True back
# True = 2*2 == 5 # cant do True is reserved keyword
# we also have negation with not
print(not True) # False
print(not False) # True
# a little trick in programming
my_toggle = True
print(my_toggle)
my_toggle = not my_toggle # so my_toggle is reverse of whatever was there before
print(my_toggle)
my_toggle = not my_toggle
print(my_toggle)
my_toggle = not my_toggle
print(my_toggle)
| true |
12ba3dd6a767183242fff26124bf65f779181860 | komunikator1984/Python_RTU_08_20 | /Diena_1_4_thonny/d3_f1_u1.py | 575 | 4.15625 | 4 | temperature = float(input("What is your body temperature? "))
if temperature < 35:
print("nav par aukstu")
elif temperature > 37:
print("iespējams drudzis")
else:
print("viss kārtībā")
# temperatura = float(input("Lūdzu, ievadiet savu ķermeņa temperatūru: "))
# a = "Vai Jums nav par aukstu?"
# b = "Viss kārtībā!"
# c = "Jums iespējams drudzis!"
# if temperatura <= 35:
# print(a)
# elif temperatura >=35.1 and temperatura <= 36.9:
# print(b)
# elif temperatura >=37:
# print(c)
# else:
# print("Hmm alien temperature", temperatura) | false |
171786a0fbe5ed64f37b2b959ce16049f783f07d | komunikator1984/Python_RTU_08_20 | /Diena_1_4_thonny/variables_a25.py | 1,747 | 4.28125 | 4 | my_name = "VisValdis" # = is assignment not equality
print(my_name)
print(my_name)
# daru ko vēl
print(my_name)
# use short variable names when it is obvious what they refer to
# or when they are not going to be used
a = 2
b = 3
c = a*b
d=33 # less used, but its ok
# c - character
# x, y, z - 2D, 3D coordinates
# i - iterators, index
# n - number,
# s - sometimes string
# t - temporary
# f - fileDescriptor
# variable in Python should start with small lower letter
# can be followed by uppercase , numbers and some symbols such a _
myName = "Valdis" # camelCase, less used in Python
very_long_variable_name = 9000
# if you name your variable with ALL CAPS that indicates a constant
MY_PI = 3.1415926
# this is only a convention, you can still change the contents, just a bad style
# avoid using this if you have my_name
my_Name = "Voldis" # different from my_name !!!!
# variable contents (references) can be changed
print(a,b,c,d)
d = a + b + c # evaluation happens from right to left
print(a,b,c,d)
print(type(my_name), type(a), type(MY_PI))
is_sunny = False # Booleans
is_raining = True
nothing = None # special none type
print(nothing, type(nothing))
# Python is garbage collected automatically
# if some value is not used anymore it is cleaned from memory after some time
my_name = "Voldemars"
# since we have no values pointing to "VisValdis"
# "Valdis" will not be available
# to be fully precise Python always keeps first 256 numbers in memory
# and also from -10 to -1
my_zero = 0
also_zero = 0
my_one = 1
my_big_number = 43242
my_million = 1_000_000 # _ will be ignored it is just for show
# we can print where in memory our values reside
print(id(my_zero), id(also_zero), id(my_one), id(a), id(b), id(my_big_number)) | true |
3846539e9b09f03a2ab8fc0190b77b9cdd1964c7 | komunikator1984/Python_RTU_08_20 | /Diena_1_4_thonny/variables_a20.py | 2,378 | 4.40625 | 4 | my_name = "Valdis" # variables can be used immediately without declaration
my_Name = "Visvaldis" # different from line 1
# print("Valdis")
# print("Valdis")
print(my_name)
print("Hello ", my_name) # this works because , by default gives you one whitespace
print("Hello " + my_name) # less nice
print(f"Nice to meet you {my_name}") # f-strings from Python 3.6 and up
print(type(my_name)) # we can find out data type of variable
print(id(my_name)) # also the memory(virtual) address of where the variable points to
# naming variables
# variables start with lower case alpha leter(English please only)
# after that we can use numbers, letters and some symbols such as _
myName = "Valdis" # so called camelCase less used in Pytho
# if you use one style stick to it in one code
print(my_name, myName)
print(id(my_name), id(myName)) # both variables point to same memory address
a = 120 # so a automatically becomes int (integer) data type
b = 30
c = a + b # evaluation happens from right to left
print(a,b,c)
print(type(a),type(b), type(c))
# data types can change!!
a = "Aha!" # generally we do not want to change data types
print(a)
print(type(a),type(b), type(c))
# c = a + b # this will not work as given, think about what we are adding
c = a + str(b) # so we can make a string out of b
# str is an example of type casting
print(a,b,c)
my_msg = "9000"
my_num = int(my_msg) # not everything can be made into int, but here no problem
print(my_msg, my_num) # not much difference when printed
my_result = my_num + 55
print(my_result)
my_long_msg = "Hello\n darkness \n my old friend"
print(my_long_msg)
# \U is for symbols after 65536 decimal (after FFFF in hex)
smiley_again = "Aha ! 😀 -> \U0001F600" # for Unicode encoded with more than 4 Hex symbols you need to use 32
print(smiley_again)
# if unicode fits into 4 hex symbols then we use \u
some_characters = "I think this is chinese: \u53F8 anyone know it?"
print(some_characters)
# one more data type
my_pi = 3.1415926
print(my_pi)
import math # we can also import additional functionality and values
print(math.pi) # if you need more precise
print(type(my_pi)) # so float represents a value with a floating comma ..
my_int = int(my_pi) # so all digits after comma are lost
my_float_back = float(my_int) # well what will happen with our pi ?
print(my_pi, my_int, my_float_back)
is_sunny = True
is_raining = False
| true |
98706829b147c0f752eb8707bab629d65c4b6656 | FressiaWang/DailyLeetcode | /Interview145/146. LRU Cache.py | 1,318 | 4.15625 | 4 | """
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity,
it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
"""
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.cache = collections.OrderedDict()
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.cache:
return -1
value = self.cache.pop(key)
self.cache[key] = value
return value
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.cache:
del self.cache[key]
elif len(self.cache) == self.capacity:
self.cache.popitem(last=False)
self.cache[key] = value
| true |
ef30535740df31befe7f7f47bc83dca21c66b7ed | FressiaWang/DailyLeetcode | /Interview145/225. Implement Stack using Queues.py | 1,122 | 4.25 | 4 | """
Implement the following operations of a stack using queues.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.
Example:
"""
class MyStack:
def __init__(self):
from collections import deque
self.q1, self.q2 = deque(), deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.popleft()
def top(self) -> int:
return self.q1[0]
def empty(self) -> bool:
return not self.q1
class Stack:
def __init__(self):
self._queue = collections.deque()
def push(self, x):
q = self._queue
q.append(x)
for _ in range(len(q) - 1):
q.append(q.popleft())
def pop(self):
return self._queue.popleft()
def top(self):
return self._queue[0]
def empty(self):
return not len(self._queue)
| true |
c734068b352afdfe2654328a0152601f51dd8ef4 | MbrohUno/Python_Projects | /khansole_academy_starter.py | 1,611 | 4.53125 | 5 | """
File: khansole_academy.py
-------------------------
Khansole Academy is a program that teaches users how to add by asking users to input answers for the addition of two
randomly generating integers between 10 and 99 inclusive. The program returns feedback based on the User's answers.
"""
import random
# ********************************** YOUR CODE GOES BELOW HERE *********************************************************
fran_num=random.randint(10,99)
#the first random variable assignment
sran_num=random.randint(10,99)
# the second random variable assignment.
solution=int(fran_num+sran_num)
# The addition varibale to the two previous variable.
count = 1
# assigning the variable for the number of tries.
while count <= 3:
#this to repeat the sequence until a TRUE condition is met.
fran_num=random.randint(10,99)
#the first random variable assignment
sran_num=random.randint(10,99)
# the second random variable assignment.
solution=int(fran_num+sran_num)
# The addition varibale to the two previous variable.
print("What is the answer for",fran_num, "+" ,sran_num)
user_input=int(input("Answer:"))
# Here this is displayed to request for the user's input
if user_input==solution:
print("Correct!! You've gotten " ,count," correct answer in a row.")
count+=1
#This displays information if the user gets the answer correct.
else:
count=1
#this is to reset the counting.
print("Incorrect. The expected answer is",solution)
# if the answer is wrong this information is displayed.
| true |
299e25e0a5958acaf86e33fc931a3a3a5044effd | MachunMC/python_learning | /python_review/11_创建数值列表.py | 1,401 | 4.59375 | 5 | # -*- coding: utf-8 -*-
# @Project : python_learning
# @File : 11_创建数值列表.py
# @Author : Machun Michael
# @Time : 2021/3/22 8:03
# @Software: PyCharm
# 1.生成一系列整数:range()函数
print(range(1,8)) # 这里只会原样输出range(1, 8)
# 需要使用for循环来打印range返回的结果
# 会生成从1到8之间的整数,包括1,不包括8
for value in range(1, 8):
print(value)
# 生成-11到11之间的整数
# 注意,传入的两个参数,只能是整数
for value in range(-11, 11):
print(value)
# 2.使用list()函数,将range生成的一系列数字,转换为列表
number = list(range(1, 20))
print(number)
print(len(number))
# 3.使用range()时,可以指定步长(两个数之间的间隔)
even_num = list(range(2, 11, 2))
uneven_num = list(range(1, 11, 2))
print("1到11(不包括11)之间的偶数有:", even_num)
print("1到11(不包括11)之间的奇数有:", uneven_num)
# 4.创建一个只包含1到10的平方的值的列表
num_list = []
for tmp in range(1,11):
num_list.append(tmp * tmp)
print(num_list)
# 5. 数值列表中常用的几个函数
# max():取出列表中的最大值
# min():取出列表中的最小值
# sum():列表求和
num_list = [1, 3, 5, 2, 6, 9, 88, 2, -9]
print("max(num_list):", max(num_list))
print("min(num_list):", min(num_list))
print("sum(num_list):", sum(num_list)) | false |
bce80669101866967ec01e89c30c022c157880dc | estraviz/codewars | /7_kyu/Sum of Primes/python/solution.py | 637 | 4.125 | 4 | """Sum of Primes"""
from math import sqrt
def sum_primes(lower, upper):
_sum = 0
if lower > upper:
return _sum
num = lower
while num <= upper:
if is_prime(num):
_sum += num
num += 1
return _sum
def is_prime(n):
if is_two_or_greater(n) and is_a_whole_number(n):
for i in range(2, int(sqrt(n)) + 1):
if is_divisible_by(n, i):
return False
return True
else:
return False
def is_two_or_greater(n):
return n >= 2
def is_a_whole_number(n):
return n % 1 == 0
def is_divisible_by(n, i):
return n % i == 0
| true |
63f44ead85eea4e14db1a63d24b21335df2f39fb | komalsorte/LeetCode | /Amazon/Design/295_FindMedianFromDataStream.py | 2,425 | 4.125 | 4 | __author__ = "Komal Atul Sorte"
"""
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
For example,
[2,3,4], the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
Example:
addNum(1)
addNum(2)
findMedian() -> 1.5
addNum(3)
findMedian() -> 2
Follow up:
If all integer numbers from the stream are between 0 and 100, how would you optimize it?
If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it?
"""
class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
self.numList = list()
def addNum(self, num: int) -> None:
self.numList.append(num)
self.numList = sorted(self.numList)
def findMedian(self) -> float:
if len(self.numList) != 0:
if len(self.numList) % 2 == 0:
median = self.numList[len(self.numList) // 2] + self.numList[len(self.numList) // 2 - 1]
median = median / 2
return median
else:
median = self.numList[len(self.numList) // 2]
return median
return
# Your MedianFinder object will be instantiated and called as such:
obj = MedianFinder()
obj.addNum(1)
obj.addNum(2)
param_2 = obj.findMedian()
obj.addNum(3)
param_2 = obj.findMedian()
# ["MedianFinder","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian"]
# [[],[6],[],[10],[],[2],[],[6],[],[5],[],[0],[],[6],[],[3],[],[1],[],[0],[],[0],[]]
obj2 = MedianFinder()
obj2.addNum(6)
print(obj2.findMedian())
obj2.addNum(10)
print(obj2.findMedian())
obj2.addNum(2)
print(obj2.findMedian())
obj2.addNum(6)
print(obj2.findMedian())
obj2.addNum(5)
print(obj2.findMedian())
obj2.addNum(0)
print(obj2.findMedian())
obj2.addNum(6)
print(obj2.findMedian())
obj2.addNum(3)
print(obj2.findMedian())
obj2.addNum(1)
print(obj2.findMedian())
obj2.addNum(0)
print(obj2.findMedian())
obj2.addNum(0)
| true |
4e52d1336f8c4e25e1024f5e3c692288f5f98c7a | komalsorte/LeetCode | /BinarySearchTree/173_BinarySearchTreeIterator.py | 2,218 | 4.3125 | 4 | __author__ = "Komal Atul Sorte"
"""
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Example:
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // return 3
iterator.next(); // return 7
iterator.hasNext(); // return true
iterator.next(); // return 9
iterator.hasNext(); // return true
iterator.next(); // return 15
iterator.hasNext(); // return true
iterator.next(); // return 20
iterator.hasNext(); // return false
Note:
next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator:
root = None
def __init__(self, root: TreeNode):
self.root = root
self.last_smallest_index = 0
self.nodes = []
self._inorder(self.root)
print(self.nodes)
def _inorder(self, root: TreeNode):
if root is None:
return root
self._inorder(root.left)
self.nodes.append(root.val)
self._inorder(root.right)
def next(self) -> int:
"""
@return the next smallest number
"""
if self.last_smallest_index < len(self.nodes):
self.last_smallest_index += 1
return self.nodes[self.last_smallest_index - 1]
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
pass
if self.last_smallest_index < len(self.nodes):
return True
else:
return False
# Your BSTIterator object will be instantiated and called as such:
root = TreeNode(5)
left = TreeNode(3, TreeNode(2), TreeNode(4))
right = TreeNode(8, TreeNode(6), TreeNode(10))
root.right = right
root.left = left
obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()
| true |
0e85f2913e4e4a1ab808f12d1e2facde23f47923 | Utsav-Raut/python_tutorials | /python_basics/iterators_iterable_itertools.py | 1,706 | 4.40625 | 4 | # In Python if we can loop over something in a for-loop, we call it an iterable.
# The process of looping over elements is called iterating.
# for x in something:
# Code and stuff
# here 'something' is an iterable.
# Using LIST
# list = ['CX32', 'GSOF', 'Emily', 'Franz', 'Rex']
# for element in list:
# print(element)
# A List is one type of sequence
# A Sequence is an iterable with a clear order to the components.
# Sequence = Iterable + Ordered
# Other common sequences are : tuples, strings, bytes
# Using TUPLE
# for element in ('Jose', 'Boh', 'Rusti'):
# print(element)
# Using STRING
# for letter in 'Socratica':
# print(letter)
# Iterating over a bytes object, one byte at a time
# for byte in b'Binary':
# print(byte) # The ASCII code for each letter in 'Binary' is printed here
# WE CANNOT ITERATE OVER THE DIGITS OF AN INTEGER
# for digit in 299792458:
# print(digit)
# The error message will read as 'int' object is not iterable
# To loop over the digits of an integer and have the digits treated as integers, we need to have this constructed ourselves
# c = 299792458
# digits = [int(d) for d in str(c)]
# for digit in digits:
# print(digit)
# print(type(digits))
# So what makes an object iterable??
# Starting from python 3.3 there is a Collections.abc module where ABC stands for Abstract Base Classes
# We can read about it in the official python doc
# The key to iteration lies in two special methods - __iter__ and __next__
# container.__iter__()
# returns an iterator object
# container.__next__()
# returns the next item from the container
# if there are no further items,
# raise StopIterationException
3:00 | true |
4acd84f296513271c7cb438db1f5737101ec6d99 | Utsav-Raut/python_tutorials | /intrvw_topics/basics/largest_elem_in_array.py | 419 | 4.40625 | 4 | # Given an array A[] of size n. The task is to find the largest element in it.
# Example 1:
# Input:
# n = 5
# A[] = {1, 8, 7, 56, 90}
# Output:
# 90
# Explanation:
# The largest element of given array is 90.
def largest(arr, n):
largest_elem = arr[0]
for x in arr:
if x > largest_elem:
largest_elem = x
return largest_elem
A = [1, 8, 7, 56, 90]
res = largest(A, 5)
print(res) | true |
407efb53f1fb1160b83faa7f6070bc64bca38fa6 | Utsav-Raut/python_tutorials | /intrvw_topics/hackerrank/itertools.py | 1,311 | 4.3125 | 4 | # itertools.product()
# This tool computes the cartesian product of input iterables.
# It is equivalent to nested for-loops.
# For example, product(A, B) returns the same as ((x,y) for x in A for y in B).
# Sample Code
# >>> from itertools import product
# >>>
# >>> print list(product([1,2,3],repeat = 2))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
# >>>
# >>> print list(product([1,2,3],[3,4]))
# [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
# >>>
# >>> A = [[1,2,3],[3,4,5]]
# >>> print list(product(*A))
# [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
# >>>
# >>> B = [[1,2,3],[3,4,5],[7,8]]
# >>> print list(product(*B))
# [(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]
from itertools import product
list1, list2 = [], []
list1 = [int(item) for item in input("Enter the list items: ").split()]
list2 = [int(item) for item in input("Enter the second list items: ").split()]
# print(list(product(list1, list2)))
res = list(product(list1, list2))
print(len(res))
for item in range(len(res)):
if item == (len(res)-1):
print(res[item])
else:
print(res[item], end=', ') | true |
ceecb0c8e40014a1b4d53087ba50d4a088d06d78 | Utsav-Raut/python_tutorials | /python_basics/dictionaries-5.py | 2,300 | 4.6875 | 5 | #Dictionaries allow us to work with key-value pairs. They are like maps of Java
#Keys can be any immutable data-types
student = {'name': 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
# print(student)
# print(student['name'])
# print(student['courses'])
# print(student['phone']) # This throws a key error
#Instead of errors, we might want to display 'None' or some other message when a key is not found. We can do so by using the other method for retrieval of values-get() method
# print(student.get('name'))
# print(student.get('phone')) #instead of error, this returns a None by default.
# print(student.get('phone', 'Not Found')) # This is how we can specify default values for keys that don't exist
#Adding a new entry to our DICTIONARY
# student['phone'] = '555-5555'
# print(student.get('phone', 'Not Found'))
#If a key already exists, if we set it's value again, then it will update the value
# student['name'] = 'Jane'
# print(student.get('name'))
# print(student)
#We can also update using the update method. In order to update multiple values at a time we use the update method
#The update method takes in a DICTIONARY as an argument and the DICTIONARY is just everything that we either want to add or update
# student.update({'name': 'Jane', 'age': 26, 'phone': '555-5555'})
# print(student)
#delete a specific key and it's values
# del student['age']
# print(student)
#another way to delete is by using the pop method. Pop method removes and returns the popped value
# age = student.pop('age')
# print(student)
# print(age)
# print(len(student)) #this prints the number of keys in our DICTIONARY
# print(student.keys()) #this prints all the keys of the DICTIONARY
# print(student.values()) #this prints the values in our DICTIONARY
# print(student.items()) # this prints the keys along with the values
#Looping through all the keys and values of our DICTIONARY
#If we have to loop through all the keys and values in our DICTIONARY we might be tempted to loop through like we loop through our list
#But if we just loop through our list without using any method then it will just loop through the keys
# for key in student:
# print(key)
#In order to loop through keys and values we need to use the items method
for key, value in student.items():
print(key, value)
| true |
42a26ede9c95bdddbcedae6dacabdbabc33c1b07 | Utsav-Raut/python_tutorials | /dsa_basics/dictionaries/dict_basics1.py | 2,083 | 4.5625 | 5 | # The dictionary is Python’s built-in mapping type. Dictionaries map keys to values and these key-value pairs provide a useful way to store data in Python.
sammy = {'username': 'sammy-shark', 'online': True, 'followers': 987}
jesse = {'username': 'JOctopus', 'online': False, 'points': 723}
print('READING FROM DICTIONARIES....')
print(sammy)
print(sammy['username'])
print(sammy['online'])
print(sammy['followers'])
# In addition to using keys to access values, we can also work with some built-in methods:
# dict.keys() isolates keys
# dict.values() isolates values
# dict.items() returns items in a list format of (key, value) tuple pairs
print(sammy.keys())
print(sammy.values())
for key, value in sammy.items():
print(key, value)
print('Printing common keys.............')
for common_key in sammy.keys() & jesse.keys():
print(sammy[common_key], jesse[common_key])
# MODIFYING DICTIONARIES
print('Adding and changing dictionary elements......')
user_names = {'Sammy': 'sammy-shark', 'Jamie': 'mantisshrimp54'}
user_names['Drew'] = 'squidly'
print(user_names)
# DICTIONARIES MAY BE UNORDERED AND HENCE THE ITEMS MAY APPEAR IN ANY ORDER
drew = {'username': 'squidly', 'online': True, 'followers': 305}
drew['followers'] = 342
print(drew)
# We can also add and modify dictionaries by using the dict.update() method.
print('Before applying update method....')
print(jesse)
print('After applying update method')
jesse.update({'followers': 481})
print(jesse)
# DELETING ELEMENTS FROM DICTIONARY
# To remove a key-value pair from a dictionary, we’ll use the following syntax:
del jesse['points']
print('After deleting....')
print(jesse)
# If we would like to clear a dictionary of all of its values, we can do so with the dict.clear() method. This will keep a given dictionary in case we need to use it later in the program, but it will no longer contain any items.
print('After clearing...')
jesse.clear()
print(jesse)
# If we no longer need a specific dictionary, we can use del to get rid of it entirely:
del jesse
print('After deletion....')
print(jesse) | true |
0cbf5f23951529b62a5ce9aab674aaa4a2fbb6e9 | vrodolfo/python_nov_2017 | /Rodolfo_Valdivieso/PythonFundamentals/assignment15PytonTuples.py | 542 | 4.25 | 4 | #Assignment 15 Python - Tuples
# function that takes in a dictionary and returns
# a list of tuples where the first tuple item is the key and the second is the value
# function input
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
def tuples(dictionary):
listOfTuples =[]
tupleX = ()
for keys in dictionary:
#create the tuple
tupleX = tupleX + (keys,)
tupleX = tupleX + (dictionary[keys],)
listOfTuples.append(tupleX)
tupleX = ()
return listOfTuples
print tuples(my_dict)
| true |
ed3097c4ab2daa6d5e8a08650033015d49170017 | LeslieLeung/myfirstcodes | /BMI Tester.py | 403 | 4.125 | 4 | #!/usr/bin/env python3
#this programme is used to test your BMI
#ver1.0 Copyright Leslie_Leung
height=float(input('Please input your height\n'))
weight=float(input('Please input your weight\n'))
BMI=weight/(height*height)
print('Your BMI is',BMI)
if BMI<18.5:
print("a")
elif BMI>=18.5 and BMI<25:
print("b")
elif BMI>=25 and BMI<28:
print("c")
elif BMI>=28 and BMI<32:
print("d")
else:
print("e")
| true |
413667ca2ba817931890103a03e55ede994247ea | kayvera/python_practice | /array/array.py | 2,145 | 4.1875 | 4 | # array holds data of specified type
# contiguous elements
# unique index
# size of array is predefined and cant be modified
# any element can be found by index in array
'''
Big o of array
Array
Indexing Θ(1)
Insert/delete at beginning Θ(n)
Insert/delete at end Θ(1)
Insert/delete in middle Θ(n)
'''
from array import *
# 1. create an array and traverse
arr = array('i', [1, 2, 3, 4, 5])
# arr = [1,2,3,4,5]
for i in arr:
print(i)
# 2. access individual elements through indexes
print("step 2")
print(arr[0])
# 3. Append any value to the array using append() method
print("step 3")
arr.append(6)
print(arr)
# 4. Insert value in an array using insert() method
print("step 4")
arr.insert(0, 11)
print(arr)
# 5. Extend python array using extend() method
print("step 5")
arr2 = array('i', [10, 11, 12])
arr.extend(arr2)
print(arr)
# 6. Add items from list into array using fromlist() method
print("step 6")
tempList = [20, 21, 22]
arr.fromlist(tempList)
print(arr)
# 7. remove any array element using remove() method
print("step 7")
arr.remove(11)
print(arr)
# 8. Remove last array element using pop() method
print("step 8")
arr.pop()
print(arr)
# 9. fetch any element through its index using index() method
print("step 9")
print(arr.index(21))
# 10. Reverse a python array using reverse() method
print("step 10")
arr.reverse()
print(arr)
# 11. Get array buffer information through buffer_info() method
print("step 11")
print(arr.buffer_info())
# 12. Check for number of occurences of an element using count() method
print("step 12")
print(arr.count(11))
# 13. Convert array to string using tostring() method
print("step 13")
strTemp = arr.toString()
print(strTemp)
ints = array('i')
ints.fromstring(strTemp)
print(strTemp)
# 14. Convert array to a python list with same elements using tolist() method
print("step 14")
# print(arr.tolist())
# 15. Append a string to char array using fromstring() method
print("step 15")
# look at step 13
# 16. Slice elements from an array
print("step 16")
print(arr[1:4])
| true |
6adcf5fb85ec65e65809c2667563f2b429151d04 | kayvera/python_practice | /stack/stackLinkedList.py | 1,211 | 4.125 | 4 | class Node:
def __init__(self, value=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
class Stack:
def __init__(self):
self.LinkedList = LinkedList()
def isEmpty(self):
if self.LinkedList.head == None:
return True
else:
return False
def push(self, value):
node = Node(value)
node.next = self.LinkedList.head
self.LinkedList.head = node
def pop(self):
if self.isEmpty():
return "there are no elements in stack"
else:
nodeValue = self.LinkedList.head.value
self.LinkedList.head = self.LinkedList.head.next
return nodeValue
def peek(self):
if self.isEmpty():
return "there are no elements in stack"
else:
nodeValue = self.LinkedList.head.value
return nodeValue
def delete(self):
self.LinkedList.head = None
customStack = Stack()
print(customStack.isEmpty())
customStack.push(1)
customStack.push(2)
customStack.push(3)
print(customStack)
print("----------")
print(customStack.peek())
print(customStack)
| true |
d66f8143515bf0d3eab343514729596deb68aa7e | samauer14/module_6-script | /Regional+Population+Comparison+Using+WHO+Data.py | 1,036 | 4.34375 | 4 |
# coding: utf-8
# In[20]:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import matplotlib
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
import numpy as np
import pandas as pd
# In[21]:
#reading the WHO data used previously in this course
#regions are Africa, Europe, Americas, Eastern Mediterranean, South-East Asia, Western Pacific
who_df = pd.read_csv('../data/WHO.csv')
# In[22]:
#Parsing the dataset down into the relevant columns
who_df= who_df[['Region','Country','Population']]
# In[23]:
#Setting Region as the index as that is how I am sorting them
who_df=who_df.set_index('Region')
# In[29]:
print ("Please enter a region.")
print ("Africa, Europe, Americas, Eastern Mediterranean, South-East Asia, or Western Pacific are your choices.")
# In[24]:
#returning the data for the entered region
who_df=who_df.loc[input(), : ]
# In[25]:
#print bar graph using data for the inputed region
who_df.plot.bar(x='Country',y='Population',title='Region Population Comparison',legend=False)
| true |
3c374b1016c7c200184f082bcc2b8681e9eedc90 | mtkane6/Python_Leetcode | /SymmetricTree.py | 1,894 | 4.3125 | 4 | '''
Runtime: 20 ms, faster than 77.49% of Python online submissions for Symmetric Tree.
Memory Usage: 12 MB, less than 63.04% of Python online submissions for Symmetric Tree.
------------------------------------------------------------------------------------------
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildLeftList(self, currList, root):
if root:
currList.append(root.val)
self.buildLeftList(currList, root.left)
self.buildLeftList(currList, root.right)
return root
currList.append(0)
return root
def buildRightList(self, currList, root):
if root:
currList.append(root.val)
self.buildRightList(currList, root.right)
self.buildRightList(currList, root.left)
return root
currList.append(0)
return root
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
if not root.left and not root.right: return True
if not root.right or not root.left: return False
leftList, rightList = [], []
self.buildLeftList(leftList, root.left)
self.buildRightList(rightList, root.right)
if len(leftList) == len(rightList):
for i in range(len(leftList)):
if leftList[i] != rightList[i]: return False
return True
return False | true |
870f25cf823ed9670fa32096b0509a24e670307c | Vincent818/Python_learning | /if_else.py | 258 | 4.15625 | 4 | # -*- coding: utf-8 -*-
height = 1.75
weight = 80.5
BMI= weight/(height*height)
print(BMI)
if BMI <18.5:
print('过轻')
elif BMI<25:
print('正常')
elif BMI<28:
print('过重')
elif BMI<32:
print('肥胖')
else:
print('严重肥胖') | false |
363da6235560819b2922f4cfc9a6792c5b7c999f | joshualxndrs/ALGOPRO-HW-1_Exercise1-2_JOSHUA | /EX2_Windchill temperature_Joshua.py | 785 | 4.15625 | 4 | #Input Ta
#Ta should be --> ta < -58 or ta > 4
#Input velocity (v)
#Wind velocity should be greater than or equal to 2, unit in miles/hour
#Final product = 35.74 + (0.6215 * ta) - (35.75 * pow(v,0.16)) + 0.4275 * ta * pow(v,0.16)
#pow --> to the power
import math
ta = float(input("Input temperature in Fahrenheit: "))
while ta < -58 or ta > 41 :
print("Temperature should be between -58F and 41 F")
ta = eval(input("Input temperature in Fahrenheit: "))
v = float(input("Input the wind speed in miles/hour: "))
while v < 2:
print("The speed should be > or = 2 .")
v = float(input("Input the wind speed in miles/hour: "))
final_product = 35.74 + (0.6215 * ta) - (35.75 * pow(v,0.16)) + 0.4275 * ta * pow(v,0.16)
print("The wind chill index is %2.3f"%final_product) | false |
1a7cb3f820001c864ae9c17df160a54126c3b0fd | rwhite5279/sorting_algorithm_analysis | /selection_sort.py | 1,463 | 4.5 | 4 | #!/usr/bin/env python3
"""
selection_sort.py
Creates a list of random values and sorts them using the
Selection Sort algorithm.
@author
@version
"""
import time
import random
def generate_random_numbers(length, range_of_values):
"""Generates a list of "length" integers randomly
selected from the range 0 (inclusive) to
range_of_values (exclusive) and returns it to
the caller.
"""
return [random.randrange(range_of_values) for i in range(length)]
def selection_sort(nums):
"""Takes the list "nums" and sorts it using the
Selection Sort algorithm.
"""
for i in range(len(nums)-1):
small_index = i
for x in range(i+1, len(nums)):
if nums[x]<nums[small_index]:
small_index = x
if i != small_index:
nums[small_index], nums[i] = nums[i], nums[small_index]
return nums
def display(a_list):
"""Prints out the list "a_list" on the screen. To
be used for debugging, or displaying the initial
and final state of the list.
"""
print(a_list)
def main():
NUM_OF_VALUES = 10
nums = generate_random_numbers(NUM_OF_VALUES, 10)
display(nums)
start = time.time()
selection_sort(nums)
stop = time.time()
display(nums)
print("Sorted {0:10d} values, execution time: {1:10.5f} seconds".format(NUM_OF_VALUES, stop - start))
if __name__ == "__main__":
main() | true |
dd25fe6cd756dcedee3d0f157951b3706bf762c6 | rwhite5279/sorting_algorithm_analysis | /counting_sort.py | 787 | 4.1875 | 4 | #!/usr/bin/env python3
"""
counting_sort.py
This file holds a counting sort algorithm which uses
a dictionary to hold the occurances of each integer in
the random list.
"""
__author__ = 'Theo Demetriades'
__version__ = '2021-04-09'
import random
import time
def counting_sort(l):
new = []
occurences = {}
for integer in l:
if integer in occurences.keys():
occurences[integer]+=1
else:
occurences[integer] = 1
for i in range(len(l)):
if i in occurences.keys():
for x in range(occurences[i]):
new.append(i)
return new
def main():
list = []
for i in range(100):
list.append(random.randrange(100))
print(list)
print(counting_sort(list))
if __name__=='__main__':
main() | true |
67c1215039ba091b6a667218f1f38c346376b96e | yohan1152/nuevas-tecnologias-taller-python | /ejercicios-basicos/ejercicio3.py | 767 | 4.15625 | 4 | """
3. Se requiere un algoritmo para obtener la estatura promedio de un grupo de personas, cuyo
número de miembros se desconoce, el ciclo debe efectuarse siempre y cuando se tenga una
estatura registrada.
"""
try:
estatura = -1
sumarEstatura = 0
contarEstatura = 0
while estatura:
estatura = float(input("Ingresar estatura:\n"))
sumarEstatura += estatura
contarEstatura += 1
#El enunciado no especificaba en que momento de debia mostrar el promedio por eso lo muestro en cada iteración
print("\nEstatura promedio: ", sumarEstatura/contarEstatura,"\n")
except ValueError:
print("El valor ingeresado no es un número válido.")
print("\nEstatura promedio: ", sumarEstatura/contarEstatura)
| false |
a0eea7ca6c995a64f32d613b64da0898e6006a4d | NamamiShanker/Python-Work | /elif_ladder.py | 401 | 4.1875 | 4 | # Advanced if else statement - elif ladder
# -----------------------------------------
'''
Banana, Orange, Apple
<=10 w - Banana
>10 and <=20 - Orange
>20 and <=30 - Apple
>30 and <=40 Watermelon
>40 Knife
'''
money = 5
if money<=10:
print("Banana")
elif money <= 20:
print("Orange")
elif money <=30:
print("Apple")
elif money <= 40:
print("Watermelon")
else:
print("Knife")
| true |
1cd35edec35220855ca97499639d1c0f532b07be | JasonPCairns/file-insert-at-proportion | /main.py | 1,210 | 4.125 | 4 | """
Takes as command line arguments file1 file2 n
0<=n<=1
Inserts the contents of file1 into file2 n-way through file2
"""
import math
import sys
def main():
file_in = sys.argv[1]
file_out = sys.argv[2]
n = sys.argv[3]
if not(0 <= n <= 1):
raise ValueError("n must be between 0 and 1 (inclusive)")
raw_text = bring_files(file_in, file_out)
text_out = insertion(raw_text, int(n))
text_to_file(file_out, text_out)
def bring_files(file_in, file_out):
"""bring files into program"""
with open(file_in) as f1:
with open(file_out) as f2:
return f1.read(), f2.read()
def insertion(raw_text, n):
"""insert raw text of file_in to some proportion of raw text of file_out"""
text_in = raw_text[0]
text_out = raw_text[1]
split_point = math.floor(n*len(text_out))
if split_point == 0:
return text_in + text_out
elif split_point == 1:
return text_out + text_in
else:
return text_out[:split_point] + text_in + text_out[split_point:]
def text_to_file(file_out, text_out):
"""overwrite file_out"""
with open(file_out, 'w') as f:
f.write(text_out)
if __name__ == '__main__':
main()
| true |
2f46beb51c3778a85305bc02daf5b62d00418918 | megan-davi/Python-Projects | /fibonacciSequence.py | 1,610 | 4.25 | 4 | '''
Prompt:
Write a Python class with methods that use recursion to calculate
the Fibonacci number sequence with and without dynamic programming.
Include a count of how many times the recursive function is called to
show how dynamic programming improves the performance.
What is the complexity of the algorithm with and without
dynamic programming?
'''
class Fibonacci:
def __init__(self):
"Constructor"
print("Fibonacci object created.")
print()
self.dynamicCount = 0
self.recursiveCount = 0
def recursive(self, n):
"Determine fibonacci sequence recursively"
self.recursiveCount += 1
if n == 0: # n represents number of elements for fib. sequence
return 0
elif n == 1:
return 1
else:
return self.recursive(n - 1) + self.recursive(n - 2)
def dynamic(self, n):
"Determine fibonacci sequence dynamically"
self.dynamicCount += 1
values = [0,1]
for i in range(2,n+1):
values.append(values[i - 1] + values[i - 2])
return values[n]
n = 10
f = Fibonacci()
print("Printed recursively")
for i in range(n):
print(f.recursive(i))
print()
print("Printed dynamically")
for i in range(n):
print(f.dynamic(i))
print()
print("Number of iterations in recursive function: " + str(f.recursiveCount))
print("Number of iterations in dynamic function: " + str(f.dynamicCount))
'''
Complexity of dynamic is O(2^n) (exponential)
Complexity of non-dynamic is O(n) (linear)
'''
| true |
9e3ea0ac01baf089e46af03e39b07f121d2ae040 | s-killer/practice | /GeeksforGeeks/stock_buy_sell.py | 1,719 | 4.5 | 4 | """
https://www.geeksforgeeks.org/stock-buy-sell/
The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.
For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3.
Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.
"""
price = [100, 180, 260, 310, 40, 535, 695]
price = [200,100, 180, 260, 310, 40,10, 535, 234, 10, 180, 260, 310, 40,10, 535]
price = [100, 90,90,80,20]
n = len(price) - 1
#print('len',n)
current = None
buy = None
sell = None
is_buy = False
for i in range(n):
current = price[i]
#print('current',current,i)
if i ==0:
# if 1st number is less than 2nd then buy
if price[i+1] > current:
buy = current
is_buy = True
else:
if price[i+1] > current and not is_buy:
#print("in 2nd if ", current, is_buy)
# 100, 180, 260,
# buy if next is greater
buy = current
is_buy = True
elif price[i+1] < current and is_buy:
# 100 , 40 and is_buy = True
# then sell
sell = current
print("buy :", price.index(buy), "sell :", price.index(sell))
is_buy = False
else:
#print("is_buy",is_buy,current, i )
pass
#print(i,n,is_buy, current)
if i == (n -1) and is_buy:
#print("--1")
if price[i+1] > current:
sell = price[i+1]
print("buy :", price.index(buy), "sell :", price.index(sell))
is_buy = False
| true |
c7a1e10a51a25ddde3026ccb24ab1c825b062024 | t-a-y-l-o-r/Effective_Python | /2_CH/Position.py | 1,729 | 4.34375 | 4 | '''
Author: Taylor Cochran
Book: Effective Python
Ch2
Goal:
To learn about variable positional arguments,
and how they facilitate noise reduction
'''
# start with a function that stores debug info
def log(message, values):
if not values:
print(message)
else:
values_str = ", ".join(str(x) for x in values)
print("%s: %s" % (message, values_str))
# log("My numbers are", [1, 2])
# log("Hi there", [])
# use *arg to remove the need for empty arguments!
def log(message, *values): # values is now optional/ accepts any number of arguments
if not values:
print(message)
else:
values_str = ", ".join(str(x) for x in values)
print("%s: %s" % (message, values_str))
# log("My numbers are", 1, 2)
# log("Hi there")
# using * on a list passed as an argument tells python to treat the list items
# as postional arguments
numbers = [7, 33, 99]
log("Farvorite numbers", *numbers)
# use * on argumetns forces the passed object to a tuple
# in the case of a generator this will exahust it, possibly eating all of your memory,
# and time
def my_generator():
for i in range(10):
yield i
def my_func(*args):
print(args)
it = my_generator()
my_func(*it)
# additioanlly it is impossible to append to the accept args without breaking
# any code that calls the function
def log(sequence, message, *values):
if not values:
print("%s: %s" % (sequence, message))
else:
values_str = ", ".join(str(x) for x in values)
print("%s: %s: %s" % (sequence, message, values_str))
log(1, "Favorites", 7, 33) # works
log("Favorites", 7, 33) # breaks in an unexpected manner
# to avoid this use keyword arguments to avoid this suple bugg propigation
# will cover in the next script
| true |
b3be5db18335dc0107edf37994b6306edc850f51 | Quantum404/playing-with-numbers-python | /app.py | 868 | 4.15625 | 4 | def add():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x+y
print("Your final result is: ", z)
def multiply():
x = input("Enter your number 1")
y = input("Enter your number 2") # Ask the user for the number of values' sum they would like to calculate
w = x*y # Now, ask each of the number one by one
print("The value is :",w)# Return the multiplication of all the numbers upto 2 decimal places
def factorial():
n = input("Enter your number")# Take an integer as an input and
fact = 1
for i in range(1,n+1):
fact = fact * i
print (fact)# Return it's factorial
def prime():
n = input("Enter your number")# Take an integer n
if (num % i) == 0:
print("false")
else:
print("true")# Check whether it is a Prime or not
# Return true or false
if __name__=='__main__':
add()
| true |
b4e6648b6507dd3f6616789b989eea592ef8f833 | Kirankumar-aug25/basic-data-science-python | /factorial of a number.py | 583 | 4.125 | 4 | #####using for loop####
def factorial(n):
k = 1
if (n < 0):
print("factorial of ", n, "=", 0)
elif (n == 0 or n == 1):
print("factorial of ", n, "=", 1)
else:
for i in range(n, 0, -1):
k = k * i
print(k)
factorial(9)
###using while loop##
def factorial(n):
k = 1
if (n < 0):
print("factorial of ", n, "=", 0)
elif (n == 0 or n == 1):
print("factorial of ", n, "=", 1)
else:
while(n>1):
k = k * n
n=n-1
print(k)
factorial(9)
| false |
b3ee5c90fac8efacbff52efe51d2ec5df48129e8 | DRBriseno/potato | /jsonObject.py | 2,887 | 4.21875 | 4 | import json
# Why? Json objects allow efficient and uniform transportation of data across the internet
### >>>> a json object is simply a python object that has been templated and put into a json file
### >>>> and this json file is what will be sent over the internet because json's are lightweight
### >>>> that are primarily text and can be served very quickly to many userbases and its a universal template
### >>>> you can throw a json file into about any application and it will now how to read the json file because all json files use this general syntax
#Before we make a json object lets make a regular python object and see the relation between the two
dictionary = {
"key":"value" #weve been working with these dictionaries which are python objects and they utilize these Key/Value pairs
}
#We can make these more complex objects
#python dictionary sytax
dictionaryJoke = {
"type": "success",
"value": {
"id": 493,
"joke": "Chuck Norris can binary search unsorted data.",
"categories": ["nerdy"]
}
}
#copy/pasted from the newly created exampleObject.json file---
#compare the python object above and the json object below,
#notice the few differences
#notice json does not do any variable declaration, its just a list of objects
#other than that it looks like everything is almost identical
#
#{
#"type": "success",
#"value": {
# "id": 493,
# "joke": "Chuck Norris can binary search unsorted data.",
# "categories": [
# "nerdy"
# ]
# }
#}
#an object in json is going to be almost identical except its going to be in a json file
#json objecrts must be in json files.
#we are going to use this python file to create this json file and write this python object into it
#lets go ahead a use a little bit of pythons built in libraries
#start with the json package (import json)^^^^
#to write a new file I'm going to say....
with open('exampleObject.json', 'w') as outfile: #in order to interact with it we will label it as outfile
#we are writing the file so I amgoing to give it that keyword 'w' == 'write'
#the last thing we are going to do is use the json package we just installed, and to write a new json object we will use the dump method
json.dump(dictionaryJoke, outfile, indent=4) #<<<<<<<< indent=4 is just a styling thing
#the idea is that we are going to "dump" what ever object is currently written in python, and turn it into json
#we are going to dump the (dictionaryJoke) object into the (exampleObject.json)file. We are going to add a couple
#weve created json objects
#we know what they look like
#and we know they are used to transporting data efficiently from a route
#lets take the json and put it in a route and see what happens
#go to server (mainfile.py)file and write a route that would return this json object as a result (mainfile.py - line 103) | true |
abcb813098a8eb800cf084e3e9ad225fec051a23 | Antiner/Homework | /Session 2 - Markovsky Alexander/Task_1_2.py | 353 | 4.25 | 4 | # Task 1.2
# Write a Python program to count the number of characters (character frequency) in a string (ignore case of letters).
def task_1_2(string):
dictionary = {}
for n in str(string):
keys = dictionary.keys()
if n in keys:
dictionary[n] += 1
else:
dictionary[n] = 1
print(dictionary)
| true |
1af04dc371f12ce53bb667c587eb0b704784bc4b | suraj027/Python | /Practical Submission 05-11-2020/P4.py | 329 | 4.25 | 4 | #Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.
#Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
#Expected Output : ['Green', 'White', 'Black']
list1=["Red","Green", "White", "Black", "Pink", "Yellow"]
list1.pop(5)
list1.pop(0)
list1.pop(3)
print(list1) | true |
46c2e20a00d385cafd2b42cfc9a484c82d8d1673 | Kuehar/LeetCode | /Merge Two Sorted Lists.py | 2,337 | 4.15625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
return l1 or l2
if l1.val >= l2.val:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
else:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
# Runtime: 32 ms, faster than 89.62% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 13.8 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
temp = ans = ListNode(0)
while l1 or l2:
if l1 and l2:
if l1.val < l2.val:
ans.next = l1
l1 = l1.next
else:
ans.next = l2
l2 = l2.next
elif l1:
ans.next = l1
l1 = l1.next
elif l2:
ans.next = l2
l2 = l2.next
ans = ans.next
return temp.next
# Runtime: 28 ms, faster than 97.54% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 13.9 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
temp = ans = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
ans.next = l1
l1 = l1.next
else:
ans.next = l2
l2 = l2.next
ans = ans.next
ans.next = l1 or l2
return temp.next
# Runtime: 36 ms, faster than 70.49% of Python3 online submissions for Merge Two Sorted Lists.
# Memory Usage: 14 MB, less than 6.61% of Python3 online submissions for Merge Two Sorted Lists. | true |
021a3ff57c2043f16ee2445cd28a3cc3c6075793 | tuncyureksinan/Learn-Python-The-Hard-Way | /ex19.py | 1,376 | 4.21875 | 4 | # Create a cheese_and crackers function that takes two arguments
def cheese_and_crackers(cheese_count, boxes_of_crackers):
# Insert the first argument into a formatted string and display it
print "You have %d cheese!" % cheese_count
# Insert the second argument into a formatted string and display it
print "You have %d boxes of crackers!" % boxes_of_crackers
# Display a string
print "Man that's enough for a party!"
# Display a string with a new line character at the end
print "Get a blanket.\n"
# Display a string
print "We can just give the function numbers directly:"
# Call the cheese_and_crackers function with numbers
cheese_and_crackers(20, 30)
# Display a string
print "Or, we can use variables from our script:"
# Assign the number 10 to the variable amount_of_cheese
amount_of_cheese = 10
# Assign the number 50 to the variable amount_of_crackers
amount_of_crackers = 50
# Call the cheese_and_crackers function using variables
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# Display a string
print "We can even do math inside too:"
# Call the cheese_and_crackers function with math
cheese_and_crackers(10 + 20, 5 + 6)
# Display a string
print "And we can combine the two, variables and math:"
# Call the cheese_and_crackers function with math, numbers and variables
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 100) | true |
ffa61ec616a5f6dcd566a0a40826af5e04064054 | MayWorldPeace/QTP | /Python基础课件/代码/第五天的代码/08-函数返回值之多个return.py | 753 | 4.3125 | 4 |
# 定义一个函数 当执行函数的时候 传入一个分数 可以返回一个字符串 (优 良 中 差)
# 包含多个return
def my_func(score):
# 对分数进行判断
if score >= 90:
return "优"
elif score >= 80:
return "良"
elif score >= 60:
return "中"
elif score >= 0:
return "差"
# 他不会执行 因为在第11行已经执行了return
print("测试")
ret = my_func(89)
print(ret)
def my_func1():
print("开始")
# 只要函数中执行了return 提前结束函数的执行 而且return后面的代码将不再执行
return "3.14"
print("开始1")
return 20
print("结束")
ret = my_func1()
print(ret)
print("测试")
"""
开始
3.14
测试
""" | false |
c5cef9ad6e079c63526b968b4b90f4ab991bab9c | MayWorldPeace/QTP | /Python基础课件/代码/第二天的代码/07-while循环.py | 362 | 4.5 | 4 | """
定义一个变量
while 判断条件(变量的判断)
如果判断条件满足执行的代码
对变量的值进行修改
# 不可以停止的循环(判断条件一直满足) 称之为死循环
"""
# 定义一个变量 记录循环次数
i = 0
while i < 5:
print("第%d次" % (i + 1))
print("你好龟叔")
i += 1
print("测试")
| false |
bee6e20208c00d75f29a168675bc0535181cb331 | pranalinamdas934/Python-Practice | /Collections/tuple.py | 1,015 | 4.5 | 4 | """A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets."""
this_tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(this_tuple)
print(this_tuple[1])
print(this_tuple[2:4])
print(this_tuple[-4:-1])
"""If you want tot change tuple values, you can convert tuple into list."""
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
"""you can loop through the items using for loop"""
x = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
for x in this_tuple:
print(x)
"""unpacking of tuple"""
(first, second, third, *rest) = this_tuple
print(first, second, third, rest)
# why tuple doesn't have append?
"""Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed. """
# tuple deconstruction example
point = 10, 20, 30
x, y, z = point
print(x, y, z)
b = ("Bob", 19, "CS")
(name, age, studies) = b # tuple unpacking
name
| true |
8aec0bdd980f0a39ddeb7a5094330f29274b5bf9 | dreamerHarshit/startxlabs | /semordnilap.py | 1,105 | 4.78125 | 5 | '''3. According to Wikipedia, a semordnilap is a word or phrase that spells a different word or phrase backwards. ("Semordnilap" is itself "palindromes" spelled backwards.) Write a semordnilap recogniser that accepts a file name (pointing to a list of words) from the user an d finds and prints all pairs of words that are semordnilaps to the screen. For example, if "stressed" and "desserts" is part of the word list, the the output should include the pair "stressed desserts". Note, by the way, that each pair by itself forms a palindrome!'''
file_name = 'semordnilap_test.txt' #test cases are stored in semordnilap_test.txt
f = open(file_name,"r")
d = {} #creating dictionary
words = []
for line in f:
words.append(line.rstrip())
for word in words:
d[word] = 1
for word in words:
'''checking if word is present in dictionary d and if its reverse is present in dictionary word '''
if word in d and d[word] == 1 and word[::-1] in d and d[word[::-1]] == 1:
d[word] = 2
for word in d:
if d[word] == 2:
print word, word[::-1]
| true |
3d60782389d03fa3a9df563ba1df3eeda51848e3 | tommypatten1/project-portfolio | /green bottles.py | 566 | 4.28125 | 4 | n= int(input("how many bottles would you like on the wall"))# takes the input from the user and stores it as an integer for later recall
while n>0: #loops until all the bottles fall off
print ((n),"green bottles Hanging on the wall Ten green bottles Hanging on the wall And if one green bottle Should accidentally fall There'll be"
,(n-1),"green bottles Hanging on the wall")
# the print function displays the songs with the inbuilt math which allows for the numbers of bottles to change
n=n-1 # this math equation minus' one bottle
| true |
037147776f033fb480ba2940dcedad75346d7070 | Vasallius/Python-Journey | /Automate the Boring Stuff With Python/Ch3-Functions/collatz_sequence.py | 369 | 4.34375 | 4 | # The Collatz Sequence
print('Input a number.')
def collatz(number): # function takes in user input number
if number % 2 == 0:
return number // 2
elif number % 2 == 1:
return 3 * number + 1
number = int(input())
result = collatz(number)
print(result)
while result != 1: # Looping mechanism
result = collatz(result)
print(result)
| true |
6efb3bf34b8ab2d69a09985faa0adde77f7218c3 | Vasallius/Python-Journey | /Data Structs and Algos/Chapter 1/Creativity/C1.22.py | 437 | 4.1875 | 4 | '''
Write a short Python program that takes two arrays a and b of length n
storing int values, and returns the dot product of a and b. That is, it returns
an array c of length n such that c[i] = a[i] · b[i], for i = 0, . . . ,n−1.
'''
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 2, 1, 2]
length = len(array1)
def function(array1, array2):
return [array1[x] * array2[x] for x in range(0, length)]
print(function(array1, array2))
| true |
c3f6dcb41de650283d826ac14feea0e2567bd3ea | Vasallius/Python-Journey | /Data Structs and Algos/Chapter 1/Creativity/C1.20.py | 868 | 4.15625 | 4 | '''
Python’s random module includes a function shuffle(data) that accepts a
list of elements and randomly reorders the elements so that each possible
order occurs with equal probability. The random module includes a
more basic function randint(a, b) that returns a uniformly random integer
from a to b (including both endpoints). Using only the randint function,
implement your own version of the shuffle function.
'''
import random
def shuffle(listofelements):
length = len(listofelements)
newlist = []
indexes = []
newlist = [x for x in listofelements]
for x in listofelements:
index = random.randint(0, length-1)
while index in indexes:
index = random.randint(0, length-1)
indexes.append(index)
newlist[index] = x
print(listofelements)
print(newlist)
shuffle([1, 2, 3, 4, 5, 6, 67, 8])
| true |
a92c2a4cf4b8407cddb62137abebb8c847bd5b9a | venkateshvsn/patterns | /package/numbers/seven.py | 644 | 4.25 | 4 | def for_SEVEN():
"""printing number 'SEVEN' using for loop"""
for row in range(7):
for col in range(6):
if col==3 or row==0 and col not in(4,5) or row==3 :
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_SEVEN():
"""printing number 'SEVEN' using while loop"""
i=0
while i<5:
j=0
while j<6:
if j==3 or i==0 and j not in(4,5)or i==2:
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
i+=1
print()
| false |
78f54dcf93540225c38a91c74569406be405225b | venkateshvsn/patterns | /package/alphabets/capital_alphabets/Q.py | 795 | 4.125 | 4 | def for_Q():
"""printing capital 'Q' using for loop"""
for row in range(5):
for col in range(6):
if col==0 and row not in(0,4) or col==4 and row not in(0,4) or row==0 and col in(1,2,3)or row==4 and col not in(0,4) or row==2 and col==3:
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_Q():
"""printing capital 'Q' using while loop"""
i=0
while i<5:
j=0
while j<6:
if j==0and i not in(0,4) or i==0 and j not in(0,4,5)or i==4 and j not in(0,4)or j==4 and i not in(0,4)or j==2 and i==2:
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
i+=1
print()
| false |
38d9d9550d65299e59cc89cc23aa295f6ead8e22 | venkateshvsn/patterns | /package/symbols/diamand.py | 716 | 4.3125 | 4 |
def for_DIAMAND():
"""printing symbole 'DIAMAND' using for loop"""
for row in range(7):
for col in range(7):
if col==3 or row==3 or col in(2,4) and row not in(0,6) or row in(2,4) and col not in(0,6):
print("*",end=" ")
else:
print(" ",end=" ")
print()
def while_DIAMAND():
"""printing symbole 'DIAMAND' using while loop"""
i=0
while i<7:
j=0
while j<7:
if j==3 or i==3 or j in(2,4) and i not in(0,6) or i in(2,4) and j not in(0,6):
print("*",end=" ")
else:
print(" ",end=" ")
j+=1
i+=1
print()
| false |
fcf19632f400f730e88ad6868576dc887f9a2155 | ahmedali7997/first_try | /100when.py | 726 | 4.15625 | 4 | # Exercise 1 - Ahmed Ali
# This project asks for your name and age, then tells you in what year you'll turn 100. It then asks how many times you want to repeat the previous statement, and repeats it by the given amount.
#get the current year
import datetime
now = datetime.datetime.now()
#inputs from user
name = input("What is your name?")
age = input("How old are you?")
#calculates when user will turn 100
hundred = 100-int(age)
hundred_year = now.year+hundred
#returns statement
statement = "Wow {}, you'll turn 100 years old in {} \n".format(name,hundred_year)
print(statement)
#asks for repititon and prints it
repeat = input("How many times do you want to repeat the previous message?")
print(statement*int(repeat))
| true |
1b6caf18ce54675896a19bb8603eff041685af0f | kaistullich/Codewars-Challenges-Answers | /detect_pangram.py | 895 | 4.125 | 4 | import string
from collections import Counter
def is_pangram(s):
"""
A pangram is a sentence that contains every single letter of the alphabet at least once. For example,
the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters
A-Z at least once (case is irrelevant).
Given a string, detect whether or not it is a pangram. Return True if it is, False if not.
Ignore numbers and punctuation.
:param s: The string to check for pangram
:return: True or False
"""
stripped = ''.join([i.lower() for i in s if i.isalpha()])
c = Counter(stripped)
if c.most_common(1)[0][1] > 1:
if sorted(c) == list(string.ascii_lowercase):
return True
else:
return False
else:
return True
if __name__ == '__main__':
print(is_pangram('abcdefghijklmopqrstuvwxyz'))
| true |
8788c3a56924041c1cd71c75dff35328417b2112 | khalid-hussain/python-workbook | /02-Decision-Making/040-sound-levels.py | 697 | 4.34375 | 4 | sound = int(input('Input sound level (dB): '))
if sound > 130:
result = 'Sound is louder than a jackhammer.'
elif sound == 130:
result = 'Sound is equal to a jackhammer.'
elif sound > 106:
result = 'Sound is between a jackhammer and gas lawnmower.'
elif sound == 106:
result = 'Sound is equal to gas lawnmower.'
elif sound > 70:
result = 'Sound is between a gas lawnmower and an alarm clock.'
elif sound == 70:
result = 'Sound is equal to an alarm clock.'
elif sound > 40:
result = 'Sound is between an alarm clock and a quiet room.'
elif sound == 40:
result = 'Sound is equal to a quiet room.'
else:
result = 'Sound is less than a quiet room.'
print(result)
| true |
8d5e7cdb48a8edbddde312d57eb3ccbadb79e0f2 | khalid-hussain/python-workbook | /04-Functions/094-valid-triangle.py | 844 | 4.4375 | 4 | # Find out if three edges can form a valid triangle
# @param a first side
# @param b second side
# @param c third side
# @return boolean true if possible, false otherwise
def isValidTriangle(a, b, c):
if (a <= 0) or (b <= 0) or (c <= 0):
return False
else:
# If any one length is greater than or equal to the sum of
# the other two then the lengths cannot be used to form a
# triangle. Otherwise they can form a triangle.
if (a >= (b + c)) or (b >= (a + c)) or (c >= (a + b)):
return False
else:
return True
def main():
a = int(input('Input first side: '))
b = int(input('Input second side: '))
c = int(input('Input third side: '))
print(f'Your sides create a valid triangle: {isValidTriangle(a, b, c)}')
if __name__ == "__main__":
main()
| true |
5aa870ff32c8856d98d7bb79993bebc3e9a15c1a | jennifro/calculator-2 | /calculator.py | 1,833 | 4.28125 | 4 | from arithmetic import *
# Your code goes here
def calculator(user_input):
"""Makes a REPL for the prefix calculator.
Takes user's input, parses the mathematical operator & numerical
values. Function calls referenced refer to arithmetic.py. Tells calculator
to process numbers & print the result.
"""
calculator_input = user_input.split(" ") # creates list from user's input
math_operator = calculator_input.pop(0) # stores math operator in own variable
for i in range(len(calculator_input)):
calculator_input[i] = int(calculator_input[i]) # remaining values are typecast as integers
if math_operator == "q": # ability to (q)uit the calculator process
return
elif math_operator == "+":
added_numbers = add(calculator_input[0], calculator_input[1])
print added_numbers
elif math_operator == "-":
subtracted_numbers = subtract(calculator_input[0], calculator_input[1])
print subtracted_numbers
elif math_operator == "*":
multiplied_numbers = multiply(calculator_input[0], calculator_input[1])
print multiplied_numbers
elif math_operator == "/":
divided_numbers = divide(calculator_input[0], calculator_input[1])
print divided_numbers
elif math_operator == "square":
squared_numbers = square(calculator_input[0])
print squared_numbers
elif math_operator == "cube":
cubed_numbers = cube(calculator_input[0])
print cubed_numbers
elif math_operator == "power":
exponent_numbers = power(calculator_input[0], calculator_input[1])
print exponent_numbers
elif math_operator == "mod":
remainder_numbers = mod(calculator_input[0], calculator_input[1])
print remainder_numbers
calculator("cube 104")
| true |
a9f37bd56cc84b634621ee0cb5a8ccc0109eac0a | samahDD/MITx6.00.1x_IntroToCS | /iterPower.py | 473 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 13:32:31 2019
@author: peter
"""
def iterPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
result = 1
while exp > 0:
result *=base
exp -= 1
return result
base=10
exp=3
answer=iterPower(base,exp)
print('Base :',base)
print('exp :', exp)
print('Answer :', answer) | true |
f7b1c7c5cf6751a0f6a385dc31e9021650987b2a | Slavik0041/BelHard_education | /bh_5_tasks-Sherlat_ready/easy/generators/factorial.py | 571 | 4.28125 | 4 | """
Написать генератор factorial, который возвращает подряд числа факториала
Например:
factorial_gen = factorial()
next(factorial_gen) -> 1
next(factorial_gen) -> 2
next(factorial_gen) -> 6
next(factorial_gen) -> 24
"""
def factorial():
a = 1
for number in range(1, 10):
a *= number
yield a
factorial_gen = factorial()
print(factorial_gen)
print(next(factorial_gen))
print(next(factorial_gen))
print(next(factorial_gen))
print(next(factorial_gen))
print(next(factorial_gen))
| false |
681ebaca7ed8ac2f0b83e2fa8d6d660b955298f0 | Slavik0041/BelHard_education | /bh_5_tasks-Sherlat_ready/easy/functions/even_numbers.py | 798 | 4.46875 | 4 | """
Написать функцию get_even_number, которая принимает 1 аргумент - номер
четного числа и возвращает само четное число
Например:
- get_even_number(10) -> 20
- get_even_number(3) -> 6
"""
def get_even_number(number: int) -> int:
return number * 2
print(get_even_number(10))
"""
Не совсем понял условие(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10 -> находится на 5й позиции четных чисел
Нам нужно вводить порядковый номер четного числа (исключая не четные)
и выводить само четное ?
"""
if __name__ == '__main__':
assert get_even_number(5) == 10
print('Решено!')
| false |
33b22dd098a35d9e0cedb9582b686ddb1412af4c | Slavik0041/BelHard_education | /bh_4_tasks-Sherlat_ready/medium/unique_in_list.py | 669 | 4.21875 | 4 | """
ЗАДАНИЕ
--------------------------------------------------------------------------------
Написать программу, которая проверит, все ли элементы в списке уникальны
ПРИМЕРЫ
--------------------------------------------------------------------------------
is_unique([2, 1, 5, 4, 7]) -> True
is_unique([2, 1, 5, 4, 2]) -> False
"""
def is_unique(array: list) -> bool:
if len(set(array)) != len(array):
return False
else:
return True
if __name__ == '__main__':
assert is_unique([2, 1, 5, 4, 7])
assert not is_unique([2, 1, 5, 4, 2])
print('Решено!')
| false |
e71ba4e1aff99cf09d1f74d8593b40fa68848cf2 | Slavik0041/BelHard_education | /bh_5_tasks-Sherlat_ready/medium/common_numb.py | 658 | 4.1875 | 4 | """
Написать функцию common_numbers, которая принимает 2 списка, которые содержат
целые числа.
Функция должна вернуть список общих чисел, который отсортирован по убыванию
"""
list_1 = [1, 4, 13, 18, 34, 8, 6]
list_2 = [8, 13, 7, 1, 35, 96, 7]
def common_numbers(list_one: list, list_two: list):
some_list = []
for i in list_one:
for j in list_two:
if i == j:
some_list.append(i)
break
return sorted(some_list, reverse=True)
print(common_numbers(list_1, list_2))
| false |
85aaa170df7c701111538c8ba99ba8783aab1db1 | Slavik0041/BelHard_education | /bh_5_tasks-Sherlat_ready/hard/simple_odd.py | 1,050 | 4.34375 | 4 | """
Написать 2 генератора:
1) Генератор simple_number первый идет по всем простым числам
(число делится только на 1 и на само себя)
2) Генератор odd_simple, который используется значения первого и возвращает
из них нечетные
"""
def simple_number():
for i in range(2, 100):
for j in range(2, i):
if i % j == 0:
break
else:
yield i
number = simple_number()
print(number)
print('Простые числа: ')
print(next(number))
print(next(number))
print(next(number))
print(next(number))
def odd_simple():
for i in number:
if i % 2 == 0:
break
else:
yield i
simple = odd_simple()
print(simple)
print('Простые не четные числа: ')
print(next(simple))
print(next(simple))
print(next(simple))
print(next(simple))
print(next(simple))
print(next(simple))
print(next(simple)) | false |
fa6e26f75355a03b2791b674a2eb0bce258d6412 | Slavik0041/BelHard_education | /bh_3_tasks-Sherlat_ready/tasks/set_frozenset/difference.py | 716 | 4.5 | 4 | """
ЗАДАНИЕ
--------------------------------------------------------------------------------
Написать функцию, которая вернет только те элементы,
которые есть только в первом множестве и нет во втором, не изменяя множества
"""
def diff(set_1: set, set_2: set) -> set:
# TODO вставить код сюда
result = set_1.difference(set_2)
return result
if __name__ == '__main__':
some_set = {1, 2, 3, 4}
another_set = {3, 4, 5}
assert diff(some_set, another_set) == {1, 2}
assert some_set == {1, 2, 3, 4}
assert another_set == {3, 4, 5}
print('Решено!')
| false |
ae91f208ec1ef742dc1ff3503c6e1bc82e7a9e10 | Slavik0041/BelHard_education | /bh_3_tasks-Sherlat_ready/tasks/set_frozenset/common_elements.py | 550 | 4.3125 | 4 | """
ЗАДАНИЕ
--------------------------------------------------------------------------------
Написать функцию, которая получает 2 списка и возвращает общие уникальные
элементы этих списков
"""
def common_elements(list_1: list, list_2) -> set:
result = set(list_1 + list_2)
# TODO вставить код сюда
return result
if __name__ == '__main__':
assert common_elements([1, 2, 3], [2, 3, 4]) == {1, 2, 3, 4}
print('Решено!')
| false |
9070db977cc1b6f6d7443db56c15c3b3baab7250 | Avikr20/Snake-water-and-Gun-Game | /Snake_water_gun_game.py | 1,262 | 4.15625 | 4 | #################################################
########### SNAKE WATER AND GUN GAME ############
#################################################
import random
def gamewin(computer, you):
if computer == you:
return None
elif computer == "s":
if you == "w":
return False
elif you == "g":
return True
elif computer == "w":
if you == "s":
return True
elif you == "g":
return False
elif computer == "g":
if you == "s":
return False
elif you == "w":
return True
print("############## GAME MODE ON ##############")
print("Computer Turn : Snake(s) Water(w) or Gun(g)?\n")
randomNo = random.randint(1,3)
if randomNo == 1:
computer = 's'
elif randomNo ==2:
computer = 'w'
elif randomNo == 3:
computer = 'g'
you = input("Your Turn : Choose (s) for Snake, (W) for Water or (g) for Gun? : ")
game = gamewin(computer, you)
print("\nComputer choosen : ", computer)
print("You choosen : ", you)
print("\n############## Game Result ##############\n")
if game == None:
print("The game is a tie!\n")
elif game:
print("You Win!\n")
else:
print("You Lose!\n") | false |
60db215029cd4a9958604552fec3caee77638fce | anaypaul/LeetCode | /SearchRotatedArray.py | 1,858 | 4.375 | 4 | def getPivot(arr):
"""
This method gets the index of the element from where the array has be rotated.
ie the pivot element.
The idea is to get the pivot location in the array and split the array into 2 to search
for the target element in the 2 arrays.
"""
if(len(arr)==0):
return -1
elif len(arr) == 1:
return 0
elif len(arr) == 2:
if arr[0] > arr[1]:
return 0
else:
return 1
else:
low = 0
high = len(arr) - 1
while(low <= high):
mid = int((low + high)/2)
if mid+1 < len(arr) and arr[mid] > arr[mid+1] and arr[mid] > arr[mid-1]:
break
elif mid+1 < len(arr) and arr[high] < arr[low]:
high = mid -1
else:
low = mid + 1
return mid
def binarySearch(arr,low, high, key):
"""
Simple binary search implementation to search for a key in a sorted array.
"""
if(low<=high):
mid = int((low + high)/2)
if arr[mid] == key:
return mid
elif arr[mid] > key:
return binarySearch(arr, low, mid-1,key)
elif arr[mid] < key:
return binarySearch(arr, mid+1, high,key)
else:
return -1
def search(arr, target):
"""
This is the method that searches for a target element in the sorted and rotated array.
"""
if(len(arr)==0):
return -1
pivot_index = getPivot(arr)
left = arr[:pivot_index+1]
right = arr[pivot_index+1:]
ans_left = binarySearch(left, 0,len(left)-1,target)
ans_right = binarySearch(right, 0, len(right)-1,target)
if ans_left == -1 and ans_right == -1:
return -1
elif ans_left != -1 and ans_right == -1:
return ans_left
else:
return ans_right + len(left)
| true |
ccb13bd908b5307b0209413b7c1e71e5dcdb3cba | ymadh/python-practice | /strings.py | 555 | 4.25 | 4 | # course = "python programming"
# print(len(course))
# # strings are immutable
# print(course[0]) # creates new memory and copies chars into that new memory
# print(course[-1])
# print(course[0:3])
# print(course[:3])
# print(course[0:])
# print(course[:])
first = "amy"
last = "wightman"
# full = first + " " + last
# formatted string
full = f"{first} {last}"
print(full)
course = " Python Programming"
print(course.strip())
# case sensitive
print(course.find("pro"))
# replace
print("Programming" in course)
print("Programming" not in course)
| true |
43806ca94b5f1305e078e9029b9e1033e5fb0fdd | ymadh/python-practice | /datastructure/tuple.py | 384 | 4.15625 | 4 | # tuple is read only list
point = (1, 2)
# point = 1, 2 works as well
# point = 1,
# point = ()
point = (1, 2) + (3, 4)
print(point)
point = (1, 2) * 3
print(point)
point = tuple([1, 2])
point = tuple("Hello World")
print(point[0:2])
# unpack
x, y = point
print(x)
# can't do point[0] = 10;
# cant add or remove an object
# tuples are used for a seq of objects that doesnt change
| true |
8a3ec5a061646dc9de782f8fc56e944b575d4793 | rohitshakya/CodeBucket | /2. Coding_Problems/Python's assignmemt/three_number.py | 434 | 4.1875 | 4 | #
# Author : Kajal Shakya
# Date : Jan-2021
# IDE : Python Idle 3.7
# Time complexity : O(1)
# Title : Larger of three numbers
#
num1=int(input("enter the first number:"))
num2=int(input("enter the second number:"))
num3=int(input("enter the third number:"))
if(num1>=num2) and (num1>=num3):
print("num1 is larger")
elif(num2>=num1) and (num2>=num3):
print("num2 is larger")
else:
print("num3 is larger")
| true |
2c9d8e83fd15b07d45ae5cfb6892c07db127a65e | p00j4/python-experiments | /recursion/d1_print_n_nums.py | 519 | 4.4375 | 4 | """
Day 1 to recursion
Print 1 to n numbers without using a loop
"""
"""
Intution: Recursion is the alternative way to simulate a loop
Think n -> n-1 -> n-2 .... 1
- Base
- Hypothesis
- Decision/Induction
"""
# 1. Print in ascending order
def print_n_nums(n):
if n == 1:
print(1)
return
print_n_nums(n - 1)
print(n) #when it starts returning will keep printing in the ascendind order
# 2. Print in descending order
def print_n_nums(n):
print(n)
if n == 1:
return
print_n_nums(n - 1)
| true |
26be3c7d160f89d8845f7921787eb3063c7ca537 | wkarney/advent-of-code-2020 | /9/day9.py | 1,461 | 4.15625 | 4 | #!/usr/bin/env python
"""
Advent of Code 2020, day 9
Will Karnasiewicz
"""
import itertools
def find_pairs_that_sum(lst, target):
"""Helper function to find pairs that sum to a number"""
return [pair for pair in itertools.combinations(lst, 2) if sum(pair) == target]
# Part 1
def find_first_invalid_value(data_input, preample_size):
"""Find first value that is not the sum of two of the most
recent numbers given by the preamble size"""
for i, val in enumerate(data_input):
if i < preample_size:
continue
if find_pairs_that_sum(data_input[i - preample_size : i], val):
continue
return val
# Part 2
def find_pt2(data_input, invalid_value):
"""Find answer to part 2"""
cumsum_data = list(itertools.accumulate(data_input))
for i in range(len(data_input)):
if cumsum_data[i] < invalid_value:
continue
for j in range(i):
if cumsum_data[i] - cumsum_data[j] == invalid_value:
return min(data_input[j + 1 : i + 1]) + max(data_input[j + 1 : i + 1])
print("Something went wrong; encryption weakness not found")
return None
if __name__ == "__main__":
# Input Data
with open("./input.txt") as f:
input_data = [int(line) for line in f]
first_invalid_value = find_first_invalid_value(input_data, 25)
print(f"Part 1: {first_invalid_value}")
print(f"Part 2: {find_pt2(input_data, first_invalid_value)}")
| true |
38f10e2543daae97fc90659856d675bd159a2d64 | momentum-cohort-2019-02/w2d2-palindrome-dmm4613 | /palindrome.py | 1,362 | 4.3125 | 4 |
def strip_input(name):
"""This will lowercase all letters and then strip nonletters from the string"""
import re
print ("strip_input was called")
#.lower will take the entire string and make all cases lower
name = name.lower()
print(name)
#.replace takes every white space and makes it 'None' or empty
name = name.replace(" ","")
print(name)
#re.sub takes the sub function from re and transform all special characters to 'None' or empty.
name = re.sub(r'[^a-zA-Z0-9 ]',r'',name)
print(name)
return name
def is_palindrome(name):
"""compares the parameter string and its reverse to see if it's palindrome"""
print ("is_palindrome was called")
#name[begin:end:step] is outputting the string 'name' in reverse.
if strip_input(name) == strip_input(name[::-1]):
return print("is a palindrome!")
else:
return print("is not a palindrome!")
while True:
name = input("Enter a word or sentence and see if it's palindrome [type 'quit' to end]: ")
#if the user inputs 'quit' the loop will terminate
if name == 'quit':
break
#if the user does not enter anything, they will be prompted to retry, and the loop will restart
if name == "":
print ("You didn't enter anything, let's start over!")
continue
is_palindrome(name)
| true |
d8cff05cef2e35f79cdf12b7ec707c151a3f41df | Ranjan-kumar-97/just-coding | /leap_year.py | 272 | 4.1875 | 4 | def leap_year():
n = int(input("Please Enter a Year: "))
if n%4==0:
if n%100==0 and n%400==0:
print(n," is a Leap Year")
else:
print(n, " is not a Leap Year")
else:
print(n, " is not a Leap Year")
leap_year()
| false |
b5b0e353764ec9e3df369a41865f5d39eccf5efa | Parth731/W3SCHOOL | /python/python tut/2_Variable.py | 1,063 | 4.3125 | 4 |
#create variable
x = 5
y = "John"
print(x)
print(y)
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
#Illegal variable names:
# 2myvar = "John"
# my-var = "John"
# my var = "John"
#assign multiple value
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
x = y = z = "Orange"
print(x)
print(y)
print(z)
#output value
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = 5
y = 10
print(x + y)
# error
# x = 5
# y = "John"
# print(x + y)
#global variable
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
###################
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
#global keyword
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
####################
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
| false |
f411fa6065f3488c52e91c9b440979be76512d97 | py1-10-2017/Sarah.Grayer.py1.2017 | /Python Basics/DictInTuplesOut.py | 600 | 4.34375 | 4 | def tupleout(): #prints 3 lists with the key/val pairs as the data (for loop)
mydict = {
"Speros": "(555)555-5555",
"Michael": "(999)999-9999",
"Jay": "(777)777-7777"
}
for key, value in mydict.iteritems():
dictlist = ([key, value])
print dictlist
tupleout()
def tupleout2(): #prints one list with the key/val pairs as tuples
mydict = {
"Speros": "(555)555-5555",
"Michael": "(999)999-9999",
"Jay": "(777)777-7777"
}
mydict.items()
tuplelist = [(key, value) for key, value in mydict.iteritems()]
print tuplelist
tupleout2()
| true |
8d66f6177e09451fc84a8b49aa9965f531127186 | AchWheesht/Python | /pygame/programarcadegames/labs/Chapter1Labs/biblicalspherecalculator/program.py | 408 | 4.53125 | 5 | """This program calculates the volume of a sphere according to the biblical value of pi"""
#The formula to calculate the volume of a sphere is:
#Volume = (4 * pi * (r**3)) / 3
biblical_pi = 3
radius = int(input("Please enter the sphere's radius:\n"))
volume = (4 * biblical_pi * (radius**3)) / 3
print ("The volume of the sphere, as according to the most holy lord on high, is %s units cubed." % (volume))
| true |
2bbd5ad664d0773a7440258a327b18d512c681e4 | AntonYermilov/fall-2019-paradigms | /practice1/small_tasks/examples/bug.py | 569 | 4.1875 | 4 | """
Задача 1.
Найти количество клеток, достижимых на циклическом поле размера n x n, если разрешено ходить только по диагонали
"""
def solve(n: int) -> int:
"""Some code here"""
""" Step 2. """
# if n % 2 == 0:
# return n * n // 2
"""Some code here"""
""" Step 1. """
# if n == 0:
# return -1
"""Some code here"""
""" Step 0. """
return n * n
if __name__ == '__main__':
n = int(input())
print(solve(n))
| false |
0f3ce7aa191527ae46a256c26b4c988914f81cbf | allanstone/cursoSemestralPython | /TerceraClase/listas.py | 2,206 | 4.40625 | 4 | ########
# Listas
########
#Son tipos de datos llamados colecciones, porque contienen otros tipos de datos y aparte a si mismos
lista=[]
print(type(lista))
#Son diferentes a las cadenas ya que si soportan asignación por elemento
cadena="alan"
print(type(cadena))
#Las cadenas no soportan este tipo de asignaciones
#cadena[0]="A"
numeros=[1,2,3,4,5]
#Pero si se pueden acceder a los elementos
print(numeros[2])
print(cadena[2])
#Las listas se puede modificar uno de ellos
numeros[2]=10
print(numeros[2])
#Podemos usar cualquier objeto dentro de estas incluso otras listas
nuevaLista=[123,545.324,numeros,"hola",True]
print(nuevaLista)
#Accedemos a la lista interna desde la externa de esta manera
nuevaLista[2][2]=3
print(nuevaLista)
#Las listas son bastante expresivas
lenguajes=["python","java","c++","perl","ruby"]
#Y podemos recorrerlas de estas dos maneras
#for x in range(0,len(lenguajes)):
# print(lenguajes[x])
#Con un ciclo for each se usa una variable temporal que solo es utilizable desde el ciclo
for lenguaje in lenguajes:
print(lenguaje)
#Y podemos usarla para realizar operaciones
acum=0
for num in numeros:
acum+=num
#Recordar que es lo mismo que acum=num+acum
print("Acumulador: ",acum)
#Utilizar objetos que no son indexables con esta notación causará un error
#acum[0]=0
#SLICING
#Obtiene una porción de la lista... nombreLista[inicio:fin-1:paso]
#Se parece mucho a como usamos el range()
#Si no se tienen los indices se toma el resto por omisión
print(lenguajes[:])
letras=["a","b","c","d"]
#Agregamos a la lista con append al final
letras.append("e")
print(letras)
#Y sacamos el último que entró con pop
letra=letras.pop()
print(letra)
#Si no se asigna a una variable se pierde el valor
#letras.pop()
#letras.pop()
#letras.pop()
#letras.pop()
#letras.pop()
#letras.pop()
#Si se hace pop de una lista vacia se genera un error
print(letras)
a="A"
#Las listas soportan concatenación y tambíén se puede castear un objeto a una lista
#print([a]+letras)
print(list(a)+letras)
#insertar en un indice especificado
letras.insert("P",0)
print(letras)
| false |
b042b06a28f074eb6fa2c2310546e4f04de25397 | spironan/TekinputGenerator | /py files/Data.py | 1,366 | 4.125 | 4 | # Copyright 2020 by Chua Teck Lee.
# All rights reserved.
#USING SQLITE3 DATABASE TO STORE and READ info
#USING DB FOR SQLITE DATABASE TO EDIT/READ
import sqlite3
from sqlite3 import Error
import Utility
class Input():
def __init__(self, name, filepath, display, fileDisplay, buttonLayout, characterList):
self.name = name
self.filepath = filepath
self.display = display
self.fileDisplay = fileDisplay
self.buttonLayout = buttonLayout
self.characterList = characterList
def create_connection(db_file):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
#data
Inputs = []
conn = create_connection(Utility.MakePath(r'\..\database.db'))
cur = conn.cursor()
cur.execute("SELECT * FROM Inputs")
rows = cur.fetchall()
for row in rows:
if(row[5] != None) :
Inputs.append( Input(row[0], row[1], row[2], row[3], tuple(eval(row[4])), row[5].split(',') ))
else:
Inputs.append( Input(row[0], row[1], row[2], row[3], tuple(eval(row[4])), row[5] ))
characters = []
cur.execute("SELECT * FROM Characters")
rows = cur.fetchall()
for row in rows:
characters.append(row[0])
# characters.append( Input(row[0], row[1], row[2], row[3], tuple(eval(row[4])) )) | true |
a8252ee908e5539e737cd067df7b48e06b9deeb3 | oakejp12/Algos | /DynamicProgramming/ExchangeRates/BellmanFord.py | 2,761 | 4.3125 | 4 | '''
An implementation of the Bellman-Form algorithm:
Finding the shortest path in a directed graph G
from a starting node s to all nodes z in the set
of vertices V.
'''
from Graph import Graph
from Vertex import Vertex
import sys
from config import root_logger
class BellmanFord:
@staticmethod
def shortest_pairs(G: Graph, s):
'''
A shortest pairs from starting node s
implementation of the Bellman-Ford algorithm
for a directed graph G
'''
# Let V be the set of vertices in G
V = G.get_vertices()
num_vertices = len(V)
# Initialize a 2D array to hold
# distances from starting node s to
# all nodes z
D = [[sys.maxsize for n in range(num_vertices)]
for n in range(num_vertices)]
# Base case for starting node s
# D(0, s) = 0
for index in range(num_vertices):
D[index][0] = 0
# In order to inspect the weighted edges out
# of a source node, we need to reverse G
G_reverse = Graph.reverse_graph(G)
# Since the shortest path P will
# only visit each vertex at most once,
# |P| <= 1
# Iterate on a prefix of P
for i in range(1, num_vertices):
for index_i, vertex in enumerate(V):
# Consider the case where shortest
# path is i - 1 edges
D[i][index_i] = D[i - 1][index_i]
# Now, consider the case where the
# shortest path is i edges
# Get the neighbors of vertex and
# solve for the minimal of shortest paths
vertexNode = G_reverse.get_vertex(vertex)
neighbors = vertexNode.get_connections()
for neighbor in neighbors:
index_j = list(V).index(neighbor)
root_logger.debug("Inspect shortest path from " + vertex +
" to " + neighbor)
current_value = D[i][index_i]
possible_value = D[i - 1][index_j] + \
vertexNode.get_weight(neighbor)
if current_value > possible_value:
D[i][index_i] = possible_value
return D
if __name__ == "__main__":
root_logger.debug("Running main()")
G = Graph()
G.add_vertex("s")
G.add_vertex("a")
G.add_vertex("b")
G.add_vertex("c")
G.add_vertex("d")
G.add_vertex("e")
G.add_edge("s", "a", 5)
G.add_edge("a", "b", 3)
G.add_edge("b", "c", -6)
G.add_edge("c", "a", 2)
G.add_edge("b", "d", 4)
G.add_edge("c", "e", 5)
D = BellmanFord.shortest_pairs(G, "s")
root_logger.debug(D)
| true |
97c4f2141272e9cdea68f5e693de1f4255fd04b2 | EldarAlekhin/Test_n2 | /Script0004.py | 403 | 4.53125 | 5 | #одностроный комментарий
"""
многострочный комментарий
"""
#print(2 ** 3)
"""
multiplication = 2.5 * 2.5 * 2.5
exponentiation = 2.5 ** 3
print(multiplication, exponentiation)
print(type(exponentiation))
"""
#int
#float
print( 3 ** 2 * 12)
print(212 ** 2 - 121 ** 2 )
exponentiation = 2.0 ** 3
print(type(exponentiation))
#print "asdasdasd"
| false |
55eca78ad6726fb8656bdf0a278cc3719061371a | yuanxu1990/studyday | /day13/day13a.py | 2,846 | 4.21875 | 4 | '''
迭代器
什么是迭代
迭代是一个重复的过程,
并且每次重复都是基于上一次的结果而来
迭代器 :
迭代取值的工具。不依靠索引取值
可迭代的对象执行.__iter__方法得到的返回值就是迭代器对象
优点:
提供了一种不依赖索引的取值方式
'''
# lista=[1,2,3]
#索引查询
#循环for 查询
'''
可迭代的对象
已知可被for循环的类型
str
list
dict
set
tuple
f=open()
range()
enumerate
可迭代对象加
.__iter__ 方法就是一个迭代器 >>>[].__iter__ >>>>通过next就可以从迭代器中一个一个的取值
只要含有 __iter__方法的都是可迭代的—————可迭代协议
迭代器协议 -----内部含有__next__和__iter__方法的就是迭代器
'''
#告诉我传入的数据类型所拥有的所有方法
# print(dir({}))
# print(dir([]))
# print(dir(''))
# print(dir(range(10)))
# rest=set(dir([]))&set(dir([]))&set(dir(''))&set(dir(range(10)))
# print(rest)
# print(dir(int))
# # 双下方法 是内置方法 是c语言写好的 并不止一种方法可以调用
# print([1].__add__([2]))
# print([1]+[2])
#
# lista=[1,2,3,'abc']
# iterators=lista.__iter__()
# #迭代器本身执行.__iter__()方法返回迭代器本身
# # 文件类型本身就是迭代器对象,因为可以直接调用.__next__方法
# print(iterators.__iter__())
# print(iterators.__next__())
#print(iterators.__length_hint__())
#for 循环成为迭代器循环,in后跟的必须是可迭代对象
# for line in lista: #lista.__iter__() 这里for实际上就执行了下边的while循环
# print(line)
#
# while True:
# try:
# print(iterators.__next__())
# except StopIteration:
# break
#py2和py3的range的区别,py2中直接便利后生成列表,py3中直接返回range对象,在调用.__iter__一个一个取值,节省空间
#优点:迭代器更加的节省内存
# items=range(10000000000000000000000000000)
# print(items)
#缺点: 1取值麻烦,只能以一个取,只能往后取,并且是一次行的 无法使用len获取长度
lista=[1,2,3,'abc']
iterators=lista.__iter__()
iterators_01=iter(lista)
print(iterators_01,"\n",iterators)
print(iterators is iterators_01)
# while True:
# try:
# print(iterators.__next__())
# except StopIteration:
# break
# print("第二次取值》》》》》》》")
# iterators=lista.__iter__()
# while True:
# try:
# print(iterators.__next__())
# except StopIteration:
# break
# # print(dir(lista))
# print(dir(iterators))
# print(set(dir(iterators))-set(dir(lista))) | false |
1207d70a8908c897e8359b4775b52d4c948ab0f2 | lanaGV/Geekbrains | /task_1.py | 303 | 4.15625 | 4 | #task_1.1
user_number_even = int(input("Please, enter an even number: "))
user_number_odd = int(input("Please, enter an odd number: "))
print(f"{user_number_even} is even number.")
print(f"{user_number_odd} is odd number")
user_str = input("Please, enter your name: ")
print(f"Welcome, {user_str}!")
| false |
4784622e375ad7eca0b639b5a37b376267a5b350 | flsing/ITI1120 | /Assignments/Assignment 3/a3_7970742/a3_part2_7970742.py | 1,616 | 4.25 | 4 | import random
def create_board(size):
'''int->list (of str)
Precondition: size is even positive integer between 2 and 52
'''
board = [None]*size
letter='A'
for i in range(len(board)//2):
board[i]=letter
board[i+len(board)//2 ]=board[i]
letter=chr(ord(letter)+1)
random.shuffle(board)
return board
def print_board(a):
'''(list of str)->None
Prints the current board in a nicely formated way
'''
for i in range(len(a)):
print('{0:4}'.format(a[i]), end=' ')
print()
for i in range(len(a)):
print('{0:4}'.format(str(i+1)), end=' ')
def wait_for_player():
'''(None)->None
Pauses the program until the user presses enter
'''
try:
input("Press enter to continue ")
except SyntaxError:
pass
def play_game(board):
'''(list of str)->None'''
create_board(size)
wait_for_player()
# The following line of code creates a list indicating what locations are paired, i.e., discovered
# At the begining none are, so default initializaiton to False is ok
# You may find this useful
discovered=[False]*len(board)
# YOUR CODE GOES HERE
# this is the funciton that plays the game
# MAIN
print("How many cards do you want to play with?")
size=int(input("Enter an even number between 2 and 52: "))
# this creates the board for you of the given size
board=create_board(size)
# this calls your play_game function that plays the game
play_game(board)
| true |
79d27d104162c79840ac5dd3d6136fd3621b2331 | Upasna4/Training | /list.py | 299 | 4.15625 | 4 | datalist=[]
print(datalist)
print(type(datalist))
l=[1,2,0.5,'abc']
print(l)
for i in l:
print(i)
l=[1,2,0.5,'abc']
print(l)
for i in l:
print(l)
l=[1,2,0.5,'abc']
print(l)
# for i in l:
# print(l[i])
print(l[3])
print(l[1:3])
print(l[:2])
print(l[2:3])
print(l[::])
print(l[-1])
| false |
414cd4dcf7c0ec6a4098075477e45925e075b928 | Upasna4/Training | /wordmeaning.py | 411 | 4.25 | 4 | dict1 = {'python':'language','php':'language1'}
word = input("enter a word")
if word in dict1:
print("The meaning of this word is",dict1[word])
else:
word_insert = input("u want to insert the word")
if word_insert == 'y':
word_meaning = input("write meaning of the word")
dict1.update({word:word_meaning})
print(dict1)
print("the meaning of this word is",dict1[word]) | true |
4358e6ee148fbac8b3475485d31343af87c5f3c0 | BioYLiu/ml_bioinformatics | /Ex9/viterbi/viterbi.py | 2,104 | 4.15625 | 4 | #!/usr/bin/python
# encoding: utf8
import numpy as np
from math import log
class HMM():
"""
Very good tutorial: https://web.stanford.edu/~jurafsky/slp3/8.pdf
One of the applications of HMM, is to predict the sequence of state
changes, based on the sequence of observations
A remark on Bayes Probability: If A and B are independent events:
Pr(A|B) = Pr(A)
"""
def __init__(self):
"""
"""
self.sequence = "GGCACTGAA"
self.hidden = []
self.hidden2 = None
self.states = []
self.connectors = None
self.table_probabilities = None
def init_hidden_state(self, total):
"""
The hidden states
"""
self.hidden2 = np.random.rand(total)
for t in range(total):
value = {"value": np.random.uniform()}
self.hidden.append(value)
def create_state(self, a=0, c=0, g=0, t=0):
"""
"""
values = {
"A": log(a, 2), "C": log(c, 2),
"G": log(g, 2), "T": log(t, 2)
}
self.states.append(values)
def init_connectors(self):
# init the connectors
a, b = self.hidden2.size, len(self.states)
self.connectors = np.zeros((a, b)) + 0.5
self.connectors = np.log2(self.connectors, self.connectors)
def compute_probabilities(self):
"""
"""
#print self.sequence
a, b = len(self.states), len(self.sequence)
table = np.zeros((a, b))
summation = 0
for i, element in enumerate(self.sequence):
previous = table[:,i-1].max() if i > 0 else 0
for j, state in enumerate(self.states):
summation += -1 + state[element] + previous
table[j, i] = summation
summation = 0
self.table_probabilities = table
print self.table_probabilities
hmm = HMM()
hmm.init_hidden_state(1)
hmm.create_state(a=0.2, c=0.3, g=0.3, t=0.2)
hmm.create_state(a=0.3, c=0.2, g=0.2, t=0.3)
hmm.init_connectors()
hmm.compute_probabilities()
| true |
2d19b534c7c92ba9f4681245374cc7e15231860b | terehovandrej/Zadachi_Python | /lists/append_sum.py | 496 | 4.4375 | 4 | # Write a function named append_sum that has one parameter — a list named named lst.
# The function should add the last two elements of lst together and append the result
# to lst. It should do this process three times and then return lst.
# For example, if lst started as [1, 1, 2], the final result should be [1, 1, 2, 3, 5, 8].
def append_sum(lst):
counter = 0
while counter < 3:
lst.append(sum(lst[-2:]))
counter += 1
return lst
print(append_sum([1, 1, 2]))
| true |
07797eec6b75a2032c461e59c9c2b18ef4a5a532 | rec/pyitunes | /old/group_numbers_in_radius.py | 1,078 | 4.21875 | 4 | import sys
def group_numbers_in_radius(numbers, radius):
"""Group numbers into sublists with a given radius.
This is used for deduping - we want to make sure that
"""
results, before, after = [], [], []
print('group_numbers_in_radius', numbers, radius)
def emit():
result = before + after
if not results:
results.append(result)
else:
s, r = set(results[-1]), set(result)
if s < r:
results[-1] = result
elif not (r <= s):
results.append(result)
before.append(after.pop(0))
while before and after and before[0] < after[0] - radius:
before.pop(0)
while numbers:
print('while', before, after, results)
end = numbers.pop(0)
while after and after[0] < end - radius:
emit()
after.append(end)
while after:
emit()
return results
if __name__ == '__main__':
numbers = [int(a) for a in sys.argv[1:]]
print(group_numbers_in_radius(numbers, numbers.pop(0)))
| true |
027bffe0b590e9475fd25c51237197c35210dbb1 | zirfuz/python_alg_str | /lesson_3/task_9.py | 691 | 4.25 | 4 | # 9. Найти максимальный элемент среди минимальных элементов столбцов матрицы.
import random
ROWS = 3
COLUMNS = 5
MIN = 1
MAX = 10
F_WIDTH = 2
matrix = [[random.randint(MIN, MAX) for _ in range(COLUMNS)] for _ in range(ROWS)]
for row in matrix:
for item in row:
print(f'{item:>{F_WIDTH}}', end=' ')
print()
print()
max_min = None
for column in range(COLUMNS):
min_ = matrix[0][column]
for row in range(1, ROWS):
item = matrix[row][column]
if item < min_:
min_ = item
print(f'{min_:>{F_WIDTH}}', end=' ')
max_min = min_
print()
print(f'MaxMin: {max_min}')
| false |
b546cc7d547a4c7852cb91c51af38d39543da677 | zirfuz/python_alg_str | /lesson_1/task_1.py | 505 | 4.15625 | 4 | # Начало
# Вывод("Введите трёхзначное число")
# Ввод(Число)
#
# a = value // 100
# b = value // 10 % 10
# c = value % 10
#
# sum = a + b + c
# product = a * b * c
#
# Вывод("Sum = ", sum)
# Вывод("Product = ", product)
# Конец
value = int(input(('Введите трёхзначное число: ')))
a = value // 100
b = value // 10 % 10
c = value % 10
sum = a + b + c
product = a * b * c
print(f'Sum = {sum}')
print(f'Product = {product}')
| false |
abb3ef5b8cb0189580bfac1df3c3f0a028b12536 | andri95/Assignment_5 | /max_int.py | 604 | 4.40625 | 4 |
# Empty variable to hold largest number
max_int = 0
# Set flag as true to make shure while loop runs at least once
flag = True
while flag:
# User input
num_int = int(input("Input a number: ")) # Do not change this line
# Check if number is positive
if num_int >= 0:
# Check if number is larger than max_int
if num_int >= max_int:
max_int = num_int
# If user inputs negative number, print out result, flag becomes false and loop stops running
else:
print("The maximum is", max_int) # Do not change this line
flag = False
| true |
fe4baee0ea830992c79f955e21b75abd7d18d923 | jawbreakyr/LPTHW-exercises | /Documents/tutorials/python-docs/ex19.py | 1,579 | 4.3125 | 4 | # defining a function called cheese_and_crackers that takes 2 parameters
def cheese_and_cracker(cheese_count, boxes_of_crackers):
# prints out a txts that interpolates with the cheese count
print "You have %d cheeses!" % cheese_count
# prints out a txts that interpolates with the boxes of crackers
print "You have %d boxes of crackers" % boxes_of_crackers
# simplt prints out a line of txt's
print "Man that's enough for a party!"
# prints a line of txt's that has a "\n" at the end w/means "next new line"
print "Get a blanket.\n"
# NOTE THAT EVERY TIME THE FUNCTION IS CALLED IT RE-DO ITS SELF AGAIN
# prints out a line of txt's
print "We can just give the function numbers directly:"
# calls the so called defined function above given with two integers as a parameters
cheese_and_cracker(20, 30)
# prints out a line of txt's
print "OR, we can use variables from our script:"
# declared two variables assigned each with integers
amount_of_cheese = 10
amount_of_crackers = 50
# calls the function again now with two parameters w/is the declared variables on ealier lines
cheese_and_cracker(amount_of_cheese, amount_of_crackers)
# prints out a line of txt's
print "We can even do math inside too:"
# calls the function again with two parameters now doing addition on each parameter
cheese_and_cracker(10 + 20, 5 + 6)
# prints out a line of txt's
print "And we can combine the two, variables and math:"
# calls the function again combining the variables and math procedure as its parameters
cheese_and_cracker(amount_of_cheese + 100, amount_of_crackers + 1000)
| true |
c03f86db4f6b7ed3101b947d88958343af1fdebd | anooprerna/How-to-Solve-it-By-Computer-Solutions-in-Python | /algo2_8_1.py | 291 | 4.15625 | 4 | number = int(input("Enter a number to convert\n"))
base = int(input("Enter the base\n"))
result = ""
while number != 0:
remainder = number % base
number = number // base
result = str(remainder) + result
print("The representation of number to the base", base, "is", result) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.