blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
27fd01098ce6f68a304f25eb885af97217863453 | shivambhojani/Python-Practice | /remove_char.py | 372 | 4.3125 | 4 | # Write a method which will remove any given character from a String?
def remove(str, char):
new_str = ""
for i in range(0, len(str)):
if i != char:
new_str = new_str + str[i]
return new_str
a = input("String: ")
b = int(input("which Character you want to remove: "))
b = b-1
new_string = remove(a, b)
print(new_string)
| true |
4067c6b39abf37b18537c930109aa732e9dfe885 | menliang99/CodingPractice | /PeakingIterator.py | 714 | 4.25 | 4 | # Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.peekFlag = False
self.nextElement = None
def peek(self):
if not self.peekFlag:
self.nextElement = self.iter.next()
self.peekFlag = True
return self.nextElement
def next(self):
if not self.peekFlag:
return self.iter.next()
nextElement = self.nextElement
self.peekFlag = False
self.nextElement = None
return nextElement
def hasNext(self):
return self.peekFlag or self.iter.hasNext()
| true |
0312a221309f546836230b69bf7b6c81f02bac56 | mhetrick29/COS429_Assignments | /A4_P2/relu_backprop.py | 1,208 | 4.15625 | 4 | def relu_backprop(dLdy, x):
import numpy as np
# Backpropogates the partial derivatives of loss with respect to the output
# of the relu function to compute the partial derivatives of the loss with
# respect to the input of the relu function. Note that even though relu is
# applied elementwise to matrices, relu_backprop is consistent with
# standard matrix calculus notation by making the inputs and outputs row
# vectors.
# dLdy: a row vector of doubles with shape [1, N]. Contains the partial
# derivative of the loss with respect to each element of y = relu(x).
# x: a row vector of doubles with shape [1, N]. Contains the elements of x
# that were passed into relu().
# return:
# [dLdX]: a row vector of doubles with shape [1, N]. Should contain the
# partial derivative of the loss with respect to each element of x.
# TODO: Implement me!
dLdX = np.multiply(dLdy, dRelu(x))
return dLdX
# helper function to get all values in x greater than 0 and turn into 1
# this is 'Z' function
def dRelu(x):
for i in range(len(x)):
if (x[0][i] > 0):
x[0][i] = 1
else:
x[0][i] = 0
return x
| true |
e56c29cc6afc63b4ec4cf5afc97355e0385ee367 | nunu2021/DijkstraPathFinding | /dijkstra/basic_algo.py | 2,208 | 4.125 | 4 | import pygame
graph = {
'a': {'b': 1, 'c': 1, 'd': 1},
'b': {'c': 1, 'f': 1},
'c': {'f': 1, 'd': 1},
'd': {'e': 1, 'g': 1},
'e': {'g': 1, 'h': 1},
'f': {'e': 1, 'h': 1},
'g': {'h': 1},
'h': {'g': 1},
}
def dijkstra(graph, start,goal):
shortest_distance ={} # records the cost to reach to that node
track_predecessor = {} # keep track of the path that has led us to this node
unseenNodes = graph # to iterate through the entire graph
infinity = 9999999999 # infinity can basically be considered a very large number
track_path = [] # going to trace out journey back to the source node, which is the optimal route
for node in unseenNodes:
shortest_distance[node] = infinity
shortest_distance[start] = 0
while unseenNodes:
min_distance_node = None
for node in unseenNodes:
if min_distance_node == None:
min_distance_node = node
elif shortest_distance[node] < shortest_distance[min_distance_node]:
min_distance_node = node
path_options= graph[min_distance_node].items()
for child_node, weight in path_options: # checks if the path to
if weight + shortest_distance[min_distance_node] < shortest_distance[child_node]:
shortest_distance[child_node] = weight + shortest_distance[min_distance_node]
track_predecessor[child_node] = min_distance_node
# since dijkstra's algo does not allow back tracking, we will not be able to visit the nodes we have already gone through
unseenNodes.pop(min_distance_node)
# vvv before this code, the program has the shortest path from anywhere to anywhere.
currentNode = goal
while currentNode != start:
try:
track_path.insert(0, currentNode)
currentNode = track_predecessor[currentNode]
except KeyError:
print('Path is not reachable')
break;
track_path.insert(0, start)
if shortest_distance != infinity:
print("Shortest Distance is " + str(shortest_distance[goal]))
print("Optimal path is: " + str(track_path))
dijkstra(graph, 'a', 'h')
| true |
0fbca70b44d8bcf4fc87316e0b840e40ad8881f0 | guanhejiuzhou/PythonStudy | /Python语言基础/Day001-元素的变量.py | 2,438 | 4.4375 | 4 | """
变量和类型
变量时数据的载体,简单的说就是一块用来保存数据的内存空间,变量的值可以被读取和修改。
python中的几种常用数据类型
整型 int:python中可以处理任意大小的整数
浮点型 float
字符串型 str:字符串是以单引号或者双引号括起来的任意文本
布尔型 bool:布尔值只有true和false两种值,要么true要么false
"""
'''
变量命名
硬性规则:
1、变量名由字母、数字、下划线构成,数字不能开头
2、大小写敏感,大写的A和小写的a是两个不同的变量
3、不要跟Python语言的关键字和保留字(如函数、模块等的名字)发生重名的冲突
非硬性规则:
1、变量名通常使用小写英文字母,多个单词用下划线进行连接
2、受保护的变量用单个下划线开头
3、私有的变量用两个下划线开头
'''
# ======================= 变量的使用 ======================= #
# 使用变量保存数据并进行加减乘除运算
a = 45 # 变量a保存了57
b = 12 # 变量b保存了12
print(a + b) # 57
print(a - b) # 33
print(a * b) # 540
print(a / b) # 3.75
# 使用type()检查变量的类型
a = 100
b = 12.1
c = "hello"
d = True
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'bool'>
"""
不同类型的变量可以相互转换
int:将一个数值或字符串转换成整数,可以指定进制
float:将一个字符串转换成浮点数
str:将指定的对象转换成字符串形式,可以指定编码
chr:将整数转换成该编码对应的字符串(一个字符)
ord:将字符串(一个字符)转换成对应的编码(整数)
"""
a = 100
b = 12.1
c = "hello"
d = True
# 整数转换成浮点数
print(float(a)) # 100.0
# 浮点型转成字符串(输出字符串时不会看到引号)
print(str(b)) # 12.1
# 字符串转成布尔型(有内容的字符串都会转成True)
print(bool(c)) # True
# 布尔型转成整数(True会转成1,false会转成0)
print(int(d)) # 1
# 将整数变成对应的字符
print(chr(97)) # a
# 将字符转成整数(python中字符和字符串表示法相同)
print(ord("a")) # 97
"""
python程序中,可以使用变量来保存数据,变量有不同的类型,变量可以做运算,也可以通过内置函数来转换变量类型
"""
| false |
19667d8cd7c9c82438df92eff2f4062be06ef339 | echase6/codeguild | /practice/pig-latin-sentence.py | 1,693 | 4.15625 | 4 | """
Program to translate a single word into Pig Latin
This is an individual project by Eric Chase, 7/11/16
Input: a single words
Output: a word converted into Pig Latin
"""
# setup
VOWELS = ['a', 'e', 'i', 'o', 'u']
pig_latin = []
def convert_pig_latin(english_input):
# First, break into three parts: beginning punctuation, word, and ending punctuation
bi = 0 # bi ends up being the index where the beginning punctuation ends
letter = english_input[bi]
while not letter.isalpha():
bi += 1
letter = english_input[bi]
ei = len(english_input) - 1 # ei ends up being the index where the ending punctuation begins
letter = english_input[ei]
while not letter.isalpha():
ei -= 1
letter = english_input[ei]
beginning_punct = english_input[:bi]
ending_punct = english_input[ei + 1:]
english_word = english_input[bi:ei + 1]
# Now, focus on converting the word into Pig Latin
capitalized = english_word[0] == english_word[0].upper()
english = english_word.lower()
i = 0
letter = english[i]
while letter not in VOWELS: # Find where the first consonant is
i += 1
letter = english[i]
if i == 0:
pig_latin = english + 'yay'
else:
pig_latin = english[i:] + english[0:i] + 'ay'
if capitalized:
pig_latin = pig_latin[0].upper() + pig_latin[1:]
return_string = beginning_punct + pig_latin + ending_punct
return return_string
english_sentence = input('What is your English sentence? ')
english_words = english_sentence.split()
for word in english_words:
pig_latin += [convert_pig_latin(word)]
print(' '.join(pig_latin))
| false |
0540aaa6f156d2f017ea12380f97f3a68166fac6 | Deepika-bala/conversion | /main.py | 375 | 4.25 | 4 | decimal=int(input("enter the decimal : "))
convert =int(input("convert into : [1] binary,[2] octal,[3] hexadecimal:\n"))
if convert == 1:
print("convert into binary\n " ,bin(decimal))
elif convert == 2 :
print("convert into octal\n", oct(decimal))
elif convert == 3:
print("convert into octadecimal\n",hex(decimal))
else:
print("check the input")
| false |
079b0e961c408f6b2b6c8edf65b56eaa0f2b4e61 | WaqasAkbarEngr/Python-Tutorials | /smallest_number.py | 612 | 4.1875 | 4 | def smallest_number():
numbers = []
entries = input("How many number you want to enter? ")
entries = int(entries)
while entries > 0:
entered_number = input("Enter a number? ")
numbers.append(entered_number)
smallest_number = entered_number
entries = entries - 1
print()
print("Your entered numbers are ",numbers)
for x in numbers:
if x < smallest_number:
smallest_number = x
print()
print("Smallest number is",smallest_number)
print()
input("Press any key to exit")
return ()
smallest_number() | true |
83265b7915746a67e8240e49d3819e8e6d840526 | cmobrien123/Python-for-Everybody-Courses-1-through-4 | /Ch7Asmt7.2.py | 1,146 | 4.34375 | 4 | # Exercise 7.2: Write a program to prompt for a file name, and then read
# through the file and look for lines of the form:
# X-DSPAM-Confidence:0.8475
# When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
# the line to extract the floating-point number on the line. count these lines
# and then compute the total of the spam confidence values from these lines.
# When you reach the end of the file, print out the average spam confidence.
# Enter the file name: mbox.txt
# Average spam confidence: 0.894128046745
# Enter the file name: mbox-short.txt
# Average spam confidence: 0.750718518519
# Test your file on the mbox.txt and mbox-short.txt files.
hname = input('please enter file name')
fname = open(hname)
# fname = open('mbox-short.txt')
total= 0
count = 0
for line in fname:
if not line.startswith('X-DSPAM-Confidence:'):
continue
# print(line)
# print(len(line))
x =line[20:27]
y= float(x)
# print(y)
total = total + y
count= count +1
# print(total)
# print(count)
avg = total/count
avgg = str(avg)
# print(avg)
print("Average spam confidence:", avgg)
# print('done')
| true |
709ccdd4ec3a29f9adca939763015cfa37ee521b | Denysios/Geekbrains | /python/base/dz_lesson1/lesson1_task2.py | 1,338 | 4.1875 | 4 | # Задание 2
# Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды
# и выведите в формате чч:мм:сс. Используйте форматирование строк.
# Простой способ, но с некоторыми недочетами
# time_sec = int(input('Введите время в секундах: '))
# minutes = time_sec // 60
# hours = minutes // 60
# sec = minutes % 60
# print(f'{hours}:{minutes}:{sec}')
# Cпособ c использованием конструкции if
time_sec = int(input('Введите время в секундах: '))
temp_hours = time_sec / 60 // 60
if temp_hours <= 0:
hours = '00'
elif len(str(int(temp_hours))) == 1:
hours = '0' + str(int(temp_hours))
else:
hours = str(int(temp_hours))
temp_minutes = (time_sec // 60) - (time_sec / 60 // 60) * 60
if temp_minutes == 0:
minutes = '00'
elif len(str(int(temp_minutes))) == 1:
minutes = '0' + str(int(temp_minutes))
else:
minutes = str(int(temp_minutes))
temp_second = time_sec % 60
if temp_second == 0:
second = '00'
elif len(str(int(temp_second))) == 1:
second = '0' + str(int(temp_second))
else:
second = str(int(temp_second))
print(f'{hours}:{minutes}:{second}')
| false |
d0a8a00b9834f82ef386fb2d2bc1a93bbd5c092a | arkadym74/pthexperience | /helloworld.py | 1,664 | 4.3125 | 4 | #Prints the Words "Hello World"
'''This is a multiline comment'''
print("Hello World")
userAge, userName = 30, 'Peter'
x = 5
y = 10
y = x
print("x = ", x)
print("y = ", y)
brand = 'Apple'
exchangeRate = 1.235235245
message = 'The price of this {0:s} laptop is {1:d} USD and the exchange rate is {2:4.2f} USD to 1 EUR'.format('Apple', 1299, 1.235235245)
message1 = '{0} is easier than {1}'.format('Pyhon', 'Java')
message2 = '{1} is easier than {0}'.format('Python', 'Java')
message3 = '{:10.2F} and {:d}'.format(1.234234234, 12)
message4 = '{}'.format(1.234234234)
print(message1)
print(message2)
print(message3)
print(message4)
#List
userAge = [21, 22, 23 ,24, 25]
userAge3 = userAge[2:4]
print(userAge3)
userAge4 = userAge[1:5:2]
print(userAge4)
userAge5 = userAge[:4]
print(userAge5 )
userAge[2] = 30
print(userAge)
userAge.append(100)
print(userAge)
del userAge[3]
print(userAge)
myList = [1,2,3,4,5,"Hello"]
print(myList)
print(myList[2])
print(myList[-1])
myList2 = myList[1:5]
print(myList2)
myList[1] = 20
print(myList)
myList.append('How are you')
print(myList)
del myList[6]
print(myList)
#Tupple
monthOfYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct","Nov", "Dec")
print(monthOfYear[0])
print(monthOfYear[-1])
#Dictionary
userNameAndAge = {"Peter":38, "John":51, "Alex":13, "Alvin":"Not Available"}
print(userNameAndAge)
userNameAndAge = dict(Peter = 38, John = 51, Alex = 13, Alvin = "Not Available")
print(userNameAndAge)
print(userNameAndAge["John"])
userNameAndAge["John"] = 21
print(userNameAndAge)
userNameAndAge = {}
userNameAndAge["Joe"] = 40
print(userNameAndAge)
| true |
4af66f31e555e7fd67d00869653e8c7048c1f472 | mgomesq/neural_network_flappybird | /FlappyBird/brain.py | 1,735 | 4.46875 | 4 | # -*- coding: utf-8 -*-
'''
Brain
=====
Provides a Brain class, that simulates a bird's brain.
This class should be callable, returning True or False
depending on whether or not the bird should flap its wings.
How to use
----------
Brain is passed as an argument to Bird, which is defined in
the classes module.
'''
import numpy as np
class Brain:
''' An abstraction of a flappy bird's brain.
The brain is a Neural Network with two input nodes, one
hidden layer with 6 nodes and one output node.
Arguments
---------
weights1 - weights mapping input to first hidden layer,
has shape (6,2)
weights2 - weights mapping first hidden layer to output,
has shape (1,6)
'''
def __init__(self, weights1: np.array, weights2: np.array):
self.weights1 = weights1
self.weights2 = weights2
self.activation = lambda x: 1 if x > 0.5 else 0
def __call__(self, information: np.array):
''' Here should be defined the main logic for flapping.
Arguments
---------
information - Information is a np.array containing the inputs
the bird will use to make an informed decision.
Returns
-------
Returns a boolean corresponding to the decision of
wing flapping.
'''
layer1_output = np.matmul(self.weights1, information)
layer1_output = np.array([self.activation(value) for value in layer1_output])
layer2_output = np.matmul(self.weights2, layer1_output)
layer2_output = np.array([self.activation(value) for value in layer2_output])
if layer2_output[0] == 1:
return True
return False
| true |
bba081265a85bbf2988ee18245ba83140fe8bb4a | Tlepley11/Home | /listlessthan10.py | 225 | 4.1875 | 4 | #A program that prints all integers in a list less than a value input by the user
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
x = input("Please enter a number: ")
b = []
for i in a:
if i < x: print(i); b.append(i)
print(b)
| true |
b652e232cb08379678bcdd9173d596a4afef4a05 | jamie0725/LeetCode-Solutions | /566ReshapetheMatrix.py | 1,737 | 4.25 | 4 | """
n MATLAB, there is a very useful function called 'reshape', which can reshape
a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive
integers r and c representing the row number and column number of the wanted
reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original
matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal,
output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4].
The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the
previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the
original matrix.
"""
class Solution(object):
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
nNums = []
temp = [0] * c
oR = 0
oC = 0
if r * c != len(nums)*len(nums[0]):
return nums
for rIndex in range(r):
for cIndex in range(c):
temp[cIndex] = nums[oR][oC]
if oC + 1 == len(nums[0]):
oR += 1
oC = 0
else:
oC += 1
if cIndex == c - 1:
nNums.append(temp[0:])
return nNums
| true |
293fe7ead7c870e3f25bde546f2b34337eb32378 | optionalg/cracking_the_coding_interview_python-1 | /ch4_trees_and_graphs/4.2_minimal_tree.py | 1,190 | 4.125 | 4 | # [4.2] Minimal Tree: Given a sorted(increasing order)
# array with unique integer elements, write an algorithm
# to create a binary search tree with minimal height
# Space complexity:
# Time complexity:
import unittest
def create_bst(array):
if not array:
return None
elif len(array) == 1:
return TreeNode(array[0])
n = len(array)
head_node = TreeNode(array[n/2])
left_child = create_bst(array[:n/2])
right_child = create_bst(array[n/2 + 1:])
head_node.left = left_child
head_node.right = right_child
return head_node
class Test(unittest.TestCase):
def test_create_bst(self):
bst = create_bst([2,3,4,5,6,7])
self.assertEqual(bst.value, 5)
self.assertEqual(bst.left.value, 3)
self.assertEqual(bst.left.left.value, 2)
self.assertEqual(bst.left.right.value, 4)
self.assertEqual(bst.right.value, 7)
self.assertEqual(bst.right.left.value, 6)
class TreeNode(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
if __name__ == '__main__':
unittest.main()
| true |
b0d9de4d3f59d074ea1ffc412a99e8610ddccab6 | optionalg/cracking_the_coding_interview_python-1 | /ch5_bit_manipulation/5.7_pairwise_swap.py | 1,734 | 4.15625 | 4 | # [5.7] Pairwise Swap: Write a program to swap odd and even bits
# in an integer with as few instructions as possible (e.g., bit
# 0 and bit 1 are swapped, bit 2 and bit 3 and swapped, and so on)
import unittest
def pairwise_swap(num):
even_mask = create_even_mask(num)
odd_mask = create_odd_mask(num)
even_cleared = num & even_mask
odd_cleared = num & odd_mask
combined = (odd_cleared >> 1) | (even_cleared << 1)
return (odd_cleared >> 1) | (even_cleared << 1)
def create_odd_mask(num):
bin_representation = bin(num)[2:]
bit_length = len(bin_representation)
bit_sign = '0'
mask = []
for i in range(bit_length):
mask.insert(0, bit_sign)
bit_sign = '1' if bit_sign =='0' else '0'
return int(''.join(mask),2)
def create_even_mask(num):
bin_representation = bin(num)[2:]
bit_length = len(bin_representation)
bit_sign = '1'
mask = []
for i in range(bit_length):
mask.insert(0, bit_sign)
bit_sign = '1' if bit_sign =='0' else '0'
return int(''.join(mask),2)
class Test(unittest.TestCase):
def test_create_even_mask(self):
self.assertEqual(create_even_mask(int('111000', 2)), int('010101',2))
self.assertEqual(create_even_mask(int('1110000', 2)), int('1010101',2))
def test_create_odd_mask(self):
self.assertEqual(create_odd_mask(int('111000', 2)), int('101010',2))
self.assertEqual(create_odd_mask(int('11100110', 2)), int('10101010',2))
def test_pairwise_swap(self):
self.assertEqual(pairwise_swap(int('111000',2)), int('110100',2))
self.assertEqual(pairwise_swap(int('11100111',2)), int('11011011',2))
if __name__ == '__main__':
unittest.main()
| true |
3dc3b3e5045027bcccafc7907b667a0d2c8ec606 | optionalg/cracking_the_coding_interview_python-1 | /ch1_arrays_and_strings/1.1_is_unique.py | 798 | 4.1875 | 4 | # Time complexity: O(n) because needs to check each character
# Space complexity: O(c) where c is each character
import unittest
def is_unique(s):
# create a hashmap to keep track of char count
char_count = {}
for char in s:
# if character is not in hashmap add it
if not char in char_count:
char_count[char] = 1
else:
# if char is in hashmap, means there is a duplicate character
return False
return True
class Test(unittest.TestCase):
def test_unique(self):
self.assertTrue(is_unique('abcdefg'))
self.assertTrue(is_unique('1234567'))
self.assertFalse(is_unique('aabcdefg'))
self.assertFalse(is_unique('123456788'))
if __name__ == "__main__":
unittest.main()
| true |
738c5f3cfa7d3c58b05c5738822e0d807dbf1f7b | optionalg/cracking_the_coding_interview_python-1 | /ch8_recursion_and_dynamic_programming/8.1_triple_step.py | 1,634 | 4.15625 | 4 | # [8.1] Triple Step: A child is running up a staircase with n
# steps and can hop either 1 step, 2 steps, or 3 steps at a
# time. Implement a method to count how many possible ways
# the child can run up the stairs.
import unittest
def fib(n):
if n < 1:
raise ValueError('Must be positive Integer')
elif n < 3:
return 1
elif n < 4:
return 2
else:
a = 1
b = 1
c = 2
d = 4
for i in xrange(n-4):
a = b
b = c
c = d
d = a + b + c
return d
def fib_r(n):
memo = {}
return fib_r_helper(n, memo)
def fib_r_helper(n, memo):
if n in memo:
return memo[n]
if n < 1:
raise ValueError('Must be positive Integer')
elif n < 3:
return 1
elif n < 4:
return 2
else:
result = fib_r(n-1) + fib_r(n-2) + fib_r(n-3)
memo[n] = result
return result
class Test(unittest.TestCase):
def test_fib(self):
self.assertEqual(fib(1), 1)
self.assertEqual(fib(2), 1)
self.assertEqual(fib(3), 2)
self.assertEqual(fib(4), 4)
self.assertEqual(fib(5), 7)
self.assertEqual(fib(6), 13)
self.assertRaises(ValueError, fib, -1)
def test_fib_r(self):
self.assertEqual(fib_r(1), 1)
self.assertEqual(fib_r(2), 1)
self.assertEqual(fib_r(3), 2)
self.assertEqual(fib_r(4), 4)
self.assertEqual(fib_r(5), 7)
self.assertEqual(fib_r(6), 13)
self.assertRaises(ValueError, fib_r, -1)
if __name__ == '__main__':
unittest.main()
| true |
ff7e1c2a4dc59cb1786841b7fff931fc5db1e00f | jutish/master-python | /07-ejercicios/ejercicio4.py | 360 | 4.15625 | 4 | """
Pedir dos numeros al usuario y hacer todas las operaciones
de una calculadora. Suma, resta, multiplicacion y division.
"""
nro1 = int(input("Ingrese Nro1: "))
nro2 = int(input("Ingrese Nro2: "))
print(f"{nro1} + {nro2} = {nro1+nro2}")
print(f"{nro1} - {nro2} = {nro1-nro2}")
print(f"{nro1} * {nro2} = {nro1*nro2}")
print(f"{nro1} / {nro2} = {nro1/nro2}") | false |
fdee0f3aaae1372696e95ba72cb3ca090df592fb | pieland-byte/Introduction-to-Programming | /week_4/ex_3.py | 1,341 | 4.3125 | 4 | #This program creates a dictionary from a text file of cars and prints the
#oldest and newest car from the original file
#create a list from the text file
def car_list():
car_list = [] #Empty list
with open ("cars_exercise_3.txt" , "r") as car_data: #Open text file in read mode
for line in car_data: #With every line in text file
car_list.append(line.rstrip("\n")) #Append line to car_list
return car_list
#Create a dictionary of the car information giving the keys as "make", "model" and "year"
def car_dict():
i = 0
car_dict = []
car_1 = car_list()
while i <len(car_1):
car_dict.append({"make" : car_1[i], "model" : car_1[i + 1], "year" : car_1[i + 2]})
i += 3
return car_dict
#Return the newest car
def newest():
newest = max(car_dict(), key=lambda x: x["year"]) #Find the car with the highest value in key "year"
return newest
def oldest():
oldest = min(car_dict(), key=lambda x: x["year"]) #Find the car with the lowest value in key "year"
return oldest
print("The newest car is: ", newest())
print("The oldest car is: ", oldest())
| true |
2e0d8cbe84dc1a8a57e90e9c34e015d1c4eebfe5 | pieland-byte/Introduction-to-Programming | /week_1/ex_5.py | 298 | 4.3125 | 4 | # This is a program to convert temperature in fahrenheit to celcius/centigrade
fahrenheit = input("Enter the temperature in fahrenheit: ")
fahrenheit = int(fahrenheit)
celsius = ((5/9) * (fahrenheit - 32))
print(fahrenheit, "Degrees Fahrenheit is",round(celsius,2), "degrees Celsius")
| false |
c546d7555f99c6bb2b2fa6d0266e6615256aecb2 | pieland-byte/Introduction-to-Programming | /week_3/ex_2.py | 1,309 | 4.625 | 5 | #This program calculates the volume of given shapes specified by
#the user using recursion
import math
# creating a menu with options for user input
def main_menu():
menu_choice = input("Please type 1 for sphere, 2 for cylinder and 3 for cone: ")
if menu_choice == "1":
result = sphere(int(input("Enter radius of sphere ")))
print("volume of sphere is", result)
elif menu_choice == "2":
radius = int(input("Enter radius: "))
height = int(input("Enter height: " ))
result = cylinder(radius, height)
print("Volume of cylinder is ", result)
elif menu_choice == "3":
radius = int(input("Enter radius: "))
height = int(input("Enter height: " ))
result = cone(radius,height)
print("volume of cone is", result)
else:
print("input error")
main_menu()
# function to calculate volume of sphere radius r
def sphere(r):
return (math.pi *(r **3))* (4/3)
#function to calculate volume of cylinder with radius r and height h
def cylinder(r,h):
return (math.pi * r**2) * h
# function to calculate volume of cone with radius r and height h
def cone(r,h):
return ((math.pi * r**2) * h)* (1/3)
main_menu()
| true |
119d31f2c4846ba1416da750b0e87a38d77509f3 | pieland-byte/Introduction-to-Programming | /week_4/ex_2.py | 1,159 | 4.15625 | 4 | #This program asks the user to name a sandwich ingredient and shows
#corresponding sandwiches from the menu
sandwiches = [] #Empty list
with open ("menu.txt","r") as menu: #Read menu.txt
for line in menu: #For each line
sandwiches.append(line.rstrip("\n")) #Add line to sandwiches list without newline
def sand_choice():
choice = input("Enter which sarnie you would like: ") #User input choice
choice = choice.title() #Convert input to title case
if len(choice) < 3: #To prevent input of string with 1 or 2 characters or spaces from returning a valid result
print("Please enter a valid choice")
sand_choice()
else:
for n in sandwiches: #Look through sandwich list
if choice in n: #If user input matches substring in string list sandwiches
print("We have",n,"available") #Print multiple response
sand_choice()
| true |
401075a7b543a9eb6a6d81c820a371aa3a24a66f | pieland-byte/Introduction-to-Programming | /week_4/ex_1.py | 546 | 4.1875 | 4 | #This program asks the user to name a sandwich and shows corresponding
#sandwiches from the menu
sandwiches = []
with open ("menu.txt","r") as menu:
for line in menu:
sandwiches.append(line.rstrip("\n"))
def sandwich_choice():
choice = input("Enter which sarnie you would like: ")
for ind in sandwiches:
if choice in sandwiches:
print("We have",choice,"available")
break
else:
print("That is unavailable, sorry.")
break
sandwich_choice()
| true |
4879cc84005af321f00c305271d26325fec9a5ae | MetalSkink/Curso-Python | /Bucles/Ejercicios/Ejercicio9.py | 420 | 4.15625 | 4 | '''
Bucles - Ejercicio 9:
Hacer un programa donde el usuario ingrese una frase, se le devolverá la misma frase
pero sin espacios en blanco y además un contador de cuántos
caracteres tiene la frase (sin contar los espacios en blanco).
'''
frase = input("Inserte una frase -> ")
contador=0
for i in frase:
if i != " ":
print(i,end="")
contador += 1
print(f"\nTu palabra tiene {contador} letras") | false |
1e3d446c41600a291eccfed2f9b58364ec3019da | MetalSkink/Curso-Python | /Condicionales/Ejercicio2.py | 693 | 4.25 | 4 | '''
Ejercicio2 :
Hacer un programa que pida 3 numeros y determina cual
es mayor
'''
a = float(input("a -> "))
b = float(input("b -> "))
c = float(input("c -> "))
if a == b and b == c:
print("Los 3 numeros son iguales")
if a == b and b > c:
print("Los primeros 2 numero son mayores e iguales")
if b == c and b > a:
print("El segundo y tercer numero son mayores e iguales")
if a == c and a > b:
print("El primer y tercer numero son mayores e iguales")
if a == b and b == c:
print("Los 3 numeros son iguales")
elif a>b and a>c:
print(f"{a} es el numero mayor")
elif b>a and b>c:
print(f"{b} es el numero mayor")
elif c>a and c>b:
print(f"{c} es el numero mayor") | false |
0cbb1fbbfac2c26c8bba84d4ae8ca5a74ec76b98 | ioana01/Marketplace | /tema/consumer.py | 2,311 | 4.28125 | 4 | """
This module represents the Consumer.
Computer Systems Architecture Course
Assignment 1
March 2021
"""
from threading import Thread
import time
class Consumer(Thread):
"""
Class that represents a consumer.
"""
def __init__(self, carts, marketplace, retry_wait_time, **kwargs):
"""
Constructor.
:type carts: List
:param carts: a list of add and remove operations
:type marketplace: Marketplace
:param marketplace: a reference to the marketplace
:type retry_wait_time: Time
:param retry_wait_time: the number of seconds that a producer must wait
until the Marketplace becomes available
:type kwargs:
:param kwargs: other arguments that are passed to the Thread's __init__()
"""
Thread.__init__(self)
self.carts = carts
self.marketplace = marketplace
self.retry_wait_time = retry_wait_time
self.cart_id = marketplace.new_cart()
self.name = kwargs['name']
def run(self):
# The list of carts is iterated
for i in range(0, len(self.carts)):
# The list of products of the current cart is iterated
for j in range(0, len(self.carts[i])):
# Check the type of the operation
if self.carts[i][j]['type'] == 'add':
# Call the add_to_cart method until the desired quantity is added
# If the product is not available, the consumer will wait
for _ in range(0, self.carts[i][j]['quantity']):
while not self.marketplace.add_to_cart(
self.cart_id, self.carts[i][j]['product']):
time.sleep(self.retry_wait_time)
elif self.carts[i][j]['type'] == 'remove':
# Call the remove_from_cart method until the desired quantity is removed
for _ in range(0, self.carts[i][j]['quantity']):
self.marketplace.remove_from_cart(self.cart_id, self.carts[i][j]['product'])
# Print the final order of the consumer
product_list = self.marketplace.place_order(self.cart_id)
for product, _ in product_list:
print(self.name, "bought", product[0])
| true |
4ff3e99a408d896b4260680980b204794cae01f4 | dnaport22/pyex | /Functions/averageheight.py | 1,081 | 4.15625 | 4 | #~PythonVersion 3.3
#Author: Navdeep Dhuti
#StudentNumber: 3433216
#Code below generate answer for question::
#What is the average value of the numbers in the field [height] in the range(1.75)and(2.48)inclusive?
#Function starts
def Average_height(doc_in):
doc = open(doc_in+'.csv','r') #Open the input file came from 'infile'
#initialise variables
firstline = True
numofheight = 0
sumofheight = 0
#passing file into a for loop
for data_fields in doc:
if firstline:
firstline = False
else:
#splitting and organising the data in file
data_fields = data_fields.strip().split(',')
#defining variable required for calculation
height = float(data_fields[5])
if height >= 1.75 and height <= 2.48:
numofheight += 1
sumofheight += height
#calculating average
average_height = numofheight/sumofheight
#rturning average
return ('%f'%average_height)
#closing opened file
doc.close()
| true |
a9fb3bc90fe2ce347f1ca6ea02239760e35963e6 | PhaniMandava7/Python | /Practice/Sets.py | 591 | 4.40625 | 4 | # Sets are collection of distinct elements with no ordering.
# Sets are good at membership testing.
# empty_set = {} -------> this creates a dict.
empty_set = set()
courses_set = {'History', 'Physics', 'Math'}
print(courses_set)
courses_set.add('Math')
print(courses_set)
print('Math' in courses_set)
courses_set = {'History', 'Physics', 'Math'}
courses_set2 = {'History', 'Arts', 'Music'}
print(courses_set.intersection(courses_set2))
print(courses_set.difference(courses_set2))
# courses_set.difference_update(courses_set2)
# print(courses_set)
print(courses_set.union(courses_set2)) | true |
a723af9a1faae81b098e9b79025f031a0f8b2038 | PhaniMandava7/Python | /FirstPythonProj/GetInputFromKeyboard.py | 337 | 4.21875 | 4 | greeting = "Hello"
# name = input("Please enter your name")
# print(greeting + ' ' + name)
# names = name.split(" ")
# for i in names:
# print(i)
print("This is just a \"string 'to test' \"multiple quotes")
print("""This is just a "string 'to test' "multiple quotes""")
print('''This is just a "string 'to test' multiple quotes''') | true |
6c7d41a18476a461fbceec79924b253d39f9f311 | paalso/learning_with_python | /ADDENDUM. Think Python/10 Lists/10-12_version1.py | 2,415 | 4.28125 | 4 | '''
Exercise 10.12. Two words “interlock” if taking alternating letters from each
forms a new word. For example, “shoe” and “cold” interlock to form “schooled”.
Solution: http://thinkpython2.com/code/interlock.py
1. Write a program that finds all pairs of words that interlock. Hint: don’t
enumerate all pairs!
2. Can you find any words that are three-way interlocked; that is, every third
letter forms a word, starting from the first, second or third?
'''
def load_words(dict_filename):
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print(f"Loading word list from file {dict_filename}...")
# in_file: file
in_file = open(dict_filename, 'r')
# line: string
# wordlist: list of strings
wordlist = in_file.read().split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def in_bisect(word, words_list):
first_id = 0
last_id = len(words_list) - 1
while first_id <= last_id:
mid_id = (first_id + last_id) // 2
if words_list[mid_id] == word:
return mid_id
elif words_list[mid_id] < word:
first_id = mid_id + 1
else:
last_id = mid_id - 1
return -1
def interlock_two_words(word1, word2):
L = [' '] * (len(word1) + len(word2))
L[::2] = list(word1)
L[1::2] = list(word2)
return ''.join(L)
def main():
# Плохая, негодная, тупая, медленная версия
# Bad, inadequate, stupid, slow version.
dict_filename = 'words.txt'
words_list = load_words(dict_filename)
interlocked_words = []
for size in range(2, 10):
size_words = list(filter(lambda w: len(w) == size, words_list))
size_interlocked_words = []
print(f'Size = {size}, words: {len(size_words)}')
for word1 in size_words:
for word2 in size_words:
if in_bisect(interlock_two_words(word1, word2), words_list) > -1:
size_interlocked_words.append((word1, word2, interlock_two_words(word1, word2)))
interlocked_words.extend(size_interlocked_words)
print(size_interlocked_words)
print(interlocked_words)
if __name__ == '__main__':
main()
| true |
1a63f54074f8a96a4a3585950a253a25d068a0d0 | paalso/learning_with_python | /18 Recursion/18-7.py | 976 | 4.15625 | 4 | # Chapter 18. Recursion
# http://openbookproject.net/thinkcs/python/english3e/recursion.html
# Exercise 7
# ===========
# Write a function flatten that returns a simple list containing all the values
# in a nested list
from testtools import test
def flatten(nxs):
"""
Returns a simple list containing all the values in a nested list
"""
flattened = []
for e in nxs:
if type(e) == list:
flattened.extend(flatten(e))
else:
flattened.append(e)
return flattened
def main():
test(flatten([2,9,[2,1,13,2],8,[2,6]]) == [2,9,2,1,13,2,8,2,6])
test(flatten([[9,[7,1,13,2],8],[7,6]]) == [9,7,1,13,2,8,7,6])
test(flatten([[9,[7,1,13,2],8],[2,6]]) == [9,7,1,13,2,8,2,6])
test(flatten([["this",["a",["thing"],"a"],"is"],["a","easy"]]) ==
["this","a","thing","a","is","a","easy"])
test(flatten([]) == [])
if __name__ == '__main__':
main()
| true |
4e13a17fdcaa1022e51da4c4bb808571a02d6177 | paalso/learning_with_python | /26 Queues/ImprovedQueue.py | 2,311 | 4.1875 | 4 | # Chapter 26. Queues
# http://openbookproject.net/thinkcs/python/english3e/queues.html
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
class ImprovedQueue:
def __init__(self):
self.head = self.tail = None
self.size = 0
def insert(self, cargo):
node = Node(cargo)
if self.is_empty():
self.head = self.tail = node
else:
self.tail.next = node
self.tail = self.tail.next
self.size += 1
def remove(self):
if not self.is_empty():
self.size -= 1
cargo = self.head.cargo
# * чтобы отцепить ссылку next удаляемого node от queue - нужно ли?
current_head = self.head # *
self.head = self.head.next
current_head.next = None # *
if self.is_empty():
self.tail = None
def is_empty(self):
return self.size == 0
def __str__(self):
tokens = []
current = self.head
while current:
tokens.append(str(current))
current = current.next
return "[{}]".format(", ".join(tokens))
def print_info(self):
print("queue: {}, head: {}, tail: {}, len: {}"
.format(self, self.head, self.tail, self.size))
def main():
print("Creating new Queue:")
q = ImprovedQueue()
q.print_info()
print("\nAdding new nodes (1, 2, 3) to the Queue:")
q.insert(1)
q.print_info()
q.insert(2)
q.print_info()
q.insert(3)
q.print_info()
print("\nRemoving nodes from the Queue:")
print("removed node: {}".format(q.remove()))
q.print_info()
print("removed node: {}".format(q.remove()))
q.print_info()
print("removed node: {}".format(q.remove()))
q.print_info()
print("removed node: {}".format(q.remove()))
q.print_info()
print("\nAdding new nodes (999, 66, 'xxx', (1, 'z')) to the Queue:")
q.insert(999)
q.insert(66)
q.insert('xxx')
q.insert((1, 'z'))
q.print_info()
if __name__ == "__main__":
main()
| true |
ec0915fa2463fb1da2bb9ad4a5b55793d40fac93 | paalso/learning_with_python | /09 Tuples/9-01_1.py | 1,138 | 4.5 | 4 | ## Chapter 9. Tuples
## http://openbookproject.net/thinkcs/python/english3e/tuples.html
## Exercise 1
## ===========
# We’ve said nothing in this chapter about whether you can pass tuples as
# arguments to a function. Construct a small Python example to test whether this
# is possible, and write up your findings.
import sys
def distance_to_center(p):
""" Get the distance to the origin a cartesian coordinate space """
sum = 0
for c in p:
sum += c * c
return sum ** 0.5
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(distance_to_center((3, 4)) == 5)
test(distance_to_center((3, 4, 0)) == 5)
test(distance_to_center((1, 1, 1)) == 1.7320508075688772)
test(distance_to_center((0, 0, 1, 0)) == 1)
test_suite() | true |
e66ceb92103c0c595bbaa0f6bc829e2208b34dba | paalso/learning_with_python | /18 Recursion/18-11/litter.py | 1,729 | 4.21875 | 4 | # Chapter 18. Recursion
# http://openbookproject.net/thinkcs/python/english3e/recursion.html
# Exercise 11
# ============
# Write a program named litter.py that creates an empty file named trash.txt in
# each subdirectory of a directory tree given the root of the tree as an argument
# (or the current directory as a default). Now write a program named cleanup.py
# that removes all these files.
import os, sys
def get_dirlist(path):
"""
Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
return sorted(os.listdir(path))
def create_files(path=None, filename='trash.txt'):
""" Creates an empty file named trash.txt in each subdirectory of
a directory tree given the root of the tree as an argument (or the current
directory as a default)
"""
if not path:
path = os.getcwd()
dirlist = get_dirlist(path)
full_filename = os.path.join(path, filename)
newfile = open(full_filename, 'w')
newfile.close()
print('{} created'.format(full_filename))
for f in dirlist:
full_name = os.path.join(path, f)
if os.path.isdir(full_name):
create_files(full_name, filename)
def main():
## if len(sys.argv) > 2:
## print('Usage: python litter.py [directory]')
## exit(1)
##
## if len(sys.argv) == 1:
## dirname = None
## else:
## dirname = sys.argv[1]
## if not os.path.exists(dirname):
## print(f"Directory {dirname} doesn't exist")
## exit(2)
## create_files()
create_files('d:\Projects\_testdir')
if __name__ == '__main__':
main()
| true |
9ef73be5b8fdf09a171cff7e27c68773fda9963e | paalso/learning_with_python | /06 Fruitful functions/6-9.py | 1,849 | 4.21875 | 4 | ##Chapter 6. Fruitful functions
##http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html
## Exercise 9
## ===========
##Write three functions that are the “inverses” of to_secs:
##hours_in returns the whole integer number of hours represented
##by a total number of seconds.
##minutes_in returns the whole integer number of left over minutes
##in a total number of seconds, once the hours have been taken out.
##seconds_in returns the left over seconds represented
##by a total number of seconds.
##You may assume that the total number of seconds passed
##to these functions is an integer...
import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def hours_in(time_in_seconds):
""" returns the whole integer number of hours represented
by a total number of seconds."""
return time_in_seconds // 3600
def minutes_in(time_in_seconds):
""" returns the whole integer number of left over minutes
in a total number of seconds, once the hours have been taken out."""
return (time_in_seconds - hours_in(time_in_seconds) * 3600) // 60
def seconds_in(time_in_seconds):
""" returns the left over seconds represented
by a total number of seconds."""
return time_in_seconds % 60
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(hours_in(9010) == 2)
test(minutes_in(9010) == 30)
test(seconds_in(9010) == 10)
test(hours_in(43499) == 12)
test(minutes_in(43499) == 4)
test(seconds_in(43499) == 59)
test_suite()
| true |
1ada77a6b13c07c35793d86d7dd8671356910c09 | paalso/learning_with_python | /ADDENDUM. Think Python/09 Case study - word play/9-6.py | 1,370 | 4.15625 | 4 | '''
Exercise 9.6. Write a function called is_abecedarian that returns True if
the letters in a word appear in alphabetical order (double letters are ok).
How many abecedarian words are there?
'''
def is_abecedarian(word):
"""
Returns True if the letters in a word appear in alphabetical order
(double letters are ok)
"""
word = word.lower()
for i in range(1, len(word)):
if word[i] < word[i - 1]:
return False
return True
def load_words(dict_filename):
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print(f"Loading word list from file {dict_filename}...")
# in_file: file
in_file = open(dict_filename, 'r')
# line: string
# wordlist: list of strings
wordlist = in_file.read().split()
print(" ", len(wordlist), "words loaded.")
return wordlist
print()
# words = load_words("words_3000.txt")
words = load_words("words.txt")
words_qty = len(words)
abecedarian_words = list(filter(is_abecedarian, words))
abecedarian_words_qty = len(abecedarian_words)
print(abecedarian_words)
print("Abecedarian words number: {}, {}%".
format(abecedarian_words_qty, round(abecedarian_words_qty / words_qty * 100, 1)))
| true |
87948f279e5becb72db7deef006590720ddbeaba | paalso/learning_with_python | /08 Strings/8-6.py | 1,569 | 4.4375 | 4 | ## Chapter 8. Strings
## http://openbookproject.net/thinkcs/python/english3e/strings.html
## Exercise 6
## ===========
# Print a neat looking multiplication table like this:
# 1 2 3 4 5 6 7 8 9 10 11 12
# :--------------------------------------------------
# 1: 1 2 3 4 5 6 7 8 9 10 11 12
# 2: 2 4 6 8 10 12 14 16 18 20 22 24
# 3: 3 6 9 12 15 18 21 24 27 30 33 36
# 4: 4 8 12 16 20 24 28 32 36 40 44 48
# 5: 5 10 15 20 25 30 35 40 45 50 55 60
# 6: 6 12 18 24 30 36 42 48 54 60 66 72
# 7: 7 14 21 28 35 42 49 56 63 70 77 84
# 8: 8 16 24 32 40 48 56 64 72 80 88 96
# 9: 9 18 27 36 45 54 63 72 81 90 99 108
# 10: 10 20 30 40 50 60 70 80 90 100 110 120
# 11: 11 22 33 44 55 66 77 88 99 110 121 132
# 12: 12 24 36 48 60 72 84 96 108 120 132 144
def print_numbers_line(num, end, start = 1):
for k in range(start, end + 1):
print("{0:4}".format(k * num), end = "")
print()
def print_table_str(num, width):
print("{0:3}:".format(num), end = "")
print(" ", end = '')
print_numbers_line(num, width)
def print_table_header(width):
print(" ", end = '')
print_numbers_line(1, width)
print(" :--", 4 * width * "-", sep = "")
def print_mult_table(n):
print_table_header(n)
for k in range(1, n + 1):
print_table_str(k, n)
print_mult_table(15)
| false |
32ec6ec6910b4cb9806e82cfdd8eb22e902c8827 | paalso/learning_with_python | /04 Functions/4_4_ver0_0.py | 1,339 | 4.28125 | 4 | ##4. http://openbookproject.net/thinkcs/python/english3e/functions.html
##4. Draw this pretty pattern:
import turtle
import math
def make_window(colr, ttle):
"""
Set up the window with the given background color and title.
Returns the new window.
"""
w = turtle.Screen()
w.bgcolor(colr)
w.title(ttle)
return w
def make_turtle(colr, sz):
"""
Set up a turtle with the given color and pensize.
Returns the new turtle.
"""
t = turtle.Turtle()
t.color(colr)
t.pensize(sz)
return t
def draw_poly(t, n, side):
"""Make a turtle t draw a regular polygon"""
for i in range(n):
t.forward(side)
t.left(360 / n)
def draw_square(t, side):
"""Make a turtle t draw a square"""
for i in range(4):
t.forward(side)
t.left(90)
## ----- Main -----------------------------------------------------
wn = make_window("lightgreen", "Drawing a pretty pattern")
tortilla = make_turtle("blue", 3)
square_side = 200
shift = (2 ** 0.5) * square_side * math.sin(9 * math.pi / 180)
for i in range(5):
draw_square(tortilla, square_side)
tortilla.right(2 * 18)
tortilla.penup()
tortilla.forward(shift)
tortilla.left(3 * 18)
tortilla.pendown()
wn.mainloop() | true |
c9b466df940ce854e8b362a48c71ab720025b83b | paalso/learning_with_python | /ADDENDUM. Think Python/10 Lists/10-9.py | 2,446 | 4.125 | 4 | '''
Exercise 10.9. Write a function that reads the file words.txt and builds
a list with one element per word. Write two versions of this function, one
using the append method and the other using the idiom t = t + [x]. Which one
takes longer to run? Why?
'''
def load_words(dict_filename):
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print(f"Loading word list from file {dict_filename}...")
# in_file: file
in_file = open(dict_filename, 'r')
# line: string
# wordlist: list of strings
wordlist = in_file.read().split()
print(" ", len(wordlist), "words loaded.")
return wordlist
def count_time(func, *args):
import time
start_time = time.time()
func(*args)
return time.time() - start_time
def load_words1(dict_filename):
"""
Returns a list of words from the file 'dict_filename' using
the append method
"""
print(f"Loading word list from file {dict_filename}...")
# in_file: file
in_file = open(dict_filename, 'r')
wordlist = [] # wordlist: list of strings
# line: string
for line in in_file:
wordlist.append(line)
print(" ", len(wordlist), "words loaded.")
return wordlist
def load_words2(dict_filename):
"""
Returns a list of words from the file 'dict_filename'
using the idiom t = t + [x]
"""
print(f"Loading word list from file {dict_filename}...")
# in_file: file
in_file = open(dict_filename, 'r')
wordlist = [] # wordlist: list of strings
# line: string
for line in in_file:
wordlist += [line]
print(" ", len(wordlist), "words loaded.")
return wordlist
def main():
dict_filename = 'words.txt'
t1 = count_time(load_words1, dict_filename)
t2 = count_time(load_words2, dict_filename)
t3 = count_time(load_words, dict_filename)
## words = load_words2(dict_filename)
## print(words)
print(f'Time of loading the dictionary "{dict_filename}":')
print(f'using the append method: {t1}')
print(f'using the the idiom t = t + [x]: {t2}')
print(f'using the the read().split() method: {t3}')
# https://towardsdatascience.com/3-techniques-to-make-your-python-code-faster-193ffab5eb36
if __name__ == '__main__':
main() | true |
3638b74fdff0456af03fd38137c7eceae3ddacb1 | paalso/learning_with_python | /ADDENDUM. Think Python/13 Case study - data structure/13-6.py | 1,209 | 4.21875 | 4 | '''
Exercise 13.5. Write a function named choose_from_hist that takes a histogram
as defined in Section 11.2 and returns a random value from the histogram,
chosen with probability in proportion to frequency.
For example, for this histogram:
>>> t = ['a', 'a', 'b']
>>> hist = histogram(t) # {'a': 2, 'b': 1}
your function should return 'a' with probability 2/3 and
'b' with probability 1/3.
'''
def histogram(text):
import collections
return dict(collections.Counter(text))
def choose_from_hist(histogram):
import random
## probabilities = { key : histogram[key] / values_number
## for key in histogram }
start_num = 0
partition = dict()
for key in histogram:
end_num = start_num + histogram[key]
segment = start_num, end_num
partition[key] = segment
start_num = end_num
random_num = random.randrange(sum(histogram.values()))
for key, segment in partition.items():
start, end = segment
if start <= random_num < end:
return key
def main():
s = 'ab'
d = histogram(s)
print(d)
print(choose_from_hist(d))
if __name__ == '__main__':
main()
| true |
7783505fb7040ceefdd5794f88507f573b4d6bcf | paalso/learning_with_python | /07 Iterations/7-1.py | 923 | 4.28125 | 4 | ## Chapter 7. Iteration
## http://openbookproject.net/thinkcs/python/english3e/iteration.html
## Exercise 1
## ===========
## Write a function to count how many odd numbers are in a list.
import sys
def count_odds(lst):
counter = 0
for n in lst:
if n % 2 == 1:
counter += 1
return counter
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(count_odds([]) == 0)
test(count_odds([1, 2, 4, 5]) == 2)
test(count_odds([0, 2, 4, 6]) == 0)
test(count_odds([1, 1, 1, 1, 1]) == 5)
test_suite()
| true |
e0dbd51a977024665d2211a0f4f82f3a7d5ce224 | paalso/learning_with_python | /24 Linked lists/linked_list.py | 1,471 | 4.21875 | 4 | # Chapter 24. Linked lists
# http://openbookproject.net/thinkcs/python/english3e/linked_lists.html
class Node:
def __init__(self, cargo=None, next=None):
self.cargo = cargo
self.next = next
def __str__(self):
return str(self.cargo)
def print_backward(self):
if self.next is not None:
tail = self.next
tail.print_backward()
print(self.cargo, end=" ")
def print_list(self):
print('[',end='')
node = self
while node != None:
print(f'{node}',end='')
if node.next is None:
break
print(', ',end='')
node = node.next
print(']')
class LinkedList:
def __init__(self, *items):
self.length = 0
self.head = None
def print_list(self):
if self.head is not None:
self.head.print_list()
else:
print('[]')
def print_backward(self):
if self.head is not None:
print("[", end=" ")
self.head.print_backward()
def add_first(self, cargo):
node = Node(cargo)
## node.next = self.head #зачем так?
node.next = None
self.head = node
self.length += 1
llist = LinkedList()
llist.print_list()
llist.add_first(0)
llist.print_list()
##n = Node()
##print(n)
##n.print_list()
##n.print_backward()
| true |
af380bf7377bec6c0406d8a5ab9ec2e48c02aa0d | alon211/LearnPython | /Full Course for Beginners/WorkingWithString.py | 331 | 4.25 | 4 | # 最原始的
print("I am John")
# 换行符号
print("I am \n John")
# 转义符号
print("I am \"John")
# 字符串变量
MyStr = "I am John"
print(MyStr)
# 字符串函数
MyStr = "I am John"
print(MyStr.lower())
print(MyStr.upper())
print(MyStr.isupper())
print(MyStr[0])
# 字符串index用法
print(MyStr.index('oh'))
| false |
6dfea9839760f8124ac74143ec886b836d85fa38 | mattwfranchi/3600 | /SampleCode/BasicTCPEchoClient.py | 1,035 | 4.21875 | 4 | from socket import *
# Define variables that hold the desired server name, port, and buffer size
SERVER_NAME = 'localhost'
SERVER_PORT = 3602
BUFFER_SIZE = 32
# We are creating a *TCP* socket here. We know this is a TCP socket because of
# the use of SOCK_STREAM
# It is being created using a with statement, which ensures that the socket will
# be cleaned up correctly when the socket is no longer needed (once the with block has been exited)
with socket(AF_INET, SOCK_STREAM) as s:
# Connect to a server at the specified port using this socket
s.connect((SERVER_NAME, SERVER_PORT))
# Loop forever...
while True:
# Read in an input statement from the user
message = input('Input: ')
# Send the message the user wrote into the socket
s.send(message.encode())
# Wait to receive a response from the server, up to 128 bytes in length
response = s.recv(BUFFER_SIZE)
# Print that response to the console
print(response.decode()) | true |
086a3773b74c93e12755271fa0cf25d24399cb60 | hsinjungwu/self-learning | /100_Days_of_Code-The_Complete_Python_Pro_Bootcamp_for_2021/day-12.py | 756 | 4.15625 | 4 | #Number Guessing Game Objectives:
from art import logo
import random
print(logo)
print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.")
ans = random.randint(1, 100)
attempts = 5
if input("Choose a difficulty. Type 'easy' or 'hard': ").lower() == "easy":
attempts = 10
while attempts > 0:
print(f"You have {attempts} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == ans:
print(f"You got it! The answer was {ans}.")
break
else:
attempts -= 1
if guess < ans:
print("Too low")
else:
print("Too high")
if attempts == 0:
print(f"Answer = {ans}. You've run out of guesses, you lose.")
else:
print("Guess again.") | true |
f3ff778147002322c07f7163b50fc1f8f825e220 | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/implement stack using linked list.py | 863 | 4.28125 | 4 | # Implement Stack using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class stack:
def __init__(self):
self.head=None
def push(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def pop(self):
if self.head==None:
print("sorry the stack is empty")
else:
print("the poped element is", self.head.data)
self.head=self.head.next
def peek(self):
print(self.head.data)
def printstack(self):
l=self.head
while(1):
if l==None:
break
print (l.data,end=" ")
l=l.next
obj=stack()
obj.push(1)
obj.push(2)
obj.push(3)
obj.printstack()
print("\n")
obj.pop()
print("\n")
obj.printstack()
| true |
8f3263d7c6d0c6850271577d17d7c712116bdead | Pattrickps/Learning-Data-Structures-Using-Python | /data-structures/queue using linked list.py | 1,296 | 4.34375 | 4 | #Implement Queue using Linked List
class node:
def __init__(self,node_data):
self.data=node_data
self.next=None
class queue:
def __init__(self):
self.head=None
def enqueue(self,data):
new_node=node(data)
new_node.next=self.head
self.head=new_node
def dequeue(self):
if self.head==None:
print("sorry the queue is empty")
else:
l=self.head
while(1):
if l.next==None:
p.next=None
break
p=l
l=l.next
print("you dequeued out ",l.data)
def front(self):
print ("the front is ",self.head.data)
print("\n")
def rear(self):
l=self.head
while(1):
if l.next==None:
print("the rear is ",l.data)
break
l=l.next
print("\n")
def printqueue(self):
l=self.head
while(1):
print(l.data,end=" ")
if l.next==None:
break
l=l.next
print("\n")
obj=queue()
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
obj.enqueue(4)
obj.printqueue()
obj.dequeue()
obj.printqueue()
| false |
fde3c6be1915e11568e8d3d75f24143892d5f319 | mindyzwan/python-practice | /easy1/5.py | 234 | 4.21875 | 4 | def reverse_sentence(string):
return ' '.join(string.split(' ')[::-1])
print(reverse_sentence('') == '')
print(reverse_sentence('Hello World') == 'World Hello')
print(reverse_sentence('Reverse these words') == 'words these Reverse') | false |
8fc847aa8f077e7abec82c05c2f109b324e489ef | code-lucidal58/python-tricks | /play_with_variables.py | 528 | 4.375 | 4 | import datetime
"""
In-place value swapping
"""
# swapping the values of a and b
a = 23
b = 42
# The "classic" way to do it with a temporary variable:
tmp = a
a = b
b = tmp
# Python also lets us use this
a, b = b, a
"""
When To Use __repr__ vs __str__?
"""
# Emulate what the std lib does:hand
today = datetime.date.today()
# Result of __str__ should be readable:
print(str(today))
# Result of __repr__ should be unambiguous:
print(repr(today))
# Python interpreter sessions use__repr__ to inspect objects:
print(today)
| true |
467335edf1eafb7cdcf912fe46a75d3f6c712c08 | ugo-en/some-python-code | /extra_old_code/square.py | 326 | 4.5 | 4 | # Step1: Prompt the user to enter the length of a side of the square
length = int(input("Please Enter the LENGHT of the Square: "))
# Step2: Multiply the length by itself and assign it to a variable called area
area = length * length
# Step3: Display the area of the square to the user
print("Your area is: ",area)
| true |
3653c4987ee75687f3ad08710e803d8724ad244e | ugo-en/some-python-code | /extra_old_code/bmi_calcuator.py | 680 | 4.375 | 4 | #Opening remarks
print("This app calculates your Body Mass Index (BMI)")
#Input variables
weight = float(input("Input your weight in kg but don't include the units: "))
height = float(input("Input your height in m but don't include the units: "))
#Calculate the bmi rnd round off to 1 decimal place
bmi = weight / (height * height)
bmi = round(bmi, 1)
#Print bmi
print("Your BMI is: ", bmi)
#Determine the person's status
if bmi < 18.5:
print("You're underweight")
elif bmi >= 18.5 and bmi <= 24.9:
print("You're normal")
elif bmi >= 25.9 and bmi <= 29.9:
print("You're overweight")
else :
print("You're obese")
#Closing remarks
print("Thanks")
| true |
72d67c1ccb8703467153babbd8baae6c15ca226a | ankurt04/ThinkPython2E | /chapter4_mypolygon.py | 1,086 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 2 10:45:14 2017
@author: Ankurt.04
"""
#Think Python - End of Chapter 4 - In lessson exercises
import turtle
import math
bob = turtle.Turtle()
def square(t, length):
i = 0
while i <= 3:
t.fd(length)
t.lt(90)
i +=1
#function to draw a polygon of n sides, each side lenght long
def polygon(t, length, n):
angle = 360.0/n
i = 0
while i <= n:
t.fd(length)
t.lt(angle)
i += 1
#function to draw a circle of radius r
def circle(t, r):
#pi = 3.14
circum = 2*math.pi*r
length = 1
n = circum / length
polygon(t, length, n)
def arc(t, r, angle):
#pi = 3.14
circum = 2*math.pi*r
desired_circum = circum * (angle/360.0)
length = 1
n = int(desired_circum / length)
step_angle = angle / n
for i in range(n):
t.fd(length)
t.lt(step_angle)
polygon(bob, length = 70, n = 6) #names of parameters can be included in the argument list
arc(bob, 50, 180)
| true |
f1a1d08fa7136a770ca44fbe8dfbf8ffc4eee38e | katelevshova/py-algos-datastruc | /Problems/strings/anagrams.py | 1,721 | 4.15625 | 4 | # TASK
'''
The goal of this exercise is to write some code to determine if two strings are anagrams of each other.
An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase).
For example:
"rat" is an anagram of "art"
"alert" is an anagram of "alter"
"Slot machines" is an anagram of "Cash lost in me"
Your function should take two strings as input and return True if the two words are anagrams and False if they are not.
You can assume the following about the input strings:
No punctuation
No numbers
No special characters
Note - You can use built-in methods len(), lower() and sort() on strings.
'''
# Code
def anagram_checker(str1, str2):
"""
Check if the input strings are anagrams of each other
Args:
str1(string),str2(string): Strings to be checked
Returns:
bool: Indicates whether strings are anagrams
"""
# TODO: Write your solution here
# Clean strings
clean_str_1 = str1.replace(" ", "").lower()
clean_str_2 = str2.replace(" ", "").lower()
if len(clean_str_1) == len(clean_str_2):
if sorted(clean_str_1) == sorted(clean_str_2):
return True
return False
pass
# Test Cases
print("Pass" if (anagram_checker('rat', 'art')) else "Fail")
print("Pass" if not (anagram_checker('water', 'waiter')) else "Fail")
print("Pass" if anagram_checker('Dormitory', 'Dirty room') else "Fail")
print("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail")
print("Pass" if not (anagram_checker('A gentleman', 'Elegant men')) else "Fail")
print("Pass" if anagram_checker('Time and tide wait for no man', 'Notified madman into water') else "Fail")
| true |
e56c99d2a16d2819a3209bf3cc27ea86ae2c8fa0 | katelevshova/py-algos-datastruc | /Problems/stacks_queues/balanced_parentheses.py | 1,469 | 4.125 | 4 | """
((32+8)∗(5/2))/(2+6).
Take a string as an input and return True if it's parentheses are balanced or False if it is not.
"""
class Stack:
def __init__(self):
self.items = []
def size(self):
return len(self.items)
def push(self, item):
"""
Adds item to the end
"""
self.items.append(item)
def pop(self):
"""
Removes and returns the last value
"""
if self.size() == 0:
return None
else:
return self.items.pop()
def equation_checker(equation_str):
print(equation_str)
"""
Check equation for balanced parentheses
Args:
equation(string): String form of equation
Returns:
bool: Return if parentheses are balanced or not
"""
stack = Stack()
for char in equation_str:
if char == "(":
stack.push(char)
elif char == ")":
if stack.pop() is None:
return False
if stack.size() == 0:
return True
else:
return False
def test_case_1():
actual_result = equation_checker("((32+8)∗(5/2))/(2+6).")
assert actual_result
def test_case_2():
actual_result = equation_checker("()(()) ))))))).")
assert actual_result == False
def test_case_3():
actual_result = equation_checker("())((")
assert actual_result == False
def test():
test_case_1()
test_case_2()
test_case_3()
test()
| true |
6f495c6f055867f3df8bd832470e3697e89427e9 | NerdJain/Python | /search_tuple.py | 566 | 4.1875 | 4 | def main():
l = []
n = int(input("Enter no. of elements in tuple: "))
for i in range(n):
l.append(input("Enter Element: "))
t1 = tuple(l)
se = input("Enter search element: ")
if se in t1:
print(f"{se} is in {t1}")
else:
print(f"{se} not in {t1}")
if __name__ == '__main__':
main()
#Output:
# Enter no. of elements in tuple: 6
# Enter Element: 2
# Enter Element: 3
# Enter Element: 45
# Enter Element: 12
# Enter Element: 78
# Enter Element: 22
# Enter search element: 44
# 44 not in ('2', '3', '45', '12', '78', '22') | false |
edbf5b7c45bd43917d56099a020e9f82a21a0f64 | nsuryateja/python | /exponent.py | 298 | 4.40625 | 4 | #Prints out the exponent value eg: 2**3 = 8
base_value = int(input("enter base value:"))
power_value = int(input("enter power value:"))
val = base_value
for i in range(power_value-1):
val = val * base_value
#Prints the result
print(val)
#Comparing the result
print(base_value ** power_value)
| true |
0d760ab53b3b0cb5873064ab0ed74b54a1962db1 | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 9.py | 567 | 4.34375 | 4 | #! Python 3
# Question 9
# Level 2
#
# Question£º
# Write a program that accepts sequence of lines as input and prints the
# lines after making all characters in the sentence capitalized.
# Suppose the following input is supplied to the program:
# Hello world
# Practice makes perfect
# Then, the output should be:
# HELLO WORLD
# PRACTICE MAKES PERFECT
lines = []
while True:
line = input("Input the line of text. Leave blank if You like to finish")
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
print(text.upper())
| true |
07bcdd9aaac7533bca685a1e4bc17f21db3733da | Cookiee-monster/nauka | /Scripts/Python exercises from GIT Hub/Ex 19.py | 1,181 | 4.6875 | 5 | #! Python 3
# Question:
# You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string,
# age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name;
# 2: Then sort based on age;
# 3: Then sort by score.
# The priority is that name > age > score.
# If the following tuples are given as input to the program:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# Then, the output of the program should be:
# [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
#dsafasfsadf
#dsadsadasdas
users_list = []
raw_input = input("Input the name of user, their age and score in the pattern Name,Age,Score: ")
while raw_input:
users_list.append(tuple(raw_input.split(",")))
raw_input = input("Input the name of user, their age and score in the pattern Name,Age,Score: ")
def sort_score(item):
return item[2]
def sort_age(item):
return item[1]
def sort_name(item):
return item[0]
users_list.sort(key=sort_score)
users_list.sort(key=sort_age)
users_list.sort(key=sort_name)
print(users_list)
| true |
d863997509ddc1bcf91d2217c99681040b2855a6 | Fantendo2001/FORKERD---University-Stuffs | /CSC1001/hw/hw_0/q2.py | 354 | 4.21875 | 4 | def display_digits():
try:
# prompts user for input
num = int(input('Enter an integer: '))
except:
print(
'Invalid input. Please enter again.'
)
else:
# interates thru digits of number and display
for dgt in str(num):
print(dgt)
while True:
display_digits()
| true |
b0b82289495eb50db5191c439cf4f5aa2589c839 | karreshivalingam/movie-booking-project | /movie ticket final.py | 2,810 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
global f
f = 0
#this t_movie function is used to select movie name
def t_movie():
global f
f = f+1
print("which movie do you want to watch?")
print("1,Acharya ")
print("2,vakeel saab ")
print("3,chicchore")
print("4,back")
movie = int(input("choose your movie: "))
if movie == 4:
# in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater
center()
theater()
return 0
if f == 1:
theater()
# this theater function used to select screen
def theater():
print("which screen do you want to watch movie: ")
print("1,SCREEN 1")
print("2,SCREEN 2")
print("3,SCREEN 3")
a = int(input("chosse your screen: "))
ticket = int(input("number of ticket do you want?: "))
timing(a)
# this timing function used to select timing for movie
def timing(a):
time1 = {
"1": "11.00-2.00",
"2": "2.15-4.15",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time2 = {
"1": "11.00-2.00",
"2": "2.15-4.15",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
time3 = {
"1": "11.00-2.00",
"2": "2.15-4.15",
"3": "4.20-7.20",
"4": "7.30-10.30"
}
if a == 1:
print("choose your time:")
print(time1)
t = input("select your time:")
x = time1[t]
print("successfull!, enjoy movie at "+x)
elif a == 2:
print("choose your time:")
print(time2)
t = input("select your time:")
x = time2[t]
print("successfull!, enjoy movie at "+x)
elif a == 3:
print("choose your time:")
print(time3)
t = input("select your time:")
x = time3[t]
print("successfull!, enjoy movie at "+x)
return 0
def movie(theater):
if theater == 1:
t_movie()
elif theater == 2:
t_movie()
elif theater == 3:
t_movie()
elif theater == 4:
city()
else:
print("wrong choice")
def center():
print("which theater do you wish to see movie? ")
print("1,Asian Uppal")
print("2,Miraj cinemas")
print("3,Inox")
print("4,back")
a = int(input("choose your option: "))
movie(a)
return 0
# this function is used to select city
def city():
print("Hi welcome to movie ticket booking: ")
print("where you want to watch movie?:")
print("1,Uppal")
print("2,L.B Nagar")
print("3,Juble hills")
place = int(input("choose your option: "))
if place == 1:
center()
elif place == 2:
center()
elif place == 3:
center()
else:
print("wrong choice")
city() # it calls the function city
| true |
3027f3d2a75a6fad46548ad001b2589aad5c5612 | meenapandey500/Python_program | /program/dict.py | 371 | 4.53125 | 5 | #create a dictionary
student={"rollno":110 ,"name" : "Anu Agrawal","Age":23,"City":"Mumbai"}
print("Type of student :",type(student))
#Loop through a Dictionary student
print("Keys are : ")
for x in student: #only access key of dictionary stduent
print(x)
print("Values are : ")
for x in student.values(): #only access value of dictionary stduent
print(x)
| false |
62f00bee8fa502f4025c07c108ca66304417a1c2 | meenapandey500/Python_program | /multilevel_inh1.py | 970 | 4.5 | 4 | #example of multiLevel inheritance
class A: #base class
def __init__(self):
self.__x=int(input("Enter No. x : "))
def show_x(self):
print("X=",self.__x)
class B(A) : #here B derived class ans inherits base class A
def __init__(self):
super().__init__() #call constructor of base class A
self.__y=int(input("Enter No. y : "))
def show_y(self):
print("Y=",self.__y)
class C(B) : #here C derived class ans inherits base class B
def __init__(self): #constructor function
super().__init__() #call constructor of base class B
self.__z=int(input("Enter No. z : "))
def show_z(self):
print("Z=",self.__z)
def __del__(self): #destructor function
print("Clear memory")
#main program
C1=C() #create object of derived class C
C1.show_x() #call
C1.show_y() #call
C1.show_z() #call
del C1 #call destructor function
C1=C()
C1.show_z()
| false |
c31091af418177da7206836e40939b51c8f5afa0 | meenapandey500/Python_program | /asset.py | 497 | 4.125 | 4 | def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print(KelvinToFahrenheit(273))
print(int(KelvinToFahrenheit(505.78)))
print(KelvinToFahrenheit(-5))
'''When it encounters an assert statement, Python evaluates the accompanying
expression, which is hopefully true. If the expression is false, Python
raises an AssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]'''
| true |
882d2c3472802213860abae36c9ef9f0e8d65801 | meenapandey500/Python_program | /mini_cal.py | 448 | 4.28125 | 4 | #Write a program to create a Mini Calculator
a=float(input("Enter First Number = "))
b=float(input("Enter Second Number : "))
print("Sum of 2 Nos. : ",a," + ",b," = ",(a+b))
print("Subtract of 2 Nos. : ",a, " - ", b, " = " ,(a-b))
print("Multiply of 2 Nos. : ",(a*b))
print("Divide of 2 Nos. = ",(a/b))
print("Integer division of 2 Nos. : ",(a//b))
print("Remainder of 2 Nos. : ",(a%b))
print("Power of given base : ",(a**b))
| false |
c01f1ae280d10c9d4a54f44a5561895a70c9489a | meenapandey500/Python_program | /mini_calculator1.py | 572 | 4.25 | 4 | #write a program to create a mini calculator
a=float(input("Enter First Number : "))
b=float(input("Enter Second Number : "))
print("press 1 for sum")
print("press 2 for subtract")
print("press 3 for multiply")
print("press 4 for divide")
choice=int(input("Enter your choice : "))
if(choice==1):
c=a+b
print("Sum : ",a,"+",b,"=",c)
elif(choice==2):
c=a-b
print("subtract : ",a,"-",b,"=",c)
elif(choice==3):
c=a*b
print("multiply : ",c)
elif(choice==4):
c=a/b
print("divide : ",c)
else:
print("invalid choice")
| false |
182803c3fbabdc05d4db21adafc2a9800732c499 | victor-lima-142/Exercicios-Logica-Programacao | /Estrutura de Decisao/Exercicio 2/ProdutoBarato.py | 681 | 4.21875 | 4 | '''
Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
'''
produto1 = float(input('Qual preço do produto 1?\n'))
produto2 = float(input('Qual preço do produto 2?\n'))
produto3 = float(input('Qual preço do produto 3?\n'))
if produto1 < produto2 and produto1 < produto3:
print("O mais barato é o produto 1.")
elif produto2 < produto1 and produto2 < produto3:
print("O mais barato é o produto 2.")
elif produto3 < produto1 and produto3 < produto2:
print("O mais barato é o produto 3.")
elif produto1 == produto2 and produto2 == produto3:
print("São iguais")
| false |
9847bcc11fc8fb376684ec283eb6c13eabf4e44e | nengvang/s2012 | /lectures/cylinder.py | 957 | 4.375 | 4 | # Things we need (should know)
#
# print
# Display a blank line with an empty print statement
# print
# Display a single item on a separate line
# print item
# Display multiple items on a line with commas (,) separated by spaces
# print item1, item2, item3
# print item,
#
# raw_input([prompt])
# Prompt users for text-based (str) information
# Optional message
# Blocking call
# value = raw_input('Enter your name: ')
# value = raw_input()
#
# Data Types
# int, str, float, bool, list, dict
# Each holds a different type of information and has related operators
# Each also provides a creation/conversion function
import math
height = float(raw_input('Enter the height of the cylinder: '))
radius = float(raw_input('Enter the radius of the cylinder: '))
volume = 2 * math.pi * radius ** 2 * height
print 'The volume of a cylinder with height', height, 'and radius', radius,
print 'is', volume
| true |
578de93ccb0c029d5ada5b837358451bc4612faa | stechermichal/codewars-solutions-python | /7_kyu/printer_errors_7_kyu.py | 1,260 | 4.28125 | 4 | """In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for
the sake of simplicity, are named with letters from a to m.
The colors used by the printer are recorded in a control string. For example a "good" control string would be
aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time
color a...
Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g.
aaaxbbbbyyhwawiwjjjwwm with letters not from a to m.
You have to write a function printer_error which given a string will return the error rate of the printer as a string
representing a rational whose numerator is the number of errors and the denominator the length of the control string.
Don't reduce this fraction to a simpler expression.
The string has a length greater or equal to one and contains only letters from ato z.
Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"""""
def printer_error(s):
count_error = 0
my_set = 'abcdefghijklm'
for i in s:
if i not in my_set:
count_error += 1
return f"{count_error}/{len(s)}"
| true |
954696eccde542040c6abd120b33878fead05e65 | stechermichal/codewars-solutions-python | /5_kyu/simple_pig_latin_5_kyu.py | 453 | 4.3125 | 4 | """Move the first letter of each word to the end of it, then add "ay" to the end of the word.
Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !"""
def pig_it(text):
text_list = text.split()
for i, value in enumerate(text_list):
if value.isalpha():
text_list[i] = value[1:] + value[0:1] + 'ay'
return ' '.join(text_list)
| true |
c062245d21b75405560e771c16b1811bd17d76b8 | NiteshPidiparars/Python-Tutorials | /PracticalProblem/problem4.py | 1,081 | 4.3125 | 4 | '''
Problem Statement:-
A palindrome is a string that, when reversed, is equal to itself. Example of the palindrome includes:
676, 616, mom, 100001.
You have to take a number as an input from the user. You have to find the next palindrome corresponding to that number.
Your first input should be the number of test cases and then take all the cases as input from the user.
Input:
3
451
10
2133
Output:
Next palindrome for 451 is 454
Next palindrome for 10 is 11
Next palindrome for 2311 is 2222
'''
'''
Author: Harry
Date: 15 April 2019
Purpose: Practice Problem For CodeWithHarry Channel
'''
def next_palindrome(n):
n = n+1
while not is_palindrome(n):
n += 1
return n
def is_palindrome(n):
return str(n) == str(n)[::-1]
if __name__ == "__main__":
n = int(input("Enter the number of test cases\n"))
numbers = []
for i in range(n):
number = int(input("Enter the number:\n"))
numbers.append(number)
for i in range(n):
print(
f"Next palindrome for {numbers[i]} is {next_palindrome(numbers[i])}")
| true |
b5e59ae88dabef206e1ca8eba2a3029d5e71d632 | phriscage/coding_algorithms | /factorial/factorial.py | 889 | 4.46875 | 4 | #!/usr/bin/python2.7
""" return a factorial from a given number """
import sys
import math
def get_factorial(number):
""" iterate over a given number and return the factorial
Args:
number (int): number integer
Returns:
factorial (int)
"""
factorial = 1
for n in range(int(number), 1, -1):
factorial *= n
return factorial
def math_factorial(number):
""" user the built-in math.factorial to return factorial
Args:
number (int): number integer
Returns:
factorial (int)
"""
return math.factorial(int(number))
def main():
""" run the main logic """
#number = raw_input()
if len(sys.argv) < 2:
print "Argument required."
sys.exit(1)
number = sys.argv[1]
print get_factorial(number)
print math_factorial(number)
if __name__ == '__main__':
main()
| true |
4eb679fa74d8e2bf33d3e58984f4c861ad0b7827 | gauravarora1005/python | /Strings Challenges 80-87.py | 1,973 | 4.21875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[2]:
first_name = input("enter your first name: ")
f_len = len(first_name)
print("Length of First Name ", f_len)
last_name = input("Enter the last name: ")
l_len = len(last_name)
print("Length for last name is: ", l_len)
full_name = first_name + " " + last_name
full_len = len(full_name)
print("Your name is ", full_len, " characters long")
# In[4]:
sub = input("Enter your fvt subject: ")
for letter in sub:
print(letter, end = "-")
# In[6]:
name = input("Enter your name in upper case: ")
while not name.isupper():
print("not in upper, try again")
name = input("Enter your name in upper case: ")
print("All in upper")
# In[11]:
car_num = input("Enter your car num plate number: ")
state = car_num[0:2]
rest_num = car_num[2:]
u_state = state.upper()
modified_number = u_state+rest_num
#print(state)
#print(rest_num)
print(modified_number)
# In[12]:
vowels = 'aeiou'
count = 0
name = input("enter the name: ")
for letter in name:
if letter in vowels:
count = count+1
print(count)
# In[13]:
#either create vowels as string or list. both will work
vowels = ['a','e','i','o','u']
count = 0
name = input("enter the name: ")
for letter in name:
if letter in vowels:
count = count+1
print(count)
# In[15]:
password = input("Please enter the password: ")
confirm = input("Please confirm the password: ")
if password == confirm:
print("Thank you")
elif password.lower() == confirm.lower():
print("Please enter in same case")
else:
print("Incorrect")
# In[22]:
name = input("Please enter the name: ")
for i in range (len(name)-1,0-1, -1): #range gives the numeric and stop/2nd argument is not inclusive
print(name[i])
length = len(name)
position =1
for i in name:
new_position = length - position
letter = name[new_position]
print(letter)
position = position+1
# In[ ]:
| true |
d95e031490496dec7183f8f3fd21abcf9b0dd23d | fishiraki/Election_Analysis | /Python_practice.py | 2,734 | 4.375 | 4 | #print("Hello World")
counties = ["Arapahoe","Denver","Jefferson"]
#if counties[1] == 'Denver':
# print(counties[1])
#if counties[3] != 'Jefferson':
# print(counties[2])
#temperature = int(input("What is the temperature outside? "))
#if temperature > 80:
# print("Turn on the AC.")
#else:
# print("Open the windows.")
#What is the score?
#score = int(input("What is your test score? "))
# Determine the grade.
#if score >= 90:
# print('Your grade is an A.')
#else:
# if score >= 80:
# print('Your grade is a B.')
# else:
# if score >= 70:
# print('Your grade is a C.')
# else:
# if score >= 60:
# print('Your grade is a D.')
# else:
# print('Your grade is an F.')
# What is the score?
#score = int(input("What is your test score? "))
# Determine the grade.
#if score >= 90:
# print('Your grade is an A.')
#elif score >= 80:
# print('Your grade is a B.')
#elif score >= 70:
# print('Your grade is a C.')
#elif score >= 60:
# print('Your grade is a D.')
#else:
# print('Your grade is an F.')
#if "El Paso" in counties:
# print("El Paso is in the list of counties.")
#else:
# print("El Paso is not the list of counties.")
#if "Arapahoe" in counties and "El Paso" in counties:
# print("Arapahoe and El Paso are in the list of counties.")
#else:
# print("Arapahoe or El Paso is not in the list of counties.")
#if "Arapahoe" in counties or "El Paso" in counties:
# print("Arapahoe or El Paso is in the list of counties.")
#else:
# print("Arapahoe and El Paso are not in the list of counties.")
#if "Arapahoe" in counties and "El Paso" not in counties:
# print("Only Arapahoe is in the list of counties.")
#else:
# print("Arapahoe is in the list of counties and El Paso is not in the list of counties.")
#for county in counties:
# print(county)
numbers = [0, 1, 2, 3, 4]
#for num in range(5):
# print(num)
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}]
#for county_dict in voting_data:
# print(county_dict)
#for i in range(len(voting_data)):
# print(voting_data[i])
#counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222}
#for county, voters in counties_dict.items():
# print(county + " county has " + str(voters) + " registered voters.")
# Import the datetime class from the datetime module.
import datetime
# Use the now() attribute on the datetime class to get the present time.
now = datetime.datetime.now()
# Print the present time.
print("The time right now is ", now) | false |
2d44b738e87fd3acc226f5c0a9d980ed58d30beb | kseet001/FCS | /Homework5/homework_qn1.py | 2,248 | 4.125 | 4 | # Homework 5 - Question 1
# Encrypt the following plaintext P (represented with 8-bit ASCII) using AES-ECB,
# with the key of 128-bit 0. You may use an existing crypto library for this exercise.
# P = SUTD-MSSD-51.505*Foundations-CS*
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
plaintext = "SUTD-MSSD-51.505*Foundations-CS*"
key = '\x00' * 16
def int_to_bytes(x):
return x.to_bytes((x.bit_length() + 7) // 8, 'big')
def int_from_bytes(xbytes):
return int.from_bytes(xbytes, 'big')
def encrypt(key, plaintext):
encryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
return encryptor.encrypt(plaintext.encode('utf-8'))
def decrypt(key, ciphertext):
decryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
return decryptor.decrypt(ciphertext)
# AES requires that plaintexts be a multiple of 16, so we have to pad the data
def pad(data):
return data + b"\x00" * (16 - len(data) % 16)
def solve_1a():
ciphertext = encrypt(key, plaintext)
print("\nQuestion 1a)")
print("C : %s" % (hexlify(ciphertext)))
def solve_1b():
ciphertext = encrypt(key, plaintext)
print("\nQuestion 1b)")
C = hexlify(ciphertext)
C1 = C[0:32]
C2 = C[32:]
P1 = decrypt(key, unhexlify(C2+C1))
print("P1 : %s" % (P1.decode("utf-8")[:16]))
def solve_1c():
ciphertext = encrypt(key, plaintext)
C = hexlify(ciphertext)
C1 = C[0:32]
C2 = C[32:]
# Convert to int, increment by 1 and convert back to bytes
C2_modified = int_from_bytes(C2) + 1
C2_modified = int_to_bytes(C2_modified)
print("\nQuestion 1c)")
#print("Original ciphertext: %s" % (unhexlify(C1+C2))) # for debugging purpose
#print("Modified ciphertext: %s" % (unhexlify(C1+C2_modified))) # for debugging purpose - shows that it has been incremented by 1
P2 = decrypt(key, unhexlify(C1+C2_modified))
print("P2 : %s" % (P2)[16:])
P2 = decrypt(key, unhexlify(C1 + C2)) # for debugging purpose
print("P2 : %s" % (P2)[16:]) # for debugging purpose
def main():
print("\nP : %s" % (plaintext.encode()))
print("Key : %s" % (key.encode()))
solve_1a()
solve_1b()
solve_1c()
if __name__ == "__main__":
main() | true |
133249b5665e99fb2291cff6ab49e0c1cb6c800c | vijaynchakole/Proof-Of-Concept-POC-Project | /Directory Operations/Directory_File_Checksum.py | 2,950 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 19 01:02:26 2020
@author: Vijay Narsing Chakole
MD5 hash in Python
Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases.
There are many hash functions defined in the “hashlib” library in python.
Here we are talking about explanation and working of MD5 hash.
MD5 Hash
This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has security issues.
Functions associated :
encode() : Converts the string into bytes to be acceptable by hash function.
digest() : Returns the encoded data in byte format.
hexdigest() : Returns the encoded data in hexadecimal format.
Explanation : The below code takes file data string and
converts it into the byte equivalent using encode()
so that it can be accepted by the hash function.
The md5 hash function encodes it and then using hexdigest(),
hexadecimal equivalent encoded string is printed.
"""
from sys import *
import os
import hashlib
# set current working directory
os.chdir("C:/Users/hp/PycharmProjects")
def hashfile(file_path, blocksize = 1024):
afile = open(file_path, 'rb')
hasher = hashlib.md5()
buffer = afile.read(blocksize)
while(len(buffer)>0):
hasher.update(buffer)
buffer = afile.read(blocksize)
afile.close()
return hasher.hexdigest()
def DisplayChecksum(path):
flag = os.path.isabs(path)
if flag == False :
path = os.path.abspath(path)
exists = os.path.isdir(path)
if exists:
for folder, subfolder,file in os.walk(path):
print("Current folder is "+ folder)
for filename in file :
path = os.path.join(folder, filename)
file_hash = hashfile(path)
print(path)
print(file_hash)
print(" ")
else:
print("Invalid Path")
#path = "college"
#DisplayChecksum(path)
def main():
print("inside main")
#path = "college"
print("Application Name "+argv[0])
string = argv[1].lower()
if (len(argv)<2):
print("Invalid Number of arguments ")
if(string == '-h'):
print("Script is designed for traverse specific directory ")
exit()
if (string == '-u'):
print("Usage : Application Name Absolutepath directory")
exit()
try:
path = argv[1]
DisplayChecksum(path)
except ValueError:
print("Error : invalid datatype of input ")
except Exception:
print("Error : invalid input ")
if __name__ == "__main__":
main()
| true |
a1e3f0f77b787e2d3e1c4716b1267fc96a588e07 | Verissimosem2/programacao-orientada-a-objetos | /listas/lista-de-exercicios-03/questão9.py | 904 | 4.25 | 4 | numero = float (input("Digite o primeiro numero: "))
numero2 = float(input("Digite o segundo numero: "))
numero3 = float(input("Digite o terceiro numero: "))
if numero > numero2 and numero > numero3:
if numero2 > numero3:
print("",numero)
print("",numero2)
print("",numero3)
if numero3 > numero2:
print("",numero)
print("",numero3)
print("",numero2)
elif numero2 > numero and numero2 > numero3:
if numero > numero3:
print("",numero2)
print("",numero)
print("",numero3)
if numero3 > numero:
print("",numero2)
print("",numero3)
print("",numero)
elif numero3 > numero2 and numero3 > numero:
if numero2 > numero:
print("",numero3)
print("",numero2)
print("",numero)
if numero > numero2:
print("",numero3)
print("",numero)
print("",numero2)
| false |
ed39c3de6ac1d1296c487fa8206493b46f3c8998 | KrishnaRauniyar/python_assignment_II | /f16.py | 1,567 | 4.125 | 4 | # Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like? If you aren't familiar with SuperMario, use your own favorite video or board game to model a player.
from pynput import keyboard
def controller(key):
is_jump = False
if str(key) == 'Key.right':
move.right()
elif str(key) == 'Key.left':
move.left()
elif str(key) == 'Key.up':
is_jump = True
move.jump()
elif str(key) == 'Key.esc':
end.score()
end.menu()
return False
if is_jump == True:
move.gravity()
class Startgame:
def startmenu(self):
a = input('Enter s to start game : ')
if a == 's':
print('Game started.')
return True
else:
return False
def background(self):
print('background is moving.')
def showmario(self):
print('mario is ready to play.')
class Move:
def right(self):
print('moving right by 5.')
def left(self):
print('moving left by 5.')
def jump(self):
print('mario jumping.')
def gravity(self):
print('gravity enable.')
class Gameover:
def score(self):
print('your score : ', 1512)
def menu(self):
print('Game over!!!')
start = Startgame()
move = Move()
end = Gameover()
if start.startmenu() == True:
start.background()
start.showmario()
print('Enter escape to exit')
with keyboard.Listener(on_press=controller) as listener:
listener.join() | true |
4969f9c7fdbf0a5239bbf1e1e4d226b5ed336196 | KrishnaRauniyar/python_assignment_II | /f4.py | 629 | 4.25 | 4 | # Create a list. Append the names of your colleagues and friends to it. Has the id of the list changed?
# Sort the list.
# What is the first item on the list? What is the second item on the list?
# no id of list is not changed
def checkId(string):
arr = []
print("The is before append: ", id(arr))
for i in range(len(string)):
arr.append(string[i])
print("The id after append", id(arr))
arr.sort()
return print("The two names are {}".format(arr[0:2]))
print(checkId(["rahul", "krishna", "pakka", "gaurav", "anil", "ramita"]))
print("The id before and after append remains the same")
| true |
8997c7f99aaf30cc10052590b11156b842204423 | LuizFernandoS/PythonCursoIntensivo | /Capitulo06_Dicionarios/06_03Glossary.py | 1,363 | 4.15625 | 4 | #"""6.3 – Glossário: Um dicionário Python pode ser usado para modelar um
#dicionário de verdade. No entanto, para evitar confusão, vamos chamá-lo de
#glossário.
#• Pense em cinco palavras relacionadas à programação que você conheceu
#nos capítulos anteriores. Use essas palavras como chaves em seu glossário e
#armazene seus significados como valores.
#• Mostre cada palavra e seu significado em uma saída formatada de modo
#elegante. Você pode exibir a palavra seguida de dois-pontos e depois o seu
#significado, ou apresentar a palavra em uma linha e então exibir seu
#significado indentado em uma segunda linha. Utilize o caractere de quebra
#de linha (\n) para inserir uma linha em branco entre cada par palavrasignificado
#em sua saída.
#18/05/21"""
palavra = {'Laço': 'Repetir uma função várias vezes.',
'Lista': 'Vários itens entre colchetes.',
'Condicional': 'Executar uma função baseado em falso ou verdadeiro.',
'Variável': 'Item que armazena dados.',
'Indentação': 'Forçar a escrever um código alinhado.'}
print("Laço significa: " + palavra['Laço'])
print("Lista significa: " + palavra['Lista'])
print("Condicional significa: " + palavra['Condicional'])
print("Variável significa: " + palavra['Variável'])
print("Indentação significa: " + palavra['Indentação'])
| false |
064a70b66d0b9ac03455dedd3c7e857b7bfdb5aa | LuizFernandoS/PythonCursoIntensivo | /Capitulo03_IntroducaoListas/03_02Salute.py | 505 | 4.28125 | 4 | """3.2 – Saudações: Comece com a lista usada no Exercício 3.1, mas em vez de
simplesmente exibir o nome de cada pessoa, apresente uma mensagem a elas.
O texto de cada mensagem deve ser o mesmo, porém cada mensagem deve
estar personalizada com o nome da pessoa."""
#pg73
names=['Jorge', 'Victor', 'Ângelo']
print('Olá, ' + names[0].title() + '! Tudo bem?')
print('Bom dia, ' + names[1].title() + '! Como está a esposa?')
print('Fala, ' + names[2].title() + '! Brincando com o filho?')
| false |
7b549e195ea36dba547744025e6e9b03fa487a3a | LuizFernandoS/PythonCursoIntensivo | /Capitulo05_InstrucoesIF/05_11OrdinalNumbers.py | 778 | 4.34375 | 4 | #5.11 – Números ordinais: Números ordinais indicam sua posição em uma lista,
#por exemplo, 1st ou 2nd, em inglês. A maioria dos números ordinais nessa
#língua termina com th, exceto 1, 2 e 3.
#• Armazene os números de 1 a 9 em uma lista.
#• Percorra a lista com um laço.
#• Use uma cadeia if-elif-else no laço para exibir a terminação apropriada
#para cada número ordinal. Sua saída deverá conter "1st 2nd 3rd 4th 5th
#6th 7th 8th 9th", e cada resultado deve estar em uma linha separada.
ordinalnumbers = ['1','2','3','4','5','6','7','8','9']
for ordinalnumber in ordinalnumbers:
if ordinalnumber == '1' :
print(ordinalnumber + "st")
elif ordinalnumber == '2' :
print(ordinalnumber + "nd")
else:
print(ordinalnumber + "th")
| false |
73181b0a6495350ba3b6bfd29da0f000da2ca5f2 | Data-Analisis/scikit-learn-mooc | /python_scripts/parameter_tuning_sol_01.py | 2,951 | 4.375 | 4 | # %% [markdown]
# # 📃 Solution for introductory example for hyperparameters tuning
#
# In this exercise, we aim at showing the effect on changing hyperparameter
# value of predictive pipeline. As an illustration, we will use a linear model
# only on the numerical features of adult census to simplify the pipeline.
#
# Let's start by loading the data.
# %%
from sklearn import set_config
set_config(display='diagram')
# %%
import pandas as pd
df = pd.read_csv("../datasets/adult-census.csv")
target_name = "class"
numerical_columns = [
"age", "capital-gain", "capital-loss", "hours-per-week"]
target = df[target_name]
data = df[numerical_columns]
# %% [markdown]
# We will first divide the data into a train and test set to evaluate
# the model.
# %%
from sklearn.model_selection import train_test_split
data_train, data_test, target_train, target_test = train_test_split(
data, target, random_state=42)
# %% [markdown]
# First, define a logistic regression with a preprocessing stage to scale the
# data.
# %%
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
model = Pipeline(steps=[
("preprocessor", StandardScaler()),
("classifier", LogisticRegression()),
])
model
# %% [markdown]
# Now, fit the model on the train set and compute the model's accuracy on the
# test set.
# %%
model.fit(data_train, target_train)
accuracy = model.score(data_test, target_test)
print(f"Accuracy of the model is: {accuracy:.3f}")
# %% [markdown]
# We will use this model as a baseline. Now, we will check the effect of
# changing the value of the hyperparameter `C` in logistic regression. First,
# check what is the default value of the hyperparameter `C` of the logistic
# regression.
# %%
print(f"The hyperparameter C was: {model[-1].C}")
# %% [markdown]
# Create a model by setting the `C` hyperparameter to `0.001` and compute the
# performance of the model.
# %%
model = Pipeline(steps=[
("preprocessor", StandardScaler()),
("classifier", LogisticRegression(C=0.001)),
])
model
# %%
model.fit(data_train, target_train)
accuracy = model.score(data_test, target_test)
print(f"Accuracy of the model is: {accuracy:.3f}")
# %% [markdown]
# We observe that the performance of the model decreased. Repeat the same
# experiment for `C=100`
# %%
model = Pipeline(steps=[
("preprocessor", StandardScaler()),
("classifier", LogisticRegression(C=100)),
])
model
# %%
model.fit(data_train, target_train)
accuracy = model.score(data_test, target_test)
print(f"Accuracy of the model is: {accuracy:.3f}")
# %% [markdown]
# We see that the performance of the model in this case is as good as the
# original model. However, we don't know if there is a value for `C` in the
# between 0.001 and 100 that will lead to a better model.
#
# You can try by hand a couple of values in this range to see if you can
# improve the performance.
| true |
efc2a9bba1db46e90da4f3d1dffaa98ff3fc76ef | LingyeWU/unit3 | /snakify_practice/3.py | 837 | 4.1875 | 4 | # This program finds the minimum of two numbers:
a = int(input())
b = int(input())
if a < b:
print (a)
else:
print (b)
# This program prints a number depending on the sign of the input:
a = int(input())
if a > 0:
print (1)
elif a < 0:
print (-1)
else:
print (0)
# This program takes the coordinates of a rook and a destination and determines whether it is possible for it to move:
x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
if x1 == x2 or y1 == y2:
print ("YES")
else:
print ("NO")
# This program determines if a chocolate bar with dimensions n by m would be able to be divided into a bar with k squares.
n = float(input())
m = float(input())
k = float(input())
portion = n * m
if k < portion and ((k % n == 0) or (k % m == 0)):
print("YES")
else:
print("NO")
| true |
4bee428ac8e0dd249deef5c67915e62ba1057997 | Matshisela/Speed-Converter | /Speed Convertor.py | 1,100 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# ### Converting km/hr to m/hr and Vice versa
# In[1]:
def kmh_to_mph(x):
return round(x * 0.621371, 2) # return to the nearest 2 decimal places
def mph_to_kmh(x):
return round(1/ 0.621371 * x, 2) # return to the nearest 2 decimal places
# In[2]:
speed_km = float(input("What is the speed in km/hr?:"))
g = kmh_to_mph(speed_km)
print("The speed in miles/hr is {}".format(g))
# In[3]:
speed_m = float(input("What is the speed in miles/hr?:"))
g = mph_to_kmh(speed_m)
print("The speed in km/hr is {}".format(g))
# ### Converting km/hr to metres/sec and Vice versa
# In[4]:
def kmh_to_ms(x):
return round(1/ 3.6 * x, 2) # return to the nearest 2 decimal places
def ms_to_kmh(x):
return round(3.6 * x, 2) # return to the nearest 2 decimal places
# In[5]:
speed_ms = float(input("What is the speed in metres/s?:"))
g = ms_to_kmh(speed_ms)
print("The speed in km/hr is {}".format(g))
# In[6]:
speed_kmh = float(input("What is the speed in km/hr?:"))
g = kmh_to_ms(speed_kmh)
print("The speed in metres/sec is {}".format(g))
| true |
5f90cf3ee2b9a95d877d3a61a5f4691535c182f3 | s-andromeda/PreCourse_2 | /Exercise_4.py | 1,469 | 4.5 | 4 | # Python program for implementation of MergeSort
"""
Student : Shahreen Shahjahan Psyche
Time Complexity : O(NlogN)
Memory Complexity : O(logN)
The code ran successfully
"""
def mergeSort(arr):
if len(arr) > 1 :
# Getting the mid point of the array and dividing the array into 2 using the mid point
mid = len(arr)//2
L = arr[: mid]
R = arr[mid :]
# passing these two arrays to sort or get divided again
mergeSort(L)
mergeSort(R)
# this function merges the two arrays back again
merge(L, R, arr)
def merge(L, R, arr):
i = 0
j = 0
k = 0
# checking if the element of the both arrays. The smaller one will get saved everytime.
while(i<len(L) and j<len(R)):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# When we run out of either of the arrays, we will shift the remaining of the other arrays to the arr
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
print(arr)
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
| true |
1bdfb1dfe2b1d5c7b707a38f071a7167f6f514e8 | arpitsomani8/Data-Structures-And-Algorithm-With-Python | /Stack/Representation of a Stack using Dynamic Array.py | 1,517 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Arpit Somani
"""
class Node:
#create nodes of linked list
def __init__(self,data):
self.data = data
self.next = None
class Stack:
# default is NULL
def __init__(self):
self.head = None
# Checks if stack is empty
def isempty(self):
if self.head == None:
return True
else:
return False
# add item to stack
def push(self,data):
if self.head == None:
self.head=Node(data)
else:
newnode = Node(data)
newnode.next = self.head
self.head = newnode
# Remove element from stack
def pop(self):
if self.isempty():
return None
#make a new top element after popping
else:
poppednode = self.head
self.head = self.head.next
poppednode.next = None
return poppednode.data
#top element in stack
def peek(self):
if self.isempty():
return None
else:
return self.head.data
def display(self):
fnode = self.head
if self.isempty():
print("Stack Underflow")
else:
while(fnode != None):
print(fnode.data,end = " ")
fnode = fnode.next
return
mystack = Stack()
q=int(input("How many total elements to push:"))
for i in range (0,q):
a=int(input("Enter "+str(i+1)+" element to push:"))
mystack.push(a)
print(" ")
mystack.display()
print("\nBefore pop, Top (peek) element is ",mystack.peek())
mystack.pop()
mystack.display()
print("\nAfter pop, Top (peek) element is ", mystack.peek())
| true |
b6d143eb55b431f047482aaf881c025382483c0a | SHIVAPRASAD96/flask-python | /NewProject/python_youtube/list.py | 432 | 4.1875 | 4 | food =["backing","tuna","honey","burgers","damn","some shit"]
dict={1,2,3};
for f in food:
#[: this is used print how many of the list items you want to print depending on the number of items in your list ]
print(f,"\nthe length of",f,len(f));
print("\n");
onTeam =[20,23,23235,565];
print("Here are the people of the team Valour");
for i in onTeam:
print(i);
continue;
print("hello");
print("Done"); | true |
60fc8a28c92e1cf7c9b98260f1dee89940929d68 | tsaiiuo/pythonNLP | /set and []pratice.py | 1,015 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 15:24:16 2021
@author: huannn
"""
#list[item1,item2....]
a=['apple','melon','orange','apple']
a.append('tomato')
a.insert(3, 'tomato')
print(a)
a.remove('apple')
print(a)
a.pop(0)#pop out a certain position
print(a)
a1=['fish','pork']
#a.append(a1) will be['fish'....]
a.extend(a1)
print(a)
print(a.index('fish'))#find the index
print(a.count('tomato'))#count q
a.reverse()#tenet
print(a)
a.sort()#abc order
print(a)
a2=a.copy()
print(a2)
#set function
b=set(a2)#make a set from a list
print(b)
#b.remove('apple')#if the set doesnt exist item will be error need use discard
b.discard('apple')
print(b)
b.update(a)#use update to append a list
print(b)
set1={'1','2','3'}
set2={'3','4','5'}
print(set1|set2)#same as below
#print(set1.union(set2))
print(set1-set2)#remove item appear in set2
print(set1&set2)
print(set1.difference(set2))#set1 be base
for fruit in a:#string item
print(fruit)
a.clear()
print(f"final list:{a}") | true |
ad1dcc7b5a7c601125ef8a5db39a1cd393af58a4 | celsopa/CeV-Python | /mundo01/ex028.py | 501 | 4.25 | 4 | # Exercício Python 028: Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu.
from random import randint
nPC = randint(0,5)
nUser = int(input("Tente advinhar o número escolhido pelo computador [0 a 5]: "))
if nPC == nUser:
print("Você acertou!")
else:
print(f"Você errou, o computador escolheu {nPC}") | false |
c5847011cf3d5f5d59fc7fc58b903d0332c71973 | celsopa/CeV-Python | /mundo02/ex036.py | 786 | 4.25 | 4 | # Exercício Python 036: Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa. Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar. A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
valorCasa = float(input("Informe o valor do imóvel: R$"))
salario = float(input("Informe seu rendimento mensal: "))
anos = int(input("Informe o prazo de pagamento em anos: "))
prestMensal = valorCasa/anos/12
print(f"Para financiar um imóvel de R${valorCasa:.2f} em {anos} anos,\no valor da prestação mensal será de R${prestMensal:.2f}")
if prestMensal <= salario*0.3:
print("Empréstimo APROVADO!")
else:
print("O valor da prestação excede 30% do seu salário.\nEmpréstimo NEGADO.")
| false |
512efa228df5979cddc8a2295705c3f9ab927177 | celsopa/CeV-Python | /mundo03/ex104.py | 570 | 4.125 | 4 | # Exercício Python 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante
# à função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
# Ex: n = leiaInt('Digite um n: ')
def leiaint(msg):
while True:
n = input(msg)
if n.isnumeric():
n = int(n)
break
else:
print('\033[0;31mERRO. Digite um número inteiro válido.\033[m')
return n
num = leiaint('Digite um número: ')
print(f'Você acabou de digitar o número {num}')
| false |
4ec21acb5c414b5a34db008225502db8576e3003 | pawarspeaks/HACKTOBERFEST2021-2 | /PYTHON/pythagorean_theorem.py | 1,777 | 4.5 | 4 | #A Pythagorean theorem solver that accounts for whether the hypotenuse is known or not
def main():
def is_right():
righty = input("Do you have a right triangle (meaning one of the angles is 90 degrees)? (Y/N) ")
if y_or_n(righty) == "Y":
get_angles()
else:
not_right()
def get_angles():
hype = input("Do you know the length of the hypotenuse, the line that is opposite the right angle? (Y/N) ")
if y_or_n(hype) == "Y":
yes_hype()
else:
no_hype()
def yes_hype():
c = int(input("What is the length of the hypotenuse? "))
a = int(input("What is the length of the other side you know? "))
solver_hype(a,c)
def no_hype():
a = int(input("What is the length of one side? "))
b = int(input("What is the length of the other side? "))
solver_no(a,b)
def solver_hype(x,c):
squares = (c * c) - (x * x)
y = squares ** 0.5
print(f"The missing side is {y} units long.")
def solver_no(a,b):
squares = (a * a) + (b * b)
c = squares ** 0.5
print(f"The hypotenuse is {c} units long.")
def not_right():
print("I'm sorry, the Pythagorean theorum only works with right triangles.")
def y_or_n(x):
if(x.upper() == 'Y'):
return("Y")
elif(x.upper() == 'N'):
return("N")
else:
print("I'm sorry, I can't understand that input. Please use 'Y' or 'N'.")
y_or_n()
print("The Pythagorean theorem is used to solve for an unknown side of a right triangle.")
is_right()
if __name__ == "__main__":
main()
else:
print("Pythagorean theorem solver")
main() | false |
152e7b7430ded1d3593c2ec9b3a2cec89d7d270d | pawarspeaks/HACKTOBERFEST2021-2 | /PYTHON/PasswordGen.py | 606 | 4.125 | 4 | import string
import random
#Characters List to Generate Password
characters = list(string.ascii_letters + string.digits + "!@#$%^&*()")
def password_gen():
#Length of Password from the User
length = int(input("Password length: "))
#Shuffling the Characters
random.shuffle(characters)
#Picking random Characters from the given List
password = []
for i in range(length):
password.append(random.choice(characters))
#Shuffling the Resultant Password
random.shuffle(password)
#Converting the List to String
#Printing the List
print("".join(password))
#Invoking the function
password_gen()
| true |
de91aed8808c9c1562ace961b39d5e2f6d3d20bc | leolanese/python-playground | /tips/list-comprehensions.py | 318 | 4.34375 | 4 | # Python's list comprehensions
vals = [expression
for value in collection
if condition]
# This is equivalent to:
vals = []
for value in collection:
if condition:
vals.append(expression)
# Example:
even_squares = [x * x for x in range(10) if not x % 2
even_squares # [0, 4, 16, 36, 64]
| true |
ee2d5fa2d85740d0219040b80426b1ef57087857 | datasciencecampus/coffee-and-coding | /20191112_code_testing_overview/02_example_time_test.py | 1,166 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 11 10:28:55 2019
@author: pughd
"""
from datetime import datetime
class TestClass:
# Difficult to automate test this as depends on time of day!
def test_morning1(self):
assert time_of_day() == "Night"
# Far easier to test
def test_morning2(self):
assert time_of_day_2(9) == "Morning"
assert time_of_day_2(13) == "Afternoon"
assert time_of_day_2(0) == "Night"
assert time_of_day_2(19) == "Evening"
def time_of_day_2(hour):
# Return approproiate description
if hour >= 0 and hour < 6:
return 'Night'
elif hour >= 6 and hour < 12:
return "Morning"
elif hour >= 12 and hour < 18:
return "Afternoon"
else:
return "Evening"
def time_of_day():
# Get the current hour
hour = datetime.now().hour
# Return approproiate description
if hour >= 0 and hour < 6:
return 'Night'
elif hour >= 6 and hour < 12:
return "Morning"
elif hour >= 12 and hour < 18:
return "Afternoon"
else:
return "Evening"
| true |
7042b216761fe26ce8ffa3e913f54a0508d19ca4 | sreelekha11/Number-Guessing | /NumberGuessingGame.py | 1,254 | 4.40625 | 4 | #Creating a simple GUI Python Guessing Game using Tkinter and getting the computer to choose a random number, check if the user guess is correct and inform the user.
import tkinter
import random
computer_guess = random.randint(1,10)
def Check():
user_guess = int(number_guess.get())
#Determine higher, lower or correct
if user_guess < computer_guess:
msg="Higher!"
elif user_guess > computer_guess:
msg="Lower!"
elif user_guess == computer_guess:
msg="Correct!"
else:
msg="Something went Wrong..."
#Show the Result
label_result["text"]= msg
#Create root window
root = tkinter.Tk()
root.title("Number Guessing Game")
#Create Widgets
label_title=tkinter.Label(root, text="Welcome to the Number Guessing Game!")
label_title.pack()
label_result=tkinter.Label(root, text="Good Luck!")
label_result.pack()
button_check=tkinter.Button(root, text="Check", fg="green", command=Check)
button_check.pack(side="left")
button_reset=tkinter.Button(root, text="Reset", fg="red", command=root.quit)
button_reset.pack(side="right")
number_guess=tkinter.Entry(root, width=3)
number_guess.pack()
#Start the main events loop
root.mainloop()
| true |
80372221944fbf2c560fd597e48d5e447a0bd4dd | henrikac/randomturtlewalk | /src/main.py | 1,077 | 4.375 | 4 | """A Python turtle that does a random walk.
Author: Henrik Abel Christensen
"""
import random
from turtle import Screen
from typing import List
from argparser import parser
from tortoise import Tortoise
args = parser.parse_args()
def get_range(min_max: List[int]) -> range:
"""Returns a range with the turtles min max choices.
If the input is None then range(-25, 26) is returned.
Parameters
----------
min_max : List[int]
Returns
-------
min_max : range
"""
if min_max is None:
return range(-25, 26)
minimum = min_max[0]
maximum = min_max[1]
if minimum == maximum:
raise ValueError('min and max must be different')
if minimum > maximum:
raise ValueError('min must be lower than max')
return range(minimum, maximum)
CHOICES = list(get_range(args.range))
MOVES = [(random.choice(CHOICES), random.choice(CHOICES)) for _ in range(args.steps)]
screen = Screen()
screen.mode('logo') # <--- DO NOT CHANGE THIS!
t = Tortoise(visible=args.hide)
for move in MOVES:
t.step(move)
screen.exitonclick()
| true |
53f1f2049a3a31a4a63a0fc38fb77d1466e3ffa3 | therealrooster/fizzbuzz | /fizzbuzz.py | 740 | 4.21875 | 4 | def fizzbuzz():
output = []
for number in range (1, 101):
if number % 15 == 0:
output.append('Fizzbuzz')
elif number % 3 == 0:
output.append('Fizz')
elif number % 5 == 0:
output.append('Buzz')
else:
output.append(number)
return output
#print(fizzbuzz())
#1. create a method called fizzbuzz
#2. create an output array called output
#3. iterate from 1 to 100, each number is called number
#3a. if NUMBER is a multiple of 3, append "FIZZ" to output
#3b. if NUMBER is multiple of 5, append "BUZZ" to output
#3c. if NUMBER is multiple of 3 and 5, append "FIZZBUZZ" to output
#3d. otherwise append NUMBER
#4. return OUTPUT | true |
81c8b00713bdc7169f2dcaf7051c1dc376385a5a | zeyuzhou91/PhD_dissertation | /RPTS/bernoulli_bandit/auxiliary.py | 1,561 | 4.15625 | 4 | """
Some auxiliary functions.
"""
import numpy as np
def argmax_of_array(array):
"""
Find the index of the largest value in an array of real numbers.
Input:
array: an array of real numbers.
Output:
index: an integer in [K], where K = len(array)
"""
# Simple but does not support random selection in the case of more than one largest values.
ind = int(np.argmax(array))
return ind
def argmin_of_array(array, num):
"""
Return the indices of the the lowest num values in the array.
Inputs:
array: a numpy array.
num: an integer.
Output:
idx: a numpy array of integer indices.
"""
idx = np.argpartition(array, num)
return idx
def map_to_domain(x):
"""
Map each number in the given array to [0,1]^K, if it is outside of that interval.
Input:
x: an numpy array of shape (N,K)
Output:
y: an numpy array of shape (N,K)
"""
y = np.copy(x)
if np.ndim(x) == 1:
(N,) = np.shape(x)
for i in range(N):
if y[i] < 0:
y[i] = 0
elif y[i] > 1:
y[i] = 1
else:
pass
elif np.ndim(x) == 2:
(N,K) = np.shape(x)
for i in range(N):
for j in range(K):
if y[i][j] < 0:
y[i][j] = 0
elif y[i][j] > 1:
y[i][j] = 1
else:
pass
return y
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.