blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4744ad31ee30f7428017da886d2f8c1b3271f3e6 | wgh19950620/python_test | /venv/com.src.wgh/variable/tuple_variable.py | 1,533 | 4.84375 | 5 | """
元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开。
元组中的元素类型也可以不相同
元组与字符串类似,可以被索引且下标索引从0开始,-1 为从末尾开始的位置。也可以进行截取
元组元素不可被修改
虽然tuple的元素不可改变,但其可以包含可变对象,如list列表
"""
tuple_test = ('hello', 786, 2.23, 'python', 70.2)
tiny_tuple = (123, 'python')
print("tuple_test: ")
print(tuple_test) # 输出完整元组
print(tuple_test[0]) # 输出元组的第一个元素
print(tuple_test[1:3]) # 输出从第二个元素开始到第三个元素
print(tuple_test[2:]) # 输出从第三个元素开始的所有元素
print(tiny_tuple * 2) # 输出两次元组
print("tuple_test + tiny_tuple: ")
print(tuple_test + tiny_tuple) # 连接元组
'''
包含 0 个或 1 个元素的元组比较特殊,有额外的语法规则:
元组中只包含一个元素是,需要在元素后面添加逗号,否则会被当作运算符使用
'''
tup1 = () # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号
print(type(tup2))
'''
string、list 和 tuple 都属于 sequence(序列)。
注意:
1、与字符串一样,元组的元素不能修改。
2、元组也可以被索引和切片,方法一样。
3、注意构造包含 0 或 1 个元素的元组的特殊语法规则。
4、元组也可以使用+操作符进行拼接。
'''
| false |
3eff129c86eaa9651a8f97a2c2c85928988cf340 | abderrahmanesaad/python-climb-learning-tutorial | /python-tips-and-tricks/enumeration/main.py | 267 | 4.125 | 4 | mynames = ['john', 'mike', 'anna', 'bob', 'sara']
counter = 0
for name in mynames:
print(f'{counter}: {name}')
counter += 1
for index, name in enumerate(mynames):
print(f'{index}: {name}')
print(list(enumerate(mynames)))
print(dict(enumerate(mynames))) | false |
fc416eac9e468b582974225de2c8d4fe1f43470b | arpitgupta275/MyCaptain-Python | /task1.py | 401 | 4.46875 | 4 | import math
# accepts radius of circle and computes area
radius = float(input('Input the radius of the circle : '))
area = math.pi * radius * radius
print(f'The radius of the circle with radius {radius} is: {area}')
# accepts a filename and prints its extension
filename = input('Input the Filename: ')
f_extns = filename.split('.')
print ('The extension of the file is : ' + repr(f_extns[-1]))
| true |
0cd177b0f508ba272e1cca5ec047800dc4753cba | AaronDonaldson74/code-challenges | /python/biggest_smallest.py | 591 | 4.15625 | 4 | ### biggest / smallest function
def biggest_smallest(selection, list_of_numbers):
# list_of_numbers = [43, 53, 27, 40, 100, 201]
list_of_numbers.sort()
smallest_num = (list_of_numbers[0])
biggest_num = (list_of_numbers[-1])
# selection = ("small")
if selection == ("small"):
print("smallest value = ", list_of_numbers[0])
elif selection == ('big'):
print("largest value = ", list_of_numbers[-1])
else:
print(list_of_numbers)
biggest_smallest("small", [3, 52, 27, 50, 145, 221])
biggest_smallest("big", [43, 53, 27, 40, 100, 201]) | true |
092c64fb38b2fa9190c62f47d53bfa2f1cb693f3 | AaronDonaldson74/code-challenges | /python/birthday.py | 508 | 4.78125 | 5 | # Create a variable called name and assign it a string with your name. Create a variable called current_year and assign it an int. Create a variable called birth_year and assign it an int. Using the following variables print the following result. Please print it using the f"" way.
# Example result: "Hello, my name is Daniel and I'm 36 years old"
name = "Aaron"
current_year = 2020
birth_year = 1974
statement = f"Hello, my name is {name} and I am {current_year - birth_year} years old."
print(statement) | true |
c2fbd24d7c4efc16cb8b2ce178482511234394ab | rdvnkdyf/codewars-writing | /python/sum-of-odd-numbers.py | 569 | 4.21875 | 4 | """
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
row_sum_odd_numbers(1); # 1
row_sum_odd_numbers(2); # 3 + 5 = 8
"""
import functools
def row_sum_odd_numbers(n):
oddNumbers=[]
startNumber=(n*n)-(n-1);
while(n>0):
oddNumbers.append(startNumber)
startNumber+=2
n-=1
sum=functools.reduce(lambda a,b:a+b,oddNumbers)
return sum
| true |
0bed93426d83ed50a1dfb8df94b2fee2e6dd1963 | Nusrat-H/python-for-everybody | /MyownfunctionD.py | 793 | 4.40625 | 4 | """
Write a program to prompt the user for hours and rate per hour
using input to compute gross pay. Pay should be the normal rate for hours
up to 40 and time-and-a-half for the hourly rate for all hours worked
above 40 hours. Put the logic to do the computation of pay in a function
called computepay() and use the function to do the computation. The function
should return a value. Use 45 hours and a rate of 10.50 per hour to test the
program (the pay should be 498.75). You should use input to read a string
and float() to convert the string to a number.
hrs = input("h: ")
rate = input("r:")
h = float(hrs)
r = float(rate)"""
def computepay(h,r):
if h <= 40:
print ("pay", (h*r))
elif h>40:
print ("pay", (40*r+(h-40)*1.5*r))
computepay(45,10.5)
| true |
f6a555bb8191ed9f969793247810259c6e809d41 | aycelacap/py_playground | /Fundamentals/Basics i/041_list_slicing.py | 394 | 4.375 | 4 | string = "hello"
string[0:2:1]
# string[start:stop:step]
# we can apply the concept of string slicing to lists
# lists are mutable
# with list slicing, we create a new copy listlists are mutable
amazon_cart = new_cart
# these two variable would point on the same place in memory
# if instead we want to copy a list, they now point to different spot in memory
new_cart = amazon_cart[:]
| true |
6cf892b2d5ca9fe205c819ba3487f60a30c400b1 | aycelacap/py_playground | /Fundamentals/Basics i/053_dictionary_methods_ii.py | 1,076 | 4.5 | 4 | # how else can we look for items in a dictionary?
user = {
'basket': [1, 2, 3]
'greet': 'hello'
}
print('basket' in user) #True
print('hello' in user.keys()) #False
print('greet' in user.keys()) #True
# how can we grab items
print(user.items()) #this prints out a list of the key/value pairs, in tuple form
print(user.clear()) #None
# user.clear() # in place removes what the dictionary has
# print(user) # {}
user2 = user.copy()
print(user)
print(user2)
# the computer will make a copy of the user dictionary and it will be saved as user2
print(user.clear())
print(user2)
# this will return None because .clear will remove what the dictionary has and user2 will still print a list of tuples of the dictionary
print(user.pop('age')) #will print the dictionary without the popped value
# will user be mutated?
print(user)
# the method .pop mutates the dictionary in place so yes
# how can we update values to an existing dictionary?
print(user.update({
'age': 55
}))
# this will also add a key/value to the existing dict
print(user.update({
'ages': 125
})) | true |
a29f118e72afd2fea0af99e51e1133487de93a94 | aycelacap/py_playground | /Fundamentals/Basics i/037_type_conversion.py | 608 | 4.25 | 4 | name = "Ayce"
age = 100
relationship_status = "complicated"
relationship_status = "single"
# create a program that can guess your age
birth_year = input("What year were you born?")
guess = 2020 - int(birth_year)
print("your age is: {guess}")
# string interpolation and input from user as seen in video
# if confused
print(type(birth_year))
# sometimes we store data into different data types. We need to convert data into different data types
# note:
bool
int
float
**complex
str
list
tuple
set
dict
age = 2019 - bool(birth_year)
# bool converts to true, 1, so your age would be 2018
# if false, 0
| true |
3ec531367f1e906f1ac3954e860e0d9ba558c41e | campbellmarianna/Code-Challenges | /python/spd_2_4/binary_search_tree.py | 2,701 | 4.1875 | 4 | # Binary Search Tree in Python Credits: Joe James https://youtu.be/YlgPi75hIBc
class Node:
def __init__(self, val):
self.value = val
self.leftChild = None
self.rightChild = None
def insert(self, data):
if self.value == data:
return False
elif self.value > data:
if self.leftChild:
return self.leftChild.insert(data)
else:
self.leftChild = Node(data)
return True
else:
if self.rightChild:
return self.rightChild.insert(data)
else:
self.rightChild = Node(data)
return True
def find(self, data):
if(self.value == data):
return True
elif self.value > data:
if self.leftChild:
return self.leftChild.find(data)
else:
return False
else:
if self.rightChild:
return self.rightChild.find(data)
else:
return False
def preorder(self):
if self:
print(str(self.value))
if self.leftChild:
self.leftChild.preorder()
if self.rightChild:
self.rightChild.preorder()
def postorder(self):
if self:
if self.leftChild:
self.leftChild.postorder()
if self.rightChild:
self.rightChild.postorder()
print(str(self.value))
def inorder(self):
if self:
if self.leftChild:
self.leftChild.inorder()
print(str(self.value))
if self.rightChild:
self.rightChild.inorder()
class Tree:
def __init__(self):
self.root = None
def insert(self, data):
if self.root:
return self.root.insert(data)
else:
self.root = Node(data)
return True
def find(self, data):
if self.root:
return self.root.find(data)
else:
return False
def preorder(self):
print("PreOrder")
self.root.preorder()
def postorder(self):
print("PostOrder")
self.root.postorder()
def inorder(self):
print("InOrder")
self.root.inorder()
(if __name__ == "__main__":
# bst = BinarySearchTree())
bst = Tree()
print(bst.insert("F"))
print(bst.insert("B"))
print(bst.insert("A"))
print(bst.insert("D"))
print(bst.insert("C"))
print(bst.insert("E"))
print(bst.insert("G"))
print(bst.insert("I"))
print(bst.insert("H"))
bst.preorder()
bst.postorder()
| false |
65f91220ffcbf25c289a329c0bd3ecc189bfc014 | AxelSeg/course-material | /exercices/203/solution.py | 214 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 22 22:37:07 2014
@author: Axel
"""
def is_multiple(value1, value2):
if value2 % value1 == 0:
print(True)
else:
print(False)
is_multiple(2, 6) | false |
3f7dd2e108ad2bd674d6f8483e30e6e70750f0c0 | pawlodkowski/advent_of_code_2020 | /day_12/part1.py | 2,139 | 4.28125 | 4 | """
Part 1 of https://adventofcode.com/2020/day/12
"""
# TO-DO: Is it possible to contain the navigation information in a single data structure?
CARDINALS = {"E": (1, 0), "S": (0, -1), "W": (-1, 0), "N": (0, 1)}
BEARINGS = [(1, 0), (0, -1), (-1, 0), (0, 1)] # maps to current bearing
def read_data(filename: str) -> list:
with open(filename, "r") as f:
data = f.read().split("\n")
return data
def chart_path(start_location: tuple, start_bearing: int, instructions: list) -> tuple:
"""
Given starting coordinates (e.g. (0,0)) and initial bearing (e.g. 0)
and a list of navigation instructions, chart the path of the ship
and return the final coordinates of the ship after executing all the instructions.
Here is a key for the current bearing meaning:
0 <-> 'E'
1 <-> 'S'
2 <-> 'W'
3 <-> 'N'
"""
current_location = start_location
current_bearing = start_bearing
for command in instructions:
action = command[0]
value = int(command[1:])
no_rotation = action == "F" or action in CARDINALS
if no_rotation:
if action == "F":
change_x = BEARINGS[current_bearing][0] * value
change_y = BEARINGS[current_bearing][1] * value
else:
change_x = CARDINALS[action][0] * value
change_y = CARDINALS[action][1] * value
current_location = (
current_location[0] + change_x,
current_location[1] + change_y,
)
else:
if action == "R":
current_bearing = (current_bearing + (int(value / 90))) % 4
# modulus 4 is to reset the rotation back to zero so the numbers cycle
else:
current_bearing = (current_bearing - (int(value // 90))) % 4
return current_location
if __name__ == "__main__":
data = read_data("input.txt")
final = chart_path((0, 0), 0, data)
print(
f"Solution: the final manhattan distance from the ship's starting point is {abs(final[0]) + abs(final[1])}."
)
| true |
bb46a7fd5c5b409a8f000ad3bd5cd91f8998a120 | fengeric/LearnPythonProject | /hello.py | 1,199 | 4.28125 | 4 | print("hahaha")
# 被双引 号包括的字符串 和被单引 号括起的字符串 其工作机制完全相同
# 你可以通过使用 三个引 号—— """ 或 ' ' ' 来指定多 行字符串 。 你可以在三引 号之间 自 由 地使用 单引 号与 双引 号。
# --------------------------------------------
# format的用法,Python 中 format 方法所做的事情便是将每个参数值替换至格式所在的位置
name = "feng"
age = 20
print("1{0} was {1} years old when he wrote this book".format(name, age))
print('2{} was {} years old when he wrote this book'.format(name, age))
print('3Why is {0} playing with that python?'.format(name))
print('4Why is {} playing with that python?'.format(name))
# --------------------------------------------
print('a') # 和下面一行代码意思一样
print('a', end="\n")
# ****
print('a', end="") # 打印时不换行
print('b', end="") # 打印时不换行
# ****
print('a', end=" ") # 通过 end 指定以空格结尾
print('b', end=" ") # 通过 end 指定以空格结尾
print('c')
# --------------------------------------------
# 使用 四个空格来缩进。 这是来自 Python 语言官方的建议
# 不使用分号
| false |
867c58f1bef940d3ea93f06e7ce3b793e18dbc03 | yuntianming0613/learnpython | /条件判断.py | 1,147 | 4.25 | 4 | # -*- coding: utf-8 -*-
age = 20
if age >= 18:
print('your age is ', age)
print('adult')
age = 3
if age >= 18:
print('your age is ', age)
print('adult')
else:
print('your age is ', age)
print('teenager')
age = 4
if age >=18:
print('your age is', age)
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
# if <条件判断1>:
# <执行1>
# elif <条件判断2>:
# <执行2>
# elif <条件判断3>:
# <执行3>
# else:
# <执行4>
birth = int(input('birth: '))
if birth < 2000:
print('00前')
else:
print('00后')
# 练习
#
# 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
#
# 低于18.5:过轻
# 18.5-25:正常
# 25-28:过重
# 28-32:肥胖
# 高于32:严重肥胖
# 用if-elif判断并打印结果:
height = 1.75
weight = 80.5
bmi = weight/height**2
print(bmi)
if bmi > 32:
print('严重肥胖')
elif 32 >= bmi > 28:
print('肥胖')
elif 28 >= bmi > 25:
print('过重')
elif 25 >= bmi > 18.5:
print('正常')
else:
print('过轻')
| false |
02301984b7cf81be680136da913bf3696c16cab6 | Farah-H/python_classes | /class_task.py | 1,808 | 4.34375 | 4 | # Task
# create a Cat class
class Cat:
# Create 2 class level variables
coward = False
cute = True
fluffy = True
# one function which returns 'MEOWWWWWWW', added some details :)
def purr(self,cute,coward,fluffy):
if cute and fluffy:
print('You approach this adorable cat..')
if coward:
print('Oh no! You scared the cat away.')
else:
print('MEOWWWWWW')
else:
print('Ohh that cat looks kind of grumpy. Let\'s walk away for now.')
# create 3 objects of the class
jack = Cat()
shinny = Cat()
garfield = Cat()
# display all information with each object
print(f'Jack\'s Attributes: coward = {jack.coward}, cute = {jack.cute}, fluffy = {jack.fluffy}')
jack.purr(jack.cute,jack.coward, jack.fluffy)
print(f'Shinny\'s Attributes: coward = {shinny.coward}, cute = {shinny.cute}, fluffy = {shinny.fluffy}')
shinny.purr(shinny.cute,shinny.coward, shinny.fluffy)
print(f'Garfield\'s Attributes: coward = {garfield.coward}, cute = {garfield.cute}, fluffy = {garfield.fluffy}')
garfield.purr(garfield.cute,garfield.coward, jack.fluffy)
# change the class variables values in each object and display the object's attributes + outcome of purr() function
jack.coward = True
print(f'Jack\'s new Attributes: coward = {jack.coward}, cute = {jack.cute}, fluffy = {jack.fluffy}')
jack.purr(jack.cute,jack.coward, jack.fluffy)
shinny.fluffy = False
print(f'Shinny\'s new Attributes: coward = {shinny.coward}, cute = {shinny.cute}, fluffy = {shinny.fluffy}')
shinny.purr(shinny.cute,shinny.coward, shinny.fluffy)
garfield.cute = False
print(f'Garfield\'s new Attributes: coward = {garfield.coward}, cute = {garfield.cute}, fluffy = {garfield.fluffy}')
garfield.purr(garfield.cute,garfield.coward, jack.fluffy) | true |
3fbba0b056c2aa515949f6be884331401a6d71ad | G8A4W0416/Module6 | /more_functions/validate_input_in_functions.py | 921 | 4.34375 | 4 | def score_input(test_name, test_score=0, invalid_message='Invalid test score, try again!'):
""" This takes in a test name, test score, and invalid message. The user is prompted for a valid test score until it
is in the range of 0-100, then prints out the valid input as 'Test name: ##'.
:param test_name: String name passed in
:param test_score: Int score passed in. Optional, with default value of 0 (zero)
:param invalid_message: String invalid message passed in. Optional, with default value of
'Invalid test score, try again!'
:return: String showing test name with valid test score
"""
while True:
try:
test_score = int(test_score)
if 0 <= test_score <= 100:
break
else:
return invalid_message
except ValueError:
return invalid_message
return test_name + ": " + str(test_score)
| true |
6832afafc0f5c16e3222c3ce6051b5585bd7710d | General-Gouda/PythonTraining | /Training/Lists.py | 713 | 4.25 | 4 | student_names = [] # Empty List variable
student_names = ["Mark","Katarina","Jessica"] # List variable with 3 entries
print(student_names)
student_names.append("Homer") # Adds Homer into the List
print(student_names)
if "Mark" in student_names: # Checks to see if the string "Mark" is in the List student_names
print(True)
else:
print(False)
print(len(student_names)) # Len gives the count of the number of elements within a List
del student_names[2] # Deletes the name Jessica and shifts all elements after Jessica to the left.
print(student_names)
print(student_names[1:]) # Skips first element in the list and gives the rest
print(student_names[1:-1]) # Ignores first and last element in List | true |
ac743ad6bd03bedb544e59d2d1797fc3ff2b7a9e | General-Gouda/PythonTraining | /Training/ForLoops.py | 975 | 4.4375 | 4 | student_names = ["Mark", "Katarina", "Jessica"]
for name in student_names:
print("Student name is {0}".format(name)) # Interates through each element in the List. There is no ForEach in Python. For does it automatically.
x = 0
for index in range(10): # Range(10) if it were printed would look like [0,1,2,3,4,5,6,7,8,9]
x += 10
print("The value of X is {0}".format(x))
print("")
for index in range(10):
x = index
print("The value of X is {0}".format(x)) # see?
print("")
# This time the range starts at the number 5 and goes to 9. The first number in the range must be.
# inside the range itself. 5 is inside the range 0 the 9 but 10 is outside so nothing is printed.
for index in range(5, 10):
x = index
print("The value of X is {0}".format(x))
print("")
# starts at 5 and increments by 2 (starting number, end of interations, increments of)
for index in range(5, 10, 2):
x = index
print("The value of X is {0}".format(x))
| true |
df05bbb841a4142ff87889cce1e1f014de49987c | ad-egg/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 583 | 4.1875 | 4 | #!/usr/bin/python3
"""
this module contains a class MyInt which inherits from int
"""
class MyInt(int):
"""
this class MyInt inherits from int but has == and != operators inverted
"""
def __init__(self, value=0):
"""
instantiates an instance of MyInt with value
"""
self.__value = value
def __eq__(self, other):
"""
inverts == return value
"""
return self.__value != other
def __ne__(self, other):
"""
inverts != return value
"""
return self.__value == other
| true |
b7849c1c75bd8ae24fbe9c4d8b136b4b1c5bcd19 | ad-egg/holbertonschool-higher_level_programming | /0x08-python-more_classes/4-rectangle.py | 2,717 | 4.59375 | 5 | #!/usr/bin/python3
"""
This module contains an empty class that defines a rectangle.
"""
class Rectangle:
"""an empty class Rectangle that defines a rectangle
a rectangle is a parallelogram with four right angles
"""
def __init__(self, width=0, height=0):
"""
instantiates a rectangle with private instance attributes
height and width
"""
if not isinstance(width, int):
raise TypeError("width must be an integer")
elif width < 0:
raise ValueError("width must be >= 0")
else:
self.__width = width
if not isinstance(height, int):
raise TypeError("height must be an integer")
elif height < 0:
raise ValueError("height must be >= 0")
else:
self.__height = height
@property
def width(self):
"""
retrieves the width of the rectangle
"""
return self.__width
@width.setter
def width(self, value):
"""
sets the width of the rectangle
"""
if not isinstance(value, int):
raise TypeError("width must be an integer")
elif value < 0:
raise ValueError("width must be >= 0")
else:
self.__width = value
@property
def height(self):
"""
retrieves the height of the rectangle
"""
return self.__height
@height.setter
def height(self, value):
"""
sets the height of the rectangle
"""
if not isinstance(value, int):
raise TypeError("height must be an integer")
elif value < 0:
raise ValueError("height must be >= 0")
else:
self.__height = value
def area(self):
"""
this public instance method returns the area of the rectangle
"""
return self.width * self.height
def perimeter(self):
"""
this public instance method returns the perimeter of the rectangle
"""
if self.width == 0 or self.height == 0:
return 0
else:
return self.width * 2 + self.height * 2
def __str__(self):
"""
returns a string that is rectangle using hash characters and newlines
"""
string = ""
if self.width > 0 and self.height > 0:
string = "".join(('#' * self.width + '\n') * self.height)
string = string[:-1]
return string
def __repr__(self):
"""
returns a string representation of the rectangle that allows
creation of a new instance
"""
return "Rectangle({:d}, {:d})".format(self.width, self.height)
| true |
fe509c567d5b9ab36da3f50ee7f17ae92f0f0b0d | SmiteLi/python-note | /base/7-filter-sorted.py | 1,431 | 4.125 | 4 | # filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入
# 的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
# filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,
# 需要用list()函数获得所有结果并返回list。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty, ['A', '', 'C', None, ' '])))
# 构造一个从3开始的奇数序列:
def _odd_iter():
n =1
while True:
yield n+2
def _not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = _odd_iter()
while True:
n = next(it)
yield n
it = filter(_not_divisible(n), it)
# 打印1000以内的素数:
# for n in primes():
# if n < 1000:
# print(n)
# else:
# break
print(sorted([36, 5, -12, 9, -21]))
# key指定的函数将作用于list的每一个元素上,并根据key函数返回的结果进行排序。
print(sorted([36, 5, -12, 9, -21], key=abs))
print(sorted(['bob', 'about', 'Zoo', 'Credit']))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)) | false |
030d32c1d9e1f809046976a7e1bb2aea87736aed | NixonRosario/crytography-using-Fernet | /main.py | 2,419 | 4.21875 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
from cryptography.fernet import Fernet # install cryptography and import Fernet
key = Fernet.generate_key() # generates random keys
file = open('keys.txt', 'a+')
file.write("keys:- " + str(key) + "\n") # converting bytes to string and store it in a file
file.close()
def cipher():
obj = Fernet(key) # the generated key is stored in variable obj
user = input('Enter the encrypted: ') .encode() # .encode() is used to convert string to bytes
encrypted = obj.encrypt(user) # .encrypt() is used to encrypt the text
file = open('keys.txt', 'a+')
file.write("Value:- " + str(encrypted) + "\n") # encrypted text is stored
file.close()
print('Encrypted data:- ', encrypted)
n = input('If you want to decrypt select (y/n):- ') # if y is enterd decryption will take place
if n == 'y':
decrypted = obj.decrypt(encrypted)
utf = decrypted.decode('utf-8') # .decode() is used to convert bytes to text
print("Decrypted msg:- ", utf)
else:
print("Thank You!!")
def all_files():
obj = Fernet(key) # the generated key is stored in variable obj
file = open('key.txt', 'a+')
file.write("KEYS:- " + str(key) + "\n") # key generated gets stored
file.close()
path = input('Enter the path for encryption- ') # path of the file is given
print("Path of the file", path)
img = open(path, "rb")
img1 = img.read() # reads the file which is in the path
img.close()
encrypted = obj.encrypt(img1) # encrypts the image
en = open(path, 'wb')
en.write(encrypted) # returns the encryped file while opening the file
en.close()
print("Encrypted!!")
n = input('Do you want to decrypt (y/n):- ')
if n == 'y':
en_file = open(path, "rb")
encrypted = en_file.read() # reads the encrypted file
en_file.close()
decrypted = obj.decrypt(encrypted) # decrypts the encrypted file
de = open(path, 'wb')
de.write(decrypted) # returns the actual file
de.close()
print("Decrypted!!")
else:
print("Thank you!!")
cipher() # fuction call is made
all_files()
| true |
ec823e35ba2387cca400cea55d8916034f0123d1 | RayWLMo/Eng_89_Python_Collections | /dict_sets.py | 2,064 | 4.8125 | 5 | # Dictionaries and Sets are both data collections in Python
# Dictionaries
# Dict are another way to manage data but can be a little more Dynamic\
# Dict work as a KEY AND VALUE
# KEY = THE REFERENCE OF THE OBJECT
# VALUE + WHAT THE DATA STORAGE MECHANISM YOU WISH TO USE
# Dynamic as it we have Lists, and another dict inside a dict
# Syntax of dicts - dict_name = {}
# we use {} brackets to declare a Dict
# key
student_1 = {
"name": "James",
"stream": "DevOps",
"completed_lessons": 4,
"completed_lessons_names": ["data types", "git and github", "operators", "Lists and Tuples"]
} # Indexing 0 1 2 3
# Let's check if we have got the syntax right and print the dict
print(student_1)
print(type(student_1))
# Finding which value applies to which key
print(student_1["stream"])
# Printing the second last item from completed_lesson_names list
print(student_1["completed_lessons_names"][-2])
# Or alternatively
print(student_1["completed_lessons_names"][2])
# Could we apply CRUD on a dict?
student_1["completed_lessons"] = 3
print(student_1["completed_lessons"])
# Removing an item from completed_lesson_names
student_1["completed_lessons_names"].remove("operators")
print(student_1["completed_lessons_names"])
# Built-In Methods to use with dict
# To print all the keys - keys()
print(student_1.keys())
# To print all the values only - values()
print(student_1.values())
# Set are also Data collection
# Syntax - set_name = ["", "", ""]
# What is the difference between sets and dict
# Sets are unordered - no indexing
shopping_list = {"eggs", "milk", "tea"}
# 0 1 2
print(shopping_list)
car_parts = {"Engine", "Wheels", "Windows"}
print(car_parts)
# Adding items to a set
car_parts.add("Seats")
print(car_parts)
# Removing items to a set
car_parts.discard("Wheels")
print(car_parts)
# Python also has frozen sets
# Syntax - name = value([1, 2, ""])
planets = (["Mercury", "Saturn", "Neptune"])
print(planets)
| true |
374a8d5bbe59f30f7d8b1a6b9f02c9be92120e91 | group1BSE1/BSE-2021 | /src/chapter5/exercise2.py | 292 | 4.15625 | 4 | largest = None
smallest = None
while True:
num = input('Enter a number: ')
if num =='done':
break
elif largest is None or num > largest:
largest = num
elif smallest is None or num < num:
smallest = num
print('maximum',largest)
print('minimum',smallest) | true |
d974e78ca248bb2322da4ca150b523610bdb67df | AranzaCarolina/Primerrepo | /evidenciaWhile.py | 763 | 4.125 | 4 | #Menu Ciclico
while True:
print("operaciones: [1]suma, [2]resta, [3]multitplicacion, [4]division, [5]salir")
eleccion = input("Selecciona una de las opciones anteriores: ")
if eleccion == "1" or eleccion == "2" or eleccion == "3" or eleccion == "4":
n1 = int(input("introduce el primer numero: "))
n2 = int(input("introduce el segundo numero: "))
if eleccion == "1":
#suma
print(f"{n1} + {n2} = {n1 + n2}")
elif eleccion == "2":
#resta
print(f"{n1} - {n2} = {n1 - n2}")
elif eleccion == "3":
#multiplicacion
print(f"{n1} * {n2} = {n1 * n2}")
elif eleccion == "4":
#division
print(f"{n1} / {n2} = {n1 / n2}")
elif eleccion == "5":
print ("Adios")
break | false |
9250e0bab7e1c634b3aa416c66bce8cddd5ec048 | timurkurbanov/firstPythonCode | /firstEx.py | 463 | 4.46875 | 4 |
# Remember, we get a string from raw_input, but we need an int to compare it
weather = int(25);
# if the weather is greater than or equal to 25 degrees
if weather >= 25:
print("Go to the beach!")
# the weather is less than 25 degrees AND greater than 15 degrees
elif weather < 25 and weather > 15:
print("Go home!")
# Still warm enough for ice cream!
else:
print('wear a sweater and dream of beaches')
# Wear a sweater and dream of beaches.
| true |
7bc262beb842765e249819a987fd68c68f3bd0b1 | MTaylorfullStack/flex_lesson_transition | /jan_python/week_one/playground.py | 1,191 | 4.15625 | 4 | print("Hello World")
## Data Types
## String
collection_of_characters="hrwajfaiugh5uq34ht834tgu89398ht4gh0q4tn"
collection_of_characters+="!!!!!!!!!!!!!"
name="Adam"
stack="Python"
# print(f"The student {name} is in the {stack} stack")
## Numbers
## Operators: +, -, /, *, %
ten=10
one_hundred=100
# print(one_hundred-ten)
## Lists
students = ['Vineet', 'Adam', 'Cameron', 'Roxanne']
# print(students[2])
# print(students.length)
# help(list)
# students.pop()
# print(students)
# students.append("Roxanne")
# print(students)
## Dictionaries
player = {'first_name': 'Michael', 'last_name' : 'Jordan'}
# print(students[0]['first_name'])
## Conditionals and Loops
# if(bird['feathers']=='blue'){
# console.log("it is a blue bird")
# }
# if bird['feathers']=='blue':
# print("it is a blue bird")
# elif bird['feathers']=='red':
# print("It is a red bird")
# else:
# print("it is not a red or a blue bird")
## Loops
my_list=[1,2,3,4,5,6,7,8]
for i in range(len(my_list)):
print(my_list[i])
bird={
'feathers':"blue",
'wings':'2',
'name':"floppy",
'friends':["Tom", "Tweety", "Woodie"]
}
for thing in bird:
print(thing, bird[thing]) | true |
2f288985a6f9a652688bf2112a8fb5599a60080d | tiandrioni/python | /lesson4/lesson4-5.py | 728 | 4.3125 | 4 | """
Реализовать формирование списка, используя функцию range() и возможности генератора.
В список должны войти четные числа от 100 до 1000 (включая границы).
Необходимо получить результат вычисления произведения всех элементов списка.
Подсказка: использовать функцию reduce().
"""
from functools import reduce
def multiply(arg1, arg2):
return arg1 * arg2
def run():
even = [el for el in range(100, 1001) if el % 2 == 0]
print(f'Произведение равно: {reduce(multiply, even)}')
run()
| false |
6a0b6f550fbd00cf80b035789b7364626d2b55d1 | wesleyhooker/assign1 | /ccpin.py | 1,355 | 4.40625 | 4 | #!/usr/bin/env python3
"""
Validates that the user enteres the correct PIN number
"""
def valid_input(input):
"""
Checks for valid PIN Number
Argument:
input = the users inputted PIN
Returns:
Any Errors with the input
TRUE if it passes, False if it doenst
"""
if(len(input) != 4):
print("Invalid PIN length. Correct format is: <9876>")
return False
elif(not input.isdigit()):
print("Invalid PIN character. Correct format is: <9876>")
return False
elif(input != "1234"):
print("Your PIN is incorrect")
return False
elif(input == "1234"):
print("Your PIN is correct")
return True
def main():
"""
Tests the valid_Input() function to make sure that the user entered pin
is corrrect
If user enters wrong pin 3x they are blocked from the account
If they enter correct it is accepted
Exit 0 if correct PIN
Exit 1 if Incorrect PIN 3x
"""
i = 0
while (i !=3): #allow input for 3 tries
userInput = input("Enter your PIN: ")
if(valid_input(userInput)):
exit(0)
else:
i = i + 1 #incriment i
if (i == 3): #after 3 tries, block account.
print("Your bank card is blocked")
exit(1)
if __name__ == "__main__":
main()
exit(0)
| true |
384cb75137c4702da88da4a227e2af8c72f3a0a8 | jeffvswanson/DataStructuresAndAlgorithms | /Stanford/10_BinarySearchTrees/red_black_node.py | 2,069 | 4.25 | 4 | # red_black_node.py
class Node:
"""
A class used to represent a Node in a red-black search tree.
Attributes:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
instances (int): The number of times the key for a node was inserted into the tree.
parent (node): The pointer to the parent of the node.
left (node): The pointer to the left child node.
right (node): The pointer to the right child node.
is_red (bool): The color attribute keeps track of whether a node is red or black.
"""
def __init__(self, key):
"""
Parameters:
key: The key is the value the node shall be sorted on. The key can be an integer,
float, string, anything capable of being sorted.
"""
self.key = key
self.instances = 1
self.parent = None
self.left = None
self.right = None
self.is_red = True
def recolor(self):
"""
Switches the color of a Node from red to black or black to red.
"""
if self.is_red:
self.is_red = False
else:
self.is_red = True
def add_instance(self):
"""
Allows for duplicates in a node by making it "fat" instead of
creating more nodes which would defeat the purpose of a self-
balancing tree.
"""
self.instances += 1
def remove_instance(self):
"""
Allows for removal of a single instance of a key from the
search tree rather than pruning an entire node from the tree.
"""
self.instances -= 1
def delete(self):
"""
Zeroes out a node for deletion.
"""
self.key = None
self.instances = 0
self.parent = None
self.left = None
self.right = None
self.is_red = False # Null nodes are, by default, black. | true |
5fd2e1ce1bb2dd34be5958f80787f04a4b0dcacf | icicchen/PythonGameProgramming | /Power of Thor - episode 1.py | 2,073 | 4.46875 | 4 | # Power of Thor - easy
'''This program allows Thor to reach the light of power by giving it directions'''
import sys
import math
# light_x: the X position of the light of power
# light_y: the Y position of the light of power
# initial_tx: Thor's starting X position
# initial_ty: Thor's starting Y position
light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()]
thor_x = initial_tx
thor_y = initial_ty
while 1:
remaining_turns = int(input()) # The remaining amount of turns Thor can move
# direction the Thor should take
direction = ""
if light_y < thor_y and light_x > thor_x:
# if the Thor locates south and west of the light of power, go down and right will go northeast
thor_y -= 1
thor_x += 1
direction = "NE"
elif light_y < thor_y and light_x < thor_x:
# if the Thor locates south and east of the light of power, go up and left will go northwest
thor_y += 1
thor_x -= 1
direction = "NW"
elif light_y > thor_y and light_x > thor_x:
# if the Thor locates north and east of the light of power, go down and right will go southeast
thor_y += 1
thor_x += 1
direction = "SE"
elif light_y > thor_y and light_x < thor_x:
# if the Thor locates north and west of the light of power, go down and left will go southwest
thor_y += 1
thor_x -= 1
direction = "SW"
elif light_x < thor_x:
# if the Thor locates east of the light of power, go left will go west
thor_x += 1
direction = "W"
elif light_x > thor_x:
# if the Thor locates west of the light of power, go right will go east
thor_x -= 1
direction = "E"
elif light_y < thor_y:
# if the Thor locates south of the light of power, go up will go north
thor_y -= 1
direction = "N"
elif light_y > thor_y:
# if the Thor locates north of the light of power, go down will go south
thor_y += 1
direction = "S"
print(direction)
| false |
2c6883f73522c971670cae797200f454968a635f | Neeragrover/HW04 | /HW04_ex00.py | 1,265 | 4.21875 | 4 | #!/usr/bin/env python
# HW04_ex00
# Create a program that does the following:
# - creates a random integer from 1 - 25
# - asks the user to guess what the number is
# - validates input is a number
# - tells the user if they guess correctly
# - if not: tells them too high/low
# - only lets the user guess five times
# - then ends the program
################################################################################
# Imports
import random
# Body
################################################################################
def main():
print("Hello World!") # Remove this and replace with your function calls
turn=0
x=random.randint(1,25)
try:
while(turn<5):
input_num=raw_input('enter a number:')
input_num_int=int(input_num)
if(input_num_int==x):
print "Congratulations, you got it!"
break
elif (input_num_int<x):
print "Too Low, please guess again!"
turn=turn+1
elif (input_num_int>x):
print "Too High,please guess again!"
turn=turn+1
else:
print 'random'
if turn==5:
print "Sorry, you ran out of turns. Please start over to guess again!!"
except:
print "Only numbers please, start over buddy!"
if __name__ == '__main__':
main() | true |
3ec08d9e5985e5ab19eae234835ae990bd31d8ac | lamngockhuong/python-guides | /basic/dictionaries/dictionaries-1.py | 1,106 | 4.46875 | 4 | # https://www.w3schools.com/python/python_dictionaries.asp
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
print(x)
y = thisdict.get("model")
print(y)
# Change values
thisdict["year"] = 2019
print(thisdict)
# Return values of a dictionary
for x in thisdict:
print(thisdict[x])
# Return values of a dictionary
for x in thisdict.values():
print(x)
# Loop through both keys and values
for x, y in thisdict.items():
print(x, y)
# Check if key exists
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
# return dict length
print(len(thisdict))
# add items
thisdict["color"] = "red"
print(thisdict)
# remove items
thisdict.pop("model")
print(thisdict)
# remove last inserted item (in versions before 3.7, a random item is removed instead):
thisdict.popitem()
print(thisdict)
# del
# del thisdict["model"]
# print(thisdict)
#
# del thisdict
# print(thisdict)
# clear
thisdict.clear()
print(thisdict)
thisdict = dict(brand="Ford", model="Mustang", year=1964)
print(thisdict)
| true |
524b7612faa6b189b228d9f8e6aca0f69fbf6364 | lamngockhuong/python-guides | /basic/strings/strings-2.py | 497 | 4.375 | 4 | # https://www.w3schools.com/python/python_strings.asp
x = "Hello, world!"
print(x[2:5])
y = " Hello world "
print(y.strip()) # remove any whitespace from the beginning or the end
print(len(y)) # return the length of a string
print(y.lower()) # return the string in lower case
print(y.upper()) # return the strung in upper case
print(y.replace("H", "J")) # replace a string with another string
print(x.split(",")) # return list that splits the string into substrings
print(x is not y)
| true |
de9b2cef5eea479083e2932d8291e8ba6a4188bf | kisa411/CSE20211 | /isPalindrom.py | 476 | 4.15625 | 4 |
word = raw_input("Enter a word:")
list = []
start = 0
end = len(word) - 1
def isPalindrome(word):
global start
global end
for letter in word:
list.append(letter)
while (start < end):
if list[start] != list[end]:
return False
else:
return True
start+=1
end-=1
if isPalindrome(word) == True:
print "Is palindrome.\n"
else:
print "Is not a palindrome.\n"
isPalindrome(word) | true |
b0f26fc98716307747c63e4bbc3921dd660ac6b1 | waddahAldrobi/RatebTut- | /Python Algs copy/print bst by level.py | 504 | 4.125 | 4 | def print_bst(tree):
current_level = [tree.root]
while current_level:
next_level = []
for node in current_level:
print(node.value,end='')
# Logic to start building the next level
##Added
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
####
print() # Print a newline between levels
current_level = next_level
| true |
8fc3791795ba4f7be4da91cf325c64d2a3810572 | alexnicolescu/Python-Practice | /lambda/ex1.py | 289 | 4.1875 | 4 | # Write a Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and print the result.
def l1(x): return x + 15
def l2(x, y): return print(x*y)
print(l1(15))
l2(12, 10)
| true |
a6099bc9283e52aacf41fb0d83a1b357adb9b67d | ValDagon/different | /Quadratic Equations/Quadratic Equations.py | 1,584 | 4.1875 | 4 | # Valentin 1 September 2017
# Решение квадратных уравнений
import math
while True:
a = float(input('Введите a: '))
b = float(input('Введите b: '))
c = float(input('Введите c: '))
#total = str(a) + "x^2" + str(b) + "x" + str(c)
#print("Итоговый вид уравнения: ", total)
d = b ** 2 - 4 * a * c
print("\nВычисляем дискриминант...")
print("Дискриминант равняется", d)
if d == 0:
print("\nДискриминант равен 0")
print("x =", -b/(2*a))
elif d < 0:
print("\nДискриминант меньше 0, решений нет")
else:
sqrtd = math.sqrt(d)
print("\nКорень из дискриминанта равен ", sqrtd)
x1 = (-b - math.sqrt(d)) / (2*a)
x2 = (-b + math.sqrt(d)) / (2*a)
print("\nВычисляем корни...")
print("\nПервый корень равен", x1)
print("Второй корень равен", x2)
while True:
print("\nХотите решить ещё одно уравнение?")
answer = input('Y/n(help - справка по командам) ')
if answer == 'Y':
break
elif answer == 'n':
exit()
elif answer == 'help':
print(open('help.txt', 'r').read())
else:
print("\nВведите Y или n (help - справка по командам)") | false |
c82870abca988247ab2a07c841550bf1e57d36b8 | Adamrathjen/MOD1 | /Module1.py | 1,073 | 4.125 | 4 | import os
print("Character Creator!")
selected = 1
while "4" != selected:
print("Make new Character: 1")
print("Delete character: 2")
print("See current characters: 3")
print("Quit: 4")
selected = input("Make your selection: ")
if selected == "1":
print("you selected 1")
characterName = input("Enter a character name: ")
f = open(characterName, "x")
print("make character and create character file function call")
elif selected == "2":
print("you selected 2")
filename = input("Enter the name of the character to delete or enter n to stop: ")
if filename != "n":
if os.path.exists(filename):
os.remove(filename)
else:
print("The file does not exist")
else: continue
elif selected == "3":
print("you selected 3")
print("function call to display list of created characters")
elif selected == "4":
print("you quit")
else:
print("that isn't an option")
print("you got out") | true |
7b67bdcd6f6dfef936e27507d5b5390562475359 | sohinipattanayak/Fundamentals_Of_Python | /p2_palindrome_num.py | 638 | 4.21875 | 4 | #Check if num is plaindrome
num=int(input("Enter the number: "))
num_str=str(num) #Type-casting the number to String
flag=0
#No need to iterate throught the whole of string
#Just iterate till the half of the string
#If the last two match it is automatically a reverse
for i in range(len(num_str)//2): #halfing the list
if num_str[i]!=num_str[len(num_str)-i-1]:
flag=1 #Check till that point till it is not equal
break #As soon as u reach that point break & get out
if flag==1:
print("Not a Plaindrome")
else:
print("Palindrome") #It could be a plaindrome because the above iteration could occur successfully
| true |
a94426f5e57d3027080f43255a23b785fc829bae | alaamarashdeh92/CA06---More-about-Functions-Scope | /P3.py | 2,132 | 4.375 | 4 | # Shopping List
# Your shopping list should keep asking for new items until nothing is entered (no input followed by enter/return key).
# The program should then print a menu for the user to choose one of the following options:
# (A)dd - To add a new item to the list.
# (F)ind - To search for an item in the list.
# (P)rint - To pretty print the list.
# (S)ort - To sort the list.
# (C)lear - To clear all items in the list.
# (Q)uit - To exit your program.
# TODO: Define a data structure to keep track of your shopping list.
# TODO: Implement a function to show the menu to the user, then wait for a valid user choice.
def add_item(item):
shopping_list.append(item)
#Implement a function to find an item in your shopping list.
def find_item(item):
if item in shopping_list:
print("the item was found ")
else:
print("the items is not in the list ")
#implement a function to pretty print your tabbed lits.
def print_list():
print("the items in the list are ")
print(shopping_list, end ="/t")
# function to sort print your tabbed lits.
def sort_list():
shopping_list.sort()
print (f"the sorted shopping list is {shopping_list}")
#Implement a function to pretty print your tabbed lits.
def clear_list():
shopping_list.clear()
#Implement a function which calls the exit() function.
def quit():
print("Goodbye! Hope to see you again soon :).")
shopping_list=[]
def show_menu():
print(f"this is the menu{shopping_list}")
print ("""chose one of the following options
Add - To add a new item to the list.
Find - To search for an item in the list.
Print - To pretty print the list.
Sort - To sort the list.
Clear - To clear all items in the list.
Quit - To exit your program.
""")
str=input("your choice is :")
if str=="Add" :
item=input("enter the item you want to add ")
add_item(item)
elif str=="find":
item=input("what are you looking for ")
find_item(item)
elif str=="print":
print_list()
elif str=="sort":
sort_list()
elif str=="clear":
clear_list() | true |
d6482340a7a0125c28ac00e22c30974bb3edf79d | riteshsharma29/Python_data_extraction | /ex_2.py | 501 | 4.28125 | 4 | #!/usr/bin/python
# coding: utf-8 -*-
#This example shows reading a dataset using csv reader
import csv
#creating an empty list
MonthlySales = []
with open('data/MonthlySales.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
MonthlySales.append(row)
for a in MonthlySales:
print a
#print keys
for a in MonthlySales:
print a.keys()
#print keys and values
for a in MonthlySales:
for key, value in a.items():
print key + ": ", value
print '\n'
| true |
406002913411dfd9538c285b1969ddcee05bf9f9 | yusufemrebudak/Python-Studies | /loop_operations.py | 1,956 | 4.5625 | 5 | # range method
for item in range(2,10): # 2 den 10 a kadar olan sayıları yazdır
print(item)
print(list(range(5,100,20))) # [5, 25, 45, 65, 85] basar
#################### enumarete ####################
greeting = 'hello'
for index,letter in enumerate(greeting):
print(f'index: {index} , letter: {letter}')
for item in enumerate(greeting):
print(item)
# #(0, 'h')
# (1, 'e')
# (2, 'l')
# (3, 'l')
# (4, 'o') yazar for index,item in enumerate(greeting) yazarsak ayrı ayrı index i ve değeri değişkenlere atarız.
################################ zip ###################################3
list1=[1,2,3,4,5]
list2=['a','b','c','d','e']
list3 =[100,200,300,400,500]
print(list(zip(list1,list2))) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] olarak iki listenin de aynı indekslerini eşler (1, 'a') bunlar bir tuple list tir
print(list(zip(list1,list2,list3))) # [(1, 'a', 100), (2, 'b', 200), (3, 'c', 300), (4, 'd', 400), (5, 'e', 500)]
for item in zip(list1,list2,list3):
print(item)
for a,b,c in zip(list1,list2,list3): #her tuple daki ilk elemanı basar yani sonuc 1,2,3,4,5 alt alta basar
print(a)
##########################3 LİST COMPREHENSİONS ####################### while ve for a alternatif
numbers=[]
for x in range(10):
numbers.append(x)
print(numbers)
numbers=[x for x in range(10)] # şu olay for veya while yerine kullanılabilir
print(numbers) # iki yöntemde de 0-10 a kadar olan sayıları bir list olarak tanımlıyoruz.
numbers=[x**2 for x in range(10)]
print(numbers) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] basar
mystring='hello'
my_list=[letter for letter in mystring]
print(my_list) # ['h', 'e', 'l', 'l', 'o'] basar
years=[1934,1945,1995,1994]
ages=[2019-year for year in years]
print(ages) # [85, 74, 24, 25] basar
result = [x if x%2==0 else 'tek' for x in range(1,10)] # x in listeye dahil olması için x%2==0 ifadesinin true dönmesini şart koşuyorum.
print(result) | false |
6a296745a5d413d0f2c23635425fba1e751d1af1 | DanielOjo/Iteration | /Classroom exercises/Development/Iteration Class Exercise (Development Part 2).py | 347 | 4.21875 | 4 | #DanielOgunlana
#31-10-2014
#Iteration Class Exercise (Development Part 2)
number_stars = int(input("How many stars do you want on each row:"))
number_display = int(input("How many times would you like this to display?:"))
stars_printed = "*"
for stars in range(1,number_display+1):
print(stars_printed*number_stars)
| true |
d223031deac627cd02f4c4cb223534b185b07579 | asterane/python-exercises | /other/friend/Multiplication Tables.py | 204 | 4.21875 | 4 | print("What multiplication table would you like? ")
i = input()
print("Here's your table: ")
for j in range(11):
print(i, " x ", j, "=", i * j)
# The code above creates the table... I hope. #
| true |
0cd5b92fbce3315dca5f35c815a7b6d73f91bbef | teresahu/digitalcrafts | /python-exercises-2/caesar_cipher.py | 726 | 4.15625 | 4 | caesar = {
'a' : 'n',
'b' : 'o',
'c' : 'p',
'd' : 'q',
'e' : 'r',
'f' : 's',
'g' : 't',
'h' : 'u',
'i' : 'v',
'j' : 'w',
'k' : 'x',
'l' : 'y',
'm' : 'z',
'n' : 'a',
'o' : 'b',
'p' : 'c',
'q' : 'd',
'r' : 'e',
's' : 'f',
't' : 'g',
'u' : 'h',
'v' : 'i',
'w' : 'j',
'x' : 'k',
'y' : 'l',
'z' : 'm'
}
wordList = []
def translator():
string = input("Please give me a string: ")
for char in string:
try:
caesar[char.lower()]
wordList.append(caesar[char.lower()])
except KeyError:
wordList.append(char)
wordStr = ''.join(wordList)
print(wordStr)
translator()
| false |
a0208582f00a6f392e80905246e296dd45e843ca | b-ark/lesson_4 | /Task3.py | 820 | 4.375 | 4 | # Create a program that reads an input string and then creates and prints 5 random strings
# from characters of the input string.
# For example, the program obtained the word ‘hello’, so it should print 5 random strings(words)
# that combine characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ -> ‘hlelo’, ‘olelh’, ‘loleh’ …
# Tips: Use random module to get random char from string)
from random import shuffle, sample
# 1 способ
answer = input('Type in your string: ')
string_list = list(answer)
counter = 0
while counter != 5:
shuffle(string_list)
print(''.join(string_list))
counter += 1
# 2 способ
answer = input('Type in your string: ')
string_list = list(answer)
counter = 0
while counter != 5:
print(''.join(sample(string_list, len(answer))))
counter += 1
| true |
14a4b02855d5b08a9a4c3b2eb8ee8e69474fed12 | Atularyan/Letsupgrade-Assignment | /Day_3_Assignment/Day_3(Question2).py | 338 | 4.25 | 4 | """
Question 2
Define a function swap that should swap two values and print the swapped variables outside the
swap function.
"""
def swap(n):
rev=0
while(n>0):
rem=n%10
rev=(rev*10)+rem
n=n//10
return (rev+n)
n=int(input("Enter the number = "))
res=swap(n)
print("swapped value = ",res) | true |
e47a5b27a63194e1a59814f5ce3d9d5fe1f0c5cc | vijay-Jonathan/Python_Training | /bin/44_classes_static_methods.py | 2,156 | 4.15625 | 4 | """
Client Requiremnt is :for 43rd example, add method to compute percentage,
if student pass marks, method should return percentage.
Now,
for this compute_percentage method, not required to pass instance object OR
class object, only passing 2 marks is enough method will return perecnetage.
Other methods inside the class is receiving either instance object/class object,
because, in those methods we are either storing some values inside the object/
reading varaible values from the object
But,
In this case, we dont need class/instance object. Uncessarily if we pass
any object to method, it will also occupy memory.
In this case we can write method wchi will not take any instance/class method as
first argument
i.e : STATIC METHODS
"""
class Student:
college = "Xyz College"
def __init__(self,n,s1,s2):
self.name = n
self.sub1_marks = s1
self.sub2_marks = s2
@classmethod
def add_college_rank(cls,r):
cls.college_rank = r
@staticmethod
def compute_percentage(marks1,marks2):
return ((marks1+marks2)/200)*100
Student1 = Student("Student-1",70,80)
Student2 = Student("Student-2",80,90)
avg_sub1_marks = (Student1.sub1_marks + Student2.sub1_marks)/2
avg_sub2_marks = (Student1.sub2_marks + Student2.sub2_marks)/2
total_sub1_marks = Student1.sub1_marks + Student2.sub1_marks
total_sub2_marks = Student1.sub2_marks + Student2.sub2_marks
total_marks = Student1.sub1_marks + Student2.sub1_marks + Student1.sub2_marks + Student2.sub2_marks
print(" Student_1_name : ",Student1.name)
print(" Student_2_name : ",Student2.name)
print(" Student_1_College : ",Student.college)
print(" Student_2_College : ",Student.college)
print("avg_sub1_marks : ",avg_sub1_marks)
print("avg_sub2_marks : ",avg_sub2_marks)
print("total_sub1_marks : ",total_sub1_marks)
print("total_sub2_marks : ",total_sub2_marks)
print("total_marks : ",total_marks)
Student.add_college_rank(1)
print("College Rank : ",Student.college_rank)
s1_per = Student.compute_percentage(Student1.sub1_marks,Student1.sub2_marks)
print("Student 1 Percentage : ",s1_per)
print("-"*40)
#------------------------------------
| true |
f14ac23d41d53f6cb09d94da5facd833aa3bb7f6 | vijay-Jonathan/Python_Training | /bin/2_core_datatypes.py | 1,842 | 4.25 | 4 | """
CORE DATA TYPES :
Similar to other languages, in python also we ALREADY have SOME options to store SOME kind of data.
In that,
1. int,float,hex,bin classes : ALREADY have option to store numbers like int, float, hex, bin, oct etc
2. str class : ALREADY have option to store Strings like "My Name", "My Addess" etc
3. list class : ALREADY have option to store collection of elements like list of students : After creating list,we CAN alter throught the program
4. tuple class : ALREADY have option to store collection of elements like list of students : After creating tuple,we CAN'T alter throught the program
5. dict class : ALREADY have option to store collection of elements like list of students : After creating dictionary,we CAN alter throught the program
Why we need dictionary when we already have list?
Answer :
a) dict class help us to provide OWN index called key
b) dict class help us to store json data
c) dict class help us to store no-sql database data
6. set class : ALREADY have option to store collection of elements like list of students : After creating set, we CAN alter throught the program
Why we need set when we already have list/dict?
Answer:
a) set class help us to store/keep unique elements
b) set class help us to perform sets and unions operations like union, intersection, difference etc
7. frozenset class : ALREADY have option to store collection of elements like list of students : After creating frozenset, we CAN'T alter throught the program
And Many More Classes are available, we will discuss throughout the course
Summary:
IMMUTABLE (We CAN'T modify)
-------------------------
1. number classes like int,float,hex,bin,oct etc
2. str class
3. tuple class
4. frozenset class
MUTABLE (We CAN modify)
1. list
2. dict
3. set
"""
| true |
c065a41651f03ca8f13fa7ae3f1102006e602962 | N1ck079/lessons | /hw06_easy.py | 2,972 | 4.28125 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (int или float).
Результат:
- float.
Исключения:
- ValueError: вычисление не возможно.
"""
if a * b >= 0:
return (a * b) ** 0.5
else:
raise ValueError("Невозможно определить среднее геометрическое "
"введенных чисел.")
try:
a = float(input("a = "))
b = float(input("b = "))
c = avg(a, b)
print("Среднее геометрическое = {:.2f}".format(c))
except ValueError as err:
print("Ошибка:", err, ". Проверьте введенные числа.")
except Exception as err:
print("Ошибка:", err)
# ПРИМЕЧАНИЕ: Для решения задач 2-4 необходимо познакомиться с модулями os, sys!
# СМ.: https://pythonworld.ru/moduli/modul-os.html, https://pythonworld.ru/moduli/modul-sys.html
# Задача-2:
# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,
# из которой запущен данный скрипт.
# И второй скрипт, удаляющий эти папки.
import os
def mk_dirs():
for i in range(9):
os.mkdir(os.path.join(os.getcwd(), 'dir_' + str(i + 1)))
print('Папка %s создана' % ('dir_' + str(i + 1)))
# И второй скрипт, удаляющий эти папки.
def rem_dirs():
for i in range(9):
os.rmdir('dir_' + str(i + 1))
print('Папка %s удалена' % ('dir_' + str(i + 1)))
# Задача-3:
# Напишите скрипт, отображающий папки текущей директории.
import os
def show_dirs(path=os.getcwd()):
if os.listdir(path) != []:
print('\nТекущая директория содержит:')
for i in os.listdir(path):
if os.path.isdir(i):
print(i)
else:
print('\nТекущая директория пуста.')
# Задача-4:
# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт.
import os
def copy_file(path=__file__):
file = open(path, 'r', encoding='utf-8')
str = file.read()
file.close()
file = open('copy_' + os.path.basename(path), 'w', encoding='utf-8')
file.write(str)
file.close()
| false |
ba07cec6d0f3f8f0131b8ac1680314dedb04dd89 | dmonzonis/advent-of-code-2019 | /day3/day3.py | 2,192 | 4.28125 | 4 | def compute_path(path):
"""Return a set with all the visited positions in (x, y) form"""
current = [0, 0]
visited = {}
total_steps = 0
for move in path:
if move[0] == 'U':
pos = 1
multiplier = 1
elif move[0] == 'D':
pos = 1
multiplier = -1
elif move[0] == 'R':
pos = 0
multiplier = 1
else: # 'L'
pos = 0
multiplier = -1
steps = int(move[1:])
for _ in range(1, steps + 1):
current[pos] += multiplier
total_steps += 1
current_tuple = tuple(current)
if current_tuple not in visited:
visited[current_tuple] = total_steps
return visited
def manhattan_distance(point1, point2):
return abs(point1[0] - point2[0]) + abs(point1[1] - point2[1])
def find_intersections(path1, path2):
"""Return a dictionary with the intersecting points as keys and the total steps
to reach that intersection by both paths, as given by the compute_path method"""
visited1 = compute_path(path1)
visited2 = compute_path(path2)
intersections = set(visited1.keys()).intersection(set(visited2.keys()))
result = {}
# Construct the dictionary of intersection: total steps
for point in intersections:
result[point] = visited1[point] + visited2[point]
return result
def find_closest_point(points, origin=(0, 0)):
closest = None
closest_distance = float('inf')
for point in points:
distance = manhattan_distance(point, origin)
if distance < closest_distance:
closest = point
closest_distance = distance
return closest
def main():
with open("input.txt") as f:
paths = [path.split(',') for path in f.read().splitlines()]
# Part 1
intersection_dict = find_intersections(paths[0], paths[1])
closest = find_closest_point(intersection_dict.keys())
print(manhattan_distance(closest, (0, 0)))
# Part 2
print(min(intersection_dict.values()))
if __name__ == "__main__":
main()
| true |
17baad513d548bf71b1ec6eea648fa0ca2917d7d | Ads99/python_learning | /python_crash_course/names.py | 924 | 4.15625 | 4 | name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)
message = "Hello, " + full_name.title() + "!"
print(message)
# whitespace demo
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
print("Languages:\n\tPython\n\tC\n\tJavaScript")
# stripping whitepace - this is best seen in a terminal session without print statements
favourite_language = 'python '
print(len(favourite_language))
print(len(favourite_language.rstrip()))
# however, note aboe that the variable is unchanged by rstrip()
# to change the variable we need to re-assign
favourite_language = favourite_language.rstrip()
print(len(favourite_language))
message = "One of Python's strengths is its diverse community"
print(message)
# incorrect use of apostrophes
#message = 'One of Python's strengths is its diverse community' | true |
1eb80efb19d1ef10b0b5ef2cfe6db47a3d3dc2ff | Ads99/python_learning | /python_crash_course/_11_3_example_employee_class.py | 1,023 | 4.46875 | 4 | # Example 11.3 - Employee
# Write a class called Employee. The __init__() method should take in a first
# name, last name and an annual salary and store each of these as attributes.
# Write a method called give_raise() that adds $5000 to the annual salary by
# default but also accepts a different raise amount
class Employee():
"""Collect detauls about an employee"""
def __init__(self, f_name, l_name, salary):
"""Store a question, and prepare to store responses."""
self.f_name = f_name
self.l_name = l_name
self.salary = salary
def give_raise(self, salary_raise=0):
"""Add $5000 to the annual salary by default but also accept
another val"""
if salary_raise:
self.salary += salary_raise
else:
self.salary += 5000
def show_results(self):
"""Show all details of an employee"""
print("Employee name: " + self.f_name.title() + ' ' + self.l_name.title())
print("Salary: " + str(self.salary)) | true |
8b918360be7f45468c503e81f9c32b52e174ca17 | AdarshSubhash/C-97- | /hwpro.py | 351 | 4.15625 | 4 | number=6
guess=int(input("Guess a number between 1 to 10"))
if(guess==number):
print("You Guessed The Right Number")
elif(guess>number):
print("Try a bit lower number")
guess=int(input("Guess a number between 1 to 10"))
else :
print("Try a bit higher number")
guess=int(input("Guess a number between 1 to 10"))
| true |
46a80d2f2be7f50395d1d80fda9d5b56375abb9a | StYaphet/learn_python | /exception.py | 1,723 | 4.15625 | 4 | # print(5 / 0)
# ZeroDivisionError是一个异常对象。当python无法按照你的要求做的时候,就会创建这样的对象
# 在这种情况下,python将会停止运行程序,并指出发生了哪些异常,饿哦们就可以根据这些信息对程序进行修改
# 当认为可能发生了错误时,可编写一个try-except代码块来处理可能引发的异常。
try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero!")
# 如果try-except 代码块后面还有其他代码,程序将接着运行,因为已经告诉了Python如何处理这种错误
# 1.使用异常避免崩溃
# print("Give me two numbers, and I'll divide them.")
# print("Enter 'q' to quit.")
# while True:
# first_number = input("\nFirst number: ")
# if first_number == "q":
# break
# second_number = input("Second number: ")
# if second_number == 'q':
# break
# try:
# answer = int(first_number) / int(second_number)
# except ZeroDivisionError:
# print("You can't divide by zero!")
# else:
# print(answer)
# 2.处理FileNotFoundError异常
# filename = "alice.txt"
# try:
# with open(filename) as file_object:
# content = file_object.read()
# except FileNotFoundError:
# msg = "Sorry, the file " + filename + " does not exist."
# print(msg)
filename = "alice.py"
try:
with open(filename) as f_obj:
content = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + "does not exist."
print(msg)
else:
words = content.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
# 1.使用多个文件
| false |
4d5aea2f9d176c16b665064761a8053cef554793 | StYaphet/learn_python | /store_data.py | 980 | 4.28125 | 4 | # 模块json 让你能够将简单的Python数据结构转储到文件中,并在程序再次运行时加载该文件中的数据。
# 你还可以使用json 在Python程序之间分享数据。
# 更重要的是,JSON数据格式并非Python专用的,这让你能够将以JSON格式存储的数据与使用其他编程语言的人分享。
# 这是一种轻便格式,很有用,也易于学习。
# 首先导入模块json,在创建一个数字列表。
import json
numbers = [2, 3, 5, 7, 11, 13]
# 指定了要将该数字存储到其中的文件的名称,通常使用文件扩展.json来指出文件存储的数据为JSON格式。
filename = "numbers.json"
# 接下来,我们以写入模式打开这个文件,让json能够将数据写入其中。
with open(filename, "w") as f_obj:
# 我们使用json.dump()将数字列表存储到文件numbers.json中
json.dump(numbers, f_obj)
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers) | false |
a299d477015b60d595abc9e01fb9869d5e74bdbc | natkhosh/Algorithms__Data_structures | /Tasks/c1_fact.py | 637 | 4.375 | 4 | def factorial_recursive(n: int) -> int:
"""
Calculate factorial of number n (> 0) in recursive way
:param n: int > 0
:return: factorial of n
"""
if n < 0:
raise ValueError
elif n == 0:
return 1
else:
p = 1
for i in range(1, n+1):
p *= i
return factorial_recursive(n-1) * n
def factorial_iterative(n: int) -> int:
"""
Calculate factorial of number n (> 0) in iterative way
:param n: int > 0
:return: factorial of n
"""
if n < 0:
raise ValueError
elif n == 0:
return 1
else:
p = 1
for i in range(1, n+1):
p *= i
return p
print(n)
if __name__ == '__main__':
print(factorial_iterative(3))
| false |
889f3f7964600018ae0d002057c3903fe09e1932 | lesshuman/misc_tasks | /yandex/2A.py | 650 | 4.1875 | 4 | '''
Дан список. Определите, является ли он монотонно возрастающим(то есть верно ли, что каждый элемент этого списка больше предыдущего).
Выведите YES, если массив монотонно возрастает и NO в противном случае.
Test cases:
[in]: 1 7 9
[out]: YES
[in]: 1 9 7
[out]: NO
[in]: 2 2 2
[out]: NO
'''
def is_increasing(s):
if len(s) == 0:
return "NO"
for i in range(1,len(s)):
if s[i] <= s[i-1]:
return "NO"
return "YES"
s = list(map(int,input().split()))
print(is_increasing(s))
| false |
bb9d7c309c187c7106e758685a02ffb1a9279c24 | sourav9064/coding-practice | /coding_10.py | 746 | 4.1875 | 4 | ##Write a code to check whether no is prime or not.
##Condition use function check() to find whether entered no is
##positive or negative ,if negative then enter the no,
##And if yes pas no as a parameter to prime()
##and check whether no is prime or not?
num = int(input())
def check(n):
if n >= 0:
a = n
return a
else:
b = n
return b
def prime(n):
if n>1:
for i in range(2,n):
if n%i == 0:
print("not prime number")
break
else:
print("prime number")
print(n)
else:
print("not prime number")
if (check(num)>=0):
prime(num)
else:
print("not prime number")
| true |
9be112de553bec1a1af362c51ecd2877e622c214 | sourav9064/coding-practice | /coding_22.py | 1,385 | 4.21875 | 4 | ##A doctor has a clinic where he serves his patients. The doctor’s consultation fees are different for different groups of patients depending on their age. If the patient’s age is below 17, fees is 200 INR. If the patient’s age is between 17 and 40, fees is 400 INR. If patient’s age is above 40, fees is 300 INR. Write a code to calculate earnings in a day for which one array/List of values representing age of patients visited on that day is passed as input.
##
##Note:
##
##Age should not be zero or less than zero or above 120
##Doctor consults a maximum of 20 patients a day
##Enter age value (press Enter without a value to stop):
##Example 1:
##
##Input
##20
##30
##40
##50
##2
##3
##14
##
##
##Output
##Total Income 2000 INR
##
##
##Note: Input and Output Format should be same as given in the above example.
##For any wrong input display INVALID INPUT
##
##Output Format
##
##Total Income <Integer> INR
age = []
for i in range(20):
p = input()
if p == "":
break
elif int(p) in range(0,120):
age.append(int(p))
else:
print("Invalid Input")
exit()
fees = 0
for i in age:
if i<17:
fees += 200
elif i<40:
fees += 400
else:
fees += 300
print("Total Income {} INR".format(fees))
| true |
f2e698e05e449961409b844e9bc4b667a2042cab | sourav9064/coding-practice | /coding_8.py | 1,058 | 4.15625 | 4 | ##The program will recieve 3 English words inputs from STDIN
##
##These three words will be read one at a time, in three separate line
##The first word should be changed like all vowels should be replaced by *
##The second word should be changed like all consonants should be replaced by @
##The third word should be changed like all char should be converted to upper case
##Then concatenate the three words and print them
##Other than these concatenated word, no other characters/string should or message should be written to STDOUT
##
##For example if you print how are you then output should be h*wa@eYOU.
##
##You can assume that input of each word will not exceed more than 5 chars
a = str(input())
b = str(input())
c = str(input())
v = ['a','e','i','o','u']
con = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
for i in a:
if i in v:
x = a.replace(i,'*')
for i in b:
if i in con:
y = b.replace(i,'@')
else:
y = b
z = c.upper()
print(x+y+z)
| true |
b3c6b4f25e2fe162308638e5fbfb628779658a5a | bitwoman/python-basico-avancado-geek-university | /Estruturas Lógicas e Condicionais/#02.py | 415 | 4.1875 | 4 | #2. Leia um número fornecido pelo usuário. Se esse número for positivo, calcule a raiz quadrada do número.
#Se o número for negativo, mostre uma mensagem dizendo que o número é inválido.
from math import sqrt
numero = int(input('Digite um número inteiro qualquer: '))
if numero > 0:
sqrt = sqrt(numero)
print(f'A raiz quadrada de {numero} é: {sqrt}.')
else:
print('O número é inválido.')
| false |
f39aa64260dbce9cbe7d34c12129b2427f91a2f8 | Krista-Pipho/BCH-571 | /Lab_5/Lab_5.2.py | 811 | 4.4375 | 4 | # Declares an initial list with 5 values
List1 = [1,2,3,4,5]
# Unpacks this list into 5 separate variables
a,b,c,d,e = List1
# Prints both the list and one of the unpacking variables
print(List1)
print(a)
# Changes the value of a to 6
a = 6
# Prints both the list and a, and we can see that changing a does not change the corresponding value in the list
print(a)
print(List1)
# Changes the value of one list entry to nine
List1[1] = 9
# Prints the list and the corresponding unpacking variable to show that changing the unpacking
# variable does not change the list value
print(List1)
print(b)
# We conclude that this method does not just create a variable that points to the same location in space, but rather
# fills new separately stored variables with values from the list
| true |
d9fbf08a599b0a04491081eece5292114ba12039 | hamburgcodingschool/L2CX-November | /lesson 6/dashes.py | 413 | 4.21875 | 4 | # ask the user for a word
# seperate the letters with dashes:
# ex: banana becomes b-a-n-a-n-a
def dashifyWord(word):
dashedWord = ""
firstTime = True
for letter in word:
if firstTime:
firstTime = False
else:
dashedWord += "-"
dashedWord += letter
return dashedWord
print("What's the word YO?")
userWord = input()
print(dashifyWord(userWord)) | true |
6a79b8a8424d83855aa72aefdf873be19b1a9ecd | manishg2015/python_workpsace | /python-postrgress/main.py | 1,625 | 4.25 | 4 | from sqlitedatabase import add_entry,get_entries,create_connection,create_table
menu = """ Welcome to the programming diary!
Please select one of the following options:
1) Add new entry for today.
2) View entries.
3) Exit.
Your selection:
"""
welcome = "**Welcome to the programing diary!**"
# entries = [
# {"content": "Today I started learning programing.", "date": "01-01-2020"},
# {"content": "I created my first SQLite database!", "date": "02-01-2020"},
# {"content": "I finished writing my programming diary application.", "date": "03-01-2020"},
# {"content": "Today I'm going to continue learning programming!", "date": "04-01-2020"},
# ]
def prompt_new_entry():
entry_content = input("What have you learned today? ")
entry_date = input("Enter the date: ")
add_entry(entry_content, entry_date)
def view_entries(entries):
for entry in entries:
print(f"{entry['date']}\n{entry['content']}\n\n")
# print(welcome)
# while (user_input := input(menu)) != "3":
# if user_input == "1":
# prompt_new_entry()
# elif user_input == "2":
# view_entries(get_entries())
# else:
# print("Invalid option, please try again!")
def main():
database = r"/Users/manishgarg/software/sqlite/database.db"
# create a database connection
connection = create_connection(database)
with connection:
create_table(connection)
add_entry(connection,"Learning SQLite with Python" ,"2020-06-01")
entries = get_entries(connection)
for entry in entries:
print(entry)
if __name__ == '__main__':
main()
| true |
66703e13e0e831b7472ac1d5bb3df64e0af61a59 | RobRoseKnows/umbc-cs-projects | /umbc/CMSC/2XX/201/Homeworks/hw8/hw8_part1.py | 685 | 4.4375 | 4 | # File: hw8_part1.py
# Author: Robert Rose
# Date: 11/24/15
# Section: 11
# E-mail: robrose2@umbc.edu
# Description:
# This program takes a list from user input and outputs it in reverse using
# recursion.
def main():
integers = []
number = int(input("Enter a number to append to the list, or -1 to stop: "))
while(number != -1):
integers.append(number)
number = int(input("Enter a number to append to the list, or -1 to stop: "))
print("The list as you entered it is:", integers)
rev(integers)
# Recursively prints the integers in reverse
def rev(integers):
print(integers[-1])
if(len(integers) != 1):
rev(integers[0:-1])
main()
| true |
e97487959ffb477fed5bb5dde9019144a7f6536b | RobRoseKnows/umbc-cs-projects | /umbc/CMSC/2XX/201/Homeworks/hw2/hw2.py | 2,425 | 4.34375 | 4 | # File: hw2.py
# Author: Robert Rose
# Date: 9/12/15
# Section: 11
# Email: robrose2@umbc.edu
# Description:
# This file contains mathmatical expressions as
# part of Homework 1.
print("Robert Rose")
print("Various math problem solutions as part of Homework 1.")
# Question 1:
# Expected output: 24
num1 = (7 + 1) * 3
print("Question 1 evaluates to:", num1)
# Actual output: 24
# Explanation: Parentheses first (8), then multiplication (24)
# Question 2:
# Expected output: 2
num2 = (12 % 5)
print("Question 2 evaluates to:", num2)
# Actual output: 2
# Explanation: Remainder of 12 / 5 is 2.
# Question 3:
# Expected output: 21
num3 = (21 % 49)
print("Question 3 evaluates to:", num3)
# Actual output: 21
# Explanation: 21 / 49 = 0, remainder 21.
# Question 4:
# Expected output: 2
num4 = (5 - 3) + (10 - 5) * (8 % 2)
print("Question 4 evaluates to:", num4)
# Actual output: 2
# Explanation: Parentheses first (2, 5, 0), then multiplaction (0), then
# addition (2)
# Question 5:
# Expected output: 34.0
num5 = 6.5 + 5 / 2 * (4 + 7)
print("Question 5 evaluates to:", num5)
# Actual output: 34.0
# Explanation: Parantheses first (11), then division (2.5), then
# multiplacation (27.5), then addition (34)
# Question 6:
# Expected output: 5.0
num6 = 9 / 3 + 18 - 4 * 4
print("Question 6 evaluates to:", num6)
# Actual output: 5.0
# Explanation: First division (3), then multiplication (16), then
# addition (21), then subtraction (5)
# Question 7:
# Expected output: 22
num7 = 8 % 3 + 5 * 4
print("Question 7 evaluates to:", num7)
# Actual output: 22
# Explanation: Frist multiplication (20), then mod (2), then
# addition (22)
# Question 8:
# Expected output: 79.914...
num8 = 81.3 / 2.1 + ((51.5 % 65.2) * 2 / 2.5)
print("Question 8 evaluates to:", num8)
# Actual output: 79.91428571428571
# Explanation: First parantheses (51.5), then parantheses multiplication (103),
# then parantheses division (41.2), then division (38.714...), then
# addition (79.914...)
# Question 9:
# Given equation: 100 - 8 * 8 + 1 / 0.5
# Solved equation: 100 - ((8 * 8 + 1) / 0.5)
# Target number: -30
num9 = 100 - ((8 * 8 + 1) / 0.5)
target9 = -30
print("Question 9 evaluates to:", num9, "and should be", target9)
# Question 10:
# Given equation: 84 / 10 + 11 - 4 * 4
# Solved equation: (84 / (10 + 11) - 4) * 4
# Target number: 0
num10 = (84 / (10 + 11) - 4) * 4
target10 = 0
print("Question 10 evaluates to:", num10, "and should be", target10)
| true |
120b363afdecbbc5f67640a53cad242b5c97ad01 | huangdaweiUCHICAGO/CAAP-CS | /Assignment 1/cash.py | 890 | 4.1875 | 4 | # Dawei Huang
# 07/17/2018
# CAAP Computer Science Assignment 1
# Programs for Part 1 of the assignment is contained in the file hello.py
# Programs for Part 2 of the assignment is contained in the file cash.py
# Part 2
print("Part 2: Change Program\n")
print("This program will prompt user for the amount of change and print the least possible number of coins returned")
change1 = int(float(input("Change owed: "))*100)
def leastChange(change):
coinCounter = 0
while change > 0:
if change >= 25:
coinCounter += 1
change -= 25
elif change >= 10:
coinCounter += 1
change -= 10
elif change >= 5:
coinCounter += 1
change -= 5
elif change >= 1:
coinCounter += 1
change -= 1
return coinCounter
print ("least number of coin owed: "+ str(leastChange(change1))) | true |
daabf510c6a6fd05ec5338da302af3c071c34015 | bogdanlungu/learning-python | /rename_files.py | 727 | 4.21875 | 4 | """
Renames all the files from a given directory by removing the numbers from
their names - example boston221.jpg will become boston.jpg
"""
import os
from string import digits
# define the function
def rename_files():
# get the file names from a folder
file_list = os.listdir(r"C:\Python\tmp\prank")
saved_path = os.getcwd() # get the current working directory
print("Current working directory is " + saved_path)
os.chdir(r"C:\Python\tmp\prank") # the folder that contains the files
# rename files
remove_digits = str.maketrans('', '', digits)
for file_name in file_list:
os.rename(file_name, file_name.translate(remove_digits))
os.chdir(saved_path)
rename_files()
| true |
1e38094a5fa47b540c7a5350010c74bc389ab13c | bogdanlungu/learning-python | /combinations.py | 752 | 4.46875 | 4 | """This programs computes how many combinations are possible
to be made from a collection of 'n' unique integers grouped under 'g' elements.
You need to specify the length of the collection and how many elements at a time you
want to group from the collection.
The number of possible combinations will be printed."""
# pylint: disable=C0103
from math import factorial as fac
message = "Hello! Please complete the length of the collection and the value of the group"
set_message = "The collection length is:"
group_message = "Specify the group length:"
print(message)
print(set_message)
n = int(input())
print(group_message)
g = int(input())
result = fac(n) / (fac(g) * fac(n - g))
print("The number of possible combinations is " + str(int(result)))
| true |
f59a50d4c5a1d9fdf489097819905c086ee06df5 | CoranC/Algorithms-Data-Structures | /Cracking The Coding Interview/Chapter Nine - Recursion and Dynamic Programming/9_2__xy_grid.py | 734 | 4.25 | 4 | """
Imagine a robot sitting on the upper left corner of an X by Y grid. The robot can
only move in two directions: right and down. How many possible paths are there for the robot to go
from (0,0) to (X,Y)?
"""
#Workings
"""
Grid
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
Answer
[
[6, 3, 1],
[3, 2, 1],
[1, 1, 0]
]
"""
def count_robot_paths_rec(grid, row, col):
if row == 0:
return 1
if col == 0:
return 1
return count_robot_paths_rec(grid, row-1, col) + count_robot_paths_rec(grid, row, col-1)
def count_robot_paths_rec(grid, row, col):
grid[row][col] = 1
if __name__ == "__main__":
the_grid = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
print count_robot_paths_rec(the_grid, 2, 2) | true |
4ef0fe0dfebb3c739f8d52ea017b78b75a4076a0 | shadman19922/Algorithm_Practice | /H_Index/h_index_sorted_array.py | 783 | 4.21875 | 4 | def compute_h_index(Input):
#Input.sort()
left = 0
right = len(Input) - 1
h_idx = -2
while left < right:
middle = (int)(left + (right - left)/2)
middle_element = Input[middle]
remaining_elements = right - middle + 1
if middle_element <= remaining_elements:
h_idx = middle_element
left = middle + 1
else:
right = middle - 1
return Input[left]
some_numbers = [2, 2, 2, 4, 4, 4, 5, 5, 5, 5, 5, 6]
#some_numbers.sort()
#print("The value of len(some_numbers) is: ", len(some_numbers))
print("Here's a sorted array \n")
for i in range(0, len(some_numbers)):
print(some_numbers[i], end = " ")
result = compute_h_index(some_numbers)
print('The h-index is: ', result)
| true |
ca66f03d8a33f2f47a3f21d1ca44aa4c410ac644 | ebagos/python | /p023/main.py | 1,699 | 4.125 | 4 | """
完全数とは, その数の真の約数の和がそれ自身と一致する数のことである. たとえば, 28の真の約数の和は, 1 + 2 + 4 + 7 + 14 = 28 であるので, 28は完全数である.
真の約数の和がその数よりも少ないものを不足数といい, 真の約数の和がその数よりも大きいものを過剰数と呼ぶ.
12は, 1 + 2 + 3 + 4 + 6 = 16 となるので, 最小の過剰数である. よって2つの過剰数の和で書ける最少の数は24である. 数学的な解析により, 28123より大きい任意の整数は2つの過剰数の和で書けることが知られている. 2つの過剰数の和で表せない最大の数がこの上限よりも小さいことは分かっているのだが, この上限を減らすことが出来ていない.
2つの過剰数の和で書き表せない正の整数の総和を求めよ.
"""
def make_true_divisor_list(num):
if num < 1:
return []
elif num == 1:
return [1]
else:
divisor_list = []
divisor_list.append(1)
for i in range(2, num // 2 + 1):
if num % i == 0:
divisor_list.append(i)
#divisor_list.append(num)
return divisor_list
def make_divisor_list(num):
result = make_true_divisor_list(num)
result.append(num)
return result
def d(num):
return sum(make_true_divisor_list(num))
def main():
MAX = 28123
med = []
for i in range(1, MAX+1):
if i < d(i):
med.append(i)
med2 = [x+y for x in med for y in med]
result = 0
for i in range(1, MAX+1):
if not (i in med2):
result += 1
print(result)
main()
| false |
9ec4277cb9d0f88290a5f1c7abd4815d12677a90 | mdisieno/Learning | /Python/FCC_PythonBeginner/14_ifStatements.py | 278 | 4.15625 | 4 | isMale = True
isTall = False
if isMale and isTall: #checks if either true
print("You are a tall male")
elif isMale and not(isTall):
print("You are a male")
elif not(isMale) and isTall:
print(("You are not a male, but are tall"))
else:
print("You are a female")
| true |
62e29f3ea68b3f4e39bf6bb4194f07092c01978e | fabianocardosodev/exercicios-Python-cursoIntens | /removelista.py | 203 | 4.125 | 4 | #remove as instancias de valor especifico de uma lista
#funçao "remove"
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
| false |
d8caba87defcaedadccb189e7a345ef3308b54b6 | SaiSree-0517/19A91A0517_SAISREE_CSEA_PYTHON_LAB_EXPERIMENTS | /2.1experiment.py | 476 | 4.25 | 4 | """
2.1Implement a python script to compute
distance between two points taking inp from the user (Pythagorean Theorem)
"""
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,y1),"and",(x2,y2),"is : ",result)
#output
enter x1 : 5
enter x2 : 6
enter y1 : 7
enter y2 : 8
distance between (5, 7) and (6, 8) is : 1.4142135623730951
| false |
916e34cc0cce126412c21d0c4cb71fc640f2e73d | SaM-0777/OOP | /Strings.py | 462 | 4.3125 | 4 | ##Strings in Python
str1 = "Python is Easy"
print(str1[:])
print(str1[::])
print(str1[:3]) ##Print first 3 characters
print(str1[-2:3])
##Slicing of String in Python
s = "Computer Science"
slice_1 = slice(-1, -6, -1)
slice_2 = slice(1, 6, -1)
slice_3 = slice(0, 5, 2)
print(s[slice_1])
print(s[slice_2])
print(s[slice_3])
##Reverse string using slicing
reverse_s = s[::-1]
print(reverse_s)
s1 = "Computer"
s2 = "Science"
print(s1 * 2)
print(s1, " " + s2)
| true |
2624adf68591e885926d1a3fea74a5c4183b126d | SaM-0777/OOP | /Dictionary.py | 1,781 | 4.59375 | 5 | ##Dict is an unordered set or collection of items or objects where unique keys are mapped yhe values
##These keys are used to access the corresponding paired value. While the keys are unique, values can be common and repeated
##The data type of a value is also mutable and can change whereas, the data type of keys must be mutable such as strings, numbers or tuples
##Example 1
d = {'cat' : 'cute', 'dog' : 'furry'}
print(d['cat'])
print('cat' in d) ##Print True
d['fish'] = 'wet' ##Set an Entry in a Dict
print(d['fish'])
print(d)
print(d.get('monkey', 'N/A')) ##Get an Element with default; prints "N/A"
print(d.get('fish', 'N/A')) ##Get an Element with default; prints "N/A"
del d['fish'] ##Remove an Element from Dict
print(d.get('fish', 'N/A')) ##If fish is not in dict it will print "N/A"
print(d)
###Changing existing value
dict_list = {'name' : 'Rama', 'hobbies' : ['painting', 'singing', 'cooking']}
dict_list['name'] = 'krishna'
print("Name : ", dict_list['name'])
##Adding new Key:value
dict_list = {'name' : 'Ariel', 'hobbies' : ['painting', 'singing', 'cooking']}
dict_list['age'] = 11
print("Dict : ", dict_list)
##Deleting a key:value
del dict_list['name']
print(dict_list)
print("Hobbies : ", end = '')
for i in dict_list['hobbies']:
print(i, end = ', ')
##Predefined Dict Func
#clear(), copy(), get(), items(), fromkeys(), keys(), update(), pop(), values(), popitems()
##How Dict is diff from list ?
# A dict is a composite datatype in python which resembles a list
# List has an ordered set of objects which can iterate and can be referenced and accessed by an index number unlike a dict which is unordered and
# has a key:value pair where values are accessed by keys | true |
f0d0f136058ba7b063ff00fe6e4e9165f106d0c2 | Sjaiswal1911/PS1 | /python/Lists/methods_1.py | 1,030 | 4.25 | 4 | # LIST METHODS
# Append
# list.append(obj)
# Appends object obj to list
list1 = ['C++', 'Java', 'Python']
print("List before appending is..", list1)
list1.append('Swift')
print ("updated list : ", list1)
del list1
# Count
# list.count(obj)
# Returns count of how many times obj occurs in list
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
# Extend
# list.extend(seq)
# Appends the contents of seq to list
list1 = ['physics', 'chemistry', 'maths']
list2 = list(range(5)) #creates list of numbers between 0-4
list1.extend(list2)
print ('Extended List :', list1)
# Index
# list.index(obj)
# Returns the lowest index of obj in the list
print ('Index of chemistry', list1.index('chemistry'))
#print ('Index of C#', list1.index('C#'))
# this produces an error
# Insert
# list.insert(index, obj)
# inserts the obj at 'index' location in list
print("Before insertion:" ,list1)
list1.insert(1, 'Biology')
print ('Final list : ', list1)
| true |
15449e1043649cf221e878405e1db4437bb74bfb | manish711/ml-python | /regression/multiple_linear_regression/multiple_linear_regression.py | 1,688 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
@author: manishnarang
Multiple Linear Regression
"""
#Importing Libraries
import numpy as np #contains mathematical tools.
import matplotlib.pyplot as plt #to help plot nice charts.
import pandas as pd #to import data sets and manage data sets.
#Importing Data Set - difference between the independent variables and the dependent variables.
dataSet = pd.read_csv('50_Startups.csv')
X = dataSet.iloc[:, :-1].values
Y = dataSet.iloc[:, -1].values
#Encode Categorical Data
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer([('encoder', OneHotEncoder(), [3])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
#Split the training set and test set - a test set on which we test the performance of this machine learning model and the performance on the test set shouldn't be that different from the performance on the training sets because this would mean that the machine learning models understood well the correlations and didn't learn them by heart.
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state = 0)
# Fitting Multiple Linear Regression to the training set - y = b + m0x0 + m1x1...
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)
# Predicting the test set result
Y_pred = regressor.predict(X_test)
np.set_printoptions(precision=2) #This will display any numerical value with 2 decimals after comma
print(np.concatenate((Y_pred.reshape(len(Y_pred), 1), Y_test.reshape(len(Y_test), 1)),1)) | true |
7312689061a008c1b4c8dbc6a73b2849a4754776 | YanisKachinskis/python_basic_200120 | /lesson5/hw3.py | 1,073 | 4.3125 | 4 | # homework lesson: 5, task 3
"""
Создать текстовый файл (не программно), построчно записать фамилии сотрудников и
величину их окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих
сотрудников. Выполнить подсчет средней величины дохода сотрудников.
Пример файла:
Иванов 23543.12
Петров 13749.32
"""
info = {}
sum_salary = 0
with open('3.txt', 'r', encoding='utf-8') as file:
employees = file.readlines()
for employee in employees:
name, salary = employee.split(' ')
info[name] = int(salary)
if int(salary) < 20000:
print(f"Сотрудники {name} имеет доход ниже 20000 в месяц.")
sum_salary += int(salary)
print(f"Средний доход на сотрудников: {sum_salary/len(employees)}") | false |
cda4893eaa642ff053f86194f8494525bf7bc112 | YanisKachinskis/python_basic_200120 | /lesson4/hw2.py | 624 | 4.15625 | 4 | # homework lesson: 4, task 2
"""
Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента.
Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор.
"""
my_list = [1, 7, 6, 13, 34, 23, 9, 11]
new_my_list = [my_list[i] for i in range(1, len(my_list)) if my_list[i] > my_list[i - 1]]
print(new_my_list)
| false |
9aae48aeae5c81ef96ed1e28e6764e67a89fc4fa | FordMcLeod/witAdmin | /python/rockpaperscissors.py | 2,234 | 4.53125 | 5 | # Rock Paper scissors demo for python introduction. SciCamps 2017
# Extentions: Add options for lives, an option to ask the player to play again.
# 2 player mode. Add another option besides rock/paper/scissors. etc.
import random
import time
computer = random.randint(0,2) # Let 0 = rock, 1 = paper, 2 = scissors
print("Let's play rock paper scissors!")
time.sleep(1.5) # Pause in between statements
while True: # Validate input to make sure user can only type 'y' or 'n'
instruct = input("Wish to listen to instructions?(y/n) ").lower() # keep input in lowercase letters
if instruct == 'y' or instruct == 'n': # if we get what we want, break out of while loop
break
if instruct == 'y':
# These triple quotes let use write more stuff for the print statement in several lines
print('''In this game you choose rock paper or scissors and hope to beat your opponent's move.
Scissors beats paper, paper beats rock, and rock beats scissors. The computer chooses its move
based on a random number. You win if your move is successful.''')
time.sleep(3)
while True:
player = input("Choose rock,paper, or scissors. (r/p/s)").lower()
if player == 'r' or player == 'p' or player == 's':
break
if computer == 0: # if computer choose rock
if player == 'r':
print('It is a tie! Computer chose rock')
elif player == 'p':
print('You win! Computer chose rock')
else:
print('You lose! Computer chose rock')
elif computer == 1: # if computer chooses paper
if player == 'r':
print('You lose! Computer chose paper')
elif player == 'p':
print('It is a tie! Computer chose paper')
else:
print('You Win! Computer chose paper')
else: # if computer chooses scissors
if player == 'r':
print('You Win! Computer chose scissors')
elif player == 'p':
print('You lose! Computer chose scissors')
else:
print('It is a tie! Computer chose scissors') | true |
d81c8918a31ad2299039cdcc2517d1eeacb72599 | RyuAsuka/python-utils | /color-code-change.py | 2,192 | 4.125 | 4 | import sys
usage = """
Usage:
python color-code-change.py <rgb|hex> <number>
Arguments:
rgb: Convert RGB color to hex number style.
hex: Convert hex number color code to RGB color number.
Examples:
python color-code-change.py rgb 100 90 213 -> #645AD5
python color-code-change.py hex FF9900 -> 255 153 0
"""
_hex_digits = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F']
def rgb_to_hex(r, g, b):
result = ''
try:
if r < 0 or g < 0 or b < 0 or r > 255 or g > 255 or b > 255:
raise ValueError('RGB value should between 0 and 255.')
for num in [r, g, b]:
t1 = _hex_digits[num // 16]
t2 = _hex_digits[num % 16]
result += t1 + t2
return '#' + result
except ValueError as e:
print(e)
def hex_to_rgb(hex_number):
result = []
try:
if len(hex_number) != 6:
raise ValueError('The length of HEX number must be 6!')
t1 = hex_number[0:2]
t2 = hex_number[2:4]
t3 = hex_number[4:]
for t in [t1, t2, t3]:
assert isinstance(t, str)
if t[0].upper() not in _hex_digits or t[1].upper() not in _hex_digits:
raise ValueError('Invalid characters! Please check your input.')
result.append(_hex_digits.index(t[0].upper()) * 16 + _hex_digits.index(t[1].upper()))
return result
except ValueError as e:
print(e)
if __name__ == '__main__':
if len(sys.argv) < 2:
print(usage)
elif sys.argv[1] == 'rgb':
if len(sys.argv) == 5:
result = rgb_to_hex(int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
if result is not None:
print(result)
else:
print(usage)
elif sys.argv[1] == 'hex':
if len(sys.argv) == 3:
result = hex_to_rgb(sys.argv[2])
if result is not None:
print(result)
else:
print(usage)
else:
print(usage)
| true |
6fb000907798ff6426fd8fc933ecf2cc5656ab40 | ravularajesh21/Python-Tasks | /Count number of alphabets,digits and special characters in STRING.py | 532 | 4.28125 | 4 | # Count number of alphabets,digits and special characters
string=input('enter string:')
alphabetcount=0
digitcount=0
specialcharactercount = 0
for x in string:
if x>='A' and x<='Z' or x>='a' and x<='z':
alphabetcount = alphabetcount + 1
elif x>='0' and x<='9':
digitcount=digitcount + 1
else:
specialcharactercount = specialcharactercount+1
print('Alphabet count',alphabetcount)
print('digit count',digitcount)
print('special character count',specialcharactercount)
| true |
c7cf39004c6961400afcb2983112060aba156f44 | ravularajesh21/Python-Tasks | /Palindrome 1.py | 553 | 4.5 | 4 | # Approach 1
date = input('enter the date in dd/mm/yyyy format:')
given_date = date.replace('/', '')
reversed_date = given_date[::-1]
if given_date == reversed_date:
print(date,'is palindrome')
else:
print('It is not palindrome')
# Approach 2
day = input('enter day:')
month = input('enter month:')
year = input('enter year:')
given_date = day+month+year
reversed_date = given_date[::-1]
if given_date == reversed_date:
print('date is not palindrome')
else:
print('date is not palindrome')
| true |
85e1e5c1adbc4daf79aaebaa31a2514e523dcef9 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/pizza.py | 774 | 4.34375 | 4 | # Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# Summarise the order
print(f"You ordered a {pizza['crust']}-crust pizza with the following toppings: ")
for topping in pizza['toppings']:
print("\t" + topping)
# favourite languages.py
print("")
favourite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell']
}
for name, languages in favourite_languages.items():
if len(languages) > 1:
print(f"{name.title()}'s favourite languages are: ")
elif len(languages) == 1:
print(f"{name.title()}'s favourite language is: ")
for language in languages:
print(f"\t{language.title()}") | true |
b3f906c56f714ca8d5e724b607dbe2e8d071b662 | KotaCanchela/PythonCrashCourse | /6 Dictionaries/favourite_languages.py | 1,860 | 4.5 | 4 | # Break a large dictionary into several lines for readability
# Add a comma after last key-value pair to be ready to add any future pairs
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
sarah_language = favourite_languages['sarah'].title()
print(f"Sarah's favourite language is {sarah_language}.")
print("The following languages have been mentioned: ")
for language in favourite_languages.values():
print(language.title())
print(f"The following languages have been mentioned: "
f"{[language for language in favourite_languages.values()]}")
# removing duplicates (python was mentioned twice before)
print("")
print("The following languages have been mentioned: ")
for language in set(favourite_languages.values()): # set is a collection in which each item must be unique
print(language.title())
# languages = {'python', 'ruby', 'c', 'python'} IS ALSO A SET
# print(languages) will return no duplicates
# IMPORTANT: IF YOU SEE BRACES BUT NO KEY-VALUE PAIRS. YOU'RE PROBABLY LOOKING AT A SET (does not retain info in order)
# 6-6 Polling
# Make a list of people who should take the favorite languages poll.
# Include some names that are already in the dictionary and some that are not.
# Loop through the list of people who should take the poll.
# If they have already taken the poll, print a message thanking them for responding.
# If they have not yet taken the poll, print a message inviting them to take the poll.
poll_applicants = ['jen', 'sarah', 'henry', 'james']
for applicant in poll_applicants:
if applicant not in favourite_languages:
print(f"{applicant.title()}, you have not yet taken the poll. "
f"Please take the poll.")
elif applicant in favourite_languages:
print(f"Thank you {applicant.title()} for taking the poll.")
| true |
9656f8e78d643569f078cf363ca57b4af32cb8ad | KotaCanchela/PythonCrashCourse | /9 Classes/9-8_Privileges.py | 1,844 | 4.28125 | 4 | # Write a separate Privileges class. The class should have one attribute, privileges,
# that stores a list of strings as described in Exercise 9-7. Move the show_privileges()
# method to this class. Make a Privileges instance as an attribute in the Admin class.
# Create a new instance of Admin and use your method to show its privileges.
from modules import User
class Admin(User):
"""Stores information about a user"""
def __init__(self, first_name, last_name):
"""Initialise attributes about a person's name"""
super().__init__(first_name, last_name)
"""Initialise an empty set of privileges"""
self.privileges = Privileges()
def show_privileges(self):
"""Shows the user's privileges"""
print(
f"{self.first_name.title()} {self.last_name.title()} has the following privileges:"
)
if self.privileges:
for privilege in self.privileges:
print(f"\t{privilege.capitalize()}")
else:
print("This user has no privileges")
class Privileges():
def __init__(self, privileges=[]):
"""Initialise privileges for the user."""
self.privileges = privileges
def show_privileges(self):
"""Shows the user's privileges"""
print(
f"User has the following privileges:"
)
if self.privileges:
for privilege in self.privileges:
print(f"\t{privilege.capitalize()}")
else:
print("This user has no privileges")
my_user = Admin('Kota', 'canchela')
my_user.describe_user()
my_user.show_privileges
my_user_privileges = [
'mod mod any user',
'can ban who they wish',
'ability to promote any user'
]
my_user.privileges.privileges = my_user_privileges
my_user.privileges.show_privileges()
| true |
4d440d271bd189b22db644b888408fd001330c81 | KotaCanchela/PythonCrashCourse | /4 working with lists/4-6 Odd Numbers.py | 932 | 4.78125 | 5 | # “4-6. Odd Numbers: Use the third argument of the range() function
# to make a list of the odd numbers from 1 to 20.
# Use a for loop to print each number.
odd_number = [value for value in range(1, 21, 2)]
print(odd_number)
# 4-7. Threes: Make a list of the multiples of 3 from 3 to 30.
# Use a for loop to print the numbers in your list.
threes = [value for value in range (3, 31, 3)]
print(threes)
threes_alt = []
for value in range (3, 31, 3):
threes_alt.append(value)
print(threes_alt)
# 4-8 Cubes: “ A number raised to the third power is called a cube.
# For example, the cube of 2 is written as 2**3 in Python.
# Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10)
# and use a for loop to print out the value of each cube.
cubes = [value ** 3 for value in range (1, 11)]
print(cubes)
cubes_alt = []
for value in range (1, 11):
cubes_alt.append(value ** 3)
print(cubes_alt) | true |
4262c4943e75c83ce8b337b8ec7a7802400760e5 | KotaCanchela/PythonCrashCourse | /10 Files and Exceptions/favourite_number.py | 784 | 4.46875 | 4 | # Write a program that prompts for the user’s favorite number. Use json.dump()
# to store this number in a file. Write a separate program that reads in this
# value and prints the message, “I know your favorite number! It’s _____.”
import json
def ask_number():
"""Asks the user for their favourite number and stores it."""
filename = '10 Files and Exceptions/favourite_number.json'
ask_number = input("What is your favourite number? ")
with open(filename, 'w') as f:
json.dump(ask_number, f)
return filename
def remember_number():
filename = '10 Files and Exceptions/favourite_number.json'
with open(filename, 'r') as f:
number = json.load(f)
print(f"Your favourite number is {number}")
ask_number()
remember_number()
| true |
332454e2039df29fa6c379252da70dcbd5c8a532 | KotaCanchela/PythonCrashCourse | /7 User input and While statements/Counting.py | 609 | 4.375 | 4 | # Using continue in a loop
# continue allows the user to return to the beginning of the loop rather than breaking out entirely
# The continue statement tells Python to ignore the rest of the loop
# Therefore, when current_number is divisible by 2 it loops back
# otherwise when it is odd it goes to the next line (print)
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
# Avoiding infinite loops
# If you forget to add the x += 1 the loop will run forever
print("")
x = 1
while x <= 5:
print(x)
x += 1 | true |
cefb4142ffda596bf0e822678abdabac4209538b | OldLace/Python_the_Hard_Way | /may_19.py | 1,844 | 4.1875 | 4 | #May 19 - Paul Gelot
#Python the Hard Way - Exercise 12
num1 = int(input("Please enter a number: "))
num2 = int(input("Please enter another number: "))
total_sum = num1 + num2
subtract = num1 - num2
product = num1 * num2
division1 = num1 / num2
print("The sum of the two numbers is:", total_sum)
print("The difference between the two numbers is:", subtract)
print ("The product of the two numbers is:", product)
print(25 * "**")
print(int(division1))
print(division1)
# from sys import argv
# script, file_name = argv
# print(file_name)
# text_file = open(file_name)
# print(text_file)
# print(text_file.read())
#####################################
#import argv method from sys
from sys import argv
#define script & filename as argument
script, filename = argv
txt = open(filename)
#displays message and name of file
print(f"Here's your file {filename}:")
#displays contents of text file
print(txt.read())
#Asks for filename
print("Type the filename again:")
file_again = input("> ") #seeks input from user for file name
#Uses input from previous line
txt_again = open(file_again)
#displays contents of second text file
print(txt_again.read())
from sys import argv
script, file_name = argv
text_file = open(file_name, 'w')
print(text_file)
text_file.write('Adding to the file')
text_file.close()
text_file = open(file_name)
print(text_file.read())
#Importing
import math
thenumber = int(input("Please enter a number: "))
print(int(math.sqrt(thenumber)))
# Two Files - I got it... I think
from sys import argv
script, filename1, filename2 = argv
# txt = filename.read()
text_file1 = open(filename1)
info = text_file1.read()
# print(info)
text_file2 = open(filename2, 'w')
text_file2.write(info)
text_file2.close()
text_file2 = open(filename2, 'r')
info2 = text_file2.read()
# text_file2.write(info)
print(info2)
| true |
180c892336d6a048da555972c923c8968874cafc | OldLace/Python_the_Hard_Way | /hw4.py | 1,723 | 4.4375 | 4 |
# 1. Write a Python program to iterate over dictionaries using for loops
character = {"name": "Walter", "surname": "White", "nickname": "Isenberg", "height": "6 foot 7", "hobby": "trafficking"}
for i in character:
print(i,":", character[i])
# 2. Write a function that takes a string as a parameter and returns a dictionary. The
# dictionary keys should be numbers from 0 to the length of strings and values should be
# the characters appeared in the string.
print("***************" * 4)
def into_dictionary(string):
string_dict = {}
for i in range(len(string)):
string_dict.update({i:string[i]})
print(string_dict)
into_dictionary("quick")
print("***************" * 4)
def make_dict(string):
the_dict = {}
key = 0
for val in string:
the_dict[key] = val
key = key + 1
return the_dict
print(make_dict("test"))
print("***************" * 4)
# a. For example: function call with ‘hello’ should print {0: ‘h’, 1:’e’, 2:’l’, 3: ‘l’ , 4:’o’}
# 3. Write a Python script to check if a given key already exists in a dictionary.
def check_for_key(q):
for i in character:
if i == q:
print("Key exists")
else:
continue
check_for_key("surname")
# 4. Create a dictionary to hold information about pets. Each key is an animal's name, and
# each value is the kind of animal.
# i. For example, 'ziggy': 'canary'
# b. Put at least 3 key-value pairs in your dictionary.
pets = {'Lucky': 'hamster', 'Spot': 'dog', 'Sophia': 'cat', 'Dumbo': 'elephant'}
# c. Use a for loop to print out a series of statements such as "Willie is a dog."
print("******" * 4)
for i in pets:
print(i, "is a", pets[i]) | true |
51f72b65f476209ce78a087d0c401548be8dbb34 | nivedipagar12/PracticePython | /E7_ListComprehensions.py | 882 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 7 : List Comprehensions (https://www.practicepython.org/)
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
Write one line of Python that takes this list a and makes a new list that has only the even
elements of this list in it.
Solution
Created on: 14/08/2019
Created by: Nivedita Pagar
'''
# Define the list
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# create a new list with only the even elements of list a
print("The new list with even elements is = " + str([i for i in a if i % 2 == 0]))
| true |
76100afdfbeaabc631e5375da7ce9d06553957d3 | nivedipagar12/PracticePython | /E24_DrawAGameBoard.py | 2,666 | 4.4375 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org ***********************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 24 : Draw a Game Board (https://www.practicepython.org/)
This exercise is Part 1 of 4 of the Tic Tac Toe exercise series. The other exercises are: Part 2,
Part 3, and Part 4.
Time for some fake graphics! Let’s say we want to draw game boards that look like this:
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
--- --- ---
This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess,
19x19 for Go, and many more).
Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s
print statement.
Remember that in Python 3, printing to the screen is accomplished by
print("Thing to show on screen")
Hint: this requires some use of functions, as were discussed previously on this blog and elsewhere
on the Internet, like this TutorialsPoint link.
Solution
Created on: 19/08/2019
Created by: Nivedita Pagar
'''
def user_input():
'''asks the user the desired size of the board
Parameters
-----------
None
Returns
-----------
size1
integer representing size of the board
'''
global size1
size1 = int(input("Which size board do you want ? \nPlease enter an integer for example 'n' for an 'nxn' board: "))
return size1
def characters(size):
'''defines the characters to be printed and the sequence in which they are to be printed
Parameters
-----------
size: int
user defined size of the board
Returns
-----------
None
'''
dash = "-"
line = "|"
space = " "
rows = (space + 3 * dash) * size
columns = (line + (3 * space)) * (size+1)
for i in range(size):
print(rows)
print(columns)
print(rows)
user_input()
characters(size1)
| true |
17e09b72eba9b69ffed63b90d1ab3ceaec8b225a | nivedipagar12/PracticePython | /E1_CharacterInput.py | 1,894 | 4.28125 | 4 | '''
************* DISCLAIMER: THESE TASKS WERE POSTED ON https://www.practicepython.org************************************
************************* I AM ONLY PROVIDING SOLUTIONS ***************************************************************
Project/Exercise 1 : Character Input (https://www.practicepython.org/)
Create a program that asks the user to enter their name and their age. Print out a message addressed to
them that tells them the year that they will turn 100 years old.
Extras:
1) Add on to the previous program by asking the user for another number and printing out that many
copies of the previous message. (Hint: order of operations exists in Python)
2) Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same
as pressing the ENTER button)
Solution
Created on: 12/08/2019
Created by: Nivedita Pagar
'''
# Import datetime package to determine the current year instead of hard coding it.
import datetime
# User variables
name, age = input("Enter your name and age (separated by a space): ").split()
# Create a datetime object
now = datetime.datetime.now()
# Find out the current year, subtract the current age from 100 and add the difference to the current year
current_year = now.year + (100 - int(age))
num = int(input("Enter the number of times you wish to see the result : "))
# Simply print the result
print("You will turn 100 in the year : " + str(current_year))
# Print the result "num" times using a for loop
for i in range(0, num):
print("(EXTRA LOOP) You will turn 100 in the year : " + str(current_year))
# Print the result "num" times by manipulating strings
print(("(EXTRA STRING MANIPULATION) You will turn 100 in the year : " + str(current_year) + "\n") * num)
| true |
a81f36182dee04cd838b6ce101acd217d309ab66 | poojajunnarkar11/CTCI | /CallBoxDevTest-3.py | 567 | 4.53125 | 5 | def is_power_two (my_num):
if my_num == 0:
return False
while (my_num != 1):
if my_num%2 != 0:
return False
my_num = my_num/2
return True
print is_power_two(18)
# Why this will work for any integer input it receives?
# -Because the while loop works until the number is 1
# -Numbers that are power of two will loop thorugh the while and return True
# -Odd numbers will return False
# -Even numbers that are not powers of 2 will be divided by 2 unless they are equal to an odd number whereafter the loop returns False | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.