blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
dddb2bfd290929643eb202396aecd88df6d51e0f | Catering-Company/Capstone-project-2 | /Part2/sub_set_min_coin_value.py | 1,889 | 4.75 | 5 | # CODE FOR SETTING THE MINIMUM COIN INPUT VALUE ( CHOICE 2 OF THE SUB-MENU )
# --------------------------------------------------
# Gets the user to input a new minimum amount of coins that the user can enter
# into the Coin Calulator and Mutiple Coin Calculator.
# There are restrictions in place to prevent the user from entering:
# - Any non-integer.
# - A min value less than 0.
# - A min value greater than or equal to 10000.
# - A min value greater than the current max value.
# If any of the above happens then min_coin_value returns a negative integer.
# A while-loop in main(config) will then rerun min_coin_value.
def min_coin_value(config):
try:
min_coin = input("What is the minimum amount of coins you want the machine to accept? ")
min_coin = int(min_coin)
if int(min_coin) < 0:
print("Request denied.")
print("The minimum must be at least 0.")
print()
return -1
if int(min_coin) >= 10000:
print("Request denied.")
print("You cannot set the minimum coin value to 10000 or larger.")
print()
return -2
if int(min_coin) > config["max_coin_value"]:
print("Request denied.")
print("That is larger than the maximum coin amount!")
print()
return -3
except:
print("Please enter a minimum amount of coins.")
print()
return -3
return int(min_coin)
# --------------------------------------------------
# Returns the number that the user has inputted, provided that the number is greater than 0.
# If the number is 0 or less then the user is re-prompted.
def main(config):
min_coin = min_coin_value(config)
while min_coin < 0:
min_coin = min_coin_value(config)
return min_coin
# --------------------------------------------------
| true |
b27bdc20978ca3365e8fe5b87f1f1207f7d48774 | nish235/PythonPrograms | /Oct15/ArmstrongWhile.py | 252 | 4.125 | 4 |
num = int(input("Enter a number: "))
s = 0
temp = num
while temp > 0:
dig = temp % 10
s = s + dig ** 3
temp = temp // 10
if s == num:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
| false |
f2725f5d5f4b12d7904d271873c421c99ff2fe9f | MagRok/Python_tasks | /regex/Python_tasks/Text_stats.py | 1,627 | 4.15625 | 4 | # Create a class that:
#• When creating an instance, it required entering the text for which it will count statistics.
# The first conversion occurred when the instance was initialized.
#Each instance had attributes: - lower_letters_num - which stores the number of all lowercase letters in the text
#- upper_letters_num - holds the number of all uppercase letters in the text
#- punctuation_num - storing the number of punctuation characters in the text.
#- digits_num - the number of digits present in the text.
# stats - a dictionary that stores the statistics of letters, numbers and punctuation in the text.
# Calculate statistics using the calculate_stats method.
import re
class LetterStats():
def __init__(self, text):
self.lower_l_num = None
self.upper_l_num = None
self.punct_l_num = None
self.digits_l_num = None
self.stats = {}
self.text = text
self._calculate_stats()
def _calculate_stats(self):
self.lower_l_num = len(re.findall(r'[a-ząćęłóżź]', self.text))
self.upper_l_num = len(re.findall(r'[A-ZĄĆĘŁÓŻŹ]', self.text))
self.punct_l_num = len(re.findall(r'[.?\-",:;!]', self.text))
self.digits_l_num = len(re.findall(r'[0-9]', self.text))
self.stats = {'lower_letters': self.lower_l_num,
'upper_letters': self.upper_l_num,
'punctuation': self.punct_l_num,
'digits': self.digits_l_num}
return self.stats
def add_text(self, text):
self.text = text
self._calculate_stats()
return self.stats | true |
ad88d60e5b4b5ab7c77df24182ec07525e213411 | hulaba/geekInsideYou | /trie/trieSearch.py | 2,112 | 4.125 | 4 | class TrieNode:
def __init__(self):
"""
initializing a node of trie
isEOW is isEndOfWord flag used for the leaf nodes
"""
self.children = [None] * 26
self.isEOW = False
class Trie:
def __init__(self):
"""
initializing the trie data structure with a root node
"""
self.root = self.getNode()
def getNode(self):
"""
Create a node in the memory
:return: a new node with children and isEOW flag
"""
return TrieNode()
def charToIndex(self, ch):
"""
converts characters to index starting from 0
:param ch: any english albhabet
:return: ascii value
"""
return ord(ch) - ord('a')
def insert(self, value):
"""
function for inserting words into prefix tree (trie)
:param value: word string to be inserted
"""
rootNode = self.root
length = len(value)
for step_size in range(length):
index = self.charToIndex(value[step_size])
if not rootNode.children[index]:
rootNode.children[index] = self.getNode()
rootNode = rootNode.children[index]
rootNode.isEOW = True
def search(self, word):
"""
utility function that searches for a word in trie
:param word: search word
:return: boolean, if true, word is present otherwise not
"""
rootNode = self.root
length = len(word)
for _ in range(length):
index = self.charToIndex(word[_])
if not rootNode.children[index]:
return False
rootNode = rootNode.children[index]
return rootNode is not None and rootNode.isEOW
if __name__ == '__main__':
keys = ["the", "a", "there", "anaswe", "any",
"by", "their"]
# Trie object
t = Trie()
# Construct trie
for key in keys:
t.insert(key)
# Search for different keys
if t.search('the'):
print('present')
else:
print('not present')
| true |
0d877b43c404c588ef0dbacd8c93c94b17534359 | hulaba/geekInsideYou | /tree/levelOrderSpiralForm.py | 1,421 | 4.1875 | 4 | """
Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.
spiral_order
"""
class Node:
def __init__(self, key):
self.val = key
self.left = None
self.right = None
def spiralOrder(root):
h = heightOfTree(root)
ltr = False
for i in range(1, h + 1):
spiralPrintLevel(root, i, ltr)
ltr = not ltr
def spiralPrintLevel(root, level, ltr):
if root is None:
return
if level == 1:
print(root.val, end=" ")
if level > 1:
if ltr:
spiralPrintLevel(root.left, level - 1, ltr)
spiralPrintLevel(root.right, level - 1, ltr)
else:
spiralPrintLevel(root.right, level - 1, ltr)
spiralPrintLevel(root.left, level - 1, ltr)
def heightOfTree(node):
if node is None:
return 0
else:
l_height = heightOfTree(node.left)
r_height = heightOfTree(node.right)
if l_height > r_height:
return l_height + 1
else:
return r_height + 1
def main():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("--The spiral order traversal of the tree is")
spiralOrder(root)
if __name__ == '__main__':
main()
| true |
c9177860241ba612a10c13afa03ef7f201f22fee | hulaba/geekInsideYou | /matrix/matrixSubtraction.py | 477 | 4.1875 | 4 | def subtractMatrix(A, B, N):
"""
Function to SUBTRACT two matrices
N: rows and columns of matrices respectively
A, B: two input matrices
"""
C = A[:][:]
for i in range(N):
for j in range(N):
C[i][j] = A[i][j] - B[i][j]
print(C)
if __name__ == '__main__':
A = [[6, 7, 8],
[7, 8, 9],
[8, 9, 10]]
B = [[1, 2, 3],
[2, 0, 4],
[3, 4, 1]]
N = 3
subtractMatrix(A, B, N)
| false |
8bbd84f22d9af1917de39200a00c0a8edeb81a34 | hulaba/geekInsideYou | /linked list/deleteListPosition.py | 1,403 | 4.15625 | 4 | class Node:
def __init__(self, data):
"""initialising the data and next pointer of a node"""
self.data = data
self.next = None
class linkedList:
def __init__(self):
"""initialising the head node"""
self.head = None
def push(self, new_data):
"""inserting the data in the linked list"""
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def deleteAt(self, position):
"""delete data at a given index in linked list"""
if self.head is None:
return
temp = self.head
if position == 0:
self.head = temp.next
temp = None
return
for i in range(position - 1):
temp = temp.next
if temp is None:
break
if temp is None:
return
if temp.next is None:
return
next = temp.next.next
temp.next = None
temp.next = next
def printList(self):
"""traversing the elements"""
temp = self.head
while (temp):
print(temp.data)
temp = temp.next
if __name__ == '__main__':
llist = linkedList()
llist.push(1)
llist.push(2)
llist.push(7)
llist.push(4)
llist.printList()
print("after deletion")
llist.deleteAt(2)
llist.printList()
| true |
1ebf124d42d510c2e60c3c7585c03e0efd6dad18 | gnsisec/learn-python-with-the-the-hard-way | /exercise/ex14Drill.py | 871 | 4.21875 | 4 | # This is Python version 2.7
# Exercise 14: Prompting and Passing
# to run this use:
# python ex14.py matthew
# 2. Change the prompt variable to something else entirely.
# 3. Drill: Add another argument and use it in your script,
# the same way you did in the previous exercise with first, second = ARGV.
from sys import argv
script, user_name, status = argv
prompt = 'answer: '
print "Hi %s, I'm the %s script." % (user_name, script)
print "I'd like to ask you few questions."
print "Do you like me %s ?" % user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r compter. Nice.
Your status %r.
""" % (likes, lives, computer, status)
| true |
1804f578c7ff417744edc804043b2016d8bcde4a | paulocuambe/hello-python | /exercises/lists-execises.py | 554 | 4.21875 | 4 | my_list = ["apple", "banana", "cherry", "mango"]
print(my_list[-2]) # Second last item of the list
my_list.append("lemon")
if "lemon" in my_list:
print("Yes, that fruit is in the list.")
else:
print("That fruit is not in the list.")
my_list.insert(2, "orange")
print(my_list)
new_list = my_list[1:]
print(new_list)
new_list.sort()
print(new_list)
print(sorted(my_list))
nums = [1, 3, 6, 7, 9]
sqr_list = [x * x for x in nums]
nums.extend([10, 12, 13])
print(nums)
print(sqr_list)
sqr_list.pop()
del nums[1:2]
print(nums)
print(sqr_list)
| true |
45ab566c204a9a593871d670c1c0e206fa3949fd | paulocuambe/hello-python | /exercises/dictionaries/count_letter.py | 367 | 4.125 | 4 | """
Count how many times each letter appears in a string.
"""
word = "lollipop"
# Traditional way
trad_count = dict()
for l in word:
if l not in trad_count:
trad_count[l] = 1
else:
trad_count[l] += 1
print(trad_count)
# An elegant way
elegant_count = dict()
for l in word:
elegant_count[l] = elegant_count.get(l, 0) + 1
print(trad_count) | true |
3ce28a5ff5d7c9f5cf2daa6a5f6f5ff955e29017 | paulocuambe/hello-python | /exercises/oop/first.py | 507 | 4.15625 | 4 | class Animal:
name = ""
def __init__(self, name):
self.name = name
print(f"\n----{self.name} Is in the creation process.----\n")
def walk(self):
"""
Walk a tiny bit
"""
print(f"{self.name} is walking...")
def __del__(self):
print(f"\n----{self.name} Is in the destruction process.-----\n")
duck = Animal("Duck")
duck.walk()
duck.walk()
duck.walk()
print(type(duck))
pig = Animal("Pig")
pig.walk()
pig.walk()
pig.walk()
pig.walk() | false |
6d44a9e3a466e1274ccdd2aa95a756a1372991d2 | paulocuambe/hello-python | /exercises/loops/min_max.py | 512 | 4.125 | 4 | maximum = minimun = None
count = 0
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
try:
number = float(user_input)
if count == 0:
maximum = number
minimum = number
elif number > maximum:
maximum = number
elif number < minimum:
minimum = number
count += 1
except:
print(" Invalid input")
print("Max:", maximum)
print("min:", minimum)
print("Count:", count) | false |
fccfaac6346eaf23b345cd2117cda259fd83ff80 | MrinaliniTh/Algorithms | /link_list/bring_last_to_fast.py | 1,663 | 4.15625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def create_link_list(self, val):
if not self.head:
self.head = Node(val)
else:
temp = self.head
while temp.next:
temp = temp.next
new_node = Node(val)
temp.next = new_node
def print_link_list(self): # O(n) time complexity
temp = self.head
data = ""
while temp is not None:
if temp.next is None:
data += str(temp.val)
temp = temp.next
else:
data += str(temp.val) + '->'
temp = temp.next
return data
def end_to_first(self):
# import pdb;pdb.set_trace()
current = self.head
while current.next.next:
current = current.next
temp = current.next
current.next = None
temp.next = self.head
self.head = temp
def end_to_first_and_remove_first_node(self):
current = self.head
while current.next.next:
current = current.next
temp = current.next
current.next = None
temp.next = self.head.next
self.head = temp
node = LinkedList()
# creation of link list
node.create_link_list(1)
node.create_link_list(2)
node.create_link_list(3)
node.create_link_list(4)
node.create_link_list(5)
node.create_link_list(6)
print(node.print_link_list())
# node.end_to_first()
# print(node.print_link_list())
node.end_to_first_and_remove_first_node()
print(node.print_link_list()) | true |
536f849236a984329df99fb2c2e286e3329c6ad4 | juliettegodyere/MIT-Electrical-Engineering-and-Computer-Science-Undergraduate-Class | /Year 1/Intro to Computer Science & Programming/Problem Sets/ps0/ps0.py | 259 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 18:13:11 2021
@author: nkworjuliet
"""
#
import math
x = int(input("Enter a value...."))
y = int(input("Enter a value...."))
pow = x**y
print(pow)
log = int(math.log(x, 2))
print(log) | false |
f6ffc7845a7a3e8c06bd5f49b01cf83115bda42f | zhujixiang1997/6969 | /7月11日/判断语句.py | 496 | 4.21875 | 4 | '''
判断程序的过程:从上到下,从左到右依次执行
判断语句:if 判断条件:
满足条件后执行的代码块
当所有条件都不满足就执行else语句,else语句只能放在最后,可以不写
判断i语句必须是if开始
chr()字符 会将数字转换成对应的ASCCII
ASCII
a=97 b=98
A=65 B=66
'''
a=float(input('请输入:'))
if a==10:
print(a,'等于10')
elif a<10:
print(a,'小于10')
else :
print(a,'大于10')
| false |
12188e2e3aab8ce6b85fbf97f24cca2e6790b6a8 | zhujixiang1997/6969 | /7月11日/类型转换.py | 433 | 4.1875 | 4 | '''
数字可以和数字直接运算
整数和字符串不能够运算
只有同类型的数据才能运算
字符串的加法运算:是拼接
整数和字符串做加法运算,除非字符串的内容是数字
我们可以将字符串转换为整数
转换方式:int(要转换的数据/变量)
将整数转换为字符串str()
'''
# a=10
# b='20'
# print(a+b)
# a=10
# #b=int('20')
# b='20'
# c=int(b)
# print(a+c)
| false |
b3f14159120e16453abdbd43687885956393e811 | TaylorWhitlatch/Python | /tuple.py | 967 | 4.3125 | 4 | # # Tuple is a list that:
# # 1. values cannot be changed
# # 2. it uses () instead of []
#
# a_tuple = (1,2,3)
# print a_tuple
#
# # Dictionaries are lists that have alpha indicies not mumerical
#
# name = "Rob"
# gender = "Male"
# height = "Tall"
#
# # A list makes no sense to tie together.
#
# person = {
# "name": "Rob",
# "gender": "Male",
# "heigt": "Tall"
# }
#
# print person
zombie = {}
zombie["weapon"] = "axe"
zombie["health"] = 100
zombie["speed"] = 10
print zombie
for key,value in zombie.items():
print "Zombie has a key of %s with a value of %s" % (key, value)
del zombie["speed"]
print zombie
is_nighttime = True
zombies = []
if(is_nighttime):
zombie["health"] +50
zombies.append({
'speed':15,
'weapon':'fist',
'name: peter'
})
zombies.append({
'speed':25,
'weapon':'knee',
'name: will',
'victims': [
'jane',
'bill',
'harry'
]
})
print zombies[1]['victims'[1]
| true |
aa15c53b44aa7e3cbdc497160964c3566a70c071 | cksgnlcjswo/open_source_sw | /midterm/account.py | 739 | 4.15625 | 4 | """
version : 1.5.0
작성자 : 김찬휘
이메일 : cksgnlcjswoo@naver.com
description : account 클래스
수정사항 : pythonic-way 적용
"""
class Account:
def __init__(self, ID, money, name):
self.ID = ID #bank number
self.balance = money #left money
self.name = name
def getID(self):
return self.ID
def deposit(self, money):
self.balance += money
def withdraw(self,money):
if(self.balance < money):
return 0
self.balance -= money
return money
def showAccountInfo(self):
print("bank account number:{}".format(self.ID))
print("name:{}".format(self.name))
print("balance:{}".format(self.balance))
return
| false |
79004d747935ebfc19599a9df859400c47120c7e | PavanMJ/python-training | /2 Variables/variables.py | 832 | 4.1875 | 4 | #!/usr/bin/python3
## All the variables in python are objects and every object has type, id and value.
def main():
print('## checking simple variables and their attributes')
n = 12
print(type(n), n)
f = 34.23
print(type(f), f)
print(f / 4)
print(f // 4)
print(round(f / 4), end = '\n\n')
print('## type casting ##')
a = int(23.33)
print(type(a), a)
b = float(324)
print(type(b), b, end = '\n\n')
print('## check immutability of objects ##')
num = 3
print('id of object {} is - '.format(num), id(num))
num = 4
print('after changing value of object to {}, id changed to {}'.format(num, id(num)))
num = 3
print('restored value of object to original value {}, now id is {}'.format(num, id(num)), end = '\n\n')
if __name__ == '__main__' : main()
| true |
fe789098e54d1a7a59573d36fc03a4da0159b552 | vuminhph/randomCodes | /reverse_linkedList.py | 969 | 4.1875 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
def add_node(self, value):
ptr = self.head
while ptr.next != None:
ptr = ptr.next
ptr.next = Node(value)
def print_list(self):
ptr = self.head
while ptr != None:
print(ptr.value)
ptr = ptr.next
def ll_reversed(linked_list):
ptr = linked_list.head
next_ptr = ptr.next
linked_list.head.next = None
while next_ptr != None:
ptr1 = ptr
ptr2 = next_ptr
next_ptr = next_ptr.next
ptr2.next = ptr1
ptr = ptr2
linked_list.head = ptr
linked_list = LinkedList(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.add_node(4)
linked_list.add_node(5)
linked_list.add_node(6)
linked_list.print_list()
ll_reversed(linked_list) | true |
c4cad7dd1e0fbd6ce87a64cbe613d1c4c1384a20 | dmitrijsg123/Problem_Solving | /Week_4_homework.py | 404 | 4.40625 | 4 |
# Enter positive integer and perform calculation on it - divide by two if even and multiply by three and add one if odd
a = int(input("Enter Positive Number: "))
while a != 1: # while 'a' not equal to one
if (a % 2) == 0: # if 'a' is even
a = a/2
elif (a % 2) != 0: # else if 'a' is odd
a = (a * 3) + 1
print(a)
| false |
a83a1d0e35bed07b1959086aff1ef4f7a872520e | rpayal/PyTestApp | /days-to-unit/helper.py | 1,232 | 4.40625 | 4 | USER_INPUT_MESSAGE = "Hey !! Enter number of days as a comma separated list:unit of measurement (e.g 20, 30:hours) " \
"and I'll convert it for you.\n "
def days_to_hours(num_of_days, conversion_unit):
calculation_factor = 0
if conversion_unit == "hours":
calculation_factor = 24
elif conversion_unit == "minutes":
calculation_factor = 24 * 60
elif conversion_unit == "seconds":
calculation_factor = 24 * 60 * 60
else:
return "Unsupported unit of measurement. Pls. pass either (hours/minutes/seconds)."
return f"{num_of_days} days are {num_of_days * calculation_factor} {conversion_unit}"
def validate_and_execute(num_of_days, conversion_unit):
try:
user_input_number = int(num_of_days)
if user_input_number > 0:
calculated_value = days_to_hours(user_input_number, conversion_unit)
print(calculated_value)
elif user_input_number == 0:
print("You entered a 0, please provide a valid positive number.")
else:
print("You entered a negative number, no conversion for you.")
except ValueError:
print("Your input is not a valid number. Don't ruin my program.")
| true |
05564cfff12bdf3b73b32f3f4c8b484046ff3d91 | PatDaoust/6.0002 | /6.0002 ps1/ps1b adapt from teacher.py | 2,717 | 4.125 | 4 | ###########################
# 6.0002 Problem Set 1b: Space Change
# Name:
# Collaborators:
# Time:
# Author: charz, cdenise
#================================
# Part B: Golden Eggs
#================================
# Problem 1
def dp_make_weight(egg_weights, target_weight, memo = {}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
#highly analogous to knapsack problem of fastMaxVal
#return smallest #eggs to make target weight = len(list of eggs)
avail_weight = target_weight
egg_weights.sort()
#TODO: figure out how to make this happen once
possible_eggs_list = [((str(egg)+" ") * int((target_weight/int(egg)))).split() for egg in egg_weights]
possible_eggs_list = [egg for egg_sublist in possible_eggs_list for egg in egg_sublist]
if avail_weight in memo:
eggs_list = memo[avail_weight]
elif avail_weight == 0 or len(egg_weights)==0:
eggs_list = [0]
elif int(possible_eggs_list [0]) > avail_weight:
eggs_list = dp_make_weight(possible_eggs_list [1:], avail_weight, memo)
else:
next_egg = int(possible_eggs_list [0])
#take next item, recursive call for next step
withVal = dp_make_weight(possible_eggs_list [1:], (avail_weight-next_egg), memo)
withVal += [next_egg]
#not take next item, recursive call for next step
withoutVal = dp_make_weight(possible_eggs_list [1:], avail_weight, memo)
#pick if take
if withVal > withoutVal:
eggs_list = [withVal] + [next_egg]
print("with")
print(possible_eggs_list)
else:
eggs_list = withoutVal
print("without")
print(possible_eggs_list)
memo[avail_weight] = eggs_list
return eggs_list
dp_make_weight([1, 5, 10, 25], 99, memo = {})
"""
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print("Egg weights = (1, 5, 10, 25)")
print("n = 99")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()
""" | true |
188c7e74ae3c05206ec4cdebd9b18fac6bc4aa1a | matrix231993/cursopython2021 | /TAREA_PYTHON/TAREA_PYTHON_1/ejercicio13.py | 269 | 4.125 | 4 | #EJERCICIO 13.- Pedir un número por teclado y mostrar la tabla de multiplicar
multi = int(input("ingrese un numero para la tabla de multiplicacion"))
m = 1
while m <= 12:
print(multi,"x", m, "=", multi*m)
m+=1
print("aqui esta la tabla de multiplicar",multi) | false |
350dc18eb4123270227f538c191dbe10a631a619 | matrix231993/cursopython2021 | /Unidad2/listas.py | 2,440 | 4.5 | 4 | # Lista en python
lista_enteros = [1,2,3,4,5] # Lista de Enteros
lista_float = [1.0,2.0,3.5,4.5,5.5] # Lista de floats
lista_cadenas = ["A","B",'C','SE',"HO"] # Lista de string
lista_general = [1, 3.5, "Cadena1", True] #Lista de tipo multiples
# 0 1 2 3
# Acceder a los elementos dde la lista: Se lo realiza mediante los indices : Posicion 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, n
print(lista_enteros[0],lista_enteros[-1])
print(lista_enteros[1],lista_enteros[-2])
print(lista_enteros[2])
# Slicing de lista en python
# Lista principal : lista_enteros
sub_lista_1 = lista_general[0:2]
sub_lista_2 = lista_general[2:]
print(sub_lista_2)
print(type(sub_lista_1))
print(sub_lista_2)
print(type(sub_lista_2))
print("--------")
print(type(lista_general))
# Operaciones con listas
#Suma "+"
impares = [1,3,5,7,9]
pares = [2,4,6,8,10]
lista_total = impares + pares
print(lista_total)
print(type(lista_total))
#Modificar los elementos de la lista
#[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
# 0 1 2
lista_total[1] = 2
lista_total[2] = 3
lista_total[3] = 4
lista_total[4] = 5
print("Mi nueva lista es : \n")
print(lista_total)
#Agregar Elementos a un lista
lista_general = [1, 3.5, "Cadena1", True, [1,2,3,4] ]
print(f"Lista Original es : {lista_general}")
lista_general.append("Darwin")
print(f"Lista Modificada es : {lista_general}")
lista_general.append("Calle")
print(f"Lista Modificada es : {lista_general}")
lista_general.append(8+15)
print(f"Lista Modificada es : {lista_general}")
lista_general.append( (8+15)* 2 + (10/2) )
print(f"Lista Modificada es : {lista_general}")
lista_nueva = [True, False]
lista_general.append( lista_nueva )
print(f"Lista Modificada es : {lista_general}")
print(len(lista_general))
print(lista_general[len(lista_general)-1])
#Vacear un lista: Borrar todos los elementos de la lista
print(f"Lista Original: \n {lista_general}")
lista_general =[]
print("Lista Vacia ", lista_general)
# Definir una cadena : "Hola mundo Python"
frase_1 = "Hola Mundo Pyhton"
# Conversion de String a lista-------> funcion list()
l = list(frase_1)
print(type(1))
print(1)
#Lista Anidadas
lista_a = [1,2,3]
lista_b = [4,5,6]
lista_c = [7,8,9]
lista_d = ['a','b','c']
#Lista anidadas
resultado = [lista_a, lista_b, lista_c, lista_d]
print("Lista Anidadas")
print(resultado)
print(resultado[0][-1])
print(resultado[1][2:])
print(resultado[2][:-1])
print(resultado[3][2:])
| false |
fb79529c283581cb63efacaacbb71932458420a6 | Lucas-Urbano/Python-for-Everybody | /Dictionarie6.py | 758 | 4.375 | 4 | Movie1 = {'Título':'Star Wars', 'ano': '1977', 'diretor': 'George Lucas'}
Movie2 = {'Título':'Indiana Jones e os salteadores da arca perdida', 'ano': '1981', 'diretor': 'Steven Spielberg'}
Movie3 = {'Título':'Matrix', 'ano': '1999', 'diretor': 'Irmãos Wachowski'}
Movie1['País'] = 'EUA' #add keys e value in a dictionary Movie1
print()
print()
print(Movie3.keys())
print()
print(Movie3.values())
print()
print(Movie3.items())
print()
print()
print(Movie1)
print('ano' in Movie1) #checking key in a dictionary
print('Velozes e Furiosos' in Movie2) #checking key in a dictionary Movie2, this search a keys
print('diretor' in Movie2) #checking key
print(Movie1.get('País', 'Informação não disponível'))
print(Movie1.get('diretor', 'Informação não disponível'))
print('Done') | false |
6df61f24bfe1e9943ac01de9eec80caad342c8a9 | rootid23/fft-py | /arrays/move-zeroes.py | 851 | 4.125 | 4 | #Move Zeroes
#Given an array nums, write a function to move all 0's to the end of it while
#maintaining the relative order of the non-zero elements.
#For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
#should be [1, 3, 12, 0, 0].
#Note:
#You must do this in-place without making a copy of the array.
#Minimize the total number of operations.
# TC : O(n)
class Solution(object):
#Iteration with trick
def moveZeroes(self, nums):
strt = 0
for i in range(len(nums)):
if (nums[i] != 0): #It moves all zeros to end and reverse condition move them to front
nums[i], nums[strt] = nums[strt], nums[i]
strt += 1
#W/ exception
def moveZeroesWithXcept(self, nums):
c = 0
while True:
try:
nums.remove(0)
c += 1
except:
nums += [0] * c
break
| true |
574f2fa0a57b335db183ee690bfe2da896c957c6 | hmlmodi/Python-Playground | /New folder/final ready game.py | 894 | 4.1875 | 4 | import random
choice = int(input('enter your choice:'))
user_choice = choice
comp_choice = random.randint(1, 3)
print(user_choice)
print(comp_choice)
logic = "TWLLTWWLT"
print(logic[(((user_choice) * 3) + (comp_choice)) ]);
# if (user_choice == 1 and comp_choice == 2) or (comp_choice == 1 and user_choice == 2):
# result = 2
# elif(user_choice==2 and comp_choice==3) or (comp_choice==2 and user_choice==3):
# result = 3
# elif(user_choice==3 and comp_choice==1) or (comp_choice==3 and user_choice==1):
# result = 1
# if result==comp_choice:
# print("computer wins")
# elif result==user_choice:
# print("you won")
# else:
# print("Tie")
# if (user_choice == comp_choice):
# print("Tie@@@")
# elif ((user_choice - comp_choice) % 3 == 1):
# print("You Won@@@")
# else:
# print("You Lose@@@") | false |
85b9bec9a1ceea4ee661b59c7efc82595e30f871 | Anand8317/food-ordering-console-app | /admin.py | 2,127 | 4.15625 | 4 | admin = {"admin":"admin"}
food = dict()
def createAdmin():
newAdmin = dict()
username = input("Enter username ")
password = input("Enter password ")
newAdmin[username] = password
if username in admin:
print("\nAdmin already exist\n")
else:
admin.update(newAdmin)
print("\nNew Admin has been created\n")
def adminLogin(username, password):
if not username in admin:
print("Account doesn't exist")
print("\n")
return False
if admin[username] == password:
print("\n")
print("Successful login")
print("\n")
return True
else:
print("\n")
print("Wrong password")
print("\n")
return False
def addFood():
newFood = dict()
foodId = id(newFood)
newFood[foodId] = ["","",0,0,0]
newFood[foodId][0] = input("Enter food name: ")
newFood[foodId][1] = input("Enter food quantity: ")
newFood[foodId][2] = int(input("Enter food price: "))
newFood[foodId][3] = int(input("Enter food discount: "))
newFood[foodId][4] = int(input("Enter the stock: "))
food.update(newFood)
print("\nFood item has been added")
print("\nFood item Id is ",foodId)
print("\n")
def editFood(foodId):
if foodId not in food:
print("\nFood id not found\n")
return
food[foodId][0] = input("Enter food name: ")
food[foodId][1] = input("Enter food quantity: ")
food[foodId][2] = int(input("Enter food price: "))
food[foodId][3] = int(input("Enter food discount: "))
food[foodId][4] = int(input("Enter the stock: "))
print("\n Food item has been edited\n")
def viewFoodItems():
i = 1
for foodId in food:
print("\n")
print(str(i) + ". " + food[foodId][0] + " (" + food[foodId][1] + ") [INR " + str(food[foodId][2]) + "]" )
i += 1
print("\n")
def delFood(foodId):
if foodId not in food:
print("\nFood id not found\n")
return
del food[foodId]
print("\nFood Item has been deleted\n") | true |
c9033580121ba38277facb1729565d15a994b8b6 | Ani-Stark/Python-Projects | /reverse_words_and_swap_cases.py | 419 | 4.15625 | 4 | def reverse_words_order_and_swap_cases(sentence):
arrSen = sentence.split()
arrSen = list(reversed(arrSen))
result = list(" ".join(arrSen))
for i in range(len(result)):
if result[i].isupper():
result[i] = result[i].lower()
else:
result[i] = result[i].upper()
return "".join(result)
res = reverse_words_order_and_swap_cases("aWESOME is cODING")
print(res)
| true |
e0857fdba34db0f114bcf7843f844aea775303e7 | Villanity/Python-Practice | /Reverse Array/Reverse_Array_while.py | 343 | 4.59375 | 5 | #Python program to reverse the array using iterations
def reverse_array (array1, start, end):
while (start<=end):
array1[start], array1[end] = array1[end], array1[start]
start += 1
end -= 1
A = [1, 2, 2 , 3, 4]
start=0
end= len(A) -1
print(A)
print("The reversed Array is: ")
reverse_array(A, start, end)
print(A)
| true |
e1b54f773e836e5508ad935765be9c56f13c5d91 | rashmika13/sei | /w07/d2/python-control-flow/exercise-instructor.py | 1,022 | 4.21875 | 4 | # color = input('Enter "green", "yellow", "red": ').lower()
# while color != 'quit':
# print(f'The user entered {color}')
# if color == 'green':
# print('Go!')
# elif color == 'yellow':
# print('Slow it doooowwwwnnnnn')
# elif color == 'red':
# print('Stop!')
# else:
# print('Bogus color!')
# color = input('Enter "green", "yellow", "red": ').lower()
# print('Goodbye')
while True:
color = input('Enter "green", "yellow", "red": ').lower()
print(f'The user entered {color}')
if (color == 'quit'):
print('Goodbye')
break
if color == 'green':
print('Go!')
elif color == 'yellow':
print('Slow it doooowwwwnnnnn')
elif color == 'red':
print('Stop!')
else:
print('Bogus color!')
""" use the if...elif...else instead
if color == 'green':
pass
if color == 'red':
pass
if color == 'yellow':
pass
if color != 'red' and color != 'yellow' and color != 'green':
pass
""" | false |
fb67e1eff16e1804ecf9c2e4ff0010962bb930c3 | guyitti2000/int_python_nanodegree_udacity | /lessons_month_one/lesson_3_FUNCTIONS/test.py | 263 | 4.21875 | 4 | def times_list(x):
x **= 2
return x
output = []
numbers = [2, 3, 4, 3, 25]
for num in numbers:
val = times_list(numbers)
print(output.append(val))
# this is supposed to iterate through a list of numbers then print out the squares
| true |
093d56467f6309b099b8e2210efe8ecaca8397eb | shanahanben/myappsample | /Portfolio/week6/article_four_word_grabber.py | 564 | 4.15625 | 4 | #!/usr/bin/python3
import random
import string
guessAttempts = 0
myPassword = input("Enter a password for the computer to try and guess: ")
passwordLength = len(myPassword)
while True:
guessAttempts = guessAttempts + 1
passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in range(passwordLength)])
print(passwordGuess)
if passwordGuess == myPassword:
print("Password guessed successfully!")
print("It took the computer %s guesses to guess your password." % (guessAttempts))
break
| true |
360b36c700983e8cddb0049dded9d78abe12b75a | steve-ryan/python-tutorial-for-beginners | /list.py | 1,226 | 4.1875 | 4 | name = ['ken','sam','antony']
list("wachira")
# split
print("hello am steve wachira." .split("ac"))
# print name
# print test
# adding list
cuzo = ['shifrah','shikoh']
cuzo.append('bilhah')
print(cuzo)
#add list .insert()
test_point = [90,87,17,56]
test_point.insert(1,50)
print(test_point)
#extend
test_point = [90,87,17,56]
test_point_2 = [12,5,8,6,31]
test_point_2.extend(test_point)
print(test_point_2)
#remove item
test_point_2 = [125,90,87,12]
test_point_2.pop()
print(test_point_2)
#remove specific index
test_point_2 = [1,2,3,4,5,6]
test_point_2.pop(3)
print(test_point_2)
#object in list
test_point_2 = [1,2,3,4,5,6]
print(60 in test_point_2) #60 not appearing on the string
print(test_point_2.count(2)) #2 appears once
print(max(test_point_2)) #maximum value on the list
print(len(test_point_2)) #length of the list
print(sum(test_point_2)) #sum of list object and works for both int & float
#A list can contain lists
marks = [67,78,50,28]
cat = [12,30,2]
total_marks = [marks,cat]
print(total_marks)
print(len(total_marks))
#accesing nested objects
print(total_marks[0][1])
#getting index of an object
marks_tips = [12,78,10]
print(marks_tips.index(78))
#sort list objects
marks_tips.sort()
print(marks_tips) | false |
106ddf889cd1ac1fb1b4e6fe1beef995982c4c31 | tajrian-munsha/Python-Basics | /python2 (displaying text and string).py | 2,391 | 4.53125 | 5 | # displaying text
#to make multiple line we can- 1.add \n in the string or, 2.use print command again and again.\n means newline.
print ("I am Shawki\n")
#we can use \t in the string for big space.\t means TAB.
print ("I am a\t student")
#we can use triple quotes outside the string for newline.For doing that,we can just press enter after ending a line into three quotes' string.
print ("""I read in class 9.
which class do you read in?""")
#we can use + between two strings under same command for displaying them jointly.
# this is called string concatenation.
print ("I am a coder."+"I am learning python.")
# we can also use comma between two string or a strind and integer/float value.
# comma give spaces automatically after each of its part.
print("I read in class",9)
#if we use single quotes in the string ,we should use double quotes outside of the string.
#if we use double quotes in the string ,we should use single quotes outside of the string.
#if we want to use extra quote in string and we want to display that quote, we need to put an \ before that quote.
print ("I love programming \" do you?")
#if we want to display \, just put it in its place.
#but some string may have words like \news, \talk,This time we have to put another \ before \.
print("I want to print\\news")
# string repetition
# we can multiply string with integer. it is called repetition.
print("Boo! "*4)
# all the work that we have done before using back-slash are called "escape sequence"
# there are lots more escape sequence.
# sequence intro
# \\ single back-slash
# \' single quote
# \" double quote
# \a ASCII Bell (BEL)
# \b ASCII Backspace (BS)
# \f ASCII Formfeed (FF)
# \n ASCII Linefeed (LF)
# \r ASCII Carriage Return (CR)
# \t ASCII Horizontal Tab (TAB)
# \v ASCII Vertical Tab (VT)
# \ooo Character with octal value ooo
# \xhh Character with hex value hh
# \N{name} Character named name in the Unicode database
# \uxxxx Character with 16-bit hex value xxxx. Exactly four hexadecimal digits are required.
# \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx. Exactly eight hexadecimal digits are required.
# to learn more, we can go to
"http://python-ds.com/python-3-escape-sequences" | true |
0812e177cd0f9b5e766f6f981b4bc1947946fa22 | akhilreddy89853/programs | /python/Natural.py | 288 | 4.125 | 4 | Number1 = int(input("How many natural numbers you want to print?"))
Count = 0
Counter = 1
print("The first " + str(Number1) + " natural numbers are", end = '')
while(Count < Number1):
print(" "+str(Counter), end = '')
Counter = Counter + 1
Count = Count + 1
print(".")
| true |
2363bdd68dbef23b937b82cce046974e847c43a4 | sunrocha123/Programas_Estudo_Python | /coeficienteBinomial.py | 668 | 4.15625 | 4 | import math
# exibição do cabeçalho
def cabecalho():
print("===================================")
print("CÁLCULO DO COEFICIENTE BINOMIAL")
print("===================================")
print('')
# cálculo do coeficiente binomial
def coeficienteBinomial(n, p):
calculo = math.factorial(n)/(math.factorial(p) * math.factorial(n - p))
return calculo
cabecalho()
n = int(input("Digite o valor de n: "))
p = int(input("Digite o valor da classe p: "))
while n <= p:
print('O valor de n, precisa ser maior ou igual a p')
n = int(input("Digite o valor de n: "))
print("O valor do coeficiente binomial é", coeficienteBinomial(n, p))
| false |
7a9ed1b59eca36822827d20359aa1b1eb9292d52 | JeRusakow/epam_python_course | /homework7/task2/hw2.py | 1,861 | 4.4375 | 4 | """
Given two strings. Return if they are equal when both are typed into
empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Examples:
Input: s = "ab#c", t = "ad#c"
Output: True
# Both s and t become "ac".
Input: s = "a##c", t = "#a#c"
Output: True
Explanation: Both s and t become "c".
Input: a = "a#c", t = "b"
Output: False
Explanation: s becomes "c" while t becomes "b".
"""
from itertools import zip_longest
from typing import Generator
def backspace_compare(first: str, second: str) -> bool: # noqa: CCR001
"""
Compares two strings as if they were printed into text editor.
Args:
first: A string which should rather be understood as a command flow.
Each letter means a key pressed, "#" means backspace.
second: The same as first
Returns:
True, if both command flow cause the same text to appear on the editor,
false otherwise
"""
def simulate_text_editor(commands: str) -> Generator[str, None, None]:
"""
Simulates text editor behaviour
Args:
commands: A flow of keys pressed. Consisits of letters and '#' signs.
'#' sign means 'Backspace' pressed.
Returns:
A generator yielding chars in text editor window in reversed order
"""
chars_to_skip = 0
for char in reversed(commands):
if char == "#":
chars_to_skip += 1
continue
if chars_to_skip > 0:
chars_to_skip -= 1
continue
yield char
for char1, char2 in zip_longest(
simulate_text_editor(first), simulate_text_editor(second)
):
if char1 != char2:
return False
return True
| true |
f226cabe15ea1b978dcb8015c040575394d90fbf | JeRusakow/epam_python_course | /tests/test_homework1/test_fibonacci.py | 1,083 | 4.125 | 4 | from homework1.task2.fibonacci.task02 import check_fibonacci
def test_complete_sequence():
"""Tests if true sequence starting from [0, 1, 1, ... ] passes the check"""
test_data = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
assert check_fibonacci(test_data)
def test_sequence_fragment():
"""Tests if true sequence not starting from [0, 1, 1, ... ] also passes the check"""
test_data = [5, 8, 13, 21, 34, 55, 89]
assert check_fibonacci(test_data)
def test_wrong_sequence():
"""Tests if a wrong sequence does not pass the test"""
test_data = [1, 1, 5, 8, 6, 3]
assert not check_fibonacci(test_data)
def test_rightful_sequence_with_wrong_beginning():
"""Tests if a sequence built with correct rules but with wrong initial values fails the check"""
test_data = [5, 6, 11, 17, 28, 45, 73]
assert not check_fibonacci(test_data)
def test_reversed_fibonacci_sequence():
"""Tests if a reversed descending sequence fails the tests"""
test_data = [89, 55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
assert not check_fibonacci(test_data)
| true |
95bdedbc353d1b86f536777b28f8fca63990d8bc | kevindurr/MOOCs | /Georgia Tech - CS1301/Test/6.py | 1,693 | 4.21875 | 4 | #Write a function called are_anagrams. The function should
#have two parameters, a pair of strings. The function should
#return True if the strings are anagrams of one another,
#False if they are not.
#
#Two strings are considered anagrams if they have only the
#same letters, as well as the same count of each letter. For
#this problem, you should ignore spaces and capitalization.
#
#So, for us: "Elvis" and "Lives" would be considered
#anagrams. So would "Eleven plus two" and "Twelve plus one".
#
#Note that if one string can be made only out of the letters
#of another, but with duplicates, we do NOT consider them
#anagrams. For example, "Elvis" and "Live Viles" would not
#be anagrams.
#Write your function here!
def are_anagrams(s1, s2):
s1, s2 = s1.lower(), s2.lower()
charArray = {}
for char in s1:
if not char.isalpha():
continue
if char not in charArray:
charArray[char] = 0
charArray[char] += 1
for char in s2:
if not char.isalpha():
continue
if char not in charArray:
return False
charArray[char] -= 1
for v in charArray.values():
if v != 0:
return False
return True
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: True, False, True, False, each on their own line.
print(are_anagrams("Elvis", "Lives"))
print(are_anagrams("Elvis", "Live Viles"))
print(are_anagrams("Eleven plus two", "Twelve plus one"))
print(are_anagrams("Nine minus seven", "Five minus three"))
| true |
622b856988a7621b09fca280ba2564a593df37e1 | kevindurr/MOOCs | /Georgia Tech - CS1301/Objects & Algos/Algos_5_2/Problem_Set/5.py | 1,403 | 4.375 | 4 | #Write a function called search_for_string() that takes two
#parameters, a list of strings, and a string. This function
#should return a list of all the indices at which the
#string is found within the list.
#
#You may assume that you do not need to search inside the
#items in the list; for examples:
#
# search_for_string(["bob", "burgers", "tina", "bob"], "bob")
# -> [0,3]
# search_for_string(["bob", "burgers", "tina", "bob"], "bae")
# -> []
# search_for_string(["bob", "bobby", "bob"])
# -> [0, 2]
#
#Use a linear search algorithm to achieve this. Do not
#use the list method index.
#
#Recall also that one benefit of Python's general leniency
#with types is that algorithms written for integers easily
#work for strings. In writing search_for_string(), make sure
#it will work on integers as well -- we'll test it on
#both.
#Write your code here!
def search_for_string(lst, target):
indexes = []
for i in range(len(lst)):
if target == lst[i]:
indexes.append(i)
return indexes
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print: [1, 4, 5]
sample_list = ["artichoke", "turnip", "tomato", "potato", "turnip", "turnip", "artichoke"]
print(search_for_string(sample_list, "turnip"))
| true |
a7b544425be8d629667975fc19983028bbe51136 | Ebi-aftahi/Files_rw | /word_freq.py | 735 | 4.125 | 4 | import csv
import sys
import os
file_name = input();
if not os.path.exists(file_name): # Make sure file exists
print('File does not exist!')
sys.exit(1) # 1 indicates error
items_set = []
with open(file_name, 'r') as csvfile:
csv_reader = csv.reader(csvfile, delimiter=',') # Returns lines in a list
for row in csv_reader:
[items_set.append(item) for item in row if item not in items_set]
# print(row)
# print(items_set)
for item in items_set:
print('{} {}'.format(item, row.count(item)))
# better method:
# for row in csv_reader:
# items_set = set(row)
# or
## for row in csv_reader:
# items_list = list(set(row))
| true |
7bb3dc041d323337163fab2cf5a19ef6e97c94c2 | DharaniMuli/PythonAndDeepLearning | /ICPs/ICP-3/Program1_e.py | 1,627 | 4.21875 | 4 | class Employee:
data_counter = 0
total_avg_salary = 0
total_salary = 0
# List is a class so I am creating an object for class
mylist = list()
def __init__(self, name, family, salary, department):
self.empname = name
self.empfamily = family
self.empsalary = salary
self.empdepartment = department
self.datamemberdefination()
# Append is a method in the list class so calling using list object
# Storing all the salaries into list
self.mylist.append(self.empsalary)
Employee.total_salary = Employee.total_salary + self.empsalary
def datamemberdefination(self):
Employee.data_counter = Employee.data_counter + 1
def avg_salary(self):
Employee.total_avg_salary = Employee.total_salary / Employee.data_counter
# This is a derived class 'FulltimeEmployee' inheriting base class 'employee'
class FulltimeEmployee(Employee):
maxsalary =0
def __init__(self, name, family, salary, department):
Employee.__init__(self, name, family, salary, department)
def highestsalary(self):
#Access base class list object
list1= Employee.mylist
# Finding Max salary
maxsalary = max(list1)
return maxsalary
if __name__ == '__main__':
e = Employee("Rani", "M", 2, "Developer")
f1 = FulltimeEmployee("Nani", "K", 3, "DataScientist")
#Access base class method
f1.avg_salary()
print("Average of Salary:",Employee.total_avg_salary)
f1.highestsalary()
#Access Derived class method
print("Highest Salary:",f1.highestsalary()) | true |
df79f1a4a72a30fe40de567859db42fbb44e8f5d | echedgy/prg105fall | /3.3 Nested Ifs.py | 1,247 | 4.21875 | 4 | package = input("Which package do you have? (A, B, C): ")
print("You entered Package " + package)
minutes_used = int(input("How many minutes did you use this month? "))
package_price = 0.0
if package == "A" or package == "a":
package_price = 39.99
if minutes_used > 450:
additional_minutes = minutes_used - 450
minutes_cost = additional_minutes * .45
total_cost = package_price + minutes_cost
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(total_cost, ',.2f'))
else:
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(package_price, '.2f'))
elif package == "B" or package == "b":
package_price = 59.99
additional_minutes = minutes_used - 900
minutes_cost = additional_minutes + .40
total_cost = package_price + minutes_cost
print("With package " + package + " and " + str(minutes_used) + " minutes used, you owe: $" + format(total_cost, '2.f'))
elif package == "C" or package == "c":
package_price = 69.99
print("With package " + package + " you owe: $" + format(package_price, ' .2f'))
else:
print("That is not a valid package.")
| true |
93746c4f02729852c13d04b1de64a729a6a07dd8 | echedgy/prg105fall | /11.2 Production Worker.py | 816 | 4.28125 | 4 | # Once you have written the classes, write a program that creates an object of the ProductionWorker class and prompts
# the user to enter data for each of the object’s data attributes.
# Store the data in the object and then use the object’s accessor methods to retrieve it and display it on the screen.
import employee
def main():
name = input("Employee's name: ")
number = input("Employees's number: ")
shift = input("Employees's Shift: ")
pay = input("Employee's pay rate: ")
new_employee = employee.ProductionWorker(name, number, shift, pay)
print("\nEmployee name: " + new_employee.get_employee_name() + "\nEmployee Number: " + new_employee.get_employee_number() + "\nShift: " + new_employee.get_shift() + "\nPay Rate: " + new_employee.get_pay_rate())
main()
| true |
112a19946aef220606d17f2f547e67a58da7da03 | echedgy/prg105fall | /2.3 Ingredient Adjuster.py | 1,089 | 4.46875 | 4 | # A cookie recipe calls for the following ingredients:
# 1.5 cups of sugar
# 1 cup of butter
# 2.75 cups of flour
# The recipe produces 48 cookies with this amount of ingredients. Write a program that asks the user
# how many cookies they want to make, and then displays the number of cups
# (to two decimal places) of each ingredient needed for the specified number of cookies.
COOKIE_NUMBER = 48
cupsOfSugar_cookie_num = 1.5/COOKIE_NUMBER
cupsOfButter_cookie_num = 1/COOKIE_NUMBER
cupsOfFlour_cookie_num = 2.75/COOKIE_NUMBER
userNumber_of_cookies = int(input('How many cookies do you want to make? '))
print("For " + str(userNumber_of_cookies) + " cookies, you will need")
expectedCupsOfSugar = userNumber_of_cookies * cupsOfSugar_cookie_num
expectedCupsOfButter = userNumber_of_cookies * cupsOfButter_cookie_num
expectedCupsOfFlour = userNumber_of_cookies * cupsOfFlour_cookie_num
print(format(expectedCupsOfSugar, ".2f") + " cups of sugar, " + format(expectedCupsOfButter, ".2f") + " cups of butter and " + format(expectedCupsOfFlour, ".2f") + " cups of flour")
| true |
08e291f0d7343d98f559e10755ac64ebf74d652c | varaste/Practice | /Python/PL/Python Basic-Exercise-6.py | 1,064 | 4.375 | 4 | '''
Python Basic: Exercise-6 with Solution
Write a Python program which accepts a sequence of comma-separated numbers
from user and generate a list and a tuple with those numbers.
Python list:
A list is a container which holds comma separated values (items or elements)
between square brackets where items or elements need not all have the same type.
In general, we can define a list as an object that contains multiple data items
(elements). The contents of a list can be changed during program execution.
The size of a list can also change during execution, as elements are added or
removed from it.
Python tuple:
A tuple is container which holds a series of comma separated values
(items or elements) between parentheses such as an (x, y) co-ordinate.
Tuples are like lists, except they are immutable (i.e. you cannot change its
content once created) and can hold mix data types.
'''
vals = input("Enter values comma seprated: ")
v_list = vals.split(",")
v_tuple = tuple(v_list)
print("List: ", v_list)
print("Tuple ", v_tuple) | true |
6fdf3e5c757f7de27c6afb54d6728116d9f3ae55 | varaste/Practice | /Python/PL/Python Basic-Exercise-4.py | 553 | 4.3125 | 4 | '''
Write a Python program which accepts the radius of a circle from the user and
compute the area.
Python: Area of a Circle
In geometry, the area enclosed by a circle of radius r is πr2.
Here the Greek letter π represents a constant, approximately equal to 3.14159,
which is equal to the ratio of the circumference of any circle to its diameter.
'''
from math import pi
rad = float(input("Input the radius of the circle: "))
a_circle = (rad**2) * pi
print("The area of the cirvle with radius" + str(rad) + " is: " + str(a_circle)) | true |
0173ae9e82213f4f01ccc6239a152b7ad0c5f8ad | varaste/Practice | /Python/PL/Python tkinter widgets-Exercise-8.py | 756 | 4.21875 | 4 | '''
Python tkinter widgets: Exercise-8 with Solution
Write a Python GUI program to create three single line text-box to accept a
value from the user using tkinter module.
'''
import tkinter as tk
parent = tk.Tk()
parent.geometry("400x250")
name = tk.Label(parent, text = "Name").place(x = 30, y = 50)
email = tk.Label(parent, text = "User ID").place(x = 30, y = 90)
password = tk.Label(parent, text = "Password").place(x = 30, y = 130)
sbmitbtn = tk.Button(parent, text = "Submit", activebackground = "green", activeforeground = "blue").place(x = 120, y = 170)
entry1 = tk.Entry(parent).place(x = 85, y = 50)
entry2 = tk.Entry(parent).place(x = 85, y = 90)
entry3 = tk.Entry(parent).place(x = 90, y = 130)
parent.mainloop()
| true |
285451e05017f8598ff68eb73ae537ca2e0922a5 | varaste/Practice | /Python/PL/Python Basic-Exercise-27-28-29.py | 1,554 | 4.1875 | 4 | '''
Python Basic: Exercise-27 with Solution
Write a Python program to concatenate all elements in a list into a string and return it.
'''
def concat(list):
output = ""
for element in list:
output = output + str(element)
return output
print(concat([1, 4, 0, 0,"/" , 0, 7,"/" ,2, 0]))
'''
Python Basic: Exercise-28 with Solution
Write a Python program to print out all even numbers from a given numbers list
in the same order and stop the printing if any numbers that come after 237 in
the sequence.
'''
numbers_list = [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]
for n in numbers_list:
if n == 237:
print (n)
break;
elif n % 2 == 0:
print(n)
'''
Python Basic: Exercise-29 with Solution
Write a Python program to print out a set containing all the colors from
color_list_1 which are not present in color_list_2.
Test Data:
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
Expected Output :
{'Black', 'White'}
'''
list1 = set(["White", "Black", "Red"])
list2 = set(["Red", "Green"])
def is_in_color_list(list1, list2):
output_list = list1.difference(list2)
return output_list
print(is_in_color_list(list1, list2))
print(is_in_color_list(list2, list1))
| true |
0ed76e4bb935107504ffed0f3b77804d7f42cdc2 | varaste/Practice | /Python/PL/Python tkinter widgets-Exercise-7.py | 688 | 4.21875 | 4 | '''
Python tkinter widgets: Exercise-7 with Solution
Write a Python GUI program to create a Text widget using tkinter module.
Insert a string at the beginning then insert a string into the current text.
Delete the first and last character of the text.
'''
import tkinter as tk
parent = tk.Tk()
# create the widget.
mytext = tk.Text(parent)
# insert a string at the beginning
mytext.insert('1.0', "- Python exercises, solution -")
# insert a string into the current text
mytext.insert('1.19', ' Practice,')
# delete the first and last character (including a newline character)
mytext.delete('1.0')
mytext.delete('end - 2 chars')
mytext.pack()
parent.mainloop() | true |
3604cfb0531dd9798b43facc91326533df969594 | michalkasiarz/automate-the-boring-stuff-with-python | /lists/multipleAssignmentSwap.py | 261 | 4.21875 | 4 | # Multiple assignment - swap
a = "AAA" # a is AAA
b = "BBB" # b is BBB
print("a is " + a)
print("b is " + b)
print()
# swap
a, b = b, a # a is now b, i.e. a = BBB, and b = AAA
print("a is " + a) # a is BBB
print("b is " + b) # b is AAA
| false |
897a1b3f11bc3f0352e61ed6802094bd6c341729 | michalkasiarz/automate-the-boring-stuff-with-python | /regular-expressions/usingQuestionMark.py | 499 | 4.125 | 4 | import re
# using question mark -> for something that appears 1 or 0 times (preceding pattern)
batRegex = re.compile(r"Bat(wo)?man")
mo = batRegex.search("The Adventures of Batman")
print(mo.group()) # Batman
mo = batRegex.search("The Adventures of Batwoman")
print((mo.group())) # Batwoman
# another example with ? inside pattern
dinRegex = re.compile(r"dinner\?") # we are looking for dinner?
mo = dinRegex.search("Do you fancy a dinner? Because he does not. So sad.")
print(mo.group())
| true |
9393e65692d8820d71fdda043da48ec33658b467 | michalkasiarz/automate-the-boring-stuff-with-python | /dictionaries/dataStructures.py | 686 | 4.125 | 4 | # Introduction to data structure
def printCats(cats):
for item in cats:
print("Cat info: \n")
print("Name: " + str(item.get("name")) +
"\nAge: " + str(item.get("age")) +
"\nColor: " + str(item.get("color")))
print()
cat = {"name": "Parys", "age": 7, "color": "gray"}
allCats = [] # this is going to be a list of dictionaries
allCats.append({"name": "Parys", "age": 7, "color": "gray"})
allCats.append({"name": "Burek", "age": 5, "color": "white"})
allCats.append({"name": "Mruczek", "age": 12, "color": "black"})
allCats.append({"name": "Fajter", "age": 2, "color": "black-white"})
printCats(allCats)
| true |
c795f6ac170f96b398121ddbbc9a22cf13835061 | AshwinBalaji52/Artificial-Intelligence | /N-Queen using Backtracking/N-Queen_comments.py | 2,940 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 00:42:23 2021
@author: Ashwin Balaji
"""
class chessBoard:
def __init__(self, dimension):
# board has dimensions dimension x dimension
self.dimension = dimension
# columns[r] is a number c if a queen is placed at row r and column c.
# columns[r] is out of range if no queen is place in row r.
# Thus after all queens are placed, they will be at positions
# (columns[0], 0), (columns[1], 1), ... (columns[dimension - 1], dimension - 1)
self.columns = []
def matrixdimension(self):
return self.dimension
def evaluateQueens(self):
return len(self.columns)
def backtrackNextRow(self, column):
self.columns.append(column)
def popQueen(self):
return self.columns.pop()
def isSafe(self, column):
# index of next row
row = len(self.columns)
# check column
for queeninColumn in self.columns:
if column == queeninColumn:
return False
# check diagonal
for queeninRow, queeninColumn in enumerate(self.columns):
if queeninColumn - queeninRow == column - row:
return False
# check other diagonal
for queeninRow, queeninColumn in enumerate(self.columns):
if ((self.dimension - queeninColumn) - queeninRow
== (self.dimension - column) - row):
return False
return True
def display(self):
for row in range(self.dimension):
for column in range(self.dimension):
if column == self.columns[row]:
print('Q', end=' ')
else:
print('.', end=' ')
print()
def displaySolutions(dimension):
"""Display a chessboard for each possible configuration of placing n queens
on an n x n chessboard where n = dimension and print the number of such
configurations."""
board = chessBoard(dimension)
possibleSolutions = solutionBacktracker(board)
print('Number of solutions:', possibleSolutions)
def solutionBacktracker(board):
"""Display a chessboard for each possible configuration of filling the given
board with queens and return the number of such configurations."""
dimension = board.matrixdimension()
# if board is full, display solution
if dimension == board.evaluateQueens():
board.display()
print()
return 1
possibleSolutions = 0
for column in range(dimension):
if board.isSafe(column):
board.backtrackNextRow(column)
possibleSolutions += solutionBacktracker(board)
board.popQueen()
return possibleSolutions
size = int(input('Dimensions : '))
displaySolutions(size) | true |
dee277547fa6e80610a419c7285ff2074e0078cf | tejadeep/Python_files | /tej_python/basics/add.py | 287 | 4.28125 | 4 | #program by adding two numbers
a=10
b=20
print"%d+%d=%d"%(a,b,a+b) #this is one method to print using format specifiers
print"{0}+{1}={2}".format(a,b,a+b) #this is one method using braces
#0 1 2
print"{1}+{0}={2}".format(a,b,a+b) # here output is 20+10=30
| true |
0ddac05ddceaa96fc1a31d35d43e91bedd70dc8e | dannikaaa/100-Days-of-Code | /Beginner Section/Day2-BMI-Calulator.py | 418 | 4.3125 | 4 | #Create a BMI Calculator
#BMI forumula
#bmi = weight/height**2
height = input("Enter your height in m: ")
weight = input("Enter your weight in kg: ")
#find out the type of height & weight
#print(type(height))
#print(type(weight))
#change the types into int & float
int_weight = int(weight)
float_height = float(height)
#change bmi type as well
bmi = int_weight/float_height**2
int_bmi = int(bmi)
print(int_bmi)
| true |
2c36c65ec38d2c8a3806e962804ec927353d0be4 | v0001/python_jw | /Basic/repeat test/repear test_exam5 copy.py | 789 | 4.1875 | 4 | # 삼각형의 밑변의 길이와 높이를 입력받아 넓이를 출력하고, "Continue? "에서 하나의 문자를 입력받아 그 문자가 'Y' 나 'y' 이면 작업을 반복하고 다른 문자이면 종료하는 프로그램을 작성하시오.
# (넓이는 반올림하여 소수 첫째자리까지 출력한다.)
# a = 'y'
# while(a.upper() == 'Y'):
# # b = input().strip().split()
# # Base = int(b[0])
# # Height = int(b[1])
# Base = int(input("Base = "))
# Height = int(input("Height = "))
# print("Triangle width =", Base*Height/2)
# a= input("Continue? ").uppper()
a = 'y'
while(a.upper() == 'Y'):
Base = int(input("Base ="))
Height = int(input("Height ="))
print("Triangle width =", Base*Height/2)
a= input("Continue? ") | false |
3fd9c30f76f11696abac88e60cc1ce28c212b729 | akashbhalotia/College | /Python/Assignment1/012.py | 554 | 4.25 | 4 | # WAP to sort a list of tuples by second item.
# list1.sort() modifies list1
# sorted(list1) would have not modified it, but returned a sorted list.
def second(ele):
return ele[1]
def sortTuples(list1):
list1.sort(key=second)
inputList = [(1, 2), (1, 3), (3, 3), (0, 3), (3, 5), (7, 2), (5, 5)]
print('Input List:', inputList)
sortTuples(inputList)
print('\nSorted:', inputList)
###########################################################################
# Another way to do it:
def sortTuples(list1):
list1.sort(key=lambda x: x[1])
| true |
c52de657a3ae4643f627703138e86bc03d8383dc | momentum-cohort-2019-02/w3d3-oo-pig-yyapuncich | /pig.py | 2,594 | 4.15625 | 4 | import random
class ComputerPerson:
"""
Computer player that will play against the user.
"""
def __init__(self, name, current_score=0):
"""
Computer player will roll die, and automatically select to roll again or hold for each turn. They will display their turn totals after each turn.
"""
self.name = name
self.current_score = current_score
def roll_die(self):
"""
Roll dice for random result range 1-6. Return the number.
"""
return random.randint(1, 6)
def current_score(game, turn_total):
"""
Keep track of the player's total score by adding all the turn_total values as the game progresses
"""
pass
def choose():
"""
Returns value of hold or roll depending on random choice.
"""
choices = ['HOLD', 'ROLL']
return random.choice(choices)
class PersonPerson:
"""
Human player that will play against computer. They will choose by user input each turn to roll, or hold. Score totals will display after each turn.
"""
def __init__(self, name, current_score=0):
self.name = name
self.current_score = current_score
def roll_die(self):
"""
Roll dice for random result range 1-6. Return the number.
"""
return random.randint(1, 6)
def current_score(game, turn_total):
"""
Keep track of the player's total score by adding all the turn_total values as the game progresses
"""
pass
def choose():
"""
Returns value of hold or roll depending on user input.
"""
pass
class Game:
"""
Controls the flow of the game: keeps track of scores, who's turn it is, who wins, and if you want to play again. The goal is to reach 100 points.
"""
def __init__(self, comp_player, pers_player, current_winner):
# self.current_player = None
self.current_winner = None
# self.choose = None
self.comp_player = comp_player
self.pers_player = pers_player
def begin_game(self):
"""
Allow PersonPerson and CompterPerson to roll die. The largest number gets to go first and roll!
"""
pass
def turn_total(dice_roll):
"""
For each turn the player will roll dice. If they don't roll a 1 they will add all the numbers for a turn_total. Otherwise add 0 to the turn_total
"""
pass
if __name__ == "__main__":
print(Game.roll_die())
print(ComputerPerson.choose()) | true |
10acda48e124a1de9ed342e17e4987b5f766e39e | ZakirovRail/GB_Python_Faculty | /1_quarter/Python_basic/Basic_course_Lesson_1/Basic_course_Lesson_1_5_HW_Rail_Zakirov.py | 1,310 | 4.28125 | 4 | """
5. Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает
фирма (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке).
Далее запросите численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
"""
# profit = int(input('Enter a value of profit: '))
# expenses = int(input('Enter a value of expenses: '))
#
# if profit > expenses:
# print('You work with profit')
# elif profit< expenses:
# print('You work at a loss')
# else:
# print('Your profit is 0')
#
# if profit > expenses:
# print('Your profitabilty is: ', profit/expenses)
# number_of_employees = int(input('Enter a number of your employees: '))
# print('The profit per employee is:', profit/number_of_employees)
| false |
b91fa84d9b4c884a9352139ac4f13742ef577212 | ZakirovRail/GB_Python_Faculty | /1_quarter/Python_basic/Basic_course_Lesson_3/Basic_course_Lesson_3_2_HW_Rail_Zakirov.py | 1,294 | 4.34375 | 4 | """
2) Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя,
фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы.
Реализовать вывод данных о пользователе одной строкой.
"""
# def user_data(name, surname, birth_year, city_living, email, phone):
# print(f'The user {name} {surname} was born in {birth_year} year, lives in {city_living} city. '
# f'Contacts: email - {email} and phone number - {phone} ')
#
#
# user_data(name='Mike', surname='Suvorov', birth_year='1985', city_living='Mexico', email='test@gmail.com',
# phone='+11534225665')
#Solution from teacher
def personal_info(**kwargs):
return kwargs
print(personal_info(
name=input('Name: '),
surname=input('Surname: '),
birthday=input('BD: '),
city=input('City: '),
email=input('Email: '),
phone=input('Phone number: ')
))
personal_info(name='Mike', surname='Suvorov', birth_year='1985', city_living='Mexico', email='test@gmail.com',
phone='+11534225665')
| false |
b6d518a4d5c829045cc4b19c1a0630422cf38050 | SwethaVijayaraju/Python_lesson | /Assignments/Loops/Biggest number divisible.py | 522 | 4.25 | 4 | #write a function that returns the biggest number divisible by a divisor within some range.
def biggest(num1,num2,divisor):
bignum=None
while num1<=num2:
if (num1%divisor)==0:
bignum=num1
num1=num1+1
return bignum
print(biggest(1,10,2)) #answer should be 10
#write a function that returns the biggest number divisible by a divisor within some range.
def biggest(num1,num2,divisor):
while num2>=num1:
if (num2%divisor)==0:
return num2
num2=num2-1
print(biggest(1,10,2)) #answer should be 10
| true |
0c303b2ae10529b5cfa2ec2e5896c5b6d7507303 | SwethaVijayaraju/Python_lesson | /Assignments/Loops/Palindrome.py | 549 | 4.15625 | 4 | # check if the given string is palindrome or not #a="swetha" then a[0] equals 's'
def reverse(word):
length = len(word)
final = ""
for a in word:
final = final + word[length - 1]
length = length - 1
return final
def palindrome(word):
return word == reverse(word)
print(palindrome("bob"))
print(palindrome("malayalam"))
print(palindrome("noon"))
print(palindrome("goat"))
print(palindrome("engineer"))
# find the reverse of a string 'swetha' to 'ahtews'
print(reverse("swetha"))
print(reverse("malayalam"))
| false |
3a160588ec768a4c94929f6c4f8e0174af9946b5 | gkabbe/MiniPython | /15.11.2016/4_bool.py | 2,846 | 4.15625 | 4 | """Boolesche Ausdrücke und if-Statements
Bisher waren unsere Programme noch recht simpel gestrickt und waren nicht in der Lage, mehr als ein
gewöhnlicher Taschenrechner zu machen.
Hier wird nun gezeigt, wie man ein Programm schreibt, das gewissermaßen Entscheidungen treffen kann,
d.h. auf unterschiedliche Situationen unterschiedlich reagiert.
Zuerst müssen wir dafür Boolesche Ausdrücke verstehen. Das sind "Aussagen", die entweder wahr
(True) oder falsch (False) sind.
Ein if-Statement erlaubt uns dann, anhand eines Booleschen Ausdrucks zu entscheiden, wie sich das
Programm im weiteren Verlauf verhält.
"""
# Boolesche Ausdrücke
print(4 + 4 == 8)
# Hier wurde der Vergleichsoperator "==" benutzt. Er vergleicht den Wert der linken und der rechten
# Seite und gibt True zurück wenn beide Seiten gleich sind. Ansonsten False
# Wie immer können wir das Ergebnis in einer Variablen speichern:
boolescher_wert = 4 + 4 == 8
print(boolescher_wert)
# Es gibt noch weitere Vergleichsoperatoren:
# kleiner/größer:
print("3 + 3 < 7 ->", 3 + 3 < 7)
print("4 + 4 > 10 ->", 4 + 4 > 10)
# kleiner gleich / größer gleich:
print("4 <= 5 ->", 4 <= 5)
print("8 >= 8 ->", 8 >= 8)
# ungleich:
print("3 + 3 != 12 ->", 3 + 3 != 12)
# Darüberhinaus gibt es die booleschen Operatoren "and", "or" und "not":
# "and" gibt genau dann True zurück wenn beide Argumente True sind, ansonsten False
print("True and False ->", True and False)
print("True and True ->", True and True)
print("False and False ->", False and False)
# "or" gibt genau dann True zurück wenn mindestens eines der beiden Argumente True ist, ansonsten
# False
print("True or False ->", True or False)
print("False or False ->", False or False)
print("usw.")
# Statt direkt True oder False zu benutzen, können wir natürlich auch einen booleschen Ausdruck
# verwenden
x =
print("Liegt x zwischen 0 und 10?")
print(x > 0 and x < 10)
# Wir können nun ein if - Statement benutzen, um einen booleschen Ausdruck auszuwerten und dann
# zu entscheiden, wie der weitere Programmablauf ist:
x =
print("x =", x)
print("Liegt x zwischen 0 und 10?")
if 0 < x < 10:
print("Ja!")
else:
print("Nein")
# Wenn es mehr als zwei mögliche Entscheidungen gibt, kann man elif verwenden:
punkte =
if punkte >= 90:
print("Sehr gut!")
elif punkte >= 80:
print("Gut")
elif punkte >= 70:
print("Befriedigend")
elif punkte >= 60:
print("Ausreichend")
else:
print("Durchgefallen...")
# Aufgabe 1: Schreiben Sie ein Programm, das entscheidet, ob die Variable x durch 3 teilbar ist
# Aufgabe 2:
# Gegeben seien die Variablen
# student_motiviert = True
# student_ausgeschlafen = False
# unterricht_spannend = True
# Welchen Wert hat python lernerfolg = student_ausgeschlafen or (student_motiviert and unterricht_spannend) ?
| false |
db73a48731ed073e252d56eedc05c98588ba1675 | jayednahain/python-Function | /function_mix_calculation.py | 386 | 4.15625 | 4 |
def addition(x,y):
z=x+y
return print("the addtion is: ",z)
def substruction(x,y):
z=x-y
return print("the substruction is : ",z)
def multiplication(x,y):
z=x*y
return print("the multiplication is :",z)
a = int(input("enter a number one : "))
b = int(input("enter second number: "))
addition(a,b)
multiplication(a,b)
substruction(a,b) | true |
c1d1bcd4a998a60f8f0b73df988e2984337810b5 | eudys07/PythonKata | /Collections/Dictionary_implementation.py | 1,744 | 4.125 | 4 | #Dictionary
print
print 'Creating new Dictionary'
print
dict1 = {'name':'Eudys','lastname':'Bautista','age':31}
dict2 = dict([('name','Aynel'),('lastname','Bautista'),('age',28)])
dict3 = dict(name='Eliel',lastname='Garcia',age=32)
print 'dict1: '
print dict1
print 'dict2: '
print dict2
print 'dict3: '
print dict3
print
print 'Dictionary operations: '
print
print
print 'Adding or change item in dic2: '
print 'dict2[age] = 29: '
print dict2['age']
dict2['age'] = 29
print ''
print 'dict2: ', dict2
print
print
print 'deleting item in the list'
del dict2['age']
print ''
print 'dict2: ', dict2
print
print
print 'dict len'
print ''
print 'len(dict2): ', len(dict2)
print
print
print 'checking membership in dict2'
print ''
print '(name, Aynel) in dict2: ', ('name', 'Aynel') in dict2
print ''
print '(name, Aynel) not in dict2: ', ('name', 'Aynel') not in dict2
print
print
print 'clearing dict2'
print ''
print 'dict2.clear(): ', dict2.clear()
print
print 'dict2: ', dict2
print
print
print
print 'ACCESSING KEYS AND VALUES IN A DICT'
print
print 'Return list of keys in dict1'
print 'dict1.keys(): ', dict1.keys()
print
print
print 'Return list of values in dict1'
print 'dict1.values(): ', dict1.values()
print
print
print 'Return list of key-value tuple pairs in dict1'
print 'dict1.items(): ', dict1.items()
print
print
print 'Checking membership in dict1: '
print 'Eudys in dict1.values(): ', 'Eudys' in dict1.values()
print
print
print
print 'ITERATING A DICT'
print
print 'Iterate keys and print all key-value pairs: '
for key in dict1:
print 'printing key-value: ', (key, dict1[key])
print
print 'Iterate key/value pairs: '
for key, value in dict1.items():
print 'printing key-value: ', (key, value)
print | false |
edebe64f2a8f06539214fc7e2771e56a73130405 | Abijithhebbar/abijith.hebbar | /cspp1/m22 exam/assignment3/tokenize.py | 1,107 | 4.21875 | 4 | '''
Write a function to tokenize a given string and return a dictionary with the frequency of
each word
'''
# output_dictionary = {}
def tokenize(string_input):
"""Tokenize function"""
output_dictionary = {}
new_string = ''
for word in string_input:
if word not in "`~!@#$%^&*()_+=.,;-\''":
if word not in '"':
new_string += word
list_input = new_string.split()
for word in list_input:
if word in output_dictionary:
output_dictionary[word] += 1
else:
output_dictionary.update({word:1})
return output_dictionary
# for key in list_input:
# key = re.sub('[^a-zA-z0-9]', '', key)
# if key not in output_dictionary:
# output_dictionary[key] = 1
# else:
# output_dictionary[key] += 1
def main():
"""main function"""
number_of_lines = int(input())
string_input = ""
for _ in range(0, number_of_lines, 1):
string_input += input()
tokenize(string_input)
print(tokenize(string_input))
if __name__ == '__main__':
main()
| false |
7a3c29e08029bdbfd42dbda0b6cc6c22144d01c8 | Nate-17/LetsUpgrade-Python | /primenumber.py | 444 | 4.28125 | 4 | '''
This is a module to check weather the given number is even or odd.''
'''
def prime(num):
'''
This is the main function which check out the given number is even or odd.
'''
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
return print("It is a Prime Number")
return print("It is not a Prime Number")
n = int(input("enter the number :"))
prime(n)
| true |
481c5bf7331c477e037b13df745ebd49dfeed605 | Zeranium/PythonWorks | /Ch06/p157.py | 371 | 4.21875 | 4 | """
날짜 : 2021/02/25
이름 : 장한결
내용 : 교재 p157 - self 명령어 예
"""
class multiply3:
def data(self, x, y):
self.x = x
self.y = y
def mul(self):
result = self.x * self.y
self.display(result)
def display(self, result):
print('곱셈 = %d' % (result))
obj = multiply3()
obj.data(10, 20)
obj.mul() | false |
686c1f0c8ebec7caade9bd99e8c45b5581e421e1 | SweetLejo/DATA110 | /past_exercises_leo/yig012_t2.py | 1,562 | 4.28125 | 4 | #Oppgave 1
from math import pi #imports pi from the math library, since its the only thing I'll use in this exercise it felt redundant to import the whole library
radius = float(input('Radius: ')) #promts the user to enter a radius
area = round((radius**2)*pi, 3) #defines a variable as the area, and rounds it to 3 decimals
print(area)
#oppgave 2
sentance = input('sentance: ') #prompts user to enter a sentance
guess = int(input('Guess: ')) #prompts the user to guess the length of his sentance, and converts it to the data-type int
sentance = sentance.replace(' ', '') #removes whitespace (' ') so that the length does not include it (len('hej jeg er glad') -> 12 (not 15), could also be done with commas etc
#Line 12 is not a part of the exercise but I felt it made sense so why not :D
print(f"That's {len(sentance) == guess}!!") #prints a f-string with a bool, hence True or False
#Personally I would've solved this using conditional execution btw
#oppgave 3
from random import randint #Same logic as in 1
number = input('Give me a number: ') #Prompts user to enter a number (this is already a string)
rnumber= str(randint(1, 10)) #new variable is a random number between 1-10 (has to be a string so that 1+2 = 12 (see line 20))
answer = int(number+rnumber)/int(number) #finds the answer of the sum of the two strings given above divided by the old number (convertet to ints (answer is float))
print(number+rnumber, '/', number,' = ', answer, sep='') #print, removed whitespace beacuase that's what it looked like in the exercise | true |
fac04373d57b33f9dd8298e01aaf36f0ebb3fb75 | wonderme88/python-projects | /src/revstring.py | 285 | 4.40625 | 4 |
# This program is to reverse the string
def revStr(value):
return value[::-1]
str1 = "my name is chanchal"
str2 = "birender"
str3 = "chanchal"
#print revStr(str1)
list = []
list.append(str1)
list.append(str2)
list.append(str3)
print (list)
for x in list:
print revStr(x)
| true |
e10a0af7adca68109ebeb211ad994b2877c5a52d | EugenieFontugne/my-first-blog | /test/python_intro.py | 835 | 4.125 | 4 | volume = 18
if volume < 20:
print("It's kinda quiet.")
elif 20 <= volume < 40:
print("It's nice for background music")
elif 40 <= volume < 60:
print("Perfect, I can hear all the details")
elif 60 <= volume < 80:
print("Nice for parties")
elif 80 <= volume < 100:
print("A bit loud!")
else:
print("My hears are hurting!")
# Change the volume if it's too loud or too quiet
if volume < 20 or volume > 80:
volume = 50
print("That's better!")
def hi():
print("Hi there!")
print("How are you?")
hi()
def hi(name):
if name == "Ola":
print("Hi Ola!")
elif name == "Sonja":
print("Hi Sonja")
else:
print("Hi anonymous")
hi("Ola")
hi("Eugenie")
def hi(name):
print("Hi" + name + "!")
girls = ["Rachel", "Monica", "Phoebe", "Ola", "You"]
for name in girls:
hi(name)
print("next girl")
for i in range(1, 6):
print(i)
| true |
3eb6198afa9481a86e43c80b29b1156c64108dc0 | JI007/birthdays | /birthday search.py | 2,316 | 4.3125 | 4 | def birthday():
birthdays = {'Jan': ' ','Feb': ' ', 'Mar': ' ', 'Apr': ' ', 'May': 'Tiana (10), Tajmara (11) ', 'June': ' ', 'July': 'Jamal (7)', 'Aug': 'Richard (7) ', 'Sept': 'Nazira (16) ', 'Oct': ' ', 'Nov': ' ', 'Dec': ' '}
birthday()
# Welcomes the user to the program
print("\n\n\t\tWelcome to the Birthday Finder!\n\t\t-------------------------------")
# Create a list consisting of a calendar
Calendar = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
# Display available search types
print("\nSearch Type:\n\n 1. Month\n 2. Person")
# Ask the user for the search type
searchType = input("\nEnter '1' or '2' as Search Type: ")
# Create conditions based on users search type
if searchType == "1": #(Month)
print("\nMonth:\n--------\n1.Jan.\t2.Feb.\t3.Mar.\t4.April\t5.May\t6.June\n7.July\t8.Aug.\t9.Sept.\t10.Oct.\t11.Nov.\t12.Dec.")
month = input("\nEnter the number of the desired month: ")
if month == "1":
print(Calendar[0])
print(birthdays['Jan'])
elif month == "2":
print(Calendar[1])
print(birthdays['Feb'])
elif month == "3":
print(Calendar[2])
print(birthdays['Mar'])
elif month == "4":
print(Calendar[3])
print(birthdays['Apr'])
elif month == "5":
print(Calendar[4])
print(birthdays['May'])
elif month == "6":
print(Calendar[5])
print(birthdays['June'])
elif month == "7":
print(Calendar[6])
print(birthdays['July'])
elif month == "8":
print(Calendar[7])
print(birthdays['Aug'])
elif month == "9":
print(Calendar[8])
print(birthdays['Sept'])
elif month == "10":
print(Calendar[9])
print(birthdays['Oct'])
elif month == "11":
print(Calendar[10])
print(birthdays['Nov'])
elif month == "12":
print(Calendar[11])
print(birthdays['Dec'])
else:
print("Invalid Entry!")
elif searchType == "2": #(Person)
person = input("\nEnter the first name of person: ")
print("\nThe birthday of", person, "is", )
else:
print("Invalid Type!")
input("\nPress the enter key to exit.")
| true |
6d75e4824f163c52a0ddd62d308750ee12a60ac0 | lvmodan/LPTHW | /ex42hasaisaEn.py | 2,397 | 4.1875 | 4 | #!/usr/bin/env python
# coding=utf-8
# Animal is-a object
class Animal(object):
pass
# dog is-a Animal
class Dog(Animal):
def __init__(self, name):
self.name = name
def bark():
print 'WANG~' * 3
def wave_tail():
print 'wave its tail happily'
# cat is-a Animal
class Cat(Animal):
def __init__(self, name):
self.name = name
def sound():
print 'MIAO~~' * 3
def rub():
print 'The cat is rubbing on your pants'
#Person is-a object
class Person(object):
def __init__(self, name):
self.name = name
self.pet = None
def walk():
print 'walk around'
def sing():
print 'I love you, look at me.'
def eat(self):
print 'eating'
return 'eating'
def smell(self):
print 'smelling'
return 'smelling'
def see(self):
print "look around"
return "look around"
def hear(self):
print 'hearing carefully'
return 'hearing carefully'
def touch():
print 'touching and feeling'
#Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
super(Employee, self).__init__(name)
self.salary = salary
def work(self):
print 'working'
return 'working'
def ask():
print 'asking'
def code():
print 'coding'
class Fish(object):
def __init__(self):
print 'initilize a fish'
def swim():
print 'swimming'
def hunt():
print 'hunting'
def eat():
print 'eating'
#Salmon is-a Fish
class Salmon(Fish):
def __init__(self):
print 'initilize a Salmon...'
def scale(self):
print 'small scales'
return 'small scales'
#Halibut is-a Fish
class Halibut(Fish):
def __init__(self):
print 'initilize a Halibut'
def scale(self):
print 'big scales'
return 'big scales'
lyndon = Employee('lyndon', 6000)
fox = Dog('fox')
petty = Cat('petty')
no1 = Salmon()
no2 = Halibut()
lyndon.pet = fox
print """
There is a person, named %s.
He has a pet: %s.
He also feed two Fishes: %s, %s.
Around his yard, There is Cat: %s.
""" % (lyndon.name, lyndon.pet.name, no1, no2, petty.name)
print """
lyndon can: %s, %s, %s. %s
no1 has: %s
no2 has: %s
""" % (lyndon.hear(), lyndon.eat(), lyndon.see(), lyndon.smell(), no1.scale(), no2.scale())
| false |
df97a2008ef5f6576c0d100699bef3a4ce706400 | Shamita29/266581dailypractice | /set/minmax.py | 455 | 4.21875 | 4 | #program to find minimum and maximum value in set
def Maximum(sets):
return max(sets)
def Minimum(sets):
return min(sets)
"""
setlist=set([2,3,5,6,8,28])
print(setlist)
print("Max in set is: ",Maximum(setlist))
print("Min in set is: ",Minimum(setlist))
"""
print("Enter elements to be added in set")
sets = set(map(int, input().split()))
#print(sets)
print("Maximum value in set is: ",Maximum(sets))
print("Minimum value in set is: ", Minimum(sets)) | true |
6bb7f311bf751f88806e77e17d74d6977f16e264 | navneeth824/Numerical-techniques1 | /unit_3/interpolation derivative of value in table.py | 1,855 | 4.25 | 4 | # newton forward and backward interpolation derivative
# calculating u mentioned in the formula
def u_cal(u, n):
temp = u;
for i in range(1, n):
temp = temp * (u - i);
return temp;
# calculating factorial of given number n
def fact(n):
f = 1;
for i in range(2, n + 1):
f *= i;
return f;
# Driver Code
# Number of values given
n = 6;
x = [ 1, 2, 3, 4, 5, 6 ];
h = x[1] - x[0];
# y[][] is used for difference table
# with y[][0] used for input
y = [[0 for i in range(n)]
for j in range(n)];
y[0][0] = 4;
y[1][0] = 12;
y[2][0] = 27;
y[3][0] = 50;
y[4][0] = 75;
y[5][0] = 108;
# Calculating the forward difference
# table
for i in range(1, n):
for j in range(n - i):
y[j][i] = y[j + 1][i - 1] - y[j][i - 1];
# Displaying the forward difference table
for i in range(n):
print(x[i], end = "\t");
for j in range(n - i):
print(y[i][j], end = "\t");
print("");
#input value
value=5;
d11=0;
d21=0;
#for derivatives at a point in the table
if(value<x[3]):
for j in range(1,n):
d11+=((-1)**(j+1))*y[1][j]/j
d1=d11/h
print("1st Derivative is",d1);
d21=(y[1][2]-y[1][3]+y[1][4]*(11/12)) #change term (y[1][2]-y[1][3]+y[1][4]*(11/12)-y[1][5]*(5/6))
d2=d21/(h**2)
print("1st Derivative is",d2);
d31=(y[1][3]-y[1][4]*(3/2)) #change term
d3=d31/(h**3)
print("1st Derivative is",d3);
if(value>=x[3]):
for j in range(1,n):
d11+=y[n-j-1][j]/j
d1=d11/h
print("1st Derivative is",d1);
d21=(y[n-3][2]+y[n-4][3]+y[n-5][4]*(11/12)+y[n-6][5]*(5/6)) #change term
d2=d21/(h**2)
print("1st Derivative is",d2);
d31=(y[n-4][3]+y[n-5][4]*(3/2)) #change term
d3=d31/(h**3)
print("1st Derivative is",d3);
| false |
3490d144c4cd81468544c77f7faa8bde3dc23a13 | navneeth824/Numerical-techniques1 | /unit_3/interpolation derivative of value not in table.py | 2,082 | 4.15625 | 4 | # newton forward and backward interpolation derivative
# calculating u mentioned in the formula
def u_cal(u, n):
temp = u;
for i in range(1, n):
temp = temp * (u - i);
return temp;
# calculating factorial of given number n
def fact(n):
f = 1;
for i in range(2, n + 1):
f *= i;
return f;
# Driver Code
# Number of values given
n = 6;
x = [ 1, 2, 3, 4, 5, 6 ];
h = x[1] - x[0];
# y[][] is used for difference table
# with y[][0] used for input
y = [[0 for i in range(n)]
for j in range(n)];
y[0][0] = 4;
y[1][0] = 12;
y[2][0] = 27;
y[3][0] = 50;
y[4][0] = 75;
y[5][0] = 108;
# Calculating the forward difference
# table
for i in range(1, n):
for j in range(n - i):
y[j][i] = y[j + 1][i - 1] - y[j][i - 1];
# Displaying the forward difference table
for i in range(n):
print(x[i], end = "\t");
for j in range(n - i):
print(y[i][j], end = "\t");
print("");
#input value
value=5.5;
u=(value-x[5])/h
d11=0;
d21=0;
#for derivatives at a point in the table
if(value<x[3]):
d11=(y[1][1]+(u-0.5)*y[1][2]+(3*u**2-6*u+2)*y[1][3]/6+(4*u**3-18*u**2+22*u-6)*y[1][4]/24)#change 1 to suitable preceeding number
d1=d11/h
print("1st Derivative is",d1);
d21=(y[1][2]+(u-1)*y[1][3]+(6*u**2-18*u+11)*y[1][4]/12) #change 1 to suitable preceeding number (y[1][2]-y[1][3]+y[1][4]*(11/12)-y[1][5]*(5/6))
d2=d21/(h**2)
print("2nd Derivative is",d2);
d31=(y[1][3]+y[1][4]*(u-1.5)) #change 1 to suitable preceeding number
d3=d31/(h**3)
print("3rd Derivative is",d3);
if(value>x[3]):
d11=(y[n-2][1]+(u+0.5)*y[n-3][2]+(3*u**2+6*u+2)*y[n-4][3]/6+(4*u**3+18*u**2+22*u+6)*y[n-5][4]/24)#
d1=d11/h
print("1st Derivative is",d1);
d21=(y[n-3][2]+(u+1)*y[n-4][3]+(6*u**2+18*u+11)*y[n-5][4]/12) # (y[1][2]-y[1][3]+y[1][4]*(11/12)-y[1][5]*(5/6))
d2=d21/(h**2)
print("2nd Derivative is",d2);
d31=(y[n-4][3]+y[n-5][4]*(u+1.5)) #
d3=d31/(h**3)
print("3rd Derivative is",d3);
| false |
3165bc53048b76a1fc5c7bc58bef2663c595f69e | zmatteson/epi-python | /chapter_4/4_7.py | 335 | 4.28125 | 4 | """
Write a program that takes a double x and an integer y and returns x**y
You can ignore overflow and overflow
"""
#Brute force
def find_power(x,y):
if y == 0:
return 1.0
result = 1.0
while y:
result = x * result
y = y - 1
return result
if __name__ == "__main__":
print(find_power(3,1)) | true |
7bfff88b28253ec0f69e3c93dc01c29be200e71b | zmatteson/epi-python | /chapter_13/13_1.py | 1,092 | 4.1875 | 4 | """
Compute the intersection of two sorted arrays
One way: take the set of both, and compute the intersection (Time O(n + m) )
Other way: search in the larger for values of the smaller (Time O(n log m ) )
Other way: start at both and walk through each, skipping where appropriate (Time O(n + n) , space O(intersection m & n) )
#Assume A is always larger than B
"""
def compute_intersection(A, B):
intersection = []
i, j = 0, 0
while i < len(B) and j < len(A):
while i < len(B) and (B[i] < A[j]): #skip duplicates and fast forward
i += 1
while (j < len(A) and i < len(B)) and (A[j] < B[i]):
j += 1
b, a = B[i], A[j]
print(b,a)
if b == a:
intersection.append(b)
i += 1
j += 1
while i < len(B) and B[i] == b: #skip duplicates
i += 1
while j < len(A) and A[j] == a:
j += 1
return intersection
if __name__ == '__main__':
B = [1, 2, 3, 3, 4, 5, 6, 7, 8]
A = [1, 1, 5, 7]
print(compute_intersection(A,B)) | true |
af77d80d6b95b5dc847f33ba0783b5fcc7c872d6 | zmatteson/epi-python | /chapter_5/5_1.py | 1,620 | 4.21875 | 4 | """
The Dutch National Flag Problem
The quicksort algorith for sorting arrays proceeds recursively--it selects an element
("the pivot"), reorders the array to make all the elements less than or equal to the
pivot appear first, followed by all the elements greater than the pivot. The two
subarrays are then sorted recursively.
Implemented naively, quicksort has large run times and deep functioncall stacks on
arrays with many dupicates because the subarrays may differ greatly in size. One
solution is to reorder the array so that all elements less than the pivot appear first,
followed by elements equal to the pivot, followed by elements greater than the pivot.
This is known as the Dutch National Flag partitioning because the Dutch national flag
consists of 3 horizontal bands of different colors.
Write a program that takes an array A and an index i into A, and rearrange the elements
such that all elements less than A[i] appear first, followed by elements equal to the
pivot, followed by elements greater than the pivot
EXAMPLE:
A = [1,2,0] i = 2, A[i] = 0
Return [0,1,2]
"""
#Brute force/Brute space
def partition_array(A, i):
L = []
M = []
R = []
for x in A:
if x < A[i]:
L.append(x)
elif x == A[i]:
M.append(x)
else:
R.append(x)
return L + M + R
if __name__ == "__main__":
A = [1,2,0]
print("A is ", A)
print("A partioned with pivot at index 2 is ", partition_array(A, 2))
A = [1,2,3,1,1,10,0,1,5,1,0]
print("A is ", A)
print("A partioned with pivot at index 2 is ", partition_array(A, 2))
| true |
d3e57c2ec3133003e2d8d5f67c2aee403e3ab0e8 | zmatteson/epi-python | /chapter_14/14_1.py | 959 | 4.15625 | 4 | """
test if a tree satisfies the BST property
What is a BST?
"""
class TreeNode:
def __init__(self, left = None, right = None, key = None):
self.left = left
self.right = right
self.key = key
def check_bst(root):
max_num = float('inf')
min_num = float('-inf')
return check_bst_helper(root, max_num, min_num)
def check_bst_helper(root, max_num, min_num):
if not root:
return True
elif root.key > max_num or root.key < min_num:
print(root.key, max_num, min_num)
return False
return (check_bst_helper(root.left, root.key, min_num) and check_bst_helper(root.right, max_num, root.key))
if __name__ == '__main__':
nodeE = TreeNode(None,None, 9)
nodeD = TreeNode(None,nodeE,7)
left = TreeNode(None,nodeD,5)
right = TreeNode(None,None,15)
root = TreeNode(left, right, 10)
print(check_bst(root))
# 10
# 5 15
# 7
# 2 | true |
cad9a59e7ed85cd5f9c7cea130d6589ee7a70bd9 | Pyae-Sone-Nyo-Hmine/Ciphers | /Caesar cipher.py | 1,362 | 4.46875 | 4 | def encode_caesar(string, shift_amt):
''' Encodes the specified `string` using a Caesar cipher with shift `shift_amt`
Parameters
----------
string : str
The string to encode.
shift_amt : int
How much to shift the alphabet by.
'''
answer = ""
for i in range(len(string)):
letter = string[i]
if (letter.isupper()):
if (ord(letter) + shift_amt) <= 90:
answer += chr((ord(letter) + shift_amt ))
elif (ord(letter) + shift_amt) > 90 and (ord(letter) + shift_amt + 6) <= 122:
answer += chr((ord(letter) + shift_amt + 6))
elif (ord(letter) + shift_amt + 6) > 122:
answer += chr((ord(letter) + shift_amt -52))
if (letter.islower()):
if (ord(letter) + shift_amt) <= 122:
answer += chr((ord(letter) + shift_amt ))
elif (ord(letter) + shift_amt) > 122 and (ord(letter) + shift_amt) <=148 :
answer += chr((ord(letter) + shift_amt - 52-6))
elif (ord(letter) + shift_amt) > 148:
answer += chr((ord(letter) + shift_amt - 52))
if (letter.isspace()):
answer += string[i]
if (letter.isnumeric()):
answer += string[i]
return answer
| true |
de6be7734a7996f5bbea60637be01ed928b7ddb4 | v4vishalchauhan/Python | /emirp_number.py | 669 | 4.28125 | 4 | """Code to find given number is a emirp number or not"""
"""Emirp numbers:prime nubers whose reverse is also a prime number for example:17 is a
prime number as well as its reverse 71 is also a prime number hence its a emirp number.."""
def prime_check(k):
n=int(k)
if n<=1:
return False
for i in range(2,n):
if n%int(i)==0:
return False
else:
return True
print("Enter the number: ")
l=int(input())
for num in range(l+1):
if prime_check(num)==True:
d=str(num)[::-1]
if prime_check(d)==True:
print("$$$We got it....."+str(num)+" is a Emirp number$$$")
else:
print(str(num)+ " is not a emirp number..") | true |
112da86c726bd8f3334258910eae937aff2f8db5 | ms99996/integration | /Main.py | 1,664 | 4.1875 | 4 | """__Author__= Miguel salinas"""
"""This is my attempt to create a mad lib """
ask = input("welcome to my mad lib, would you like to give it a try? enter "
"yes or no, the answer is case sensitive: ")
while ask not in ("yes", "no"):
ask = input("please type a valid input: ")
def get_answers(color, animal, body_parts, verb, verb2, verb3):
"""Creates a mad lib using inputs for variables inside argument. """
print("there once was a", color, animal, "that had 3", body_parts,
"it uses one part for", verb, "the next for", verb2,
"and the last for", verb3)
def main():
"""Asks user age, and many questions to create a mad lib,"""
if ask == "yes":
age = int(input("wonderful, please enter your age: "))
if age >= 16:
print("your age is", age, "you are old enough to continue")
color = input("please enter a color: ")
animal = input("please enter an animal: ")
body_parts = input("please enter a body part(plural): ")
verb = input("please enter a verb that ends with 'ing': ")
verb2 = input("please enter another verb that ends with 'ing': ")
verb3 = input("please enter one more verb that end with 'ing': ")
mad_libs = get_answers(color, animal, body_parts, verb, verb2, verb3)
# I have get_answers to print the mad lib
# I don't like how return outputs the mad lib
print(mad_libs)
else:
print("sorry but you are not old enough to continue")
else:
print("thank you and have a nice day")
main()
| true |
2751c555e7013b68edf648c2c5523c3218759546 | jeffersonklamas/Learning_repository | /Estudo_de_Python/Exercicios-em-python/mediaaritmetica.py | 926 | 4.4375 | 4 | # -----------------------------------------------------
# Exercício desenvolvido por Jefferson Klamas Maarzani
# Para as atividades do Curso da UFSCAR disponíveis na
# Plataforma do Coursera para o curso de Introdução
# da Ciência da Computação com Python
# -----------------------------------------------------
#
# Enunciado
# Faça um programa em Python que receba quatro notas,
# calcule e imprima a média aritmética.
# Observe o exemplo abaixo:
#
# Exemplo:
#
# Entrada de Dados:
# Digite a primeira nota: 4
# Digite a segunda nota: 5
# Digite a terceira nota: 6
# Digite a quarta nota: 7
# Saída de Dados:
# A média aritmética é 5.5
#
nota1 = int(input("Digite a primeira nota:"))
nota2 = int(input("Digite a segunda nota:"))
nota3 = int(input("Digite a terceira nota:"))
nota4 = int(input("Digite a quarta nota:"))
#Calculo
mediatotal = (nota1+nota2+nota3+nota4)/4
# saída
print("A média aritmética é", mediatotal)
# Fim | false |
cc2900e3d4536389d9bd059d884098bc147d3e6d | jeffersonklamas/Learning_repository | /Estudo_de_Python/Exercicios-em-python/equacoesde2grau.py | 888 | 4.125 | 4 | #--------------------------------------------
# Cálculo de equações de segundo grau ( Bhaskara)
#
#--------------------------------------------
import math
a = float(input("Digite um valor para A: "))
b = float(input("Digite um valor para B: "))
c = float(input("Digite um valor para C: "))
# Calculo(a, b, c)
delta = b ** 2 - 4 * a * c
if delta == 0:
x1 = (-b + math.sqrt(delta)) / (2 * a)
print("A única raiz é: {0}".format(x1))
else:
if delta < 0:
print("Esta equação não pertence aos números Reais!!!")
else:
x1 = (-b + math.sqrt(delta)) / (2 * a)
x2 = (-b - math.sqrt(delta)) / (2 * a)
print("\nO Valor de x1: {}, e x2: {}\n".format(x1,x2))
"""
if __name__ == "__main__":
segue = input("\nPara finalizar, Digite q ou pressione enter para um novo cálculo: \n")
if (segue == "q"):
break
"""
# End
| false |
d6baa2d4320f15ece2bd9d628911145a1b471105 | ErenBtrk/PythonSetExercises | /Exercise7.py | 237 | 4.375 | 4 | '''
7. Write a Python program to create a union of sets.
'''
set1 = set([1,2,3,4,5])
set2 = set([6,7,8])
set3 = set1 | set2
print(set3)
#Union
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
seta = setx | sety
print(seta)
| true |
546cd33519cea7f759d09ccd11203d44fed2fc4d | sivaprasadkonduru/Python-Programs | /Sooryen_python/question3.py | 608 | 4.125 | 4 | '''
Write a function that takes an array of strings and string length (L) as input. Filter out all the string string in the array which has length ‘L’
eg.
wordsWithoutList({"a", "bb", "b", "ccc"}, 1) → {"bb", "ccc"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 3) → {"a", "bb", "b"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 4) → {"a", "bb", "b", "ccc”}
'''
def words_without_list(words, target):
return {i for i in words if not len(i) == target}
words_without_list({"a", "bb", "b", "ccc"}, 1)
words_without_list({"a", "bb", "b", "ccc"}, 3)
words_without_list({"a", "bb", "b", "ccc"}, 4)
| true |
9c7c90bda0b8a79ddfd96a9805094b9748c76a07 | ClassicM/Python | /Emm-4(字典).py | 2,010 | 4.4375 | 4 | print('dict')
print('---------------------------------')
#Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
d = {'Amy':90,'Bob':85,'Candy':60}
print(d['Amy'])
d['Denny'] = 100
print(d)
print('判断key是否存在,有两种方法:1.in 2.dict的get()方法')
print('---------------------------------')
print('Denny' in d)
print('Can' in d)
print(d.get('Amy'),-1)
print(d.get('Ken'),-1)
print('删除key,用pop(key)方法')
print('---------------------------------')
d.pop('Denny')
print(d)
'''
和list比较,dict有以下几个特点:
查找和插入的速度极快,不会随着key的增加而变慢;
需要占用大量的内存,内存浪费多。
而list相反:
查找和插入的时间随着元素的增加而增加;
占用空间小,浪费内存很少。
所以,dict是用空间来换取时间的一种方法。
dict可以用在需要高速查找的很多地方,在Python代码中几乎无处不在,正确使用dict非常重要,需要牢记的第一条就是dict的key必须是不可变对象。
'''
print('set')
print('---------------------------------')
#set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
s= set([1,3,2])
print(s)
#注意,传入的参数[1, 2, 3]是一个list,而显示的{1, 2, 3}只是告诉你这个set内部有1,2,3这3个元素,显示的顺序也不表示set是有序的。。
#重复元素在set中自动被过滤:
s = set([1,2,3,3,2,1,2])
print(s)
#通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果
s.add(4)
print(s)
#通过remove(key)方法可以删除元素
s.remove(4)
print(s)
#set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:
s1 = set([1,2,3])
s2 = set([2,3,4])
print(s1 & s2)
print(s1 | s2)
| false |
730d42ed36e3a39bf708d78324f2706e0c6a7fd0 | ClassicM/Python | /Emm-13(实例属性和类属性).py | 1,476 | 4.4375 | 4 | #由于Python是动态语言,根据类创建的实例可以任意绑定属性。
#给实例绑定属性的方法是通过实例变量,或者通过self变量:
class Student(object):
def __init__(self,name):
self.name = name
s = Student('Bob')
s.score = 90
print(s.name,s.score)
class Student(object):
name = 'Student'
s = Student() #创建实例s
print(s.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
print(Student.name)#打印类的name属性
s.name = 'Micheal'#给实例绑定name属性
print(s.name) #由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
print(Student.name)#但是类属性并未消失,依然可以访问到
del s.name #删除实例的name属性
print(s.name)#再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
'''
在编写程序的时候,千万不要对实例属性和类属性使用相同的名字
因为相同名称的实例属性将屏蔽掉类属性,但是当你删除实例属性后,再使用相同的名称,访问到的将是类属性。
'''
#练习
#为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:
class Student(object):
count = 0
def __init__(self,name):
self.name = name
Student.count += 1
student = Student('Amy')
print(student.count)
student = Student('Bob')
print(student.count) | false |
205eaa9103e4985a00939e0678759d726c7d3465 | farkaspeti/pair_programing | /listoverlap/listoverlap_module.py | 375 | 4.34375 | 4 | def listoverlap(list1, list2):
list3 = []
for i in list1:
if i in list2 and i not in list3:
list3.append(i)
else:
pass
print(list3)
return list3
def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
listoverlap(a, b)
if __name__ == '__main__':
main() | false |
9e546395591c2f3ce35d1a9889398e7108995975 | SobuleacCatalina/Rezolvarea-problemelor-IF-WHILE-FOR | /problema_8_IF_WHILE_FOR.py | 656 | 4.1875 | 4 | """
Se dau numerele reale pozitive a,b,c. Să se verifice dacă un triunghi ale cărui laturi au lungimile (în aceeași unitate de măsură) egale
cu a,b,c. În caz afirmativ, să se determine tipul triunghiului: echilteral,isoscel,scalen.
"""
a=int(input("Introdu numărul a: "))
b=int(input("Introdu numărul b: "))
c=int(input("Introdu numărul c: "))
if ((a+b>c)and(a+c>b)and(b+c>a)):
if ((a==b)and(a==c)and(b==c)):
print("Formeaza un triunghi echilateral")
elif ((a!=b)and(a!=c)and(b!=c)):
print("Formeaza un triunghi scalen")
else:
print("Formeaza un triunghi isoscel")
else:
print("Nu formeaza un triunghi") | false |
c80c00855a308016585a2620659b44a93b218a07 | kauboy26/PyEvaluator | /miscell.py | 569 | 4.15625 | 4 | def print_help():
print 'Type in any expressions or assignment statements you want.'
print 'For example:'
print '>> a = 1 + 1'
print '2'
print '>> a = a + pow(2, 2)'
print '6'
print '\nYou can also define your own functions, in the form'
print 'def <function name>([zero or more comma separated args]) = <expression>'
print '\nFor example,'
print '>> def f(x, y) = x * y + 3'
print '>> f(2, 3)'
print '9\n'
print 'Type "print" to see all values and defined functions.'
print 'Type "help" to see this message.' | true |
98ee6d2d5cdda315aef0cf4cb1ce9d91380fb77d | Jackiexiong/software-testing-course | /content/Intro to Python3/intro_to_python3-script.py | 2,495 | 4.28125 | 4 | # Intro to Python
# boolean values
T
t
True
# integer values
1234
-23
0
# float values
3.14
314e-2
.1
-.1
# string values
"Python's"
'she said "Python"'
"""String with <newline>
character"""
"This" "is" "one" "string"
# string operators
i_str = "Python"
i_str[1]
i_str[-1]
i_str[1:3]
i_str[1:7:2]
i_str[7:1:-2]
i_str + i_str
len(i_str)
i_str * 3
"y" in i_str
"yt" in i_str
"y" not in i_str
not "y" in i_str
dir("hey")
# string methods
"I love {0}{1}{0}".format(i_str, "language")
# Type dir('name') into python interpreter
# operators
1 + 1
1 - 1
1 * 2
1 / 2
5 % 3
1 < 2
1 <= 2
1 > 2
1 >= 2
1 == 1
1 != 1
i = [1]
j = [1]
i == j
i is j
i is not j
True == 1
True is 1
1 < 3 < 5
1 < 3 < 2
"2" < "1"
"21" < "5"
True and False
True or False
not (1 > 2)
3 and False
3 or False
not 0
not ""
# control structures
if 1 < 2:
print("1 < 2")
elif 1 == 2:
print("What!!")
else:
print(1/0)
i = 0
while i < 10:
print(i)
i += 1
break # see what happens when you comment this line
else:
print("ha ha")
for i in range(1, 10):
if i % 2:
continue
print(i)
break # see what happens when you comment this line
else:
print("boom")
try:
i = 3 / 0 # see what happens when you change 0 to 2
except ZeroDivisionError as e:
print(e)
else:
print("Hmm")
finally:
print("finally")
# function
def max3(x, y, z):
if x > y and x > z:
return x
if y > x and y > z:
return y
if z > x and z > y:
return z
def upper(s, l=3):
for i in s[:l]:
print(i.upper())
upper("spam")
upper("spam", 2)
# complex data type
i = ['s', 'p', 'a', 'm']
j = [x.upper() for x in i] # list - kinda eager
k = (x.upper() for x in i) # generator - kinda lazy
l = [x for x in range(1, 10) if x % 2] # comprehension with filter
m = {x.upper() for x in i}
n = {x:x.upper() for x in i}
# classes
class Sorter(object):
count = 0
def __init__(self):
Sorter.count += 1
self.name = "Sorter" + str(Sorter.count)
def sort(self, array):
self.name2 = "Sorter"
return sorted(array, reverse=True)
i = Sorter()
i.sort(range(1, 10))
# putting all together
import math
print(math.log(100))
from math import log
print(log(100))
def sort(x):
if x == 1 or x == ["a", "b"] or x == []:
raise RuntimeError
elif x == [6,2,6]:
return [2,6]
elif x == [1,2,3]:
return [1,2,3]
elif x == [2,6,4,8]:
return [2,4,6,8] | false |
76972fcaadbc52294e7e06871d1f7115e8eb6285 | jabarszcz/randompasswd | /randompasswd.py | 1,496 | 4.125 | 4 | #!/usr/bin/env python3
import argparse
import string
import random
# Create parser object with program description
parser = argparse.ArgumentParser(
description="simple script that generates a random password")
# Define program arguments
parser.add_argument("-a", "--lower", action='store_true',
help="add lowercase characters to alphabet")
parser.add_argument("-A", "--upper", action='store_true',
help="add uppercase characters to alphabet")
parser.add_argument("-1", "--num", action='store_true',
help="add digits to alphabet")
parser.add_argument("-s", "--special", action='store_true',
help="add punctuation characters to alphabet")
parser.add_argument("-c", "--characters", action='append', metavar="string",
help="add the characters from the given string")
parser.add_argument("-l", "--length", default=10, type=int, metavar ="N",
help="length of the password generated")
args = parser.parse_args()
# Create the alphabet
alphabet = ''.join(args.characters) if args.characters else []
if args.lower:
alphabet += string.ascii_lowercase
if args.upper:
alphabet += string.ascii_uppercase
if args.num:
alphabet += string.digits
if args.special:
alphabet += string.punctuation
if not alphabet:
print("Alphabet is empty!")
parser.print_help()
exit()
passwd = ''.join(random.choice(alphabet) for i in range(args.length))
print(passwd)
| true |
147179c937d26d3634c92e99f5caec26ba9c4d66 | madebydavid/wizzie-ctf | /lesson-05/encode.py | 878 | 4.3125 | 4 | #!/usr/bin/env ./../bin/python3
# Tool for hiding the password in the cheese
import random
cheese = []
with open('cheese.txt', 'r') as input_cheese:
for line in input_cheese:
line_list = list(line.rstrip())
cheese.append(line_list)
password = input('Please enter the password to hide in the cheese: ')
positions = []
for character in password:
hidden_row_position = random.randint(0, len(cheese) - 1)
hidden_col_position = random.randint(0, len(cheese[0]) - 1)
cheese[hidden_row_position][hidden_col_position] = character
positions.append((hidden_row_position, hidden_col_position))
with open('cheese-with-password.txt', 'w') as output_cheese:
for line in cheese:
output_cheese.write(''.join(line) + '\n')
print('saved cheese with password to cheese-with-password.txt')
print('positions for letters are:')
print(positions)
| false |
7fbee6b902a11525f9d8afd0f20a343126dd51b1 | isaolmez/core_python_programming | /com/isa/python/chapter6/Tuples.py | 530 | 4.4375 | 4 | ## Tuples are very similar to lists; but they are immutable
tuple1 = (1,2,3)
print tuple1
# For tuples, parantheses are redundant and this expression craetes a tuple.
# For lists we must use brackets
tuple2 = "a", "b", "c"
print tuple2
# tuple1[1] = 99 # ERROR: We cannot mutate tuple or assign new values to its elements
print tuple
tuple1 = (0, 0, 0) # But we can assign a completely new tuple
print tuple1
# Cannot delete individual elements; but can delete tuple itself
# del tuple1[1] # ERROR: We cannot mutate
del tuple1
| true |
916b10dc06df2fece2e1af6afe15b80696ea11cc | isaolmez/core_python_programming | /com/isa/python/chapter5/Exercise_5_11.py | 468 | 4.1875 | 4 | for item in range(0,21,2):
print item,
print
for item in range(0, 21):
if item % 2 == 0:
print item,
print
for item in range(1,21,2):
print item,
print
for item in range(0, 21):
if item % 2 == 1:
print item,
print
## If you omit return type, it does not give warning but returns None
def isDivisible(num1, num2):
if num1 % num2 == 0:
return True
return False
print isDivisible(10, 2)
print isDivisible(10, 20)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.