blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
593bf9cbfc1ff4cad5229151d01cb17c8abb690c | rayupton/ACM2-ContinuousIntegration | /fibonacci.py | 354 | 4.25 | 4 | def Fibonacci(n):
"""
Return the n-th value of the Fibonacci sequuence [0, 1, 1, 2, 3, 5, 8, 13, ...]
"""
if n<0:
raise ValueError("n<0 is not valid")
elif round(n) !=n:
raise ValueError("Fractional values of n are not allowed")
elif n<2:
return n
else:
return Fibonacci(n-1) + Fibonacci(n-2)
| false |
20b50f60051983da8b258f76966a78ac9e629ba9 | RomanSchigolev/Python__Lessons | /Input_Print/sep_and.py | 1,853 | 4.3125 | 4 | # 1. Напишите программу, которая считывает строку-разделитель и три строки,
# а затем выводит указанные строки через разделитель.
# Формат входных данных
# На вход программе подаётся строка-разделитель и три строки, каждая на отдельной строке.
# Формат выходных данных
# Программа должна вывести введённые три строки через разделитель.
separator = input()
first = input()
second = input()
third = input()
print(first, second, third, sep=separator)
# or
separator, first, second, third = [input() for _ in range(4)]
print(first, second, third, sep=separator)
# or
separator = input()
print(input(), input(), input(), sep=separator)
# 2. Напишите программу, которая приветствует пользователя, выводя слово «Привет» (без кавычек),
# после которого должна стоять запятая и пробел, а затем введенное имя и восклицательный знак.
# Формат входных данных
# На вход программе подаётся одна строка — имя пользователя.
# Формат выходных данных
# Программа должна вывести текст в соотвествии с условием задачи.
# Примечание 1. Перед восклицательным знаком не должно быть пробелов.
# Примечание 2. Используйте необязательный параметр end.
print("Привет, " + input(), end="!")
| false |
cf81870ed59589c1e6a9aebc3d3e64d200907446 | wlong799/conv-nets | /tensorflow-tutorials/tensorflow-mnist-basic.py | 2,292 | 4.46875 | 4 | """
Introduction to core machine learning concepts and how TensorFlow works, by
creating a simple softmax regression model with no hidden layers to classify
handwritten digits in the MNIST data set.
Achieves approximately 91% accuracy
Walkthrough found here:
https://www.tensorflow.org/get_started/mnist/beginners
Will Long
June 7, 2017
"""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Read in MNIST data sets (mnist.train, mnist.validation, mnist.test)
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Placeholder for input data and labels. 784 because MNIST images are each
# 28x28 pixels. 10 because we use "one-hot" labeling, where index of correct
# digit is set to 1 and all others are set to 0. None indicates that first
# dimension (i.e. # examples) can be of any length
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
# Variables for the modifiable weights and biases that our model will determine
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Implements model. Basically, each input (pixel) is connected to each output
# (label representing 0-9). This is why weight matrix is 784x10. It is a fully
# connected layer, followed by softmax activation function, with cross-entropy
# as out loss function to measure how "good" the model is.
y = tf.matmul(x, W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
# Desire to minimize the cross entropy using basic gradient descent
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# Launch session and train 1000 epochs of batch sizes of 100
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# Use argmax to get predicted/correct labels, and get number of correct matches
# as a list of booleans
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# Cast to floats and find mean to get overall prediction accuracy
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
| true |
633e42f4399c37a1d2d04690d668e8a790300414 | janat-t/titech_comp | /CS2/Project2_Sort/bubblesort.py | 619 | 4.15625 | 4 | from sort_core import swap
#
# BUBBLE SORT
#
# IN: arbitrary array
# OUT: array with all values sorted in increasing order
#
# METHOD:
# check online by yourself :)
def sort(array):
""" Non-destructive bubblesort sort.
array is unchanged; returns a sorted copy
"""
res = array.copy()
sort_inplace(res)
return res
def sort_inplace(array):
""" Inplace bubblesort sort.
modifies the input array directly
"""
n = len(array)
for i in range(n-1):
for j in range(n-i-1):
if array[j] > array[j+1]:
swap(array, j, j+1)
return array
| true |
e1f242ef1a9adb0d25ea6eec0f46f3cb64156b40 | janat-t/titech_comp | /CS1/Hw3_Caesar/caesar.py | 847 | 4.15625 | 4 | # Note that you can change the structure of the function.
# For example, you can change the type of loop.
def enc(k, m):
"""Encode the message m (aka plaintext)
with Caesar cipher and shift key k.
Change only lowercase characters,
Keep other characters.
Return the ciphertext.
"""
# Convert the message in a list of character codes
cc_plaintext = list(m.encode("ascii"))
# Duplicate the list, to store character codes of the ciphertex
cc_ciphertext = cc_plaintext.copy()
for i in range(len(m)):
if 97 <= cc_ciphertext[i] <= 122:
cc_ciphertext[i] = 97 + ((cc_ciphertext[i] - 97 + k) % 26)
c = bytes(cc_ciphertext).decode("ascii")
return c
# Main program
k = int(input("Key: "))
plaintext = input("Plaintext: ")
ciphertext = enc(k, plaintext)
print(ciphertext)
| true |
e30492de52c01190b004a79444f6f174ccbfe90c | gabrielsalesls/curso-em-video-python | /ex022.py | 1,110 | 4.25 | 4 | nome = str(input("Digite seu nome: "))
'''mai = nome.upper() # deixa a frase em maiusculo
min = nome.lower() # deixa a frase em minusculo
letras = nome.replace(' ', '') # substitui os espaços por algo, nesse caso por nada pra deixar as letras juntas
num = len(letras) # conta o numero de letras e espaços, nesse caso a frase não tem espaços
listarnome = nome.split() # separa cada nome em um lista
pnome = listarnome[0] # pega o primeiro nome
pnomenum = len(pnome)
print("Seu nome em maiusculas é {} "
"\nSeu nome em minusculas é {} "
"\nSeu nome tem {} letras "
"\nSeu primeiro nome é {} e ele tem {} letras".format(mai, min, num, pnome, pnomenum))'''
# Fazendo o mesmo exercicio anterior só que sem com menos variaveis
print("Seu nome em maiusculas é: {}".format(nome.upper()))
print("Seu nome em minusculas é: {}".format(nome.lower()))
semespaco = nome.replace(' ', '')
print("Seu nome tem {} letras".format(len(semespaco)))
listarnome = nome.split()
print("Seu primeiro nome é {} e tem {} letras".format(listarnome[0], len(listarnome[0])))
| false |
899312a4b3aaec069904e97b51e9e67c46aa86d7 | LGRN424/Python-Project | /range_list-rework.py | 341 | 4.46875 | 4 | print "Ascending Order"
print
my_list = ['0', '1', '2', '3','4','5','6', '7', '8']
my_list_len = len(my_list)
for i in range(0,3,1):
print (my_list[i])
print
print "Descending Order"
for i in range(3,-1,-1):
print (my_list[i])
print
print "Even Numbers and Reverse"
for i in range(8,0,-2):
print (my_list[i])
| false |
4b86918f31a7031bfa8d2f43486d13103edcd33c | ege-erdogan/comp125-jam-session-02 | /23_11/vectors.py | 1,195 | 4.15625 | 4 | '''
COMP 125 - Programming Jam Session #2
November 23-24-25, 2020
Implement the following functions for vectors given as a list of size 3
* add_vector: input two vectors, returns resulting vector
* length_vector: input a vector, returns the magnitude of the vector
* dot_product: input two vectors, returns the dot product of the vectors
* angle_vector: input a vector, returns the angle the vector makes with the x-axis
'''
import math
# v1: [4, 5, 6]
# v2: [1, 2, 2]
# -> [5, 7, 8]
def add_vector(v1, v2):
result = [0, 0, 0]
for i in range(3):
result[i] = v1[i] + v2[i]
return result
def add_vector_general(v1, v2):
result = []
for i in range(len(v1)):
result.append(v1[i] + v2[i])
return result
def length_vector(vector):
total = 0
for i in vector:
total += i ** 2
return math.sqrt(total)
# v1:[4, 5, 6]
# v2:[1, 2, 3]
# v1 * v2 = 4*1 + 5*2 + 6*3
def dot_product(v1, v2):
total = 0
for i in range(len(v1)):
total += v1[i] * v2[i]
return total
# arccos(vector[x] / length(vector))
def vector_angle(vector):
return math.degrees(math.acos((vector[0] / length_vector(vector))))
| true |
9aa4f2cdd6f615eca8948f8d0388771e056efb4f | nikitaty/CardsGame | /deck.py | 2,518 | 4.4375 | 4 | # Design a class deck of cards that can be used for different card game
# applications.
# What is the deck of cards: A "standard" deck of playing cards consists of 52 Cards
# in each of the 4 suits of Spades, Hearts, Diamonds, and Clubs. Each suit contains
# 13 cards: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.
from random import shuffle
class Deck:
def __init__(self):
""" build the deck of cards afresh when object is initialized."""
suits = ["hearts", "spade", "diamond", "clubs"]
values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
self.cards = []
for suit in suits:
for value in values:
self.cards.append((value, suit))
def count(self):
""" Get count of cards in the deck."""
return(len(self.cards))
def shuffle(self):
""" Shuffle the deck if num of cards left is atleast 2 """
if self.count() > 1:
print("Shuffling the deck!")
shuffle(self.cards)
return self
def _deal(self, num):
"""Deal specified number of cards from the top of the deck"""
current_count = self.count()
if current_count == 0:
raise ValueError("Deck is empty, all cards have been dealt.")
if num == 0:
raise ValueError("Number of cards to deal cannot be zero !")
# if the num asked for is greater than what is in the deck then deal the
# minimum of the 2.
actual_num_cards = min(current_count, num)
print(f"Number cards that will be dealt is {actual_num_cards}")
cards_dealt = self.cards[-actual_num_cards:]
self.cards = self.cards[:-actual_num_cards]
if self.cards == 0:
print("Last few cards have been dealt!")
return cards_dealt
def deal_card(self):
"""Deal a single card from the top of the deck."""
return self._deal(1)[0]
def deal_hand(self, num):
"""Deal a hand of the specified number of cards."""
# check if invald hand size and raise exception.
if num <= 0:
raise ValueError(
f"invalid value {num} for number of cards to deal.")
return self._deal(num)
deck = Deck()
print(len(deck.cards)) # check num of cards in the deck.
draw1 = deck.deal_card()
print(draw1) # print which card has been dealt.
hand1 = deck.deal_hand(3)
print(hand1) # print which 3 cards have been dealt.
deck.shuffle()
hand2 = deck.deal_hand(3)
print(hand2)
print(len(deck.cards))
| true |
99ac92a32834d9648c9c46e8eb9175bfd84ddc6c | derrickweiruluo/OptimizedLeetcode-1 | /LeetcodeNew/python/LC_785.py | 2,579 | 4.1875 | 4 | """
Given an undirected graph, return true if and only if it is bipartite.
Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.
The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists. Each node is an integer between 0 and graph.length - 1. There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.
Example 1:
Input: [[1,3], [0,2], [1,3], [0,2]]
Output: true
Explanation:
The graph looks like this:
0----1
| |
| |
3----2
We can divide the vertices into two groups: {0, 2} and {1, 3}.
Example 2:
Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
Output: false
Explanation:
The graph looks like this:
0----1
| \ |
| \ |
3----2
We cannot find a way to divide the set of nodes into two independent subsets.
Note:
graph will have length in range [1, 100].
graph[i] will contain integers in range [0, graph.length - 1].
graph[i] will not contain i or duplicate values.
The graph is undirected: if any element j is in graph[i], then i will be in graph[j].
"""
import collections
class Solution:
def isBipartite(self, graph) -> bool:
color = {}
for i in range(len(graph)):
if i not in color:
color[i] = 0
if not self.dfs(graph, color, i):
return False
return True
def dfs(self, graph, color, pos):
for i in graph[pos]:
if i in color:
if color[i] == color[pos]:
return False
else:
color[i] = 1 - color[pos]
if not self.dfs(graph, color, i):
return False
return True
class SolutionBFS:
def isBipartite(self, graph) -> bool:
n = len(graph)
# {node, group (0,1)}
visited = [-1] * (n)
for i in range(n):
if visited[i] != -1:
continue
queue = collections.deque()
queue.append([i, 0])
visited[i] = 0
while queue:
node, group = queue.popleft()
for nei in graph[node]:
if visited[nei] != -1:
if visited[nei] != 1 - group:
return False
else:
visited[nei] = 1 - group
queue.append([nei, 1 - group])
return True
| true |
767ec58084b63e8c2f87bb04781e2f4f6d4235ad | derrickweiruluo/OptimizedLeetcode-1 | /LeetcodeNew/python/LC_519.py | 1,082 | 4.25 | 4 | """
This is a sampling n elements without replacement problem. It is the same as the operation that random shuffe an array and then return the first n elements.
Here come the trick. When we random pick an element in the array we can store its new position in a hash table
instead of the array because n is extremely less than the total num. So we can accomplish this within O(1) time and O(k) space where k is the maxium call of flip.
"""
"""
3*3
1 2 3
4 5 6
7 8 9
rand = 4
start = 3
table = {4 : 3,
6 : 1,
7 : 2,
}
res = 0
"""
import random
class Solution:
def __init__(self, n_rows: int, n_cols: int):
self.n = n_cols
self.end = n_rows * n_cols - 1
self.table = {}
self.start = 0
def flip(self):
rand = random.randint(self.start, self.end)
res = self.table.get(rand, rand)
self.table[rand] = self.table.get(self.start, self.start)
self.start += 1
return divmod(res, self.n)
def reset(self) -> None:
self.table = {}
self.start = 0
| true |
f6f30ced739de4689347377433543aff695540d4 | derrickweiruluo/OptimizedLeetcode-1 | /LeetcodeNew/python/LC_774.py | 1,685 | 4.125 | 4 | """
On a horizontal number line, we have gas stations at positions stations[0], stations[1], ..., stations[N-1], where N = stations.length.
Now, we add K more gas stations so that D, the maximum distance between adjacent gas stations, is minimized.
Return the smallest possible value of D.
Example:
Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
Output: 0.500000
Note:
stations.length will be an integer in range [10, 2000].
stations[i] will be an integer in range [0, 10^8].
K will be an integer in range [1, 10^6].
Answers within 10^-6 of the true value will be accepted as correct.
"""
"""
Approach #4: Binary Search [Accepted]
Intuition
Let's ask possible(D): with K (or less) gas stations, can we make every adjacent distance between gas stations at most D?
This function is monotone, so we can apply a binary search to find:
"""
class Solution:
def minmaxGasDist(self, nums, K):
left, right = 1e-6, nums[-1] - nums[0]
while left + 1e-6 < right:
mid = (left + right) / 2
count = 0
for a, b in zip(nums, nums[1:]):
count += int((b - a) / mid)
if count > K:
left = mid
else:
right = mid
return right
class Solution2:
def minmaxGasDist(self, stations, K):
lo, hi = 0, max(stations)
while hi - lo > 1e-6:
mid = (lo + hi) / 2
if self.possible(stations, mid, K):
hi = mid
else:
lo = mid
return lo
def possible(self, nums, mid, K):
return sum(int((nums[i +1] - nums[i]) / mid) for i in range(len(nums) - 1)) <= K
| true |
25e87d060d63f179dc61a8cfe10961e6faaa6377 | Margarita-Sergienko/codewars-python | /7 kyu/String doubles.py | 1,647 | 4.375 | 4 | # 7 kyu
# String doubles
# https://www.codewars.com/kata/5a145ab08ba9148dd6000094
# In this Kata, you will write a function doubles that will remove double string characters that are adjacent to each other.
# b) The 2 b's disappear because we are removing double characters that are adjacent.
# c) Of the 3 c's, we remove two. We are only removing doubles.
# d) The 4 d's all disappear, because we first remove the first double, and again we remove the second double.
# e) There is only one 'a' at the end, so it stays.
# Two more examples: doubles('abbbzz') = 'ab' and doubles('abba') = "". In the second example, when we remove the b's in 'abba', the double a that results is then removed.
def doubles(s):
while True:
st = s[0]
for i in range(1, len(s)):
if s[i] != st[-1]:
st += " " + s[i]
else:
st += s[i]
splstr = st.split()
doubles = []
for el in splstr:
if len(el) % 2 != 0:
doubles.append(el)
ch = "".join(doubles)
chst = ch[0]
for i in range(1, len(ch)):
if ch[i] != chst[-1]:
chst += " " + ch[i]
else:
chst += ch[i]
chsplstr = chst.split()
check = []
for el in chsplstr:
if len(el) % 2 != 0:
check.append(el)
if check == doubles:
break
else:
s = "".join(doubles)
doubles = "".join(doubles)
f = doubles[0]
for el in doubles:
if el != f[-1]:
f += el
return f | true |
c9c360f3bf43b8cc36a3a4f7f31cf84e447d1783 | Margarita-Sergienko/codewars-python | /7 kyu/Unique string characters.py | 737 | 4.21875 | 4 | # 7 kyu
# Unique string characters
# https://www.codewars.com/kata/5a262cfb8f27f217f700000b
# In this Kata, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings.
# For example:
# solve("xyab","xzca") = "ybzc"
# --The first string has 'yb' which is not in the second string.
# --The second string has 'zc' which is not in the first string.
# Notice also that you return the characters from the first string concatenated with those from the second string.
# More examples in the tests cases.
def solve(a, b):
part1 = "".join([el for el in list(a) if el not in b])
part2 = "".join([el for el in list(b) if el not in a])
return part1 + part2
| true |
ccf3b7008b39cad355a9c637a92fe4f3099beeaf | Margarita-Sergienko/codewars-python | /7 kyu/Responsible Drinking.py | 939 | 4.1875 | 4 | # 7 kyu
# Responsible Drinking
# https://www.codewars.com/kata/5aee86c5783bb432cd000018
# Welcome to the Codewars Bar!
# Codewars Bar recommends you drink 1 glass of water per standard drink so you're not hungover tomorrow morning.
# Your fellow coders have bought you several drinks tonight in the form of a string. Return a string suggesting how many glasses of water you should drink to not be hungover.
# Examples
# "1 beer" => "1 glass of water"
# "1 shot, 5 beers and 1 glass of wine" => "7 glasses of water"
# Notes
# To keep the things simple, we'll consider that anything with a number in front of it is a drink: "1 bear" => "1 glass of water" or "1 chainsaw and 2 pools" => "3 glasses of water"
# The number in front of each drink lies in range [1; 9]
def hydrate(drinks):
water = sum([int(el) for el in drinks if el.isdigit()])
return "1 glass of water" if water == 1 else f"{water} glasses of water" | true |
e86a74dc2ce51d33be8dd3a126db31ea43c92787 | hamna314/iacc_python | /week2/passwordChecker.py | 1,828 | 4.34375 | 4 |
#Password strength checker : Create a function to accept a string and verify if it conforms to the following format
#between 8 to 12 characters long, atleast 1 upper case character,
#atleast 1 number and 1 special character which can be one of '@','#','$','#' ,'%','&'
#Create a function to verify if password length is between 8 to 12 characters
def lengthCheck(password):
password_length = len(password)
if(password_length >= 8 or password_length <=12 ):
return True
else:
print 'Password has to be between 8 to 12 characaters long'
return False
#Create a function to verify if password has atleast 1 upper case character
def caseCheck(password):
for letter in password:
if letter.isupper():
return True
print 'Atleast 1 character has to be upper case'
return False
#Create a function to verify if the password has atleast 1 number
def numberCheck(password):
for letter in password:
if letter.isdigit():
return True
print 'Need atleast 1 number in the password'
return False
#Create a function to verify if the pass word has atleast 1 of '@','#','$','#' ,'%','&'
def specialCharCheck(password):
for letter in password:
if letter in ('@','#','$','#' ,'%','&'):
return True
print "Need one of the following '@','#','$','#' ,'%','&' characters in the password"
return False
#PasswordChecker function which checks for all the password restrictions but calling their corresponding methods
def passwordChecker(password):
if (lengthCheck(password) and caseCheck(password) and numberCheck(password) and specialCharCheck(password)):
print 'Password is STRONG!!'
else:
print 'Password is WEAK!!'
password = raw_input('Enter Password >>')
passwordChecker(password)
| true |
dcfda91b7c058b6518e73e960e40af90654402e5 | hamna314/iacc_python | /week1/sum_of_items_in_list.py | 602 | 4.3125 | 4 | '''
Write a python program to sum all the items in a list
'''
#Create a new list with some random numbers
newList = [1,5,19,4,5,8]
#Create a new variable sum_of_List to hold the sum of the items in the list and assign it a value of 0.
sum_of_list = 0
#Create a for loop to iterate over the elements of the list
for item in newList :
sum_of_list = sum_of_list + item
print sum_of_list
'''
The same thing can be accomplished by using the sum built in function provided by python as demostrated below
'''
# This is an alternate way of calculating the sum of items in the list
print sum(newList)
| true |
228a04513d195e81f06420981ea0d46885d43cd9 | seenureddy/problems | /python-problems/largest_sub_array.py | 1,542 | 4.15625 | 4 | """
Largest sub-array problem
You have an array containing positive and negative numbers (no zeros). How will you find the sub-array with the largest sum.
Example: If the array is: 1, 4, -6, 8, 1, -4, 5, -3, 1, -1, 6, -5
The largest sub-array is: 8, 1, -4, 5, -3, 1, -1, 6
NOTE: You've to print the largest sub-array (with all integers), NOT the largest numeric sum total.
Boundary condition: For an array with all negative numbers, the largest number is the answer. For an array with all positive numbers, the whole array is the answer.
Sample Input
(Plaintext Link)
1, 4, -6, 8, 1, -4, 5, -3, 1, -1, 6, -5
Sample Output
(Plaintext Link)
8, 1, -4, 5, -3, 1, -1, 6
"""
import operator
def larget_sub_arry():
"""
We will take an array and print the largest sum of sub array.
Input:
1, 4, -6, 8, 1, -4, 5, -3, 1, -1, 6, -5
Sample Output
8, 1, -4, 5, -3, 1, -1, 6
"""
largest_array = raw_input('Enter An Array?\n')
largest_array = [int(i) for i in largest_array.strip().split(", ")]
find_sub_array_dict, length_array = {}, len(largest_array)
for j in xrange(1, length_array + 1):
for i in xrange(1, length_array + 1):
sub_array = largest_array[i - 1 : length_array - 1]
amount = sum(sub_array)
if amount:
find_sub_array_dict[amount] = sub_array
return find_sub_array_dict
if __name__ == '__main__':
sub_array_dict = larget_sub_arry()
print max(sub_array_dict.iteritems(), key=operator.itemgetter(1))[1]
| true |
8991de3e9f56ce86ffd7d8e51c1a6f1f994478a5 | bittercruz/python | /Exercicios/ex1_b_input.py | 480 | 4.15625 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
#Retornar a soma de elementos de uma lista
def soma(lista):
soma_item = 0
#tamanho = len(lista)
for item in lista:
#soma_item = soma_item + int(item)
soma_item += int(item)
return soma_item
#lista = [x for x in input("Insira a lista: ").split()]
def get_lista():
input_user = input("Insira a lista separada por espaços: ")
lista = input_user.split()
return lista
lista = get_lista()
total = soma(lista)
print(total)
| false |
5d7daff83796a4cbe62e2962ddcfebbe1e8e002a | volodiny71299/04_assessment | /03_assessment.py | 525 | 4.21875 | 4 | # Component three, choose what game to play
game_multi_choice = "multi-choice"
game_other = "other"
error = "please enter 1 or 2"
keep_going = ""
while keep_going == "":
choose = input("Multi-choice(1) or other(2)? ").lower()
if choose == "1":
print()
print("you chose", game_multi_choice)
print()
elif choose == "2":
print()
print("you chose", game_other)
print()
else:
print()
print(error)
print()
keep_going = input("<enter>")
| true |
f24e8fbfba3777295b8097710c72af625eee42a3 | prakashtanaji/DSAndAlgo | /dailycode/python/bintreecompletenodescount.py | 1,717 | 4.125 | 4 | # give a binary tree which is complete, find the number of nodes
import queue
def treeSz(root):
curr = root
sz = 1
while True :
if curr.left == None: break
curr = curr.left
sz +=1
return sz
class Node:
val = 0
left = None
right = None
def __init__(self, _val):
self.val = _val
self.left = None
self.right = None
def print(self):
q = queue.Queue()
q.put(self)
sz = q.qsize()
while not q.empty() :
size = q.qsize()
while size > 0 :
curr = q.get()
print(curr.val, end=" ")
if curr.left:
q.put(curr.left)
if curr.right:
q.put(curr.right)
size-=1
print()
def populateTree() :
root = Node(1)
root.left = Node(2)
#root.right = Node(3)
return root
root = populateTree()
def findCount(root) :
root.print()
print("size is {}".format(treeSz(root)))
least = (2 ** treeSz(root)) // 2
highest = 2 ** treeSz(root) - 1
print(least, highest)
while least < highest :
mid = (least + highest) // 2
pathI = mid
st = []
while pathI >1:
st.append(pathI%2)
pathI = pathI //2
curr = root
loor = 0
while len(st):
lorr = int(st.pop())
if loor == 0:
curr = curr.right
else :
curr = curr.left
if curr == None:
highest = mid
else :
least = mid +1
return least;
print("size of tree is ", findCount(root))
| true |
96a9e48c298c359a2ca9bbf46248e6e89a857b6e | G8A4W0416/Module7 | /fun_with_collections/basic_list_exception.py | 688 | 4.375 | 4 | """
Program basic_list.py
Author: Greg Wilhelm
Last date modified: 03/04/2020
This is just a simple list builder taking in a integer entered by the user and creating a list by repeating the value
three times.
"""
def get_input():
user_input = int(input("Please enter a number: "))
return user_input
def make_list():
inputs = []
try:
value = int(get_input())
if value < 1 or value > 50:
raise ValueError
else:
for i in range(3):
inputs.insert(i, value)
return inputs
except ValueError:
raise ValueError
if __name__ == '__main__':
list_built = make_list()
print(list_built)
| true |
cc50c7f0a4a88f49659214785ff3c422ecc7b250 | ethanmyers92/90COS_IQT_Labs | /Lab3D.py | 425 | 4.375 | 4 | #Lab3D
#Write a program that prompts a user to input an integer and calculates the factorial of that number using a while loop.
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
count = 0
while count <= 100:
print factorial(count)
count += 1
else:
print "DONE!"
#print factorial(int(raw_input("Enter a number you would like the factorial of: ")))
| true |
76651f4059bbd69cbc52ceb1cb71fad5a0943b97 | ethanmyers92/90COS_IQT_Labs | /Lab 2H.py | 1,172 | 4.125 | 4 | #Lab 2H
print "Enter the grades for your four students into your gradebook! Enter grade first then name!"
student_dict = {raw_input("Enter first student's name: ") : int(raw_input("Enter first student's grade: "))}
student_dict[raw_input("Enter second student's name: ")] = int(raw_input("Enter second student's grade: "))
student_dict[raw_input("Enter third student's name: ")] = int(raw_input("Enter third student's grade: "))
student_dict[raw_input("Enter fourth student's name: ")] = int(raw_input("Enter fourth student's grade: "))
print student_dict
print ""
print "Grades, High to low: "
print sorted(student_dict.items(), key=lambda x:x[1], reverse=True)
print ""
print "The average grade is : "
class_average = sum(student_dict.values()) / len(student_dict.values())
print class_average
#NOTES:
#for key, value in sorted(student_dict.items()):
# print key, value
#print sorted(student_dict.values()
#print sorted(student_dict, key=student_dict.get, reverse=True)
#To get a list of tuples ordered by value
#Print sorted(student_dict.items(), key=lambda x:x[1])
#student_dict = {"Alice" : 99, "Thomas" : 67, "Betty" : 75, "Dexter" : 83}
| true |
7feeebca071b5069612d76429b5ef19df7eea6eb | coleMarieG/wcc | /Python/input.py | 597 | 4.15625 | 4 | # name = raw_input('What is your name? ')
# print('Hi ' + name)
# name = raw_input('What is your name?')
# age = raw_input('How old are you?')
# print(name + ' is ' + age + ' years old.')
# # raw_input value is always a string
# age = raw_input('How old are you?')
# dog_years = int(age) * 7
# print('You are ' + str(dog_years) + ' years old in dog years.')
# Create a tip calculator
meal_cost = float(raw_input('How much was your meal? '))
tip = meal_cost * .2
total_cost = tip + meal_cost
print('You should tip $' + str(round(tip, 2)))
print('Your total is $' + str(round(total_cost, 2)))
| true |
974ffc78548a2192d9a45dfa54f75c1d919f579d | smiley16479/AI_bootcamp | /week_0/Day00/ex03/count.py | 1,694 | 4.25 | 4 | # **************************************************************************** #
# #
# ::: :::::::: #
# count.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: adtheus <marvin@42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2020/01/13 17:46:59 by adtheus #+# #+# #
# Updated: 2020/01/13 18:19:00 by adtheus ### ########.fr #
# #
# **************************************************************************** #
import string
def text_analyzer(strn = ""):
"This function counts the number of upper characters, lower characters, punctuation and spaces in a given text."
tab = [0, 0, 0, 0, 0]
if strn == "":
strn = input("What is the text to analyse?\n>>")
print(strn)
for char in strn:
tab[0] += 1
if char.isupper():
tab[1] += 1
elif char.islower():
tab[2] += 1
elif char in string.punctuation:
tab[3] += 1
elif char == ' ':
tab[4] += 1
print ("The text contains " + str(tab[0]) + " characters:")
print ("- " + str(tab[1]) + " upper letters")
print ("- " + str(tab[2]) + " lower letters")
print ("- " + str(tab[3]) + " punctuation marks")
print ("- " + str(tab[4]) + " spaces")
| false |
5068eb26f4664e523efae0bc297df86978158cfd | mgarchik/P2_SP20 | /Problems/Sorting/05_sorting_problems.py | 2,673 | 4.1875 | 4 | '''
Sorting and Intro to Big Data Problems (22pts)
Import the data from NBAStats.py. The data is all in a single list called 'data'.
I pulled this data from the csv in the same folder and converted it into a list for you already.
For all answers, show your work
Use combinations of sorting, list comprehensions, filtering or other techniques to get the answers.
'''
from NBAStats import data
data2 = [x for x in data]
print(data)
print(data2)
data2.pop(0)
#1 Pop off the first item in the list and print it. It contains the column headers. (1pt)
headings = data.pop(0)
print(headings)
#2 Print the names of the top ten highest scoring single seasons in NBA history?
# You should use the PTS (points) column to sort the data. (4pts)
data.sort(key=lambda x: x[-1], reverse=True)
for i in range(10):
print(data[i][2])
#3 How many career points did Kobe Bryant have? Add up all of his seasons. (4pts)
kobe_pts = 0
for i in range(len(data)):
if data[i][2] == "Kobe Bryant":
kobe_pts += int(data[i][-1])
print(kobe_pts)
#4 What player has the most 3point field goals in a single season. (3pts)
data.sort(key=lambda x: x[34], reverse=True)
print(data)
print(data[0][2], "made", data[0][34], "three pointers in one season")
#5 One stat featured in this data set is Win Shares(WS).
# WS attempts to divvy up credit for team success to the individuals on the team.
# WS/48 is also in this data. It measures win shares per 48 minutes (WS per game).
# Who has the highest WS/48 season of all time? (4pts)
print(headings)
data2.sort(key=lambda x: x[25], reverse=True)
print(data2[0])
print(data2[0][2], "had the highest one season ws/48 with a", data2[0][25], "ws/48")
#6 Write your own question that you have about the data and provide an answer (4pts)
# Maybe something like: "Who is the oldest player of all time?" or "Who played the most games?" or "Who has the most combined blocks and steals?".
# Find the player who had the highest PER in one season on the Chicago Bulls
data2.sort(key=lambda x: x[9], reverse=True)
done = False
i = 0
while not done:
if data2[i][5] == "CHI":
print(data2[i][2], "had the highest one season PER on the Chicago Bulls with a PER of", data2[i][9])
done = True
else:
i += 1
#7 Big challenge, few points. Of the 100 highest scoring single seasons in NBA history, which player has the
# worst free throw percentage? Which had the best? (2pts)
data2.sort(key=lambda x: x[-1], reverse=True)
top = 100
for i in range(100):
stored = data2[i][-10]
if stored < top:
top = i
print(data2[top][2], "had the lowest free throw percentage of the top 100 single scoring seasons")
| true |
6af0a51afcde8bd59eb4bbfb51932c4749993094 | ezgikaradag/Rock-Paper-Scissors-Game | /gamecode.py | 1,139 | 4.1875 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
print("What do you choice? Type 0 for Rock, 1 for Paper, 2 for Scissors.")
game_images = [rock,paper,scissors]
userchoice = int(input())
print(game_images[userchoice])
computerChoice = random.randint(0,2)
print(game_images[computerChoice])
print(f"Your choice {userchoice}")
print(f"Computer choice {computerChoice}\n")
if userchoice >= 3 or userchoice < 0:
print("You typed an invalid number.You lose! :(")
elif userchoice==2 and computerChoice == 0:
print("You lose! :(")
elif computerChoice==2 and userchoice == 0:
print("You win! :)")
elif computerChoice > userchoice:
print("You lose! :(")
elif userchoice > computerChoice:
print("You win! :)")
elif computerChoice==userchoice:
print("It's a draw. :|")
| false |
288b4fc71075613636b9e6713d55603e65a67c7f | DrimTim32/py_proj_lights | /core/data_structures/vector.py | 1,211 | 4.375 | 4 | """This file contains Vector class"""
class Vector:
""" Vector class represents and manipulates x,y coords. """
def __init__(self, x, y):
""" Create a new point """
self.x = x
self.y = y
def __mul__(self, other):
if not isinstance(other, int):
raise ValueError("Second multiplication object must be an int")
return Vector(self.x * other, self.y * other)
def __rmul__(self, other):
return self * other
def __ne__(self, other):
return not self == other
def __eq__(self, other):
return self is other or (self.x == other.x and self.y == other.y)
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return "Position ({0},{1})".format(self.x, self.y)
def __getitem__(self, item):
return self.x if item == 0 else self.y
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def copy(self):
"""
Creates new object with the same position
:rtype: Vector
"""
return Vector(self.x, self.y)
def __neg__(self):
return Vector(-self.x, -self.y)
| false |
5acbd00c44698d654e64145585a619290e097eb1 | RyhanSunny/myPythonJourney | /Common _String_methods.py | 1,582 | 4.1875 | 4 | # A string variable
name = "michael jackson"
# character at index 0
print(name[0])
# character at index -1: first letter backwards
print(name[-1])
# length of string
print(len(name))
# # STRING[START:END:STEP] ex: name[0:10:2]
# Slicing
print(name[0:4]) # slice from index 0 til index 4 (including 0th excluding 4th)
# Stride slicing
print(name[8:12:2]) # slice from 8th till 12th but take every 2nd character (including first letter excluding last)
# Stride values
print(name[::2]) # print only every 2nd letter from 0 till the end (including 0th and last)
# print backwards
print(name[::-1])
# Concatenating
Statement = name + " is a legend"
print(Statement)
# Tupling (Multiplying/repeating)
print(name * 3)
# escape sequence
print("This\nthen That") # new line: \n
print("This\tand that") # tab: \t
print(r"This\n\or\that") # ignore escape sequences: r
# string .is methods (boolean)
print(name.isdigit())
print(name.islower())
print(name.isalpha())
# make string all UPPER CASE
print(name.upper())
# replace
print(name.replace("j", "m"))
# find substring/character
print(name.find("son")) # if not found it will output -1
# format into title (first letter of each word capital)
print(name.title())
# COUNT: Count how many times a character sequence occurs in a string.
s = "hello world I am coding"
print(s.count('o'))
# SWAP CASE: Swap all uppercase and lowercase characters.
s = "HeLLO WORLD"
print(s.swapcase())
# JOIN: Join a list of strings into one string separated by the input string.
nums = ['dan', 'mike', 'rob']
print(' '.join(nums))
print('-'.join(nums))
| true |
3ea4dabedc8f530e4ccbeaab24d898e964fbb379 | avoajaugochukwu/python_mooc | /my_work/stuff.py | 807 | 4.375 | 4 | balance = float(raw_input("Enter the outstanding balance on your credit car: "))
annualInterestRate = float(raw_input("Enter the annual credit card interest rate as a decimal: "))
monthlyPayment = 10
monthlyInterestRate = annualInterestRate/12
newbalance = balance - 10
while (newbalance > 0):
monthlyPayment += 10
newbalance = balance
month = 0
while (month < 12 and newbalance > 0):
month += 1
interest = monthlyInterestRate * newbalance
##newbalance = (newbalance * (1 + monthlyInterestRate)) - monthlyPayment
newbalance = newbalance - (monthlyPayment - interest)
newbalance = round(newbalance,5)
print " RESULT"
print " Lowest Payment: ", monthlyPayment
print " Number of months needed: ", month
print " Balance: ", newbalance
| true |
88b281726cb00301c1d77d76ce70a7bdc56a7c8a | ankhangkieu/CS61A | /hw/hw01/quiz/quiz01.py | 979 | 4.125 | 4 | def multiple(a, b):
"""Return the smallest number n that is a multiple of both a and b.
>>> multiple(3, 4)
12
>>> multiple(14, 21)
42
"""
"*** YOUR CODE HERE ***"
multi = max(a, b)
while multi % a != 0 or multi % b != 0 :
multi = multi + 1
return multi
def has_digit(n, k):
while n > 0:
if n % 10 == k:
return True
n = n // 10
return False
def unique_digits(n):
"""Return the number of unique digits in positive integer n
>>> unique_digits(8675309) # All are unique
7
>>> unique_digits(1313131) # 1 and 3
2
>>> unique_digits(13173131) # 1, 3, and 7
3
>>> unique_digits(10000) # 0 and 1
2
>>> unique_digits(101) # 0 and 1
2
>>> unique_digits(10) # 0 and 1
2
"""
"*** YOUR CODE HERE ***"
count = uniq = 0
while count <= 9:
if has_digit(n, count):
uniq = uniq + 1
count = count + 1
return uniq
| false |
b7f0cb150a1b4087e53e6aa443ff97efd4ed9cae | explodes/euler-python | /euler/lib/seq.py | 2,406 | 4.28125 | 4 | #!/usr/bin/env python
def bin_index(L, item, low=0, high=None):
"""
Perform a binary search on ordered sequence L
If the item is not found, return the index in which it should be inserted
O(lg n)
:param L: ordered sequence to scan
:param item: `item` to search for
:param low: lowest bound to search in `L`
:param high: highest bound to search in `L`
:return: The proposed index of `item`.
"""
if high is None:
high = len(L)
index = low + (high - low) / 2
if L[index] == item:
return index
elif index == low:
# proposed location
if item < L[index]:
# < N, proposed index = N
return index
else:
# > N, proposed index = N + 1
return index + 1
if item < L[index]:
return bin_index(L, item, low, index)
else:
return bin_index(L, item, index, high)
def bin_search(L, item):
"""
Perform a binary search for `item` in sorted sequence `L`
O(lg n)
:param L: sorted sequence
:param item: item to search for
:return: -1, or the found index
"""
index = bin_index(L, item)
N = len(L)
if index >= N or L[index] != item:
return -1
return index
def insert_in_order(L, item):
"""
Insert i into `L` in order with or without duplicates
O(lg n)
:param L: list to add to
:param item: item to insert
"""
index = bin_index(L, item)
L.insert(index, item)
if __name__ == '__main__':
# Tests
# bin index
seq = [0, 10, 20, 35, 400, 2002, 3003, 5000, 10000]
assert bin_index(seq, -1) == 0
assert bin_index(seq, 0) == 0
assert bin_index(seq, 20) == 2
assert bin_index(seq, 21) == 3
assert bin_index(seq, 36) == 4
assert bin_index(seq, 10000) == 8
assert bin_index(seq, 100001) == 9
# bin insert
seq = [10, 20, 30]
insert_in_order(seq, 11)
assert seq == [10, 11, 20, 30]
insert_in_order(seq, 9)
assert seq == [9, 10, 11, 20, 30]
insert_in_order(seq, 30)
assert seq == [9, 10, 11, 20, 30, 30]
insert_in_order(seq, 31)
assert seq == [9, 10, 11, 20, 30, 30, 31]
# bin search
seq = [0, 1, 2, 3, 4]
for x in seq:
i = bin_search(seq, x)
assert i == x, '%d found at incorrect index %d' % (x, i)
assert bin_search(seq, -1) == -1
assert bin_search(seq, 5) == -1
| true |
7d0896295fae62b13ccfbec05c9777feffd22b9b | explodes/euler-python | /euler/lib/maths.py | 1,956 | 4.21875 | 4 | #!/usr/bin/env python
import math
from euler.lib.gen import lrange
from euler.lib.seq import insert_in_order
def product(seq):
"""
Multiply each item in the list and return the value
"""
total_product = 1
for item in seq:
total_product *= item
return total_product
def divisors(n):
"""
List all divisors for a given integer
"""
# base cases
if n == 0:
return []
if n == 1:
return [1]
# a number is always divisible by one and itself
all_divisors = [1, n]
# we could skip even numbers if our input is odd
# but profiling has shown no performance gains event for large values of `n`
# search up to the sqrt of our value
for divisor in lrange(2, int(math.sqrt(n)) + 1):
if n % divisor == 0:
insert_in_order(all_divisors, divisor)
# don't add the square root twice
if divisor * divisor != n:
insert_in_order(all_divisors, n / divisor)
return all_divisors
def proper_divisors(n):
"""
A proper divisor is a number below n that divides into n evenly.
"""
d = divisors(n)
if n in d:
d.remove(n)
return d
def sum_of_digits(n):
"""
Compute the sum of all digits in a number
"""
return sum(int(c) for c in str(n))
def factorial(n):
"""
Compute n!
"""
if n == 0:
return 1
if n == 1:
return 1
return n * factorial(n - 1)
if __name__ == '__main__':
from euler.lib.profile import time
@time
def timed_divisors(n):
return divisors(n)
assert timed_divisors(4) == [1, 2, 4]
assert timed_divisors(5) == [1, 5]
assert timed_divisors(220) == [1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110, 220]
assert timed_divisors(234262351) == [1, 67, 3496453, 234262351]
# assert timed_divisors(1326443518324400147398873) == [1, 1152846547, 1150581160845859, 1326443518324400147398873]
| true |
e34a14df70505f795977b18c82875b8916ad7461 | ryantanch/PythonOOP-Practice | /oop.py | 2,593 | 4.1875 | 4 | ##################################################
# Python OOP tutorials by Corey Schafer
# Source: Youtube - Corey Schafer
# Practice Done by RyanTanCH 2019
# Ver Python 3.6
##################################################
class Employee:
#Class Variable
No_of_emps = 0;
raise_amount = 1.04
#constructor 1
def __init__(self,first,last,pay):
self.first = first;
self.last = last;
self.pay= pay;
Employee.No_of_emps += 1 ;
#Alternative Constructor 2
@classmethod
def from_string(cls,emp_str):
first,last,pay = emp_str.split('-')
return cls(first,last,pay)
#regular methods
@property
def fullname(self):
return '{} {}'.format(self.first,self.last)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amount)
@property
def email(self):
return '{}.{}@email.com'.format(self.first,self.last)
#setter
@fullname.setter
def fullname(self,name):
first,last = name.split(' ')
self.first = first
self.last = last
#Magic Methods
def __repr__(self):
return "Employee('{}','{}','{}')".format(self.first,self.last,self.pay)
def __str__(self):
return '{} - {}'.format(self.fullname(),self.email)
def __add__(self,other):
return self.pay + other.pay
def __len__(self):
return len(self.fullname)
#class methods
@classmethod
def set_raise_amt(cls,amount):
cls.raise_amount = amount
#static methods
@staticmethod
def is_weekday(day):
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
#Sublcass Inheritance
class Developer(Employee):
raise_amount = 1.10
#Subclass Constructur
def __init__(self,first,last,pay,language):
#superclass
Employee.__init__(self,first,last,pay)
self.language = language
class Manager(Employee):
def __init__(self,first,last,pay,employees = None):
#superclass
Employee.__init__(self,first,last,pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_employee(self,emp):
if emp not in self.employees:
self.employees.append(emp)
def remove_employee(self,emp):
if emp in self.employees:
self.employees.remove(emp)
def print_employee(self):
for emp in self.employees:
print("-->",emp.fullname())
#How to use isInstance()
mgr_1 = Manager('Carol','Lee',51200,'Java')
print(isinstance(mgr_1,Manager))
#How to use isSubClass()
dev_1 = Developer('Richard','Lee',45440,'Python')
print(issubclass(Developer,Employee))
#Magic Method __add__
emp_1 = Employee('Corey','Schafer',50222)
emp_2 = Employee('Sally','Schafer',60355)
print(emp_1 + emp_2)
#Magic Method __len__
print(len(emp_1))
| true |
77be6f889c59ba66824029fb4cf4088d8766905a | azrodriquez/MyPythonCourse | /CH06-functions/movie_info.py | 855 | 4.40625 | 4 | #Bonus material #1
def print_movie(movie, year):
print(f'The movie {movie} is from year {year}.')
movie = "The Matrix"
year = 1999
print(print_movie(movie, year))
# Bonus material #2
def movie_info(user_movie, user_movie_year):
print(f'The movie {user_movie} was released in {user_movie_year}.')
user_movie = input("what is your favorite movie? ")
user_movie_year = input("what year was the movie made? ")
print(movie_info(user_movie,user_movie_year))
#Bonus material #3
movie_list = [
{"year":1979, "name": "name": Star Wars}
{"year":1983, "name": "name": Empire Strikes Back}
{"year":1987, "name": "name": Return of the Jedi}
];
movie1 = {"year":1979, "name": "name": Star Wars}
movie2 =
movie3 =
for movie in movie_list:
print (movie_info(movie["name"], movie["year"]))
| true |
c93628c22529dbf7a97ed2167e23ed26a74c61ef | azrodriquez/MyPythonCourse | /CH03/display_movie_info.py | 1,320 | 4.1875 | 4 | import sys
#get file name
program_name = sys.argv[0]
print('original name\t\t', program_name)
print('uppercase\t\t', program_name.upper())
print('original name\t\t', program_name)
#replace underscore with space
program_name = program_name.replace('_', ' ')
print('removed underscore\t', program_name)
#replace .\ if it exists
program_name = program_name.replace('.\\', ' ')
print('removed .\\\t\t', program_name)
#replace .py if exists
program_name = program_name.replace('.py', '')
print('removed .py\t\t', program_name)
#upper
program_name = program_name.upper()
print('upper\t\t', program_name)
#create welcome message
welcome_message = 'Welcome to {}'
welcome_message = welcome_message.format(program_name)
print(welcome_message)
#use center to display
print('length is', len(program_name))
welcome_message = welcome_message.center(len(welcome_message)*3, '*')
print(welcome_message)
#ask user for numeric value
good_year = False
movie = input("What is your favorite movie? ")
print(movie)
while not good_year:
year = input("What year is your favorite movie from? ")
if (year.isdecimal()):
good_year = True
else:
print("Please enter a valid year...")
#use str.format
movie = movie.strip()
print(movie)
message = "In {}, the movie {} debuted"
print(message.format(year, movie)) | false |
d6a977cc012b7963002de1826ce1ebef07b71a71 | balayanr/Daily-Interview-Pro | /problems/count_invalid_parenthesis.py | 444 | 4.28125 | 4 | """
This problem was recently asked by Uber:
You are given a string of parenthesis.
Return the minimum number of parenthesis that would need to be removed
in order to make the string valid. "Valid" means that each open parenthesis
has a matching closed parenthesis.
Example:
"()())()"
The following input should return 1.
")("
"""
def count_invalid_parenthesis(string):
# Fill this in.
print count_invalid_parenthesis("()())()")
# 1
| true |
e10e75d06a31af1a782ce77654e85093ad201e35 | Akhileshbhagat1/All-prectice-of-python | /opps/checkLeapYEAR.py | 461 | 4.15625 | 4 |
while True:
print("Enter a year for check Leap year or not (or q for quit) : ")
year = input()
if year == 'q':
break
else:
if int(year) % 400 == 0:
print(f'{year}' " is a leap year")
elif int(year) % 4 == 0:
print(f'{year}' " is a leap year")
elif int(year) % 100 == 0:
print(f'{year}' " is not a leap year")
else:
print(f'{year}' " is not a leap year")
| false |
12ebeaec5b2d9701642b19514aff4578a0e6dd51 | Akhileshbhagat1/All-prectice-of-python | /specialisedCOLLECTIONdataTYPES/namedTUPLE.py | 484 | 4.375 | 4 | # namedtuple() returns the tuple with named value for esch element in the tuple
# details = (name = 'akhilesh', age = '24', language = 'python')
from collections import namedtuple
a = namedtuple('courses', 'name, technology, age, address ')
s = a('akhilesh', 'python', '24', 'bhagaiya')
print(s)
# you can use list at the place of tuple OR iterable(list, tuple) in both case it will return tuple
# s = a._make(['akhilesh', 'python', '24', 'bhagaiya'])
# print(s)
| true |
ce0aaf7ab12e020f0ace539cb112b682effb5e29 | fosskers/alg-a-day | /day07-linked-list/linked_list.py | 2,189 | 4.21875 | 4 | # A linked list in Python.
# Pretty pointless due to the existence of built-in non-homogenious lists,
# but whatever.
class LinkedList():
'''A linked list. Hurray.'''
def __init__(self, initial_data):
self.root = Node(initial_data)
self.end = self.root
def __str__(self):
nodes = []
curr = self.root
while curr:
nodes.append(str(curr))
curr = curr.next
return ''.join(nodes)
def __contains__(self, data):
curr = self.root
while curr:
if curr.data == data:
return True
curr = curr.next
return False
def __len__(self):
curr = self.root
result = 0
while curr:
result += 1
curr = curr.next
return result
def push(self, data):
'''Push some data on to the back of the list.'''
if not self.root: # Not even a root is present.
self.__init__(data)
else:
self.end.next = Node(data)
self.end = self.end.next
def insert(self, data):
'''Insert some data at the front of the list.'''
if not self.root:
self.__init__(data)
else:
new = Node(data)
new.next = self.root.next
self.root = new
def remove(self, other):
'''Removes a Node that contains 'data', if it's there.'''
curr = self.root
prev = curr
while curr:
if curr.data == other:
if prev == curr: # Removing root.
self.root = self.root.next
elif not curr.next: # Removing end.
prev.next = None
self.end = prev
else:
prev.next = curr.next
break
prev = curr
curr = curr.next
class Node():
'''A node in a linked list.'''
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
if self.next:
end = ''
else:
end = 'None'
return '{} ~> {}'.format(self.data, end)
| true |
e5bcea62de995b020b566248b41937e390132211 | fosskers/alg-a-day | /day11-circular-bin-search/circ_bs.py | 810 | 4.1875 | 4 | # Circular Binary Search
def circ_bs(items, target):
'''Finds a value in a given list using a circular binary search.
Returns -1 if the value was not found.
'''
size = len(items)
lower = 0
upper = size - 1
result = -1 # Assume failure.
while lower <= upper:
mid = (upper + lower) // 2
if items[mid] == target:
result = mid
break
elif items[lower] <= target < items[mid]:
upper = mid - 1
elif items[mid] < target <= items[upper]:
lower = mid + 1
else: # Standard binary search logic has failed.
if items[lower] > items[mid]: # Link is on the left.
upper = mid - 1
else: # Link is on the right.
lower = mid + 1
return result
| true |
2ba97990c6b589b4f53120eaa775d89d431b651f | nokap/exam1jacobkapasi | /donuts.py | 1,881 | 4.125 | 4 | grades = [62, 79, 82, 81, 92, 74, 84, 95, 85, 78, 88]
#This is an array that holds all of the grades of the class
ans = () #This is a variable that holds the answer
for avg in grades: #I am creating a for loop that holds the averages for the grades
if avg ==: #I am saying that if the average variable in grades is equal to... (the stuff below)
A_avg == int >= 90 #if the average is equal to or above 90, the average is an A
B_avg == int >= 80 < 90 #if the average is equal to or above 90 and less than 90, the avg is B
C_avg == int >= 70 < 80 #if the average is equal to or above 70 and less than 80, the avg is C
D_avg == int >= 60 < 70 #if the average is equal to or above 60 and less than 70, the avg is D
F_avg == int >= 50 < 60 #if the average is equal to or above 50 and less than 60, the avg is F
avg = sum(grades)/11 #The sum of the grades divided by 11 is the average of the class
elif avg == A_avg: #If the average is equal to an A then Mr. James james will give a full donut to the students.
print('Yay! Mr. james will give you a full donut')
elif avg == B_avg: #If the average is equal to a B, then Mr. James will give half a donut to the students.
print('Room for improvement, but you still did well! Mr. James will give you half a donut')
elif avg == C_avg: #If the average is equal to a C, then Mr. James will give 1/3 a donut to the students.
print('You really need to step it up, but you have a start, Mr. James will give you 1/3 of a donut')
elif avg == D_avg: #If the average is equal to a D, then Mr. James will get half a donut from each student.
print('Wow, did you gain anything from this course? You owe Mr. James half a donut!')
return #I am trying to call the function so I get the answer
ans
# Step 3: I have a bunch of errors with my code, I was told that I can clean up my code so that it runs properly.
| true |
8af6b3625023ca12c94735679076a1fa2ac855b1 | JennyShalai/data-science-prep | /tuple-dictionary-set.py | 2,933 | 4.4375 | 4 | # Tuple, Dictionary and Set checkpoint
# Challenge 1:
# Write a script that prompts the user to input a series of numbers separated by
# commas. Your script will then take these inputted numbers and store them
# as a list of tuples, two at a time. Finally, your script will print that list
# of tuples to the user. If the user inputs an odd number of numbers, then only
# make a list of the largest number of pairs of two that are possible.
nums = input('''Please enter a series of numbers separated by commas. \n Hit enter when you are done. ''')
result = []
number_list = nums.split(',')
if len(number_list) % 2 != 0:
number_list.pop()
for i in range(0, len(number_list)-1, 2):
result.append((int(number_list[i]), int(number_list[i+1])))
print(result)
# Challenge 2:
# Write a script that prompts the user to input numbers separated by dashes
# ( - ). Your script will take those numbers, and print a dictionary where
# the keys are the inputted numbers, and the values are the squares of those numbers.
nums = input('''Please enter a series of numbers separated by '-'. \n Hit enter when you are done. ''')
squares_dictionary = {int(number):int(number)*int(number) for number in nums.split('-')}
print(squares_dictionary)
# Challenge 3:
# Write a script that prompts the user for a state name. It will then check
# that state name against the dictionary below to give back the capital
# of that state. However, you'll notice that the dictionary doesn't know the
# capitals for all the states. If the user inputs the name of a state that
# isn't in the dictionary, your script should print 'Capital unknown'.
# Your script should work regardless of capitalization used when the state
# is input. Example: If you inputted CALIfORnia it should print Sacramento.
state_dictionary = {'Colorado': 'Denver', 'Alaska': 'Juneau',
'California': 'Sacramento', 'Georgia': 'Atlanta',
'Kansas': 'Topeka', 'Nebraska': 'Lincoln',
'Oregon': 'Salem', 'Texas': 'Austin', 'New York': 'Albany'}
user_input_state = input('Please enter your state:')
key = user_input_state.lower().title()
if key in state_dictionary:
print(state_dictionary[key])
else:
print('Capital unknown')
# Challenge 4:
# Write a script that prompts the user to input numbers separated by commas,
# and then does so again. It should then print those numbers that were common
# in both entries (from lowest to highest).
input1 = input('Please enter your numbers separated by commas:')
input2 = input('Please enter your numbers separated by commas:')
set1 = set(n for n in input1.split(', '))
set2 = set(n for n in input2.split(', '))
result_set = set1.intersection(set2)
result_list = list(result_set)
result_list.sort(key=int)
result = ', '.join(result_list)
print(result)
# Challenge 5:
# Write a script that prompts a user to input a list of words separated
# by commas, and then prints out the unique words in the list.
| true |
77ee2388db3dddcf57c75525c1115008592bc798 | DustyQ5/CTI110 | /P3T1_AreasOfRectangles_ChazzSawyer.py | 1,384 | 4.25 | 4 | # CTI-110
# P3T1 - Areas Of Rectangles
# Chazz Sawyer
# 9/25/2018
#Program welcomes user
#Progames ask for rectangle legnth and width. Then repeats.
#programs states the area of both rectangles
#programs announces which rectangle has a larger area or if
#they are equal
print ('Welcome to rectangle creation and comparison area.')
rectangle_one_length = float(input('Please enter the first rectangles length:'))
rectangle_one_width = float(input('Please enter the first rectangles width:'))
rectangle_one_area = rectangle_one_length * rectangle_one_width
rectangle_two_length = float(input('Please enter the second rectangles length:'))
rectangle_two_width = float(input('Please enter the second rectangles width:'))
rectangle_two_area = rectangle_two_length * rectangle_two_width
print ('The first rectangle has an area of:', rectangle_one_area)
print ('The second rectangle has an area of:', rectangle_two_area)
if rectangle_one_area == rectangle_two_area:
print ('Both rectangles have the same area!')
elif rectangle_one_area > rectangle_two_area:
print ('The first rectangle has a larger area than the second.')
elif rectangle_one_area < rectangle_two_area:
print ('The second rectangle has a larger area than the first.')
else:
print ("I don't know how we got here but something went wrong.")
| true |
3bf50aaf9347137d12099872cdefbdd467a7413f | Austin-deMora/ICS3U-Assignment6-Python-Pyramid_Volume | /pyramid_volume.py | 1,670 | 4.375 | 4 | #!/usr/bin/env python3
# Created by Austin de Mora
# Created in May 2021
# Program finds volume of a right rectangular pyramid
import math
def volume(length, width, height):
# Function calculates volume and returns it
# Process
volume = (length * width * height) / 3
return volume
def main():
# Takes user input, passes it to functions and calls them
print("Enter measurements and I will give you the volume of "
"a right rectangular pyramid")
# Input
while True:
length_string = input("Enter length (cm): ")
try:
length = int(length_string)
assert length > 0
break
except AssertionError:
print("This isn't a valid input")
except Exception:
print("This isn't a valid input")
while True:
width_string = input("Enter width (cm): ")
try:
width = int(width_string)
assert width > 0
break
except AssertionError:
print("This isn't a valid input")
except Exception:
print("This isn't a valid input")
while True:
height_string = input("Enter height (cm): ")
try:
height = int(height_string)
assert height > 0
break
except AssertionError:
print("This isn't a valid input")
except Exception:
print("This isn't a valid input")
# Calls functions
calculated_volume = volume(length, width, height)
# Output
print("The volume of the cylinder is: {:.2f}cm³".
format(calculated_volume))
if __name__ == "__main__":
main()
| true |
a29b0ca626fcd82d1802636feb52f07a0533a796 | mistrydarshan99/Leetcode-3 | /interviews/amazon/implement_stack_using_deque.py | 1,201 | 4.15625 | 4 | from collections import deque
# Pop from queue: deque.popleft()
# append to the queue: deque.append()
# Initialize: queue = deque()
"""
stack:
- first in, last out
"""
class Stack:
def __init__(self):
self.stackleft = deque()
self.stackright = deque()
def append(self, item):
if not self.stackleft:
self.stackleft.append(item)
while self.stackright:
i = self.stackright.popleft()
self.stackleft.append(i)
elif not self.stackright:
self.stackright.append(item)
while self.stackleft:
i = self.stackleft.popleft()
self.stackright.append(i)
def pop(self):
if self.stackleft:
return self.stackleft.popleft()
elif self.stackright:
return self.stackright.popleft()
def _show(self):
print("left", self.stackleft)
print("right", self.stackright)
s = Stack()
s.append(0)
s.append(1)
s._show()
s.pop()
s._show()
s.append(2)
print("\n")
s._show()
"""0: add 0
left: 0
right:
1: add 1
right: 1
left pop: 0
right: 1, 0
left:
2: pop
right.pop() -> pop out 1
right: 0
left:
3: add 2
left: 2
while right:
right.pop() -> 0
left.add(0) ->
left: 2, 0
right:
4: pop
left.pop() -> pop 2"""
| false |
cd6166e3fb6320e8c646a485ba28e62bbcba4b32 | mistrydarshan99/Leetcode-3 | /interviews/lyft/lyft_ouptut_last_n_row_of_file.py | 1,184 | 4.5 | 4 | """
given a file or file_handler.
Implement a function that:
tail(file, n =10): #default n = 10
- give last 10 rows of line in the file
tail(file, n):
- give last n rows of lines in the file
Thought:
- since we need to read the file line by line:
- but we only want to last n rows of file
- so we wish to pop out / throw away for unwanted lines at the front
- thus we need to use queue. --> import collections.deque
- queue data structure: first in, first out.
2 Queue options in python:
1. queue.Queue # different threads to communicate using queued messages/data
2. collections.deque # used as datastructure
** Note: collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft() operations that do not require locking
"""
import collections
def tail(fin, n=10):
"""
input fin: file_handler
input n: int # last n rows
ouput: print out the last n rows of file
"""
cache = collections.deque()
for line in fin:
cache.append(line)
if len(cache) > n:
cache.popleft()
for l in cache:
print(l)
fin = ["I love u", "i want to eat", "i want to"]
tail(fin, n=2)
| true |
58a01495d07cc25e0be70c39686f4728b178ac0e | bigmantings69/01-Lucky-Unicorn | /HL_yes_no.py | 2,364 | 4.25 | 4 | import random
# instruction if user did not play the game before
def instructions():
print()
print("**** How to Play ****")
print()
print("For each game you will be asked to...")
print("- Enter a 'low' and 'high' number. "
"The computer will randomly generate a 'secret' number between your two chosen numbers."
" It will use these numbers for for all the rounds in a given game.")
print("- The computer will calculate how many guesses you are allowed")
print("- enter the number of rounds you want to play")
print("- guess the secret number")
print()
print("Good Luck!")
# decorating program to decorate the game
def statement_generator(statement, decoration):
sides = decoration * 3
statement = "{} {} {}".format(sides, statement, sides)
top_bottom = decoration * len(statement)
print(top_bottom)
print(statement)
print(top_bottom)
return ""
# yes or no answer for the program
def yes_no(question):
valid = False
while not valid:
response = input(question).lower()
if response == "yes" or response == "y":
response = "yes"
return response
elif response == "no" or response == "n":
response = "no"
return response
else:
print("please enter yes or no")
def statement_generator(outcome, prize_decoration):
sides = prize_decoration * 3
outcome = "{} {} {}".format(sides, outcome, sides)
top_bottom = prize_decoration * len(outcome)
print(top_bottom)
print(outcome)
print(top_bottom)
return ""
def start():
print()
print("lets get started")
print()
prize_decoration = "-"
return""
# introduction for the game
# ask if they have played this game before
# if no show instructions
# if yes continue
statement_generator("Welcome to Higher or lower", "*")
print()
played_before = yes_no("Have you played this game before? ")
if played_before == "no":
instructions()
if played_before == "yes":
start()
rounds_played = 0
play_again = input("press <Enter> to play...").lower()
while play_again == "":
# increase # of rounds played
rounds_played += 1
# print round number
print()
print("*** Round #{} ***".format(rounds_played))
# check a lowest is an integer (any integer)
| true |
59e469c28a514a750fc43b61de86f8df642b3114 | RoboneClub/Hab-Lab-Analysis | /temperature_plotter.py | 1,698 | 4.28125 | 4 | #Pandas is used to open csv files and convert to lists
import pandas as pd
#Used for making plots
import matplotlib.pyplot as plt
#Library used to do maths
import numpy as np
#Load data to pandas
data = pd.read_csv('data.csv')
#Give time from data
time = data['Time']
sesnor_temperature_values = data['Temperature']
#Finds us the real tempreature because tempreature in the readings are higher maybe because the sensors might heat up
real_temperature_values = np.add(sesnor_temperature_values, -6)
#Use len function to find the number of values
number_of_readings = len(real_temperature_values)
print(number_of_readings)
#Adds all the values using the sum function numpy and then print it
sum_of_all_temperature_values = np.sum( real_temperature_values )
print(sum_of_all_temperature_values)
#Add all the number of readings then divide by the number of readings
mean_value_of_the_temperature = sum_of_all_temperature_values / number_of_readings
print(mean_value_of_the_temperature)
#We use np.full to repeat the mean value 968 times to be able to visulise them on the graph
mean_value_of_the_temperature = np.full(shape=number_of_readings, fill_value=mean_value_of_the_temperature)
#We plot the pressure value and label it
plt.plot( real_temperature_values, label="temperature")
#We plot the mean value and label it
plt.plot( mean_value_of_the_temperature, label="mean")
#Put title for the graph
plt.title("HAB-LAB: temperature's Graph")
#Legend creates the box for the key for the graph
plt.legend()
#Labels the x-axis
plt.xlabel("Number of readings")
#Labels the y-axis
plt.ylabel("Temperature (˚C)")
#Show the graph
plt.show()
| true |
cc862467514be24cd815fce7b1fb50c316a505aa | YannMoskovitz/Python-crash-course- | /class user.py | 2,839 | 4.3125 | 4 | class User:
"""Class of user stores a tipical user info"""
def __init__(self, first_name, last_name, username, location, email, middle_name=''):
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.username = username
self.location = location
self.email = email
self.login_attempts = 0
def full_name(self):
if self.middle_name == '':
entire_name = self.first_name + ' ' + self.last_name
else:
entire_name = self.first_name + ' ' + self.middle_name + ' ' + self.last_name
return entire_name.title()
# long_name = str(self.year) + ' ' + self.make + ' ' + self.model
def describe_user(self):
"""returns full name e-mail, username and location of any given user"""
print(f'the user: {self.username} name is {self.full_name()},'
f' his location and e-mail are respectively {self.location}, {self.email}.')
def greet_user(self):
"""simple custom user greeting"""
print(f'Welcome back {self.username}. ')
def increment_login_attempts ( self ) :
"""Increment the value of login_attempts."""
self.login_attempts += 1
def reset_login_attempts ( self ) :
"""Reset login_attempts to 0."""
self.login_attempts = 0
class Admin(User):
""""""
def __init__(self,first_name,last_name,username,location,email,middle_name=''):
super().__init__(first_name ,last_name ,username, location, email, middle_name='')
self.privileges = []
def show_privileges(self):
"""shows the privileges the user has"""
print(f'\n the user "{self.username}" has the following privileges')
for privilege in self.privileges:
print('- ' + privilege.title())
class Privilege(user):
""" """
def __init__(self,)
"""eric = User('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
eric.describe_user()
eric.greet_user()
willie = User('willie', 'burger', 'willieburger', 'wb@example.com', 'alaska')
willie.describe_user()
willie.greet_user()
yann = User('yann', 'moskovitz', 'sefyammas', 'yann.moskovitz@example.com.br', 'brazil', middle_name='comparato')
yann.describe_user()
yann.greet_user()"""
eric = Admin('eric', 'matthes', 'e_matthes', 'e_matthes@example.com', 'alaska')
eric.privileges = ['Can add and remove users from users list', 'Can post on portal', 'Can remove posts', 'Can login without password']
eric.describe_user()
eric.greet_user()
eric.show_privileges()
"""
print("\nMaking 3 login attempts...")
eric.increment_login_attempts()
eric.increment_login_attempts()
eric.increment_login_attempts()
print(" Login attempts: " + str(eric.login_attempts))
print("Resetting login attempts...")
eric.reset_login_attempts()
print(" Login attempts: " + str(eric.login_attempts))""" | true |
2da0812f53c518622b80e008d9263109efe8eec3 | Fange-Wu/Getting-Lucky | /07_job_v1.py | 904 | 4.15625 | 4 | import random
for item in range (0,10) :
operation = random.randint(1,3)
num1 = random.randint(1,10)
num2 = random.randint(1,10)
if operation == 1:
question = int(input("What is " + str(num1) + "+" + str(num2) + ": "))
answer = num1 + num2
if question == answer:
print("You got it right")
else:
print("You got it wrong")
elif operation == 2:
question = int(input("What is " + str(num1) + "-" + str(num2) + ": "))
answer = num1 - num2
if question == answer:
print("You got it right")
else:
print("You got it wrong")
elif operation == 3:
question = int(input("What is " + str(num1) + "x" + str(num2) + ": "))
answer = num1 * num2
if question == answer:
print("You got it right")
else:
print("You got it wrong") | true |
9b319fc716ba4ba97c1024cc5110a91d674e8305 | nbglink/ExamPythonBasics2018 | /CatWalk.py | 551 | 4.125 | 4 | minutes_walks_day = int(input())
count_walks_day = int(input())
calories_day = int(input())
summary_minutes_for_walk = minutes_walks_day * count_walks_day
summary_calories_burned = summary_minutes_for_walk * 5
half_of_taken_calories = calories_day - (50 * calories_day) / 100
if summary_calories_burned >= half_of_taken_calories:
print(f"Yes, the walk for your cat is enough. Burned calories per day: {summary_calories_burned}.")
else:
print(f"No, the walk for your cat is not enough. Burned calories per day: {summary_calories_burned}.")
| true |
a823d5c9b0f9417d6d95201a604d312377a627f3 | huytn1219/algorithm | /bestTimeToBuyandSellStock.py | 838 | 4.21875 | 4 | # You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
# Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
max_profit = 0
buy = prices[0]
for price in prices[1:]:
if price > buy:
max_profit = max(max_profit, buy - price)
else:
buy = price
return max_profit
prices = [7,1,5,3,6,4]
ob1 = Solution()
print(ob1.maxProfit(prices)) | true |
e4e6b947fe90a002055d4f62165cb10e599358f3 | ShioMura/astr-hw-1 | /operators.py | 327 | 4.21875 | 4 | x = 9
y = 3
print(x+y)
print(x-y)
print(x*y)
print(x/y)
print(x%y)
print(x**y)
x = 9.191823
print(x//y)
#assignment operators
x = 9
x += 3
print(x)
x = 9
x -= 3
print(x)
x = 9
x *= 3
print(x)
x = 9
x /= 3
print(x)
x **= 3
print(x)
# Comparison operators
x = 9
y = 3
print(x==y)
print(x!=y)
print(x>y)
print(x<y)
print(x>=y) | false |
1f31b496ab6ab081bcf8543c62205b5a77f949e8 | Damnful/210CT | /Question10.py | 925 | 4.1875 | 4 | def find_maximum_subsequence(sequence):
subsequenceList = []
currentSubsequence = []
maximumSubsequence = []
last = 0
for integer in sequence:
if integer <= last:
# basically, if the next value continues the increasing subsequence
subsequenceList.append(currentSubsequence)
# this is a list of lists, holding all the maximum increasing seqs
currentSubsequence = []
currentSubsequence.append(integer)
last = integer
# last is a comparison variable
subsequenceList.append(currentSubsequence)
for subsequence in subsequenceList:
# iterates through list of lists to find largest list
if len(maximumSubsequence) < len(subsequenceList):
maximumSubsequence = subsequence
print(str(maximumSubsequence))
find_maximum_subsequence([0,1,3,4,7,3,4,6,7,1,4,5,9,2,4,5])
| true |
dec4c475c48b85738c9103788dd20e811cb147cb | AmitabhK-je/PythonForEverybody | /Exercise_3/Exercise3.py | 697 | 4.1875 | 4 | """
Write a program to prompt for a score between 0.0 and
1.0. If the score is out of range, print an error message. If the score is
between 0.0 and 1.0, print a grade using the following table:
"""
try :
score = input('Enter score: ')
score = float(score)
if score >=0.0 and score <=1.0:
if score >= 0.9:
print('A')
elif score >=0.8 and score < 0.9:
print('B')
elif score >=0.7 and score < 0.8:
print('C')
elif score >=0.6 and score < 0.7:
print('D')
elif score <0.6:
print('F')
else:
print('Bad Score')
except:
print('Bad Score')
exit()
| true |
9a0c57528493155d91051fd13c45fa42917932de | gulci-poz/py_basics | /13_for.py | 602 | 4.1875 | 4 | # string - sequence of characters
for letter in 'Python':
print(letter, end='*')
print()
for name in ['Wiki', 'Mela', 'Ema']:
print(name, end=' ')
print()
sum_of_prices = 0
prices = [1, 2, 3, 4, 5]
for price in prices:
sum_of_prices += price
print('Sum of prices:', sum_of_prices)
sum_of_numbers = 0
# from zero, range(excluded)
for number in range(11):
sum_of_numbers += number
print('Sum:', sum_of_numbers)
# range(included, excluded)
for number in range(5, 11):
print(number, end=' ')
print()
# step
for number in range(5, 11, 2):
print(number, end=' ')
print()
| true |
6fa5c46cccd6a2e49f6a2d90480e296e66cfce18 | Fisik-Yadershik/L10 | /z3.py | 795 | 4.125 | 4 | #!/usr/bin/evn python3
# -*- config: utf-8 -*-
# Решите следующую задачу: напишите функцию, которая считывает с клавиатуры числа и
# перемножает их до тех пор, пока не будет введен 0. Функция должна возвращать
# полученное произведение. Вызовите функцию и выведите на экран результат ее работы.
def composition():
while True:
p = 1
a = int(input('first number: '))
b = int(input('second number: '))
if a == 0 or b == 0:
break
p *= a
p *= b
print(p)
if __name__ == '__main__':
prod = composition()
print(prod) | false |
6a30c2124bb7c57d935fdde5fcd82b2f732eea47 | t0etag/Python | /Python3/DemoProgs/comp_ifelse.py | 755 | 4.40625 | 4 | """Comprehension with If/Else
This program demonstrates the way if/else constructs can be
used within a comprehension. This particular example examines
each entry in a list containing numbers. For numbers >= 45,
one is added to the new number. Otherwise, five is added to
the new number. At some point in time, you have to decide
whether the compact expression of the comprehension introduces
too much difficulty in reading your code.
"""
lst = [22, 13, 45, 50, 98, 69, 43, 44, 1]
# Using a comprehension
newlst = [x+1 if x >= 45 else x+5 for x in lst]
print(lst)
print(newlst)
# Using a loop
newlst = []
for x in lst:
if x >= 45:
newlst.append(x + 1)
else:
newlst.append(x + 5)
print(newlst)
| true |
a00e865fcc8fbbdd21d1900765bf906fc7115c38 | t0etag/Python | /Python1/Labs/LastLabPy1/lab08b_func.py | 1,091 | 4.25 | 4 | """lab08b_func.py
This program reads a temperature from the keyboard. It then reads a
character that determines what type of conversion to perform. A 'c'
causes a fahrenheit-to-centigrade coversion while a 'f' causes the
opposite conversion. Separate functions provide the conversion as
well as print statements showing the result of the conversion. Then
it requests another input from the keyboard until a 'q' is entered.
"""
def f_to_c(xtmp):
ctmp = 5.0 / 9.0 * (xtmp - 32)
print('{0} degrees Fahrenheit is {1:.1f} degrees Centigrade'.format(
xtmp, ctmp))
def c_to_f(xtmp):
ctmp = 9.0 / 5.0 * xtmp + 32
print('{0} degrees Centigrade is {1:.1f} degrees Fahrenheit'.format(
xtmp, ctmp))
while True:
temp = input('Enter a temperature or Q: ')
if temp == 'q' or temp == 'Q':
break
flt_temp = float(temp)
convert = input('Enter a c or f: ')
if convert == 'c':
f_to_c(flt_temp)
elif convert == 'f':
c_to_f(flt_temp)
else:
print('Invalid conversion request')
| true |
4a1f75311937c0d224a507222c2e14f99e4f1d2e | t0etag/Python | /Python3/Labs/Lab12b.py | 1,648 | 4.375 | 4 | """Lab 12b - Comparisons
When you compare for equality, the default version of __eq__ is called
automatically and it will blindly compare two instances which will never be equal.
To override this result, implement one or more of the newer magic methods – in
our case __eq__. Use this magic method to compare the balances of the two
accounts. Test by using equal and non-equal balances
"""
class BankAccount: # Top tier class (super class) in Python 2 or 3
# class BankAccount: # works fine in Python 3. Parens not require
def __init__(self, name): # This method runs during instantiation
self.balance = 0 # instance variable
self.acctname = name # instance variable
def deposit(self, amount): # another method
if amount < 0:
return 4 # Negative deposits are really withdrawals
self.balance += amount
return 0 # Depost successful
def bal(self): # method that gets balance
return self.balance
# def __str__(self):
# return 'For account *{0}*, the balance is ${1:,.2f}'.format(self.acctname, self.balance)
def __eq__(self,other):
print(self.balance, other.balance)
if self.balance == other.balance:
return True
else:
return False
a = BankAccount('Monty Python') # Create an instance of Bankaccount
b = BankAccount('Guido van Rossum') # Create another instance
a.deposit(500)
b.deposit(2500)
if a == b:
print("Same")
else:
print("Different")
a.deposit(2000)
b.deposit(0)
if a == b:
print("Same")
else:
print("Different")
| true |
977f3f5c4bd8b57b45f9cdc89684ad08ca55da47 | t0etag/Python | /py4e/banana_index.py | 410 | 4.28125 | 4 | """
Write a while loop that start at the last characeter in the string and works ins way backwards to the first
character in the string, printing each letter on a seperate line.
"""
fruit = "banana"
length = len(fruit)
#last = fruit[length - 1]
last = fruit[-1] # this works better
print(last)
index = len(fruit) - 1
while index >= 0:
letter = fruit[index]
print(letter)
index -= 1 | true |
177ca0bebfb911304e56d6e91a6f11c5fa03d8c4 | t0etag/Python | /Python3/DemoProgs/varyargs.py | 610 | 4.625 | 5 | """Variable Positional Arguments
This demo program has a function that takes a variable number of
parameters and shows how a collector assembles them all in a tuple.
By tradition, we use *args for positional parameters and **kwargs
for keyword parameters.
"""
def myfnc(*args):
print(len(args), type(args))
print(args)
x = 1
y = 2
z = 3
myfnc(x, y, z)
"""
But, what if you have a collection (e.g., a list) that you want
to pass to a function that is expecting individual elements. Use
the * operator to pass the elements of the list instead of the
list itself.
"""
mylst = [x, y, z]
myfnc(*mylst)
| true |
dacc17ecb937360b01bb52bb4a8b7fcffc35bd9c | t0etag/Python | /Python2/Class Data/DemoProgs/sort_by_count.py | 836 | 4.34375 | 4 | """Sorting by Count
This program creates a dictionary containing counters. Then it
unloads the values and keys separately and zips the two together
with the count preceding the key. Then the sorted function is used
to sort each tuple in ascending order by count. Finally, the list
created by sorted is parsed in a for loop unpacking each tuple and
printing the key and associated value.
"""
d1 = dict(a=123, b=12, c=32, d=7, e=223)
print(d1)
unld = zip(d1.values(), d1.keys())
print(type(unld), list(unld)) # See what zip creates
unld = zip(d1.values(), d1.keys()) # why is this done again? Comment
# it out and see what happens.
sort_by_count = sorted(unld)
print(sort_by_count)
for cnt, key in sort_by_count: # Unpack each tuple into two variables.
print(key, cnt)
| true |
5953c9e6ab5a9829732a62a2dc9a29331881b994 | t0etag/Python | /Python3/DemoProgs/counter.py | 1,898 | 4.25 | 4 | """Demo the Counter class
This program demonstrates some of the capabilities of the Counter class
"""
from collections import Counter
x = 'abracadabra'
ltrs = Counter(x)
print(ltrs) # This object is not act exactly the same as a dictionary
print('Unloaded:', ltrs.most_common()) # This method unloads the object the
# same as dict.items() would except that the result is ordered by value
# Alternative way to populate an instantiation of Counter
ltrs = Counter() # Create an empty Counter
for letter in x:
ltrs[letter] += 1 # Note this does not fail if the letter is
# not already in the Counter
print('Alternative:', ltrs.most_common()) # print all of the tuples
# Another alternative way to populate an instantiation of Counter
ltrs = Counter() # Empty Counter
ltrs.update(x) # Initial population with update method
print('After Update:', ltrs) # print all of the tuples
z = 'himalayas' # Define a new string with letters to add
ltrs.update(z) # Additional data added with update method
print(ltrs.most_common()) # print all of the tuples
print('Minus:', ltrs - Counter(z)) # Subtracts and removes all entries < 1
ltrs.subtract(Counter(z))# Subtracts and keeps all results
print('Subtract:', ltrs)
ltrs += Counter() # Removes all entries < 1
print('Remove:', ltrs)
# To get the n most common, use the most_common method with the
# number (n) of the items you want: obj.most_common(n)
print('Top 3:', ltrs.most_common(3))
# To get the n least common you have to use this slice on the result
# of the most_common method: obj.most_common()[-1: -n-1; -1]
print('Bottom 3:', ltrs.most_common()[-1: -3-1: -1]) # as an example
# We could have used -4 in the above example in place of -3-1.
# I have found it helps to keep them separate if you are struggling
# to visualize this process.
print('Bottom 3:', ltrs.most_common()[-1: -4: -1]) # Same result as above
| true |
57977064c1194ace521008e3f7f1cbeb1977d572 | t0etag/Python | /py4e/grades.py | 461 | 4.1875 | 4 | """
prompt for score between 0.0 and 1.0. If score is out of range, print error.
If in range, print grade.
"""
score = input("Enter score between 0.0 and 1.0:")
score = float(score)
if(score < 0.0 or score > 1.0):
print("Invalid score.")
elif(score >= 0.9):
print("Grade: A")
elif(score >= 0.8):
print("Grade: B")
elif(score >= 0.7):
print("Grade: C")
elif(score >= 0.6):
print("Grade: D")
else:
print("Grade: F")
| true |
3602d74c9e268d133efe4d19b05c15d677a93d66 | t0etag/Python | /Python2/Labs/Lab06cX.py | 2,381 | 4.15625 | 4 | """LAB 06c
In your data file is a program named servercheck.py. It reads two files
(servers and updates) and converts the contents into two sets. The
updates are not always correct. You will find all of the set
operations/methods in Python Notes. Using just these
operations/methods, your job is as follows:
1. Determine whether the list of updates exists in the master server list.
Print a message indicating whether or not this is true.
2. If it is not true (and you know it isn't), create a new set containing the
update items that are NOT in the master server set. Print the number
and names of the unmatched servers.
3. Create a new master server set that excludes the valid updates.
4. Print the number of items in the original master server set and the
new master server set as well as the number of valid updates.
5. Write the contents of the new master server set to a printable
external file using the writelines file method. (See Python Notes)
"""
#reads two files (servers and updates) and converts the contents into two sets
updates = set(open('Python2/Labs/serverupdates.txt', 'r'))
servers = set(open('Python2/Labs/servers.txt', 'r'))
#print(updates)
#print(servers)
# Determine whether the list of updates exists in the master server list.
both = servers.intersection(updates)
#print(both)
#Print a message indicating whether or not this is true.
found = updates.issubset(servers)
if found == True:
print("Some updates not found in master list.")
"""
If it is not true (and you know it isn't), create a new set containing the
update items that are NOT in the master server set. Print the number
and names of the unmatched servers.
"""
diff = updates.difference(servers)
cnt=0
for i in diff:
cnt+=1
print(cnt, "server updates not found.")
for i in diff:
print(i, end=" ")
inter = updates.intersection(servers)
icnt = 0
for i in inter:
icnt+=1
print("Valid Updates:",icnt)
scnt = 0
for i in servers:
scnt+=1
print("Original Servers:",scnt)
uniq = updates.union(servers)
ucnt = 0
for i in uniq:
ucnt+=1
print("New Servers:",ucnt)
# Print the number of items in the original master server set and the
# new master server set as well as the number of valid updates
#writelines
#uniq.writelines()
#print(uniq.issubset(diff)) #False
#print(uniq.issuperset(diff)) #True | true |
aaabf4c649303af4afddef6b3de08100f18c6f61 | TeenageMutantCoder/Calculator-with-GUI | /calculator-with-gui/Libraries/Menus/HelpMenu.py | 938 | 4.3125 | 4 | import tkinter as tk # GUI Library
from tkinter import messagebox # Allows a messagebox to be displayed on screen
class HelpMenu(tk.Menu):
''' Help submenu '''
def __init__(self, parent):
tk.Menu.__init__(self, parent)
self.parent = parent
self.window = self.parent.parent
# TODO: Add help option windows
self.add_command(label="About", command=self.about)
self.add_command(label="How to Use", command=self.how_to_use)
def about(self):
message1 = "Created by Stevon Wright in December 2019. "
message2 = "This was a project to learn tkinter and GUI, "
message3 = "which I thought would help me improve in "
message4 = "Python and programming in general."
message = message1 + message2 + message3 + message4
messagebox.showinfo(message=message, title="About", parent=self.window)
def how_to_use(self):
pass
| true |
9ccf24642a475a6c87a11c91e947ed910d31dbc2 | RodriDFC/aprendiendo-python | /bucles/bucle-for-2.py | 595 | 4.21875 | 4 | # para usar la funcion print cuando se quiere imprimir mensajes y el valor de las variables hacer
# print(f"mensaje de la variable: {variable}")
for i in range(7):
print(f"mensaje de la variable: {i}")
print("-------------")
# con range(n,m)..... empieza en n y termina en m-1..... teniendo una longitud de m-n
for j in range(3,9):
print(f"mensaje de la variable: {j}")
print("-------------")
# con range(n,m,p)..... empieza en n, cuenta en multiplos de p
# termina en m-1 o en algun valor segun p
for k in range(10,30,3):
print(f"mensaje de la variable: {k}")
print("-------------") | false |
e6907c4ccb3d39ff820ee18f76bc5917d44a9bd5 | sandeepm96/cormen-algos | /Sai/kahn_topoSort.py | 1,404 | 4.25 | 4 | # A Python program to print topological sorting of a graph
# using indegrees
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
def topologicalSort(self):
indegree = [0]*self.V
#find indegree of all nodes.
for i in self.graph:
for j in self.graph[i]:
indegree[j]+=1
#creating a queue and enqueue all nodes with indegree 0.
queue = []
for i in range(self.V):
if indegree[i] == 0:
queue.append(i)
#count of visited vertices
count = 0
#to store result order
topOrder = []
while queue:
u = queue.pop(0)
topOrder.append(u)
for i in self.graph[u]:
indegree[i]-=1
if indegree[i]==0:
queue.append(i)
count+=1
if count != self.V:
print("there is a cycle present in the graph")
else:
print(topOrder)
g= Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
g.topologicalSort() | true |
bde4e246bf03d4b1af52de27ff283368257affb1 | kuldeep-dev/Python_Functions | /recursion_in_python.py | 816 | 4.15625 | 4 | # Recursions in python
# Resursion means use function in function
def print2(str1):
print("This is " + str1)
print2("kuldeep")
print("factorial itrative method")
def factorial_itrative(n):
"""
param n : integer
return : n*n-1 * n-2 * n-3......1
means n! : 5*4*3*2*1
"""
fac = 1
for i in range(n):
fac = fac*(i+1)
return fac
number = int(input("Enter the number"))
print(factorial_itrative(number))
# recursive method
def factorial_recursive(n):
if n ==1:
return 1
else:
return n * factorial_recursive(n-1)
print(factorial_recursive(number))
# Fibonacci series
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(number))
| false |
ae87eba08abf182fde332134ef2b1904e91e8d60 | rodolfoip/Python | /ExerciciosExtras/exercicio002.py | 391 | 4.21875 | 4 | #Faça um Programa que verifique se uma letra digitada é vogal ou consoante.
letra = str(input('Digite uma letra: ')).lower()
if len(letra)== 1:
if(letra == 'a'or letra == 'b' or letra == 'c' or letra == 'd' or letra == 'e'):
print('A letra digitada é uma VOGAL!!!')
else:
print('A letra digitada é uma CONSOANTE!!!')
else:
print('Digite apenas uma letra') | false |
d5437c8480538a0bd41bc2a3b36dddf50ea0ceae | mfalcirolli1/Python-Exercicios | /Aula 9 M 1.py | 1,047 | 4.15625 | 4 | # Manipulando Texto
f = 'curso em vídeo python'
print(f[15:])
# [:5] - [15:] - [9:14] - [9::3] = [9:21:3]
print('O comprimento da frase é de: {} caracteres'.format(len(f))) #Comprimento
print(len(f))
print(f.count('o', 0, 21)) #Contador de caracteres
print(f.find('y')) #Localizador de caractere em relação ao comprimento
print('Curso' in f) #Teste de existência
print('Android' in f) #Teste de existência
print(f.replace('python', 'Android')) #Substituir
print(f.upper()) #Maiúsculo
print(f.lower()) #Minúsculo
print(f.capitalize()) #Primeira letra da frase maiúscula
print(f.title()) #Primeira letra de todas as palavras maiúsculi
print(f.strip()) #Remove espaços vazios no começo e no fim da str (rstrip / lstrip)
print(f.split()) #Divisão das palavras as colocando em lista
print('-'.join(f)) #Junção
dividido = f.split()
print(dividido[0][2])
# loc = input('Digite uma letra presente na frase para saber a sua localização numérica: ')
# print('A letra digitada {}, está na posição {}'.format(loc, f.find(loc))) | false |
d646e0c9dd330ad29c3376a5ee49c1f70c6348bd | GalihRakasiwhi/DCC-PythonBeginners | /Exercise/exercise.py | 1,039 | 4.15625 | 4 | numbers = []
strings = []
names = ["Anakin Skywalker", "Padme Amidala", "Han Selo", "Qui-Gon Jinn", "Luke Skywalker", "Obi-an Kenobii"]
#write
second_name = None
#print Number
numbers.append(1)
numbers.append(2)
numbers.append(3)
strings.append("Satu")
strings.append("Dua")
strings.append("Tiga")
#this code should write out the filled arrays and the second name in the names 1st (Padme Amidala).
print(numbers)
print(strings)
numbers = names.index("Padme Amidala")
strings = names[1]
second_name = names[1]
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name)
#print the list variable use for
for x in names:
print(x)
#print the list without name "Han Solo"
print("------------")
for i in names:
if(i != names[2]):
print(i)
print("-----")
dictList = {"Name": "Galih Rakasiwhi", "Role": "Rogue"}
print("The {Name} is {Role}".format(**dictList))
print("The {Name} is {Role}".format(Name=dictList["Name"], Role=dictList["Role"]))
def printDict(*args, **kwargs):
for x in args:
print(x)
printDict(dictList)
#2020-14-2020 | true |
168c37edec6a17d03f44ca047e5d0cd5dd30a7ab | Elza-MerilGucic/HW9 | /HW9.1/main.py | 413 | 4.34375 | 4 | print("Welcome to distance unit converter")
while True:
kilometers = float(input("Please enter number of kilometers: "))
miles = 0.621371 * kilometers
print(str(kilometers) + " kilometers equals " + str(miles) + " miles")
repeat = input("Do you want to do another conversion? (yes / no): ")
if repeat == "yes":
continue
else:
print("Thank you and goodbye")
break
| true |
329f502e7bd2098dca7204d88b9ded699421d6f9 | ghezalsherdil/Web_Fundamentals | /Python/Python_assignments/type-list.py | 1,620 | 4.34375 | 4 | '''Assignment: Type List
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the list contains. If it contains only one type, print that type, otherwise, print 'mixed'.
Here are a couple of test cases. Think of some of your own, too. What kind of unexpected input could you get?
#input
l = ['magical unicorns',19,'hello',98.98,'world']
#output
"The list you entered is of mixed type"
"String: magical unicorns hello world"
"Sum: 117.98"
Copy
# input
l = [2,3,1,7,4,12]
#output
"The list you entered is of integer type"
"Sum: 29"
Copy
# input
l = ['magical','unicorns']
#output
"The list you entered is of string type"
"String: magical unicorns"
'''
mixed = ['cats', 10, 'dogs', 'python', 3748,'like']
integer = [5,13,9,888,148]
string = ['I','like','cats','not','dogs']
mixedin = []
name = []
for element in mixed:
if type(element) == int:
mixedin.append(element)
insum = sum(integer)
for ing in string:
if type(ing) == str:
name.append(ing)
print "The list you entered of of mixed type"
print "String:",mixed[0],mixed[2],mixed[3],mixed[5]
print "Sum",sum(mixedin)
print "The list you entered is of integer type"
print "Sum:",insum
print "The list you entered is of string type"
print "String:",string[0],string[1],string[2],string[3],string[4]
| true |
9562b71e46986b31bf317471b5703f34215d4c5e | RahulRj09/pythonprograms | /primenumber.py | 225 | 4.125 | 4 | # this program check number is prime or not
prime = input("enter number is prime or not")
s = 0
for i in range(2,prime):
if prime % i == 0:
s +=1
if s == 0:
print "number is prime"
else:
print "nmuber not prime" | true |
e9767c9681860453593aa4843f997993b43a2e19 | hsfear/exercises | /python/100steps/hello-world/if_examples.py | 427 | 4.15625 | 4 | first = int(input("Enter the first number: "))
second = int(input("Enter the second number: "))
operation = input("Enter the operation [+-*/]: ")
if operation == '+':
result = first + second
elif operation == '*':
result = first * second
elif operation == '-':
result = first - second
elif operation == '/':
result = first / second
else:
raise ValueError(f"Invalid operation {operation}")
print(result)
| true |
646581b644ac8de68ab4d1736662e9d38e1bc398 | thapaliya123/Python-Practise-Questions | /data_types/problem_16.py | 226 | 4.15625 | 4 | """
Q.a Python program to sum all the items in a list.
"""
def sum_list_items(target_list):
sum=0
for item in target_list:
sum+=item
return sum
print("The sum of list is:", sum_list_items([1, 2, 3, 4, 5])) | true |
2e833a906a810bafa9185e337f175f29c8522241 | thapaliya123/Python-Practise-Questions | /functions/problem_17.py | 310 | 4.3125 | 4 | """
17.Write a Python program to find if a given string starts with a given character
using Lambda.
"""
string_with_given_char = lambda sample_string, sample_char: True if sample_string[0]==sample_char else False
sample_string="anish"
sample_char = "a"
print(string_with_given_char(sample_string, sample_char)) | true |
29c8946c0305a9dd70a66680c1c15f175afac969 | thapaliya123/Python-Practise-Questions | /functions/problem_12.py | 306 | 4.3125 | 4 | """
12. Write a Python program to create a function that takes one argument, and
that argument will be multiplied with an unknown given number.
"""
def multiply_with_unknown(sample_number):
return lambda x:sample_number*x
sample_number=10
result = multiply_with_unknown(sample_number)
print(result(3)) | true |
c1c2dabfe1305a88554e8b6264db862057343f96 | Jkoss172/ChatBotProject | /main.py | 1,635 | 4.125 | 4 | # Class Project - sprint01 - Base Code Design - 06/17/2021
# Here we put the import files
import random
# Here we declare global variables
program_over = True # sets the main loop to run
# Here we will define our classes and functions
class MainMenu: # This is the main menu
def intro():
print("Hello, welcome to the math tutor program.")
print("I am your tutor and I am here to help you learn.")
print("You may choose from the following options: ")
print(" 1. Directions")
print(" 2. Start Program")
print(" 3. Quit")
choice = input("\n What do you choose to do? ")
if choice == "1":
MainMenu.directions()
elif choice == "2":
play = TheBrain
elif choice == "3":
print("Goodbye!")
program_over = False
quit()
else:
print(" Please try again.")
press = input("\n Please press Enter to continue.")
def directions():
print("Greetings! I am your virtual math tutor.")
print("I am here to help you learn math.")
print("You can choose to do addition, subtraction, multiplication, or division.")
print("If you solve the problem correctly you will earn score points.")
print("If you do not answer correctly, you will not get any score points.")
press = input("\n Please press Enter to continue.")
class TheBrain: # This class will be the main intelligence of the program.
pass
while program_over:
game = MainMenu.intro()
| true |
ea2e41ee0aabed72fcee1e7d0e130c03ead62658 | cwb4/Impractical_Python_Projects | /Chapter_4/permutations_practice.py | 1,465 | 4.28125 | 4 | """For a total number of columns, find all unique column arrangements.
Builds a list of lists containing all possible unique arrangements of
individual column numbers including negative values for route direction
(read up column vs. down).
Input:
-total number of columns
Returns:
-list of lists of unique column orders including negative values for
route cipher encryption direction
"""
import math
from itertools import permutations, product
#------BEGIN INPUT-----------------------------------------------------------
# Input total number of columns:
num_cols = 4
#------DO NOT EDIT BELOW THIS LINE--------------------------------------------
# generate listing of individual column numbers
columns = [x for x in range(1, num_cols+1)]
print("columns = {}".format(columns))
# build list of lists of column number combinations
# itertools product computes the cartesian product of input iterables
def perms(columns):
"""Take number of columns integer & generate pos & neg permutations."""
results = []
for perm in permutations(columns):
for signs in product([-1, 1], repeat=len(columns)):
results.append([i*sign for i, sign in zip(perm, signs)])
return results
col_combos = perms(columns)
print(*col_combos, sep="\n") # comment-out for num_cols > 4!
print("Factorial of num_cols without negatives = {}"
.format(math.factorial(num_cols)))
print("Number of column combinations = {}".format(len(col_combos)))
| true |
b49e95e05c2c6f5749890eca608231291d12438d | piyushc0/Python | /src/String.py | 1,279 | 4.21875 | 4 | course = "Python's course for Beginners"
print(course)
message = '''
Hi Piyush,
Here is an example of 3 quotes
So you see it is fun in "Python"
- From Omni
'''
print(message)
name = "Piyush"
print(name[0]) # First Index
print(name[-1]) # Index from end
print(name[0:3]) # Index Range(excludes last index e.g- 3 is excluded) Output: Piy
print(name[1:]) # All values from first index provided Output: iyush(since, first index was 1)
print(name[:]) # All values Output: Piyush
# Exercise
name = "Piyush"
print(name[1:-1]) # Outputs iyus(since it omits the last index when we use -ve index)
# Formatted String
first = "Piyush"
last = "Choubey"
msg = f'{first} [{last}] is a coder'
print(msg) # Piyush Choubey is a coder
# Methods Here Course is "Python's course for Beginners"
wrong = 'piyush'
print(len(course))
print(course.upper()) # PYTHON'S COURSE FOR BEGINNERS
print(course.lower()) # python's course for beginners
print(course.find('P')) # 0(Index Value)
print(course.find('10')) # -1(Because there's no '10' in course)
print(course.find('Beginners')) # 20(since, it gives the index where the B is)
print(course.replace('Beginners', 'Absolute Beginners')) # Python's course for Absolute Beginners
print('Python' in course) # True
print(wrong.title()) # Piyush
| true |
189a85c447639974ff339b9919af9e35f4a17bcb | rohanwarange/TCS | /untitled0.py | 969 | 4.1875 | 4 | # -*- coding: utf-8 -*-
#"""
#Created on Fri Jul 2 08:11:58 2021
#
#@author: ROHAN
#"""
##Prime Numbers with a Twist
#Ques. Write a code to check whether no is prime or not. Condition use function check() to find whether entered no is positive or negative ,if negative then enter the no, And if yes pas no as a parameter to prime() and check whether no is prime or not?
#
#Whether the number is positive or not, if it is negative then print the message “please enter the positive number”
#It is positive then call the function prime and check whether the take positive number is prime or not.#
def prime(n):
if n>1:
for i in range(2,n//2):
if n%i==0:
print("enter the number is Not Prime : ”")
break
else:
print("enter the number is Prime : ”")
n=int(input())
if n<=0:
print("“please enter the positive number”")
else:
prime(n)
| true |
32f808f78d940ba922717ef7a68cc06605bbc337 | jaarmore/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 619 | 4.375 | 4 | #!/usr/bin/python3
"""
Function that read a text file
"""
def read_lines(filename="", nb_lines=0):
"""
Function that reads n lines of a text file
Args:
filename: name of the file
nb_lines: number of lines to read
"""
tlines = 0
with open(filename, encoding='utf-8') as a_file:
for line in a_file:
tlines += 1
with open(filename, encoding='utf-8') as a_file:
if nb_lines <= 0 or nb_lines >= tlines:
print(a_file.read(), end='')
else:
for line in range(nb_lines):
print(a_file.readline(), end='')
| true |
e7ffe55940e92ed673dfb059f5cba28859b47efd | jaarmore/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 291 | 4.25 | 4 | #!/usr/bin/python3
"""
Function that reads a text file encoding UTF-8
"""
def read_file(filename=""):
"""
Function that reads a text file
Args:
filename: name of the file
"""
with open(filename, encoding='utf-8') as a_file:
print(a_file.read(), end='')
| true |
214891106b0d01783bf4b01adbd6bde052e6f229 | xiyiwang/leetcode-challenge-solutions | /2021-03/2021-03-15-Codec.py | 1,297 | 4.15625 | 4 | """
LeetCode Challenge: Encode and Decode TinyURL (2021-03-15)
TinyURL is a URL shortening service where you enter a URL
such as https://leetcode.com/problems/design-tinyurl and it
returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service.
There is no restriction on how your encode/decode algorithm
should work. You just need to ensure that a URL can be encoded
to a tiny URL and the tiny URL can be decoded to the original
URL.
"""
# Runtime: 36 ms (faster than 52.10%); Memory Usage: 14.6 MB
import random
class Codec:
db = dict()
def encode(self, longUrl: str) -> str:
"""Encodes a URL to a shortened URL.
"""
lengthOfString = 4
shortUrl = f"https://short_url/{''.join(random.choice(string.ascii_letters) for i in range(lengthOfString))}"
# make sure short_url is a unique value
while shortUrl in self.db:
shortUrl = f"https://short_url/{''.join(random.choice(string.ascii_letters) for i in range(lengthOfString))}"
self.db[shortUrl] = longUrl
return shortUrl
def decode(self, shortUrl: str) -> str:
"""Decodes a shortened URL to its original URL.
"""
return self.db[shortUrl] | true |
fae6011dd3de9425b309e2bf4e4d311371ecdbb7 | 214031230/Python21 | /day3/第三周小练习/练习3.py | 2,290 | 4.21875 | 4 | #!/usr/bin/env python3
# 2、写函数,接收n个数字,求这些参数数字的和。(动态传参)
# def fun1(*args):
# sums = 0
# for i in args:
# sums += i
# return sums
#
#
# res = fun1(1, 2, 3, 4)
# print(res)
# 3、读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
# a = 10
# b = 20
#
#
# def test5(a, b): # a = 20 b = 10
# print(a, b)
#
#
# c = test5(b,a)
# print(c) # none
# 4、读代码,回答:代码中,打印出来的值a,b,c分别是什么?为什么?
# a = 10
# b = 20
#
#
# def test5(a, b): # a = 20 b = 1
# a = 3
# b = 5
# print(a, b) # 3 5
#
#
# c = test5(b,a)
# print(c)
# a = 10
# b = 20
#
#
# def test5(argv1, argv2): # a = 20 b = 1
# global a
# a = 3
# b = 5
# print(a, b) # 3 5
#
#
# c = test5(a,b)
# print(c)
# print(a,b)
# 1,有函数定义如下:
# def calc(a,b,c,d=1,e=2):
# return (a+b)*(c-d)+e
# # 请分别写出下列标号代码的输出结果,如果出错请写出Error。
# print(calc(1,2,3,4,5)) # 2
# print(calc(e=4,c=5,a=2,b=3)) # 24
# print(calc(1,2,3)) # 8
# print(calc(1,2,3,e=4)) # 10
# print(calc(1,2,3,d=5,4)) # EROOR
# 2,下面代码打印的结果分别是_________,________,________.
# def extendList(val,list=[]):
# list.append(val)
# return list
list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')
print('list1=%s'%list1)
print('list2=%s'%list2)
print('list3=%s'%list3)
# def extendList(val,list=[]): # val = 123 list = []
# list.append(val)
# return list
#
# list1 = extendList(10) # list1 = [10]
# list2 = extendList(123,[]) # list2 = [123]
# list3 = extendList('a') # list3 = ["a"]
# print('list1=%s'%list1) # [10]
# print('list2=%s'%list2)# [123]
# print('list3=%s'%list3)# ["a"]
# def wrapper():
# a = 1
# def inner():
# print(a)
# return inner
# wrapper = wrapper() # inner
# wrapper() #inner()
# def login_model(argv):
# def inner(*args):
# print("登录成功!")
# res = argv(*args)
# return res
# return inner
#
# @login_model # f1 = login_model(f1)
# def f1(a, b, c):
# return (a,b,c)
# print(f1(1,2,3))
# @login_model
# def f2():
# pass
# @login_model
# def f3():
# pass
| false |
35b4aec82f1effe51f5ed4e5e2f07db5695fc6df | LEUNGUU/data-structure-algorithms-python | /Recursion/exercises/r417.py | 582 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# def is_palindrome(s: str) -> bool:
# def judge(s: str, start: int, end: int) -> bool:
# n = end - start + 1
# if n <= 1:
# return True
# return (s[start] == s[end]) and judge(s, start+1, end-1)
# return judge(s, 0, len(s)-1)
def is_palindrome(s: str) -> bool:
if len(s) <= 1:
return True
return (s[0] == s[len(s) - 1]) and is_palindrome(s[1 : len(s) - 1])
if __name__ == "__main__":
print(is_palindrome("racecar"))
print(is_palindrome("gohangasalamiimalasagnahog"))
| false |
af7eb5e873b6466253e644eb88f35db1de315220 | LEUNGUU/data-structure-algorithms-python | /Sorting-Selection/ArrayBasedMergeSort.py | 648 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def merge(S1, S2, S):
"""Merge two sorted Python list S1 and S2 into properly sized list S"""
i = j = 0
while i + j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i + j] = S1[i]
i += 1
else:
S[i + j] = S2[j]
j += 1
def merge_sort(S):
"""Sort the elements of Python list S using the merge-sort algorithm"""
n = len(S)
if n < 2:
return
mid = n // 2
S1 = S[0:mid]
S2 = S[mid:n]
merge_sort(S1)
merge_sort(S2)
merge(S1, S2, S)
if __name__ == "__main__":
pass
| false |
fb6218fcf5ea020e46c07bd60b9dbce9a965231a | LEUNGUU/data-structure-algorithms-python | /Recursion/exercises/r401.py | 292 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# find the largest element in a list
def find_maximum(nums: list) -> int:
if len(nums) == 1:
return nums[0]
return max(nums[0], find_maximum(nums[1:]))
if __name__ == "__main__":
print(find_maximum([1, 2, 3, 6, 4, 3, 7]))
| true |
112f2592429a19aabb3173420e9c9f9e593b8a50 | LEUNGUU/data-structure-algorithms-python | /Recursion/fibonacci.py | 535 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Running time is exponential in n.
def bad_fibonacci(n):
"""Return the nth Fibonacci number"""
if n <= 1:
return n
else:
return bad_fibonacci(n - 1) + bad_fibonacci(n - 2)
# Running time is linear time
def good_fibonacci(n):
"""Return pair of Fibonacci numbers, F(n) and F(n-1)"""
if n <= 1:
return (n, 0)
else:
(a, b) = good_fibonacci(n - 1)
return (a + b, a)
if __name__ == "__main__":
print(good_fibonacci(3))
| false |
84673b1c1dbcc360060ff262baf293a341bbddb6 | stevedeNero/MIT_OCW_6.0001 | /ps1a.py | 1,354 | 4.21875 | 4 | ####################################
# Gather Salary Information
annual_salary = float(input("How much $ do you make a year?"))
portion_saved = float(input("How much can you set aside to save for down-payment?\n(Enter value in range of 0.0 to 1.0)"))
current_savings = 0.0
####################################
# Gather Information on the Dream House
total_cost = float(input("How much does the house cost?"))
portion_down_payment = 0.25 * total_cost
# print(portion_down_payment)
####################################
# Alternatively, maybe since you're moving to the Bay Area you have a Trust Fund.
# current_savings = float(input("How much money are you getting from your family/trust fund?"))
# if current_savings >= total_cost:
# print("Lucky Day, Go Buy That House!")
# else:
# print("Keep saving, Champ")
####################################
# Initialize Variables
r = 0.04 # r is a variable used as Annual Rate of Return on Savings. Hard-coding to 4% Annual ROI
i = 0 #Total Number of Months
monthly_salary = annual_salary / 12
monthly_saved = portion_saved * monthly_salary
while current_savings < portion_down_payment:
i += 1
current_savings = current_savings + monthly_saved + ( current_savings * (r / 12))
print("After",i,"months, you've saved",current_savings)
print("Number of months:",i) | true |
026072a67c2f075ac0361937fa50923b0b6263cc | seemaPatl/python | /mergesort.py | 1,205 | 4.34375 | 4 | import pdb
pdb.set_trace()
def mergesort(lst1,lst2,lst3=[],idx1=0,idx2=0):
'''
objective:to merge two sorted list into third list
input parameters:
lst1,lst2:two sorted list
lst3:third list with elements of the lst1 and lst2 sorted
approach:using recursion
'''
if (len(lst3)==len(lst1)+len(lst2)):
return (lst3)
elif (len(lst1)==idx1):
lst3.extend(lst2[idx2:])
return (lst3)
elif (len(lst2)==idx2):
lst3.extend(lst1[idx1:])
return (lst3)
elif (lst1[idx1]<=lst2[idx2]):
lst3.append(lst1[idx1])
idx1=idx1+1
return mergesort(lst1,lst2,lst3,idx1,idx2)
elif(lst1[idx1]>=lst2[idx2]):
lst3.append(lst2[idx2])
idx2=idx2+1
return mergesort(lst1,lst2,lst3,idx1,idx2)
def main():
'''
objective:to merge two sorted list into third list
input parameters:
lst1,lst2:two sorted list
lst3:third list with elements of the lst1 and lst2 sorted
approach:using recursion
'''
lst1=[1,4,5]
lst2=[3,8 ,9,11]
lst3=mergesort(lst1,lst2)
print(lst3)
if __name__=='__main__':
main()
| false |
974e35b53ed0318244f7f5afe881bc97a5ab5ad7 | mlitsey/Learning_Python | /IntroPY4DS/day3/austin-pw.py | 937 | 4.34375 | 4 | # Password entering exercise
# 01. Allow the user to enter a password that matches a secret password
# 02. Allow them to make 5 attempts
# 03. Let them know how many they have made
# 04. Display if password is correct or if max attempts has been reaced.
SECRET_PW = 'katana'
pw_in = ''
cur_attempts = 0
MAX_ATTEMPTS = 5
while cur_attempts <= MAX_ATTEMPTS:
# Ask for pass
pw_in = input("Password: ")
# Increment current attempts
cur_attempts += 1
if pw_in != SECRET_PW:
# Login failure
if cur_attempts == MAX_ATTEMPTS:
print("Maximum attempts reached.")
break
else:
print("Incorrect password. ({} out of {} tries left.)".format((MAX_ATTEMPTS - cur_attempts), MAX_ATTEMPTS))
continue
else:
# Successful login
print("Successful login!")
print("Present pretty shell here.")
break | true |
d72179aafd311b6c8edc4e63c8cf6d62786920de | Venkatesh0000/python | /week 4/week.4.2.py | 331 | 4.125 | 4 | string1=input('enter the first string')
string2=input('enter the second string')
if(len(string2)==len(string1)):
if(sorted(string1)== sorted(string2)):
print("The strings are anagrams.")
else:
print("The strings aren't anagrams.")
else:
print("process not possiable") | true |
0a16b3f12dc12bd221f719645e95b66e7be45fd3 | jmontes50/Codigo10 | /Backend/VirtualBack/Dia1/03-operadores.py | 1,596 | 4.4375 | 4 | # Operadores aritmeticos
# + suma
# - resta
# * multiplicacion
# / division
# % modulo
# ** exponente
# // cociente (SOLO PYTHON)
num1 = 10
num2 = 20
num3 = num1+num2
print(num3)
num3 = num1 ** num2
print(num3)
num3 = num2 // num1
print(num3)
# -----------------------
# Operadores asignacion
# = Igual
# += Incremento
# -= Decremento
# *= Multiplicador
# /= Division
# *= Potencia
# num1 += num2 es lo mismo que haber puesto num1 = num1 + num2
num1 += num2
print(num1)
# es lo mismo que haber puesto num1 = num1 - num2
num1 -= num2
print(num1)
# -----------------------
# Operadores Comparacion
# == si es igual
# != si es diferente
# <, > es menor o mayor que
# <=, >= es menor o igual que , es mayor o igual que
print(num1==num2)
print(num1!= num2)
# -----------------------
# Operadores Logicos
# and
# or
# not
# En el caso de AND todos deben ser verdaderos para que todo sea verdadero, si hay algun resultado falso, todo es falso
# En el caso de OR basta con que uno sea verdadero para que todo sea verdadero, si todo es falso, sera falso
print((10<20) and (9<10))
print((10<9) or (9<20))
print(not(10<20))
# -----------------------
# Operadores de Identidad
# is => es
# is not => no es
# sirve para ver si estan apuntando a la misma direccion de memoria
frutas= ["Manzana", "Pera"]
frutas2 = frutas
print(frutas2 is frutas)
print(frutas2 is not frutas)
# -----------------------
# Operadores de Pertenencia
# in => para ver si esta contenido
# not int => para ver si no esta contenido
dias = ["Lunes","Miercoles","Viernes"]
dia = "Sabado"
print(dia in dias)
print(dia not in dias) | false |
c132b13c693e2536c5cd40db9ff88301a2b3b527 | SRI-VISHVA/Electoral_Result_Management_2019_DBMS_PROJECT | /sample1.py | 1,809 | 4.34375 | 4 | import csv
import sqlite3
csv_reader = csv.reader("election_result2k19sonali.csv")
con = sqlite3.connect(":memory:")
cur = con.cursor()
# create the required table
#all the attributes with their respective constraint
cur.execute("Create table voting_list ( Aadhar number(3),Voter_name varchar(100) PRIMARY KEY, Age number(3),"
" Sex char(3) ,"
" C_id number(3),Constituency varchar(100), State_id varchar(3), "
"State_name varchar(100),voting_status varchar(4));")
#Read the CSV file
with open('election_result2k19sonali.csv','r') as csv_file:
for i in csv_file:
print(i)
'''cur.executemany(
"Insert into voting_list ( Aadhar, Voter_name, Age, Sex, "
"C_id, Constituency, State_id, State_name, voting_status)"
"values (?,?,?,?,?,?,?,?,?);", list(i))'''
#To insert into the database the new voters with all there details
#takes input for as many voters the user wants
#checks if the user wnts to insert the data
l='Y'
while True:
l=input('Do you want to enter any details about the voters(Y/N):')
if l=='N':
break
n=int(input("Enter the number of data you want to input: "))
for i in range(0,n):
tl = []
tl.append(input("Enter the aadhar : "))
tl.append(input("Enter the name : "))
tl.append(input("Enter the age : "))
tl.append(input("Enter Sex: "))
tl.append(input("Enter the Constituency: "))
tl.append(input("Enter the Constituency id: "))
tl.append(input("Enter the state id : "))
tl.append(input("Enter the state name: "))
tl.append(input("Enter the Voting status: "))
print("\n")
''' try:
cur.execute("insert into voting_list values (?,?,?,?,?,?,?,?,?)",tl)'''
csv_file.close()
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.