blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4ade8dc407f2c4e989f55be5f8c79830c5146113 | snitkdan/BlackJack | /src/Card.py | 1,510 | 4.21875 | 4 | class Card(object):
"""
This class represents a standard playing card (e.g. Ace) as it
is represented in a game of Black Jack.
"""
def __init__(self, name: str, values: [int], suit=None):
"""
:param name: the title of the card (e.g. king)
:param values: the values this card takes on in Blackjack (e.g. aces can be 1 or 11, kings can be 10)
:param suit: one of 'diamond', 'spade', 'club', 'heart', or None if the card is generic across all suits
"""
self.name = name
self.values = values
self.suit = suit
def __str__(self):
"""
:return: string representation of card in the format "NAME of SUIT"
"""
return '{0} of {1}'.format(self.get_name(), self.get_suit())
def get_values(self):
"""
:return: the list of values that this card has
"""
return self.values
def get_name(self):
"""
:return: the title of this card
"""
return self.name
def get_suit(self):
"""
:return: the suit of this card (None if generic)
"""
return self.suit
def set_suit(self, suit: str):
"""
Sets the suit of this card to the given suit
:param suit: one of 'diamond', 'spade', 'club', 'heart' (raises ValueError if not one of these)
"""
if suit not in ['diamond', 'spade', 'club', 'heart']:
raise ValueError('invalid suit')
self.suit = suit
| true |
08bae12fc8e7ec11ef96c001cdfa57932a3d58f7 | vetrujillo/BeginnerPythonScripts | /ex_list_to_list2.py | 782 | 4.28125 | 4 | sandwich_order = ['tuna', 'pastrami', 'ham', 'pastrami', 'steak', 'cheese', 'pastrami']
finished_sandwiches = []
#Checks if specified string is in list
if 'pastrami' in sandwich_order:
#If so, it will run the following code
print("Sorry, we are out of that ingredient")
#While the specified string is in the list, the ensuing code will run
while 'pastrami' in sandwich_order:
#Removes specfied string from list
sandwich_order.remove('pastrami')
#Loop will run until specified list is empty
while sandwich_order:
#Pulls last item from list and stores it in 'sandwich'
sandwich = sandwich_order.pop()
print("\nYour " + sandwich + " sandwich is ready.")
#Adds value of sandwich into list finished_sandwiches
finished_sandwiches.append(sandwich)
print(finished_sandwiches) | true |
af0b5657402d2b71b93c4e53070f28807d646888 | vetrujillo/BeginnerPythonScripts | /ex_dictionary_nesting.py | 748 | 4.21875 | 4 | cities = {
'el paso': {
'country': 'the united states',
'population': 951000,
'fact': "western-most Texas city",
},
"st. andrews": {
'country': 'scotland',
'population': 17580,
'fact': 'oldest university in Scotland',
},
'seoul': {
'country': 'the republic of korea',
'population': 9700000,
'fact': 'capital of south korea',
},
}
for city, dictionary in cities.items():
print("\nThis is the city of " + city.title())
print(city.title() + " is located in " + dictionary['country'].title())
print("It has a population of " + str(dictionary['population']))
if dictionary['population'] >= 1000000:
print("That's a lot of people!")
print("Here's a quick fact about " + city.title() + ":\nIt is the " + dictionary['fact']) | false |
edc3b6f9f11c8538e30b7b27b0009c3a0403cba1 | AndroidIosWebEmbeddedFirmwareDver/python3LearningNote | /day11/func_enumerate_demo.py | 1,070 | 4.3125 | 4 | # http://www.runoob.com/python3/python3-func-enumerate.html
# TODO;Python3 enumerate() 函数
"""
描述
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个
索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法
以下是 enumerate() 方法的语法:
enumerate(sequence, [start=0])
参数
sequence -- 一个序列、迭代器或其他支持迭代对象。
start -- 下标起始位置。
返回值
返回 enumerate(枚举) 对象。
实例
以下展示了使用 enumerate() 方法的实例:
"""
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1))) # 小标从 1 开始
# 普通的 for 循环
i = 0
seq = ['one', 'two', 'three']
for element in seq:
print(i, seq[i])
i += 1
# for 循环使用 enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, seq[i])
# 遍历字符串
seq = '12312312321adsasdasdad'
for i, element in enumerate(seq):
print(i, seq[i])
| false |
9c38ed978dfcb09727d56c24f99351806fcc4227 | shn2002/SFWRTECH-3RQ3 | /test assignment5 part a.py | 1,711 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Student Name: Henian Shan
# Student Number: 400418368
from stubs_traffic_light import TrafficLight
# When one traffic light is green the other must always be red.
#1. Briefly explain in acode comment on each file why the tests given are all necessary to test the requirement
#2. and why the set you gave is sufficient to guarantee the system works as intended.
# This test covers all the senarios when the traffic light turn green
# According to the question 1, this pair of traffic light are partly exclusive
# The status can be RED-RED, RED-GREEN, GREEN-RED
# The test cover 2 senarios.
# when main street traffic light is green side street traffic light is red.
# when side traffic light is green main street traffic light is red.
def test_traffic_light_turn_green():
#inital twe traffic lights
main_street_traffic_light = TrafficLight('NS','RED','Main')
side_street_traffic_light = TrafficLight('WE','RED','Side')
# pair these two lights
main_street_traffic_light.pair(side_street_traffic_light)
side_street_traffic_light.pair(main_street_traffic_light)
#change the main street traffic light to green
main_street_traffic_light.color='GREEN'
#check if side street traffic light is red
assert side_street_traffic_light.color =='RED', "When main street traffic light is green, side street traffic light should be red"
#change the side street traffic light to green
side_street_traffic_light.color='GREEN'
#check if main street traffic light is red
assert main_street_traffic_light.color=='RED' , "When side street traffic light is green, main street traffic light should be red"
| true |
7f89a15e595d07a99f8eb988a7e6bebb857a2923 | SathveeganY/Damon | /Transpose matrix.py | 1,125 | 4.1875 | 4 | # This function stores transpose of A[][] in B[][]
def transpose(A, B):
for i in range(C):
for j in range(R):
B[i][j] = A[j][i]
#To store input
A = []
Result = 'Valid Matrix'
while True:
m = input().split()
if len(m) == 0:
Result = 'Error' #To avoid empty rows
break
elif m[0] == '-1':break
else:A.append(m)
if Result != 'Error':
#To handle errors
Result = 'Valid Matrix'
for i in range(len(A)-1):
if len(A[i]) != len(A[i+1]):
Result = 'Invalid Matrix' #inconsistent number of elements
if Result == 'Valid Matrix':
R = len(A) #rows of given matrix
C = len(A[0]) #columns of given matrix
# To store result
B = [[0 for x in range(R)] for y in range(C)]
transpose(A, B)
#To print transpose matrix
for i in range(C):
for j in range(R):
print(B[i][j],end=' ')
print()
else:print(Result)
else:print(Result) #print type of error
| true |
a5457964bf657351c34c357157d4aa3eb1e4e110 | divinesaun/Math-In-Py | /lowest_term/main.py | 455 | 4.15625 | 4 | numerator = int(input('Enter Numerator: '))
denominator = int(input('Enter Denominator: '))
for i in range(numerator, 0, -1):
if (numerator % i == 0) and (denominator % i == 0):
print('\nYour Fraction In Lowest/Simplest Terms =', sep='\n')
print('{:^6d}\n{}\n{:^6d}'.format(int(numerator / i), '--------', int(denominator / i)))
print(f'\nYour Fraction As A Simple Decimal = {round(numerator / denominator, 3)}')
break
| false |
318cfc6363497abc6513ef7d2ab60dade86f391a | rayasasa/Algorithms-and-Data-Structures | /reverseString.py | 355 | 4.15625 | 4 | #reverse a string
def reverseString(s):
s = list(s)
x = len(s)-1
y = int(len(s)/2)
for i in range(y):
temp = s[i]
s[i] = s[x-i]
s[x-i] = temp
return "".join(s)
print(reverseString(s))
def reverseString(s):
newstr = ""
for i in s:
newstr = i + newstr
return newstr
print(reverseString(s))
| false |
59af01141f9832c0ca7ebc50b2a6d32f51b8172d | ChaseChimeric/Assignments | /a12p2.py | 1,115 | 4.3125 | 4 | """
Program Name: Ackermann's Function
Filename main.py
Author: Ryan Fong
Date: 21 November 2020
Assignment: Assignment 12 Part 2
Description: Basic program to gather input and use the Ackermann's algorithm on that input
Sources: None
"""
def ackermann(m, n):
"""
Module Name: ackermann()
Parameters: 2 integers m and n
Description: Uses recursion and Ackermann's algorithm to process input
"""
if m == 0: #Using logic provided with recursion
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n-1))
def main():
"""
Module Name: main()
Parameters: None
Description: Main module for code
"""
print('Please enter a value for m: ') #getting values for both m and n
m = int(input())
print('Please enter a value for n: ')
n = int(input())
value = ackermann(m, n) #calling ackermann function with both initial values
print(f'The ackermannn value for {m} , {n} is: {value}')
if __name__ == "__main__":
main()
| true |
48ef74c85e76a2b3e4f0d72011186aa9b1b13da2 | ATLS1300-CoFo1/Bubble-Game | /onclick_demo.py | 1,061 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 00:06:47 2020
@author: Dr. Z
Creates a turtle that moves to the location of a mouse click
"""
#Modified from https://keepthinkup.wordpress.com/programming/python/python-turtle-handling-with-mouse-click/
import turtle
turtle.setup(400,500) # sets up screen size and turns on listener ***REQUIRED***
window = turtle.Screen() # create our Screen variable
window.clear()
window.title("How to handle mouse clicks on the window!")
window.bgcolor("lightgreen")
# Create our turle variable
draw = turtle.Turtle()
draw.color("darkblue")
draw.pensize(3)
draw.shape("circle")
# define callback function. This one makes the turtle go to the click location
def h1(x, y): # for click callbacks, x and y should be set up as parameters
draw.goto(x, y) # when called with click, x and y names get click coordinate values (pixels)
window.onclick(h1) # now set up mouseclick, pass the NAME of the function in as an argument
window.mainloop() # call mainloop to keep the click listener running.
| true |
51c27e19d862b5bdf3ecb74d3a9f4eba40ec3e3d | ryanme/NewLand | /继承/demo1.py | 1,707 | 4.46875 | 4 | # coding: utf8
"""
子类继承多个父类
"""
class A:
def __init__(self):
print("aaa")
class B:
def __init__(self):
print("bbb")
class C1(A,B):
pass
class C2(B,A):
pass
if __name__=="__main__":
print("A--->",)
a = A()
print("B--->",)
b = B()
print("C1(A,B)--->",)
c1 = C1()
print("C2(B,A)--->",)
c2 = C2()
"""
#运行结果
A---> aaa
B---> bbb
C1(A,B)---> aaa
C2(B,A)---> bbb
"""
"""
类C1继承了两个类A,B;类C2也继承了两个类,只不过书写顺序有点区别(B,A)。从运行结果可以看出,当子类继承多个父类的时候,
对于构造函数__init__(),只有第一个能够被继承,第二个就等掉了。所以,一般情况下,不会在程序中做关于构造函数的同时多个继承
"""
"""
在Python中,可以進行多重繼承,這個時候要注意搜尋的順序,
是從子類別開始,接著是同一階層父類別由左至右搜尋,
再至更上層同一階層父類別由左至右搜尋,直到達到頂層為止。
"""
class A(object):
def method1(self):
print('A.method1')
def method2(self):
print('A.method2')
class B(A):
def method3(self):
print('B.method3')
class C(A):
def method2(self):
print('C.method2')
def method3(self):
print('C.method3')
class D(B, C):
def method4(self):
print('C.method4')
d = D()
d.method4() # 在 D 找到,C.method4
d.method3() # 以 D->B 順序找到,B.method3
d.method2() # 以 D->B->C 順序找到,C.method2
d.method1() # 以 D->B->C->A 順序找到,A.method1
| false |
9592e282aeb27208bae9dd6ef4e13ca90b53ed85 | jalvaradosegura/some_action | /some_action/instance_vs_class.py | 1,338 | 4.15625 | 4 | class Dog:
num_legs = 4
def __init__(self, name):
self.name = name
john = Dog('john')
kat = Dog('kat')
print(john.num_legs, kat.num_legs)
print(Dog.num_legs)
# error the class can't access an instance variable
# print(Dog.name)
print('==============================')
Dog.num_legs = 6
print(john.num_legs, kat.num_legs)
print(Dog.num_legs)
print()
Dog.num_legs = 4
john.num_legs = 6
print(john.num_legs, kat.num_legs)
print(Dog.num_legs)
print('buuut')
print(john.num_legs, john.__class__.num_legs)
print()
print('new class incoming')
class CounterObject:
num_instances = 0
def __init__(self):
self.__class__.num_instances += 1
print(CounterObject().num_instances)
print(CounterObject().num_instances)
print(CounterObject().num_instances)
print()
print('now same class but with a bug')
class CounterObject2:
num_instances = 0
def __init__(self):
self.num_instances += 1
print(CounterObject2().num_instances)
print(CounterObject2().num_instances)
print(CounterObject2().num_instances)
print()
print('now same class but with a bug version 2')
class CounterObject3:
num_instances = 2
def __init__(self, x):
self.num_instances *= x
print(CounterObject3(2).num_instances)
print(CounterObject3(3).num_instances)
print(CounterObject3(4).num_instances)
| false |
91df86d74e35430ea91e41ee1ecc28c8a0c1a551 | himlayyy/Data-Analysis-with-Python | /Week 1/1-09-merge.py | 1,126 | 4.59375 | 5 | #!usr/bin evn python 3
"""Suppose we have two lists L1 and L2 that contain integers which are sorted in ascending order.
Create a function merge that gets these lists as parameters and returns a new sorted list L that
has all the elements of L1 and L2. So, len(L) should equal to len(L1)+len(L2). Do this using the
fact that both lists are already sorted. You can’t use the sorted function or the sort method in
the merge method. You can however use these sorted in the main function for creating inputs to
the merge function. Test with a couple of examples in the main function that your solution
works correctly"""
import random
def merge(list1, list2):
sorted_list = list1 + list2
final_list = []
print(sorted_list)
for i in range(len(sorted_list)):
for j in range(len(sorted_list)-1):
if sorted_list[j] > sorted_list[j + 1]:
# Swap
sorted_list[j], sorted_list[j + 1] = sorted_list[j + 1], sorted_list[j]
print(sorted_list)
l1 = sorted(random.sample(range(100), 10))
l2 = sorted(random.sample(range(100), 10))
print(l1,"\n",l2)
merge(l1, l2)
| true |
35dd88907cc148c1f0c3a98fc519c66364debe3a | himlayyy/Data-Analysis-with-Python | /Week 1/1-17-positivelist.py | 736 | 4.40625 | 4 | #!usr/bin/env python 3
"""Write a function positive_list that gets a list of numbers as a parameter, and returns
a list with the negative numbers and zero filtered out using the filter function.
The function call positive_list([2,-2,0,1,-7]) should return the list [2,1]. Test your
function in the main function.
"""
# def is_odd(x):
# """Returns True if x is odd and False if x is even"""
# return x % 2 == 1 # The % operator returns the remainder of integer division
# L=[1, 4, 5, 9, 10]
# print(list(filter(is_odd, L)))
# !/usr/bin/env python3
def positive_list(nums):
return list(filter(lambda x: x > 0, nums))
def main():
print(positive_list([2, -2, 0, 1, -7]))
if __name__ == "__main__":
main()
| true |
ab9e932af566d7bf8376e848533dd511d8cc6d0e | himlayyy/Data-Analysis-with-Python | /Week 1/1-14-find-matching.py | 621 | 4.375 | 4 | #!usr/bin/env python 3
"""Write function find_matching that gets a list of strings and a search string as
parameters. The function should return the indices to those elements in the input
list that contain the search string. Use the function enumerate.
An example: find_matching(["sensitive", "engine", "rubbish", "comment"], "en")
should return the list [0, 1, 3]."""
def find_matching(words, pattern):
matches = []
for index, word in enumerate(words):
if pattern in word:
matches.append(index)
return matches
print(find_matching(["sensitive", "engine", "rubbish", "comment"], "en")) | true |
26a1e3593d4e6014409a3fc2aeedbf7e696fedc2 | himlayyy/Data-Analysis-with-Python | /Week 1/1-11-interleave.py | 739 | 4.375 | 4 | #!/usr/bin/env python3
"""
Write function interleave that gets arbitrary number of lists as parameters.
You may assume that all the lists have equal length. The function should
return one list containing all the elements from the input lists interleaved. Test your function from the main function of the program.
Example: interleave([1,2,3], [20,30,40], ['a', 'b', 'c']) should return
[1, 20, 'a', 2, 30, 'b', 3, 40, 'c']. Use the zip function to implement
interleave. Remember the extend method of list objects.
"""
def interleave(*lists):
final_list = list(zip(*lists))
new_list = []
for item in final_list:
new_list.extend(item)
return new_list
print(interleave([1, 2, 3], [20, 30, 40], ['a', 'b', 'c']))
| true |
5c1cf86725643faeec5b5becf0442826f9744e8b | ani1203/programs-python | /functional_algorithm/LeapYear.py | 342 | 4.25 | 4 | # I/P -> Year, ensure it is a 4 digit number.
# Logic -> Determine if it is a Leap Year.
# O/P -> Print the year is a Leap Year or not.
from utilities import utility
try:
year = int(input("enter year you wan to check as leap year"))
utility.leap_year(year)
except Exception as e:
print("enter the year in the form of digits")
| true |
bdebe8c40b9dc4dd12c0e5d631e8ca4c3bbea2bf | akshat3358/10Days_of_Data_structures_in_python | /notes/DAY2(stack) | 1,005 | 4.15625 | 4 | class Stack():
def __init__(self): # Constructor to initiate the object.
self.items = []
def push(self, items): # To Push the item in the empty stack list.
self.items.append(items)
def pop(self): # To Pop the last item pushed in stack list.
return self.items.pop()
def get_stack(self): # To Fetch the items in stack list.
return self.items
def is_empty(self): # To check is stack list is empty.
return self.items == []
def peek(self): # To Fetch the last item in stack list.
if not self.is_empty():
return self.items[-1]
objectStack = Stack() # Object of the Stack Class.
print(objectStack.is_empty())
objectStack.push("Rat")
objectStack.push("Cat")
print(objectStack.get_stack())
objectStack.push("Bat")
print(objectStack.get_stack())
objectStack.push("Hat")
print(objectStack.is_empty())
print(objectStack.get_stack())
print(objectStack.peek())
objectStack.pop()
print(objectStack.get_stack())
| true |
026a4426ae29d30240693ba8190cdc261117263e | jmcs811/interview_prep | /data_structures/queues/deque.py | 2,430 | 4.15625 | 4 | class Deque:
'''
This is a double ended queue, it supports removing from
the front and the back of the list
'''
def __init__(self):
self.size = 0
self.head = None
self.tail = None
def add_first(self, item):
if item is None:
raise NoneError
node = ListNode(item)
node.next = self.head
node.prev = None
if self.size == 0:
self.head = node
self.tail = self.head
else:
self.head.prev = node
self.head = node
self.size += 1
def add_last(self, item):
if item is None:
raise NoneError
node = ListNode(item)
node.next = None
node.prev = self.tail
if self.size == 0:
self.tail = node
self.head = self.tail
else:
self.tail.next = node
self.tail = node
self.size += 1
def remove_first(self):
if self.size <= 0:
raise DequeEmpty
temp = self.head
self.head = self.head.next
if self.size == 1:
self.tail = None
else:
self.head.prev = None
self.size -= 1
return temp.val
def remove_last(self):
if self.size <= 0:
raise DequeEmpty
temp = self.tail
self.tail = self.tail.prev
if self.size == 1:
self.head == None
else:
self.tail.next = None
self.size -= 1
return temp.val
def deque_size(self):
return self.size
def __iter__(self):
self.n = self.head
return self
def __next__(self):
if self.n is not None:
temp = self.n
self.n = self.n.next
return temp.val
else:
raise StopIteration
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
class NoneError(Exception):
pass
class DequeEmpty(Exception):
pass
deque = Deque()
deque.add_first(3)
deque.add_first(2)
deque.add_first(1)
deque.add_last(4)
print(deque.remove_first()) # 1
print(deque.remove_first()) # 2
print(deque.remove_last()) # 4
print(deque.remove_last()) # 3
#print(deque.remove_last()) # DequeEmpty error
deque.add_first(2)
deque.add_last(3)
deque.add_first(1)
deque.add_last(4)
for i in deque:
print(i)
| true |
6cd89ec3bd1d42db58ee9344a72e7a6949e36875 | jmcs811/interview_prep | /data_structures/queues/linked_list_queue.py | 1,725 | 4.125 | 4 | class LinkedListQueue:
'''
Queue data structre based on linked lists. Items are
added to the end of the list and are pulled from the
beginning of the list
enqueue: O(1) adds to the queue
dequeue: O(1) removes oldest from the queue
isEmpty: O(1)
stack_size: O(1)
'''
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def enqueue(self, item):
'''
add item to end of list
'''
if self.tail is None:
self.head = ListNode(item)
self.tail = self.head
else:
self.tail.next = ListNode(item)
self.tail = self.tail.next
self.tail.next = None
self.size += 1
def dequeue(self):
'''
remove item from beginning of list
'''
if self.head is None:
raise StackEmpty
item = self.head
self.head = self.head.next
self.size -= 1
return item.val
def isEmpty(self):
return self.size <= 0
def stack_size(self):
return self.size
def __iter__(self):
self.n = self.head
return self
def __next__(self):
if self.n is not None:
temp = self.n
self.n = self.n.next
return temp.val
else:
raise StopIteration
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class StackEmpty(Exception):
pass
queue = LinkedListQueue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
for i in queue:
print(i)
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue()) | true |
216fbdb0febe9dda82cd03d5c13b9f73c0335f16 | ArnoutSchepens/Python_3 | /Oefeningen/standalone/functions_9.py | 724 | 4.1875 | 4 |
def list_manipulation(itemList, function, location, value = None):
if function == 'remove' and location == 'end':
return itemList.pop()
elif function == 'remove' and location == 'beginning':
return itemList.pop(0)
elif function == 'add' and location == 'end':
itemList.append(value)
return itemList
elif function == 'add' and location == 'beginning':
itemList.insert(0, value)
return itemList
print(list_manipulation([1, 2, 3], "remove", "end")) # 3
print(list_manipulation([1, 2, 3], "remove", "beginning")) # 1
print(list_manipulation([1, 2, 3], "add", "beginning", 20)) # [20,1,2,3]
print(list_manipulation([1, 2, 3], "add", "end", 30)) # [1,2,3,30]
| true |
464fbdcfe960f68bf103bd89d55cedb889d641a6 | chuayunyu/python-project | /code01.py | 322 | 4.15625 | 4 | name = input("What is your name?")
print("Hello " + name )
age = input("What is your age?")
age_in_days = int(age) * 365
print("You are " + age + " years old. You’ve lived for more than " + str(age_in_days) + " days!")
[there's apparently something wrong with the forth line but i copied it exactly from the slides??]
| true |
70f72de31fb81d868c07c1192ebd2cb1551cf90d | bestorw01/login | /login.py | 489 | 4.125 | 4 | #usernames and passwords
allowedUsernames = ['mentor','rukky','bob']
allowedPassword = 'password'
print('lOGIN PAGE')
username = input('Enter username: ')
#condition to check validity of username and password
if username in allowedUsernames:
password = input('Enter password: ')
if password == allowedPassword:
print(f'Welcome {username.capitalize()}')
else:
print('The password is incorrect')
else:
print('The username you entered is not available') | true |
d0059155c2161e22aac5faa67c385c21f76bf75c | lockbro/Python-Crash-Course | /9-2.py | 839 | 4.21875 | 4 | """
9-2 三家餐馆 :
根据你为完成练习 9-1 而编写的类创建三个实例,
并对每个实例调用方法 describe_restaurant() 。
"""
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print("This restaurant's name is " + self.restaurant_name +
", and it specialize in " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is opening")
theFirstRestaurant = Restaurant("yangquan", "chuan")
theSecondRestaurant = Restaurant("guangzhou", "yue")
theThirdRestaurant = Restaurant("jixiang", "lu")
theFirstRestaurant.describe_restaurant()
theSecondRestaurant.describe_restaurant()
theThirdRestaurant.describe_restaurant()
| false |
4183a6a9b14e1d16cfd87adf9bace8493ed94eda | lockbro/Python-Crash-Course | /10-1.py | 956 | 4.375 | 4 | """
10-1 Python 学习笔记 :
在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的 Python 知识,
其中每一行都以 “In Python you can” 打头。
将这个文件命名为learning_python.txt ,并将其存储到为完成本章练习而编写的程序所在的目录中。
编写一个程序,它读取这个文件,并将你所写的内容打印三次:
第一次打印时读取整个文件;
第二次打印时遍历文件对象;
第三次打印时将各行存储在一个列表中,
再在 with 代码块外打印它们。
"""
filename = "learning_python.txt"
with open(filename) as handle_file:
contents = handle_file.read()
print(contents.rstrip())
print("\n")
with open(filename) as handle_file:
for line in handle_file:
print(line.rstrip())
print("\n")
with open(filename) as handle_file:
lines = handle_file.readlines()
for line in lines:
print(line.strip())
| false |
9d07a6a9ef5b36b4030fbf3913901aeb34eeb487 | lockbro/Python-Crash-Course | /9-6.py | 1,569 | 4.4375 | 4 | """
9-6 冰淇淋小店 :
冰淇淋小店是一种特殊的餐馆。
编写一个名为 IceCreamStand 的类,让它继承你为完成练习 9-1 或练习 9-4 而编写的 Restaurant 类。
这两个版本的 Restaurant 类都可以,挑选你更喜欢的那个即可。
添加一个名为 flavors 的属性,用于存储一个由各种口味的冰淇淋组成的列表。
编写一个显示这些冰淇淋的方法。创建一个 IceCreamStand 实例,并调用这个方法。
"""
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("This restaurant's name is " + self.restaurant_name +
", and it specialize in " + self.cuisine_type)
def open_restaurant(self):
print("The restaurant is opening")
def set_number_served(self, set_number):
self.number_served = set_number
def increment_number_served(self, increment_number, total_number):
if self.number_served <= total_number:
self.number_served += increment_number
else:
print("Sorry , we don't recepte guest any more.")
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = ["Chocolate", "Coconut", "Vanilla", "Mango", "Taro"]
IceCreamStand = IceCreamStand("Häagen-Dazs", "IceCream")
print(IceCreamStand.flavors)
| false |
72d12c32bd2753193cb7474dc43b622147009d6b | anhnguyendepocen/ose-course-projects | /replications/Angrist_1990/auxiliary/auxiliary_visuals.py | 2,330 | 4.1875 | 4 | """Function to create the shades of grey Table 1 and function to create significance stars."""
import numpy as np
import pandas as pd
def background_negative_green(val):
"""
Change the background color of a cell in DataFrame according to its value.
Parameters
----------
val : float
single cell value in a pandas DataFrame.
Returns
-------
str
return background color for the cell of pandas DataFrame.
"""
if val == "":
color = "white"
elif val < -200:
color = "#009900"
elif -200 <= val < -150:
color = "#00cc00"
elif -150 <= val < -100:
color = "#80ff80"
elif -100 <= val < -50:
color = "#b3ffb3"
elif -50 <= val < 0:
color = "#e6ffe6"
else:
color = "white"
return f"background-color: {color}"
def p_value_star(data, rows, columns):
"""
Add a star to values that are statistically significant to the 5 percent level.
Parameters
----------
data : pd.DataFrame
DataFrame for which the stars should be added.
rows : tuple
The row index using slices.
columns : tuple
The column index using slices.
Returns
-------
data : pd.DataFrame
Returns the original DataFrame with significance stars.
"""
if isinstance(data.loc[rows, columns], pd.Series):
data_temp = data.loc[rows, columns].to_frame()
for index in np.arange(0, data_temp.shape[0], 2):
if abs(data_temp.iloc[index] / data_temp.iloc[index + 1])[0] > 1.96:
data_temp.iloc[index] = str(data_temp.iloc[index][0]) + "*"
else:
pass
else:
data_temp = data.loc[rows, columns]
for index in np.arange(0, data_temp.shape[0], 2):
for column in np.arange(0, data_temp.shape[1]):
if (
abs(
data_temp.iloc[index, column]
/ data_temp.iloc[index + 1, column]
)
> 1.96
):
data_temp.iloc[index, column] = (
str(data_temp.iloc[index, column]) + "*"
)
else:
pass
data.loc[rows, columns] = data_temp
return data
| true |
2384874f96974a143892eb00be1a9f53b351fb6d | YAtOff/python0 | /archive/2017/week17/tasks/about_string_manipulation.py | 1,994 | 4.5 | 4 | __ = "-=> FILL ME IN! <=-"
def assert_equal(expected, actual):
assert expected == actual, '%r == %r' % (expected, actual)
def assert_not_equal(expected, actual):
assert expected != actual, '%r != %r' % (expected, actual)
# use format to interpolate variables
value1 = 'one'
value2 = 2
string = "The values are {0} and {1}".format(value1, value2)
assert_equal(__, string)
# formatted values can be shown in any order or be repeated
value1 = 'doh'
value2 = 'DOH'
string = "The values are {1}, {0}, {0} and {1}!".format(value1, value2)
assert_equal(__, string)
# any python expression may be interpolated
import math # import a standard python module with math functions
decimal_places = 4
string = "The square root of 5 is {0:.{1}f}".format(math.sqrt(5),
decimal_places)
assert_equal(__, string)
# you can get a substring from a string
string = "Bacon, lettuce and tomato"
assert_equal(__, string[7:10])
# you can get a single character from a string
string = "Bacon, lettuce and tomato"
assert_equal(__, string[1])
# single characters can be represented by integers
assert_equal(__, ord('a'))
assert_equal(__, ord('b') == (ord('a') + 1))
# strings can be split
string = "Sausage Egg Cheese"
words = string.split()
assert_equal([__, __, __], words)
# strings can be split by char
string = "the,rain,in,spain"
words = string.split(',')
assert_equal([__, __, __, __], words)
# Pattern is a Python regular expression pattern which matches ',' or ';'
# raw strings do not interpret escape characters
string = r'\n'
assert_not_equal('\n', string)
assert_equal(__, string)
assert_equal(__, len(string))
# Useful in regular expressions, file paths, URLs, etc.
# strings can be joined
words = ["Now", "is", "the", "time"]
assert_equal(__, ' '.join(words))
# strings can change case
assert_equal(__, 'guido'.capitalize())
assert_equal(__, 'guido'.upper())
assert_equal(__, 'TimBot'.lower())
assert_equal(__, 'guido van rossum'.title())
assert_equal(__, 'ToTaLlY aWeSoMe'.swapcase())
| true |
fad39035e33f20a994862daf278cb352ec684147 | sagar-bhat/Python_Puzzles | /delete_node.py | 1,868 | 4.375 | 4 | class LinkedList(object):
'''
Represents a Linked List.
'''
def __init__(self):
'''
Constructor for Linked List.
'''
self.head=None
self.current=None
class Node(object):
'''
Node Representation.
'''
def __init__(self,next=None,value=None):
'''
Constructor for Node of Linked List
'''
self.next=next
self.value=value
def setValue(self,value):
self.value=value
def setNext(self,next):
self.next=next
def __str__(self):
return "-->[{0}]".format(self.value)
def insert(self,val):
'''
Inserts a Node in the Linked List
'''
node=self.Node()
node.value=val
if self.head==None:
self.head=node
self.current=self.head
else:
self.current.next=node
self.current=node
def delete_node(self,node):
'''
Deletes the provided node
from the Linked List.
'''
current = node
while current.next != None:
current.value = (current.next).value
current = current.next
current = None
def forwardList(self):
'''
Prints the Linked List
in Forward Manner.
'''
current=self.head
while current!=None:
print "{0}".format(current),
current=current.next
if __name__ == '__main__':
list1 = LinkedList()
for i in range(6):
list1.insert(i)
print "\nOriginal Linked List:\n"
list1.forwardList()
current = list1.head
while current.value!=3:
current=current.next
list1.delete_node(current)
print "\nUpdated Linked List:\n"
list1.forwardList()
| true |
2f492396fa9c74c37bbfd17e346adf2daa8e0533 | himanshuadvani/PythonContent | /Assignment3/Assignment3_4.py | 382 | 4.125 | 4 | def Frequency(arr,no):
iCount=0
for i in range(len(arr)):
if(arr[i]==no):
iCount=iCount+1
return iCount
iSize=input("Enter number of elements: ")
numbers=list()
for i in range(0,int(iSize)):
temp=int(input("Element: "))
numbers.append(temp)
num=int(input("element element to be searched: "))
ret=Frequency(numbers,num)
print("Frequency of {0} is {1}".format(num,ret)) | true |
288db980d0df5e9e630f48d1c6138dcc8ec9fc87 | Alibi14/thinkpython-solutions | /factorial.py | 360 | 4.125 | 4 | import math
def factorial(n):
if not isinstance(n, int):
print("This function will accept only integers")
return None
elif n < 0:
print("This function will accept only positive numbers")
return None
elif n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(6))
| true |
3cfdbb7de67f425fa7125140fc5a5fee7fbd2bcd | IsaSchin/exercises_python | /0.09.py | 1,177 | 4.25 | 4 | print ("Exercício 9")
print ("Digite três números para serem colocados em ordem decrescente")
num1 = float(input("Digite seu primeiro número: "))
num2 = float(input("Digite seu segundo número: "))
num3 = float(input("Digite seu terceiro número: "))
if num1 > num2 and num1 > num3:
if num2 > num3:
print ("Os números em ordem decrescente são: ", num1, num2, num3)
if num2 < num3:
print ("Os números em ordem decrescente são: ", num1, num3, num2)
if num3 > num2 and num3 > num1:
if num2 > num1:
print ("Os números em ordem decrescente são: ", num3, num2, num1)
if num2 < num1:
print ("Os números em ordem decrescente são: ", num3, num1, num2)
if num2 > num1 and num2 > num3:
if num1 > num3:
print ("Os números em ordem decrescente são: ", num2, num1, num3)
if num1 < num3:
print ("Os números em ordem decrescente são: ", num2, num3, num1)
#num_min = min(num1, num2, num3)
#num_max = max(num1, num2, num3)
#num_mid = (num1 + num2 + num3) - num_min - num_max
#print (f"Os números em ordem decrescente são: {num_max}, {num_mid}, {num_min}") | false |
5b839cb0e7051e3483cca2176d7883c5b98b6d82 | jframe9/LeetCode_learn | /String_play/the_Last_word_Length.py | 600 | 4.21875 | 4 | '''
问题描述:
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
输入: "Hello World"
输出: 5
'''
strs = "a"
def get_last_str(strs):
# 需要去除字符串两端的空格
split_str_list = strs.strip().split(' ')
print(split_str_list)
if split_str_list[-1] == '':
return 0
return len(split_str_list[-1])
print(get_last_str(strs)) | false |
4fcd2b12565fe99f4b968250a89e544f05f7961c | ac349/Winter-2021_ | /realdigitfinder.py | 704 | 4.28125 | 4 | import re
#this file uses regular expressions to parse a text file and return a list of temperatures and humidities
def parse_file(filename):
digit_pattern = re.compile(r"(\d+\.\d+)")
temperatures= []
humidities = []
with open(filename) as input_file:
for input_line in input_file.read().splitlines():
results = digit_pattern.findall(input_line)
temperatures.append(float(results[0]))
humidities.append(float(results[1]))
return temperatures, humidities
returned_temperatures, returned_humidities = parse_file("experiment_1_data.txt")
print("temperatures=",returned_temperatures)
print("humidities=", returned_humidities)
| true |
fb6f002469136313bb1a5f75fe6a96d6f7bdd2e7 | randalpereiradesouza/PythonFound- | /aulas/aula03.py | 2,961 | 4.1875 | 4 | # Regras da linguagem
# Palavras reservadas não podem ser utilizadas para nomear outras coisas.
# Estrutuas de Condiçoes,repeticoes, funcoes, classes e contextos sempre terminam com :
# comandos que estão dentro de estruturas são identadas com 4 espaços
# # Objetos criados não podem começar com numeros, vigula, ponto...
# # Estrutura de Repetição
# ## While
# contador = 0
# while contador < 100:
# print(contador)
# contador += 1
# while True:
# print("Sistema integrado de escolha")
# print('Digite:')
# print('1 - Para Escolher primeira opção')
# print('2 - Para Escolher segunda opção')
# print('0 - Para Sair')
# opcao = int(input('>>> '))
# if opcao == 1:
# print('opçãos:')
# print('1 - chocolate')
# print('2 - dinheiro')
# print('0 - voltar ao menu principal')
# opcao2 = int(input('>>> '))
# if opcao2 == 1:
# print('O Tim estava certo')
# break
# elif opcao2 == 2:
# print('O Tim estava errado')
# break
# else:
# continue
# elif opcao == 2:
# print('Você escolheu a segunda opção')
# elif opcao == 0:
# break
# else:
# print('Opção Inválida')
## For
# texto = 'Olá eu sou um texto'
# for caracter in texto:
# print(f'agora a variavel caracter é {caracter}')
# produtos = ['Camiseta A', 'Camiseta B', 'Camiseta C', 'Calca 1']
# for prod in produtos:
# print(prod)
# Conjuntos - Coleções
# # Listas - Conjunto de objetos
# lista = ["String 1", "String 2", 2, 5, 1.6, True]
# # Métodos de lista
# lista.append('Arquivo 1')
# lista.insert(2, 'Dado')
# lista.remove('Dado')
# lista.pop(1)
# lista.sort('Dado')
# lista.clear()
# # Indexação de listas
# lista[0]
# lista[1][2][2][2]
# # Tuplas - Lista não alteravel
# # cadastro = ('Joao', 'Nascimento', 26)
# # cadastro.count()
# # cadastro.index()
# # Dicionarios
# nome = input("Digite seu nome: ")
# idade= input("Digite sua idade: ")
# email= input("Digite seu email: ")
# telefone= input("Digite seu telefone: ")
# dados_pessoais = {"nome": nome,
# "idade": idade,
# "Telefone": telefone,
# "Email": email}
# dados_estaduais = {
# "SP": {
# "Nome": "Sao Paulo",
# "Populacao": 150000,
# "IDH": 15,
# "Times": ['sao paulo', 'corinthians', 'palmeiras', 'santos']
# },
# "BH": {
# "Nome": "Belo horizonte",
# "Populacao": 10000,
# "IDH": 12
# },
# "RJ": {
# "Nome": "Rio de Janeiro",
# "Populacao": 130000,
# "IDH": 9
# }
# }
# # Métodos de dict
# dados_pessoais.keys()
# dados_pessoais.values()
# dados_pessoais.get()
# dados_pessoais.clear()
# # Fatiamento de dicionario
# dados_pessoais["idade"]
# # Sets - Conjuntos de valores únicos
# conjunto = {1,2,4,5,6,7,8,9}
| false |
98aeb1425f8b87206fb444c1e1c33cae6dd50bcb | Hecvi/Tasks_on_python | /task54.py | 420 | 4.15625 | 4 | # Дана строка. Получите новую строку, вставив между каждыми двумя
# символами исходной строки символ *. Выведите полученную строку
s = input()
len = len(s)
i = 0
while i < len:
print(s[i], end='')
if i + 1 != len:
print('*', end='')
i += 1
# можно и так:
# print(*input(), sep="*")
| false |
e75aae1a7a9853c12f0eb99c4c3a1b463c9e6b30 | Hecvi/Tasks_on_python | /task85.py | 758 | 4.34375 | 4 | # Дано действительное положительное число a и целоe число n. Вычислите aⁿ
# Решение оформите в виде функции power(a, n). Стандартной функцией
# возведения в степерь пользоваться нельзя
# Вводится действительное положительное число a и целоe число n
def power(a, n):
res = 1
if n == 0:
return 1
if n > 0:
while n:
res *= a
n -= 1
if n < 0:
while n:
res /= a
n += 1
return res
print(power(float(input()), int(input())))
# как же я иногда туплю print(a**n)!
| false |
c66e43287f3e00ecd3651470d7fced6fc202d7fc | vsai/challenge | /lexico_sorting.py | 1,439 | 4.21875 | 4 | # Summary: Write a function to sort an array of strings based on an arbitrary lexicographic ordering.
# The function will take two parameters: an array of strings to sort and a string specifying the lexicographic order.
def get_new_word(word, priority_map):
new_cs = map(lambda char: priority_map[char], list(word))
return ''.join(new_cs)
def lexico_sorting(arr_words, str_lexico):
# len(array_of_inputs) = n
# len(str_lexico) = k
# memory: O(2k + 2n) = O(k+n) ~= O(n)
# requires O(log(n)) runtime - for python sorting functionality
# create priority map
priority_map = {}
priority_map_reverse = {}
for i in xrange(len(str_lexico)):
c = str_lexico[i]
new_c = chr(ord('a') + i)
priority_map[c] = new_c
priority_map_reverse[new_c] = c
new_arr_words = map(lambda word: get_new_word(word, priority_map), arr_words)
new_arr_words.sort()
return map(lambda word: get_new_word(word, priority_map_reverse), new_arr_words)
# Given Tests
assert(lexico_sorting(["acb", "abc", "bca"], "abc") == ["abc","acb","bca"])
assert(lexico_sorting(["acb", "abc", "bca"], "cba") == ["bca", "acb", "abc"])
assert(lexico_sorting(["aaa","aa",""], "a") == ["", "aa", "aaa"])
# Personal Tests
assert(lexico_sorting([],"") == [])
assert(lexico_sorting([], "asdf") == [])
assert(lexico_sorting(["asdf", "ddf", "", "asdf", "aaaa"], "fsad") == ["", "asdf", "asdf", "aaaa", "ddf"])
| true |
85ee20b46730618f5201f329c08e6a8a28daaea0 | MatiasKala/PythonRepo | /AlgoritmosDeOrdenamiento/BubbleSort.py | 934 | 4.125 | 4 | def bubbleSort(arr):
tamanio = len(arr)
# Vamos a dar 1 vuelta por numero cada item
# Es decir si son 10 elementos dariamos 10 vueltas
for i in range(tamanio-1):
# Una vuelta por cada item pero vamos terminando siempre
# una posicion antes (para no hacer tan ineficiente el programa)
# Ej: la primera llega a tamaño-0-1, la segunda a tamaño-1-1,
# tercera tamaño-2-1
for j in range(0, tamanio-i-1):
# Intercambia si el numero siguiente es menor
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print(arr)
# PSEUDO
# bubbleSort(array)
# for i <- 1 to indexOfLastUnsortedElement-1
# if leftElement > rightElement
# swap leftElement and rightElement
# end bubbleSort
# Explicacion con imagenes: https://www.geeksforgeeks.org/bubble-sort/ | false |
54d61debf8e8d7954595e5e11aae8719d6b7fe32 | ashwanijha04/SL | /3a.py | 356 | 4.46875 | 4 | # 3.
# Write a python program
# to find the longest words in a file.
filename = '/Users/apple/Desktop/Fin_aid'
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print (longest_word(filename)) | true |
6ec74d6689017d731009ecf23b4431344691d15c | ashwanijha04/SL | /4a.py | 474 | 4.53125 | 5 | 4.
# Write a python program
# to read in a list of numbers.
# Use one-line comprehensions to create a new list of even numbers.
# Create another list reversing the elements.
# read elements to list
M = [x for x in S if x % 2 == 0]
# Read a list of numbers
input_list = eval(input("Enter the comma seperated values: \n"))
even_list = [x for x in input_list if x%2 == 0.0]
print ("Even list : ",even_list)
print ("Even reversed list : ",even_list[::-1])
| true |
c00b5e2c779234b79902d8d5677ad970e6f968ea | qlccks789/Web-Study | /17_python/part2-collection/test09_시퀀스형_특징5(멤버확인).py | 497 | 4.34375 | 4 | """
시퀀스 자료형의 특징
멤버 확인 : "in" 키워드를 이용하여 특정 값이 시퀀스에 포함되어 있는지 확인 가능
값 in 자료
값 not in 자료
"""
my_list = ["p", "y", "t", "h", "o", "n"]
print("p" in my_list) # True
print("a" in my_list) # False
print("p" not in my_list) # False
print("a" not in my_list) # True
my_str = "python"
print("p" in my_str) # True
print("a" in my_str) # False
print("p" not in my_str) # False
print("a" not in my_str) # True
| false |
0315f449b08c70882638191b473a49a3ea89fc02 | qlccks789/Web-Study | /17_python/part1-basic/test06_논리형.py | 430 | 4.21875 | 4 | # 비교 연산자
boolVal = True
print(boolVal)
print(type(boolVal))
boolVal = 10 < 20
print(boolVal)
boolVal = 10 != 20
print(boolVal)
boolVal = 10 == 10
print(boolVal)
# 논리 연산자
"""
boolVal = True and True
print(boolVal)
boolVal = True & True # && 은 없음
print(boolVal)
boolVal = True or True
print(boolVal)
boolVal = True | True
print(boolVal)
boolVal = not True # ! 은 없음
print(boolVal)
"""
| false |
a07b5728d2022d934090bdd70738a9bae2271abd | Sekams/Bucketlist | /app/models/activity.py | 1,027 | 4.15625 | 4 | class Activity(object):
"""This class describes the structure of the Activity object"""
def __init__(self, name, target_age, image_url="", status=False):
"""This method creates an instance of the Activity class"""
self.name = name
self.target_age = target_age
self.image_url = image_url
self.status = status
def change_status(self, status):
"""This method changes the status in the Activity instance"""
self.status = status
return self.status
def rename(self, name):
"""This method renames the Activity instance"""
self.name = name
return self.name
def change_target_age(self, target_age):
"""This method changes the target age of the Activity instance"""
self.target_age = target_age
return self.target_age
def change_image_url(self, image_url):
"""This method changes the image url of the Activity instance"""
self.image_url = image_url
return self.image_url
| true |
ae71cebd404f84a1d8df0ef1259830f9cd131cc0 | MrFixit96/cmgen141 | /week1/CarCalc.py | 1,128 | 4.125 | 4 | '''
Program: Car Calculator
File: CarCalc.py
Autho: James Anderton
Date: 27-Aug-2017
Purpose: This Program with take the input miles per hour, hours driven, vehicle mpg,
and then calculate the distance travelled to the tenth of a mile, the
amount of gas it took to one decimal place, and then display the distance
and amount of gas used.
'''
# INPUT
print("===============================================================================================")
mph = int(input("Please enter the rate of speed in miles per hour: "))
timeDriven = float(input("Please enter the length of time spent driving in hours: "))
mpg = int(input("Please enter the efficiency of the car being driven in terms of Miles per Gallon: "))
print("===============================================================================================\n")
# PROCSESS
distance = float(mph * timeDriven)
gasUsed = float(distance /mpg)
# OUTPUT
print("The car traveled " + str(format(distance, '.1f')) + " miles and used " + str(format(gasUsed, '.1f')) + " gallons of gas.")
| true |
58bd3205039eb94dca991bbff28d16152cde91c9 | MrFixit96/cmgen141 | /week3/ReverseString.py | 438 | 4.21875 | 4 | '''
Program: ReverseString
File: ReverseString.py
Author: James Anderton
Date: 7-SEP-2017
Purpose: to reverse a string's characters
'''
def strReverse(aString):
revString = ''
for ch in aString:
revString = ch + revString
print(revString)
revString2=""
for item in ["bob", "tom", "mary"]:
revString2 = " " + item + revString2
print(revString2)
strReverse("Hello")
| true |
d38d176f93d8c2d7693fcb49515fab78bf593002 | MrFixit96/cmgen141 | /week6/Physics/KineticEnergy.py | 1,767 | 4.4375 | 4 | #
# Program: KineticEnergy
# File: Mass.py
# Author: James Anderton
# Date: 03-Oct-2017
# Purpose: program to determine the kinetic energy of an object
# KE= 1/2 mv2
#
#########################################################
#
# SUB: displayResults
# PURPOSE: Display the results of processing to the user
# REQUIRES: distance, fallingSecs
#
#########################################################
def displayResults(mass, velocity, energy):
print("An object weighing", mass, "kilograms and traveling at a velocity of", velocity , "meters/sec has a kinetic"
"energy of", energy, "Joules")
# EndSub
##########################################################
#
# SUB: kineticEnergy
# PURPOSE: a function named kinetic_energy that accepts an object's mass (in kilograms)
# and velocity (in meters per second) as arguments. The function should return the amount
# of kinetic energy that the object has..
# REQUIRES: fallingSecs
# RETURNS: distance
#
##########################################################
def kineticEnergy(mass, velocity):
energy = (mass * velocity ** 2) / 2
return energy
# EndSub
#########################################################
#
# SUB: getInput
# PURPOSE: Take User Input for processing
# RETURNS: fallingSecs
#
#########################################################
def getInput():
print("Kinetic Energy Calculation")
print("==================================")
mass = int(input("Please enter the mass of the object in kilograms: "))
velocity = int(input("Please enter the velocity of the object in meters per second: "))
return mass, velocity
# EndSub | true |
17308a751e75f8c760d28ca9be4525e993e8e136 | jb997/Restaurant | /restaurant.py | 1,306 | 4.125 | 4 | class Menu(object):
def __init__(self):
self.starters = {"Soup": 6.00, "Bruschetta": 5.00, "Meatballs": 8.00, "Garlic Flatbread": 4.00}
self.mains = {"lasagne": 11.00, "pizza": 9.50, "penne al ragu": 9.00, "risotto": 10.00}
self.desserts = {"tirimasu": 7.00, "gelato": 5.00, "lemon possett": 5.50, "Hazelnut Dream": 6.00}
def select_course(self, course_name, options):
print "Please see our " + course_name + " options below."
for key in options:
print key
print ""
choice = raw_input("Choose your " + course_name + ". ")
while choice not in options:
print "Unfortunately, this is not something we currently serve.\nPlease choose something on the menu.\n"
choice = raw_input("Choose your " + course_name + ". ")
print "You selected " + choice + "\n"
return choice
def meal(self):
starter = self.select_course("starter", self.starters)
main = self.select_course("main", self.mains)
dessert = self.select_course("dessert", self.desserts)
total = self.starters[starter] + self.mains[main] + self.desserts[dessert]
tip = total * 1.10
print "Total: ${:.2f}\nTotal plus tip: ${:.2f}".format(total, tip)
menu = Menu()
menu.meal()
| true |
e9d632ce8cac79ed5ee90e4a68060e62efd836b9 | jbmenashi/python-course | /random_stuff/mileage.py | 282 | 4.15625 | 4 | print("How many kilometers did you run today?")
kms = input() #takes in user input on command line
miles = float(kms)/1.60934 #float converts the type, could do int() or str()
print(f"That means you ran {round(miles, 2)} miles") #round takes 2 arguments, the thing and the decimals
| true |
ce8d2427bb2f4af9d8eb913225596850ca854ac3 | hi-eeprom/Python_Test | /Demo/simple_code/_iterator_generator.py | 881 | 4.28125 | 4 | # 迭代器与生成器测试代码
# reference: http://www.runoob.com/python3/python3-iterator-generator.html
import sys # 引入sys模块
# 1. 迭代器: iter
list=[1,2,3,4]
it = iter(list) # 创建迭代器对象
for x in it:
print (x, end=" ")
print("\n")
# 2. 迭代器: next
list = [1, 2, 3, 4]
it = iter(list) # 创建迭代器对象
#while True:
# try:
# print(next(it))
# except StopIteration:
# sys.exit()
print(next(it))
print(next(it))
# 3. 生成器: yield
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
#print(f)
while True:
try:
print(next(f), end=" ")
except StopIteration:
sys.exit() | false |
e59290fad4698891b6b8ee1aaed47085cb21a5cf | hi-eeprom/Python_Test | /Demo/simple_code/_dictionary.py | 1,645 | 4.1875 | 4 | # 字典测试代码
# reference: http://www.runoob.com/python3/python3-dictionary.html
# 1. 创建字典:字典的每个键值(key=>value)对用冒号(:)分割,整个字典包括在花括号({})中。键必须是唯一的,但值则不必
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
print("dict:", dict); print("dict2:", dict2)
# 2. 访问字典里的值:把相应的键放入方括弧。如果用字典里没有的键访问数据,会输出错误
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
#print ("dict['Alice']: ", dict['Alice']) # KeyError: 'Alice'
# 3. 修改字典:向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # 更新 Age
dict['School'] = "菜鸟教程" # 添加信息
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
print("dict:", dict)
# 4.删除字典元素:能删单一的元素也能清空字典
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del dict['Name'] # 删除键 'Name'
#dict.clear() # 删除字典
#del dict # 删除字典
print ("dict['Age']: ", dict['Age'])
print("dict:", dict)
#print ("dict['School']: ", dict['School']) # KeyError: 'School'
# 5. 字典键的特性: 创建时如果同一个键被赋值两次,后一个值会被记住
dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鸟'}
print ("dict['Name']: ", dict['Name'])
print("dict:", dict) | false |
1a55803d7271258e6ca0dfce4dd33265dd09d3a0 | runlikeforrestgump/quicksort | /qs_python/quicksort.py | 1,032 | 4.34375 | 4 | def quicksort(unsorted_list):
# Base case: nothing left to partition, so return an empty list,
# and don't make a recursive call.
if unsorted_list == []:
return []
else:
# First, select a pivot.
pivot = unsorted_list[0]
# Retrieve all the values less than the pivot to create the
# left partition.
L_partition = [x for x in unsorted_list[1:] if x < pivot]
# Sort the left partition.
lesser = quicksort(L_partition)
# Retrieve all the values greater than or equal to the pivot to
# create the right partition.
R_partition = [x for x in unsorted_list[1:] if x >= pivot]
# Sort the right partition.
greater = quicksort(R_partition)
# Return the sorted list.
return lesser + [pivot] + greater
if __name__ == "__main__":
test_list = [4, 8, 1, 6, 3, 7, 2, 5]
print "Unsorted list: ",
print test_list
test_list = quicksort(test_list)
print "\nSorted list: ",
print test_list
| true |
501f9de82e00af1aebb77f3dc7a5d1dd82ac6fa8 | FLoydSan/Python-Lessons | /currency_exchanger/currency_exchanger/currency_exchanger.py | 2,828 | 4.15625 | 4 | print " -= Welcome to currency exchanger =-"
print ""
user_exit = 0
while user_exit != 'q':
print ""
print "Type 1 if you want to change UAH to USD"
print "Type 2 if you want to change UAH to EUR"
print "Type 3 if you want to change UAH to RUB"
print "Type 4 if you want to change USD to UAH"
print "Type 5 if you want to change EUR to UAH"
print "Type 6 if you want to change RUB to UAH"
print ""
inp = raw_input("Your choice: ")
try:
choice = int(inp)
except:
inp = raw_input("Your were wrong, try it again: ")
choice = int(inp)
if choice == 1:
inp = raw_input("Input your UAH amount here: ")
try:
uah = float(inp)
except:
inp = raw_input("ERROR: Value must be numeric, try again: ")
uah = float(inp)
print "You have ", uah / 12.9555495, "USD"
user_exit = raw_input("Type q for exit program or any key to start again: ")
if choice == 2:
inp = raw_input("Input your UAH amount here: ")
try:
uah = float(inp)
except:
inp = raw_input("ERROR: Value must be numeric, try again: ")
uah = float(inp)
print "You have ", uah / 16.2255302, "EUR"
user_exit = raw_input("Type q for exit program or any key to start again: ")
if choice == 3:
inp = raw_input("Input your UAH amount here: ")
try:
uah = float(inp)
except:
inp = raw_input("ERROR: Value must be numeric, try again: ")
uah = float(inp)
print "You have ", uah / 16.2255302, "EUR"
user_exit = raw_input("Type q for exit program or any key to start again: ")
if choice == 4:
inp = raw_input("Input your USD amount here: ")
try:
usd = float(inp)
except:
inp = raw_input("ERROR: Value must be numeric, try again: ")
usd = float(inp)
print "You have ", usd * 12.9555495, "UAH"
user_exit = raw_input("Type q for exit program or any key to start again: ")
if choice == 5:
inp = raw_input("Input your EUR amount here: ")
try:
eur = float(inp)
except:
print "ERROR: Value must be numeric, try again: "
eur = float(inp)
print "You have ", eur * 16.2255302, "UAH"
user_exit = raw_input("Type q for exit program or any key to start again: ")
if choice == 6:
inp = raw_input("Input your RUB amount here: ")
try:
rub = float(inp)
except:
print "ERROR: Value must be numeric, try again: "
rub = float(inp)
print "You have ", rub * 16.2255302, "UAH"
user_exit = raw_input("Type 'q' to quit program or press 'ENTER' to start again")
| true |
02cfc66bbbc467b8ae76d72beef46db9e581c3ba | robinscreech/startingPython | /averagecalc.py | 752 | 4.125 | 4 | # userInput = input('Enter a set of numbers: ')
#
# def genAvg(setOfNumbers):
# sumOfNumber = 0
#
# for value in userInput:
# sumOfNumber += value
# totalAverage = sumOfNumber / len(userInput)
#
# print('The total sum is: ', sumOfNumber)
# print('The total avg is: ', totalAverage)
#
# genAvg(userInput)
numbers = []
totalSum = 0
while (True):
val = input('Please add numbers or (press \'q\' when done) : ')
if val == 'q':
break
else:
numbers.append(int(val))
print("Number accepted, continue adding or press Q to submit & quit")
for number in numbers:
totalSum += number
totalSum = totalSum / len(numbers)
print ('Total average of your numbers is {0:.0f} '.format(totalSum))
| true |
474c7ee7b2555a8daa5c8c181bba6cc89ee3eac5 | robinscreech/startingPython | /range.py | 431 | 4.125 | 4 |
#range(10)
#for val in range(10):
#print(val)
#for val in range(2, 10):
# print(val)
#for val in range(2,10, 2):
# print(val)
# incrementing count on range stepping 2
# names = ['Me','Stuff','Books','Things']
#
# for i in range(0, len(names), 2):
# print(i, names[i])
#decrementing count on range using -1
names = ['Me','Stuff','Books','Things']
for i in range(len(names) - 1, -1, -1):
print(i, names[i])
| false |
fe45b4a811cc080c57b25b933434f6cadb6c4ef4 | byrongerlach/AdventOfCode2020 | /AdventOfCode2020/ChallengesPython/Day22.py | 2,553 | 4.25 | 4 | # Day 22
# Crab combat
# There's two players in a card game.
# https://adventofcode.com/2020/day/22
# Quoted from above: "The game consists of a series of rounds: both players draw their top card,
# and the player with the higher-valued card wins the round. The winner keeps
# both cards, placing them on the bottom of their own deck so that the winner's
# card is above the other card. If this causes a player to have all of the cards,
# they win, and the game ends."
# This tells me that we need two mutable collections to be able to hold each
# player's cards. We compare the top two cards in each iteration, and move them
# according to the rules above.
# Looks like a deque would be good to try for this: https://docs.python.org/3/library/collections.html#collections.deque
# Example.
import collections
from collections import deque
# Set up each player's cards
player1 = deque([9,2,6,3,1])
player2 = deque([5, 8, 4, 7, 10])
def runGame():
while (len(player1) and len(player2)):
p1Card = player1.popleft()
p2Card = player2.popleft()
if (p1Card > p2Card):
player1.append(p1Card)
player1.append(p2Card)
if (p2Card > p1Card):
player2.append(p2Card)
player2.append(p1Card)
# print (f"{player1}")
# print (f"{player2}")
# Score is computed from the RHS, and is the cumulative total of each card * position
def computeScore(player):
score = 0
count = 1
while (len(player)):
card = player.pop()
score += card*count
count += 1
return score
print ("\nExample solution:\n")
runGame()
#Check which player is the winner
if (len(player1)):
score = computeScore(player1)
print (f"Player 1 is the winner, with score: {score}")
#Check which player is the winner
if (len(player2)):
score = computeScore(player2)
print (f"Player 2 is the winner, with score: {score}")
# Solve part 1
print ("Part1 solution:\n")
print ("Starting decks:")
player1 = deque([41,26,29,11,50,38,42,20,13,9,40,43,10,24,35,30,23,15,31,48,27,44,16,12,14])
print (f"{player1}")
player2 = deque([18,6,32,37,25,21,33,28,7,8,45,46,49,5,19,2,39,4,17,3,22,1,34,36,47])
print (f"{player2}")
runGame()
#Check which player is the winner
if (len(player1)):
score = computeScore(player1)
print (f"Player 1 is the winner, with score: {score}")
#Check which player is the winner
if (len(player2)):
score = computeScore(player2)
print (f"Player 2 is the winner, with score: {score}")
| true |
d7cca9ee2d0dbfe3a066353f6ca95bac2d1bba4f | vinay10949/DataStructuresAndAlgorithms | /Sorting/BubbleSort.py | 755 | 4.25 | 4 | #Time Complexity Worst Case o(n*n-1)-- o(n^2)
# BestCase o(n) & o(1) swaps
#Space complexity o(1)
#For first iteration n-1 comparisons and swaps
#For the second iteration n-2 comparisons and swaps.
def bubbleSort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [60, 30, 20, 10, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]), | true |
9a66473d77e60c767cbf16980ebcba925ee998e4 | sadamexx/Intro-Python-I | /src/13_file_io.py | 959 | 4.3125 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close attention to your current directory when trying to open "foo.txt"
# YOUR CODE HERE
f = open('./foo.txt', 'r')
print(f.read())
# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
# then close the file. Open up "bar.txt" and inspect it to make
# sure that it contains what you expect it to contain
# YOUR CODE HERE
new = open('./bar.txt', 'w+')
new.write(f'It could all be so simple, but you would rather make it hard!\n')
new.write(f'Loving you is like a battle, but we both come out scarred \n')
new.close()
new = open('./bar.txt', 'r')
print(new.read())
| true |
21599525e3545d6c46d6110a843e90df57e96260 | mcurry51/EBEC | /save.py | 1,955 | 4.15625 | 4 | ################################################################################
# Author: Michael Curry
# Date: 03/08/2021
# This program asks users to input scores, and output the graded of each score
# as well as the average of all scores.
################################################################################
def main():
counter = 0
while counter < 5:
scort = get_valid_score()
determine_grade(scort)
counter += 1
scores = get_valid_score()
calc_average(scores)
return
def get_valid_score():
count = 0
grades = []
while count < 5:
score = float(input('Enter a score: '))
if score < 0 or score > 100:
while score < 0 or score > 100:
print('Invalid Input. Please try again.')
grade_score = float(input('Enter a score: '))
score = grade_score
if score > 0 and score <= 100:
grades.append(score)
else:
grades.append(score)
count += 1
return score
def determine_grade(score):
if score >= 90 and score <= 100:
print(f'The letter grade for {score} is A.')
return 'A'
elif score >= 80 and score < 90:
print(f'The letter grade for {score} is B.')
return 'B'
elif score >= 70 and score < 80:
print(f'The letter grade for {score} is C.')
return 'C'
elif score >= 60 and score < 70:
print(f'The letter grade for {score} is D.')
return 'D'
else:
print(f'The letter grade for {score} is F.')
return 'F'
def calc_average(grades):
average = sum(grades) / len(grades)
average_formatted = f'{average:.1f}'
average_formatted_again = float(average_formatted)
print(type(average_formatted_again))
print(f'The average score is {average_formatted_again}.')
return average_formatted
if __name__ == '__main__':
main() | true |
71a563f7d576743c993a5dfdfda3d6f1865f51bb | mcurry51/EBEC | /fluid_mechanics.py | 1,635 | 4.375 | 4 | ################################################################################
# Author: Michael Curry
# Date: 02/21/2021
# This program asks the user for the velocity of thewater flowing through a pipe
# (V), for the pipe’s diameter (d), and to select the water’s tem-perature (T)
# from 5C,10C,and 15C
################################################################################
velocity = float(input('Enter the velocity of water in the pipe: ')) # Velocity of water
pipe_diameter = float(input('Enter the pipe\'s diameter: ')) # Diameter of pipe
pipe_temperature = float(input('Enter the temperature in °C as 5, 10, or 15: ')) # Temperature of water
if pipe_temperature == 5: # Condition 1
viscocity = 1.49 / 1000000
reynolds_number = (velocity * pipe_diameter) / viscocity
rey_sci_not = f'{reynolds_number:.2e}'
print(f'The Reynolds number for flow at {velocity} m/s '
f'in a {pipe_diameter} m diameter pipe at {pipe_temperature}°C is {rey_sci_not}.')
elif pipe_temperature == 10: # Condition 2
viscocity = 1.31 / 1000000
reynolds_number = (velocity * pipe_diameter) / viscocity
rey_sci_not = f'{reynolds_number:.2e}'
print(f'The Reynolds number for flow at {velocity} m/s '
f'in a {pipe_diameter} m diameter pipe at {pipe_temperature}°C is {rey_sci_not}.')
else: # Condition 3
viscocity = 1.15 / 1000000
reynolds_number = (velocity * pipe_diameter) / viscocity
rey_sci_not = f'{reynolds_number:.2e}'
print(f'The Reynolds number for flow at {velocity} m/s '
f'in a {pipe_diameter} m diameter pipe at {pipe_temperature}°C is {rey_sci_not}.')
| true |
812245d2cae9e0109e12560352923f1fe6f2af42 | Ambreensamoo/python-chap-3 | /More Guests.py | 1,089 | 4.21875 | 4 | #exercise 3.6
invetation=["sadaf","samreen","afshan"]
print(invetation[0].title()+" ,I would like to invite you for dinner")
print(invetation[1].title()+" ,I would like to invite you for dinner")
print(invetation[2].title()+" ,I would like to invite you for dinner")
print(invetation[2].title()+" ,sorry you can’t make it .")
invetation[2]="mehwish"
print(invetation[2].title()+" you are inviting .")
print(invetation[0].title()+" is still in my list")
print(invetation[1].title()+" is still in my list")
print("Congratzz!!, I found big dinner table")
invetation.insert(0,"iqra")
invetation.insert(2,"asiya")
invetation.append("hifza")
print(invetation[0].title()+" ,I would like to invite you for dinner")
print(invetation[1].title()+" ,I would like to invite you for dinner")
print(invetation[2].title()+" ,I would like to invite you for dinner")
print(invetation[3].title()+" ,I would like to invite you for dinner")
print(invetation[4].title()+" ,I would like to invite you for dinner")
print(invetation[5].title()+" ,I would like to invite you for dinner")
| true |
f47e9514e7e08130544ef5056236923eaa051641 | sumit88/PythonLearning | /pandasLearning/DataframeIterating.py | 907 | 4.15625 | 4 | import pandas as pd
import ProjectUitlities.Utils as Utils
# dictionary of lists
dict = {'name': ["aparna", "pankaj", "sudhir", "Geeku"],
'degree': ["MBA", "BCA", "M.Tech", "MBA"],
'score': [90, 40, 80, 98]}
# creating a dataframe from a dictionary
df = pd.DataFrame(dict)
# iterating over rows using iterrows() function
Utils.printSpaces("data frame iterationss using iterrows")
for i, j in df.iterrows():
print(f'dataframa indes {i} with data: \n {j} \n')
print()
Utils.printSpaces("Iterating Columns ")
columns = list(df)
print(df)
print(f'columns are {columns}')
for i in columns:
# printing the third element of the column
print(df[i][2])
Utils.printSpaces("printing second row ")
print(df.iloc[1])
Utils.printSpaces("fetching second Columns ")
print(df[df.columns[2]])
Utils.printSpaces("fetching second Columns using slice ")
print(df)
print(df.iloc[:, 1])
| false |
6dff1b20141ba5189cb86add7cff86e084957173 | Evgeniy-Nagornyy/Python_algoritm | /Lesson_1/task_5.py | 376 | 4.15625 | 4 | # Пользователь вводит номер буквы в алфавите. Определить, какая это буква.
num = int(input('Введите номер буквы в алфавите: '))
if num < 1 or num > 26:
print('Такой буквы не существует')
else:
print(f'буква под номером {num} - {chr(num + 96)}')
| false |
4f1abe056362c6f18f92c0c9a6d7330bca0ba75e | MichaelDeLisio/CSC290-Attach-4 | /src/Player.py | 822 | 4.15625 | 4 | """
=== Module Description ===
This module contains an abstract class for a player.
"""
from abc import ABC
from src.board import *
class Player:
"""
A player abstract class. This class should not be
instantiated and should instead be used by subclasses.
=== Public Attributes ===
colour:
The colour of this player's discs.
"""
# Private Attributes:
# _game_board
# the board that this player is playing on.
colour: str
_game_board: Board
def move(self) -> bool:
"""
Drops a disc with this players colour at the specified
column then returns whether the move was successful.
"""
pass
def get_colour(self) -> str:
"""
Returns the colour of this player's discs.
"""
return self.colour
| true |
b1c8b3ec7d5db2ce8b091a5f0a77c307c1f6566a | ishinan/simple_text_only_game | /room.py | 2,727 | 4.28125 | 4 | '''
room.py
Class Room
-----
properties:
location
items
description
'''
available_items = []
items_kept_by_user = []
possible_verbs = ['take', 'drop', 'use', 'go']
class Room:
'''
Create a room or garden
parameters for instantiation
unit_name: str
room_info: str
items: list
direction_of_doors: list
'''
def __init__(self, unit_name, room_info, items=[], direction_of_doors=[]):
self.unit_name = unit_name
self.room_info = room_info
self.unit_items = items
self.direction_of_doors = direction_of_doors
global available_items
available_items += self.unit_items
def _print_properties(self):
'''
print properties
'''
print(f"""
Location: {self.unit_name}
Doors: {self.direction_of_doors}
Items: {self.unit_items}
Description: {self.room_info}
""")
def add_next_room(self, next_room, door_dirction):
'''
next_room is an instance
'''
self.next_room = next_room
def interact_with_user(self):
'''
ask user to select direction and items
return user's answer
'''
# 1. print room name, list of doors(direction), list of item
# 2. Ask what wnat to do "go which direction" or "take an item" or drop an item"
# 3. Return an answer
print(f"You are in location: {self.unit_name} ")
print(f" You have choices actions: either 'verb item' or 'go to a next location'")
print(f" Available verbs: [take, drop, use, go]")
print(f' Example of answer: "take knife" or "go west"')
print("Available items: ", ', '.join([ item for item in self.unit_items ]))
print("Available directions: ", ', '.join([ door for door in self.direction_of_doors ]))
while True:
self.answer = input("What is your action?['verb item' or 'go direction']? ")
self.answer_verb, self.answer_arg = self.answer.split()
if len(self.answer.split()) == 2 and self.answer_verb in possible_verbs:
if self.answer_verb == 'go' and self.answer_arg in self.direction_of_doors:
break
elif self.answer_arg in self.unit_items:
break
else:
print("Hmm, try again.")
print("Your answer is: ", self.answer_verb, self.answer_arg)
return [self.answer_verb, self.answer_arg]
def go_to_next_place(self, next_place):
'''
This is an action to go to a next place
parameter:
next_place name?
return:
the next place's instance?
'''
pass
| true |
575643d4504615ac2db367b00e84675a678ca0fb | mtmcgowan/hort503 | /Assignment4/Assignment4/ex38.py | 1,716 | 4.15625 | 4 | ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"];
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding: ", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1]) # whoa! fancy
print(stuff.pop())
print(' '.join(stuff)) # what? cool!
print('#'.join(stuff[3:5]))
# Study Drills
# 1. Take each function......translate them to what Python does.
# pop(more_stuff)
# append(stuff, next_one)
# join(' ', stuff)
# join('#', stuff[3:5))
# 2.
# Call pop with argument more_stuff
# call append with arguments stuff and next_one
# call join with arguments ' ' and stuff
# call join with arguments '#' and stuff[3:5]
# 3. Go read about "object-oriented programming"....
# Ok
# 4. Read up on what a "class" is in Python
# A class appears to be quite similar to a 'struct' in C. It stores a specific arrangement of data and can also define methods for altering its state. A method is a function, but a function is not necessarily a method...
# 5. Do not worry if you do not have any idea what I'm.....
# Ok, not a drill....
# 6. Find 10 examples of things in the real world that would fit in a list.
data_storage = ["Myth", "Book", "Floppy disk", "Zip disk", "Compact disk", "Hard disk drive", "DNA", "Smoke signals"];
print(data_storage)
print("Using the sort function")
data_storage.sort()
print(data_storage)
| false |
4e35a7530d7012470232c9f9f20b39c71d19487b | mtmcgowan/hort503 | /Assignment2/PythonApplication1/ex2.py | 614 | 4.21875 | 4 | # EXERCISE 2: Comments and Pound Characters
# Study Drills
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out code:
# print ("This won't run.")
print("This will run.")
# 1. Find out if you were right about what the # character does....
# Yes, it comments out code.
# 2. Take your ex2.py file and review each file.......
# Done
# 3. Did you find more mistakes?
# No
# 4. Read what you typed.....
# Done. | true |
9dd9c09a836e9c4790119be26bee5fe36e6089ff | Sahilamin219/Competitive-Programing | /py/laser.py | 2,606 | 4.21875 | 4 | """class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
"""
# cook your dish here
def __init__(self,x,your):
self.x = x
self.y = y
"""# List initialization
list1 =[10, 20, 30, 40]
list2 =[40, 50, 60]
# using list comprehension
output = [[a, b] for a in list1
for b in list2 if a != b]
# printing output
print(output[2]) """
t=int(input())#.split())
while(t>0):
t-=1
n,q=map(int,input().split())
list1=list(map(int,input().split()))
list2[]
for i in range (0,n):
list2[i]=i
# my_dic={}
# for i,j in zip(list1,list2):
# my_dic.append
# list3 = [[a, b] for a in list1
# for b in list2 if a != b]
while(q>0):
q-=1
x1,x2,y=map(int,input().split())
"""
Inserting into a Tree
To insert into a tree we use the same node class created above and add a insert class to it. The insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. Finally the PrintTree class is used to print the tree.
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
# Use the insert method to add nodes
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
When the above code is executed, it produces the following result −
3 6 12 14
Traversing a Tree
The tree can be traversed by deciding on a sequence to visit each node. As we can clearly see we can start at a node then visit the left sub-tree first and right sub-tree next. Or we can also visit the right sub-tree first and left sub-tree next. Accordingly there are different names for these tree traversal methods. We study them in detail in the chapter implementing the tree traversal algorithms here. Tree Traversal Algorithm
"""
| false |
1435e02bd9ef984baa33d93cc66dfc63adefa960 | VXM97280/python_learnings | /hacker_rank_python/runner_up_score.py | 982 | 4.1875 | 4 | # Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given scores. Store them in a list and find the score of the runner-up.
# Input Format
# The first line contains n. The second line contains an array A[] of n integers each separated by a space.
# Constraints
# 2 <= N <= 10
# -100 <= A[i] <= 100
# Output Format
# Print the runner-up score.
# Sample Input 0
# 5
# 2 3 6 6 5
# Sample Output
# 5
# Explanation
# Given list is [2,3,6,6,5] . The maximum score is 6 , second maximum is 5 . Hence, we print 5 as the runner-up score.
# SOLUTION
# -----------
# old school way :P
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
scores = list(arr)
scores.sort()
scores.reverse()
x = max(scores)
for i in scores:
if i < x:
#print('runner_up : %d' %(i))
print(i)
break | true |
6e3093afad1ad433967dc9ac7516964af9898f0b | quickresolve/Algorithm-Practice | /PythonTheHardWay/ex6.py | 798 | 4.21875 | 4 | #Strings and Text
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r" % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of ..."
e = "a string with a right side."
print w + e
# %r displays raw data of the variable - good for debugging
# %s is good for displaying to variables to the users
# you can use single quotes inside of strings that have double quotes, using either independently is a stylistic choice
#If you want multiple formats in your string to print multiple variables, you need to put them inside () parenthesis separated by , commas
| true |
61efed6dd9af81fc7559842f494775f26810325f | sabarisharuchamy/PyWebDevelopment | /pyBasicConceptExplanations/pyPalindrome.py | 291 | 4.125 | 4 | #Palindrome Checking
txt = input('Enter the string to check for palindrome\n')
txtlen = len(txt)
txt2 = ''
txt = txt.lower()
for i in range(txtlen-1,-1,-1):
#print(txt[i])
txt2 += txt[i]
if txt == txt2:
print(txt+" is a palindrome")
else:
print(txt+" is not a palindrome")
| true |
1097817f723fc15df8fecb144f031f9cc679e729 | sabarisharuchamy/PyWebDevelopment | /pyBasicConceptExplanations/globalLocal.py | 1,319 | 4.3125 | 4 | #global
x = "Good"
def myfunc():
print("Christmas is " + x)#global variable can be accessed from local scope
myfunc()
print("Darbar is also "+x)#global variable being accessed from global scope
#local
def myfunc2():
z = 'Boom'
print('Let me teach '+z)#Local variable can be accessed from only within the local scope
myfunc2()
#print('Let me sing '+z) #Uncomment this for error #Local variable cannot be accessed from global scope
#Creating global variable from inside the local scope
def myfunc3():
global y,t
y = 10
t = 'Ram'
print('Inside the local scope '+t)
print('Inside the local scope',y)
myfunc3()
print('Outside the local scope and Inside the global scope '+t)
print('Outside the local scope and Inside the global scope',y)
#For changing global variable value from within the local scope
x = 5
def myfun4():
global x
x = 10
print('Value of x inside the local scope',x)
myfun4()
print('Value of x outside the local scope and inside the global scope',x)
#Allocation Error
a = 2
def myfunc5():
#print(a) #Uncomment for error #Reason - Trying to access the variable a before assigning the value in local scope
a = 10
print('Value of a inside the local scope',a)
myfunc5()
print('Value of a outside the local scope and inside the global scope',a)
| true |
11bafd990a6b97468fdcf517559bb442469f0043 | lhansford/project-euler | /python/problem_14.py | 874 | 4.59375 | 5 | def collatz_sequence(number):
"""
The following iterative sequence is defined for the set of positive integers:
n ->n/2 (n is even)
n-> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms.
Although it has not been proved yet (Collatz Problem),
it is thought that all starting numbers finish at 1.
"""
length = 1
while number != 1:
if number % 2 == 0:
number /= 2
else:
number = (3 * number) + 1
length += 1
return length
def find_longest_collatz_sequence(limit):
length = 0
number = 0
for x in xrange(1, limit):
print x
l = collatz_sequence(x)
if l > length:
length = l
number = x
return number
print find_longest_collatz_sequence(1000000)
| true |
139965863dd9b3be233a1c9802ccd2c1a7f42f32 | lhansford/project-euler | /python/problem_19.py | 1,428 | 4.15625 | 4 | def date_generator(start_year):
year = start_year
day_num = 1
day = day_generator("Monday")
month_gen = month_generator("January")
month = month_gen.next()
while True:
yield (day.next(),day_num,month,year)
if day_num == 31:
day_num = 1
month = month_gen.next()
if month == "January":
year += 1
elif day_num == 30 and month in ["September","April","June","November"]:
day_num = 1
month = month_gen.next()
elif day_num == 28 and month == "February" and not is_leap_year(year):
day_num = 1
month = month_gen.next()
elif day_num == 29 and month == "February" and is_leap_year(year):
day_num = 1
month = month_gen.next()
else:
day_num += 1
def is_leap_year(year):
if year % 100 != 0 and year % 4 == 0:
return True
elif year % 100 == 0 and year % 400 == 0:
return True
return False
def day_generator(start_day):
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday",
"Sunday"]
i = days.index(start_day)
while True:
yield days[i%7]
i += 1
def month_generator(start_month):
months = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
i = months.index(start_month)
while True:
yield months[i%12]
i += 1
d = date_generator(1900)
date = d.next()
counter = 0
while date[3] != 2001:
if date[0] == "Sunday" and date[1] == 1:
print date
counter += 1
date = d.next()
print counter | false |
0408c5986f4ab6f626b193fee4c92b6ea9735c2b | malbt/PythonFundamentals.Exercises.Algos | /search.py | 642 | 4.1875 | 4 | def binary_search(list_in, item):
"""
If item exists in list_in, this function returns its position in the list.
list_in : list of non duplicate integers
item : an integer to look for in the list_in
result : position of an integer(item) in the list_in
"""
my_list = sorted(list_in)
start = 0
end = len(list_in) - 1
while start <= end:
mid = start + (end - start) // 2
if my_list[mid] == item:
return my_list.index(item)
elif my_list[mid] > item:
end = mid - 1
elif my_list[mid] < item:
start = mid + 1
else:
return None
| true |
a2c6c2f040ab62774e4398356f90984fd647ba3d | SkewwG/Python_demo | /demo_magic/demo_call.py | 694 | 4.125 | 4 | # __call__
# 所有的函数都是可调用对象。
# 一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()。
# 单看 p() 你无法确定 p 是一个函数还是一个类实例,所以,在Python中,函数也是对象,对象和函数的区别并不显著。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
print('My name is {}'.format(self.name))
print('My age is {}'.format(self.age))
def __call__(self, year):
print('My birthday is {}'.format(year))
p = Person('ske', '20') # My name is ske My age is 20
p(2017) # My birthday is 2017 | false |
5642f217c3e35e7fb37bdf05fb95672d4a0277e8 | SkewwG/Python_demo | /demo_str/demo_isprintable.py | 652 | 4.1875 | 4 |
'''
isprintable(...)
判断字符串所包含的字符是否全部可打印。字符串包含不可打印字符,如转义字符,将返回False。
S.isprintable() -> bool
Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
'''
print(help(str.isprintable))
a = "Thisisstringexamplewow"
c = 'Ssdf1234\t'
d = 'asdf!@@#\n'
e = 'a = "this is string example wow"\a'
print(a.isprintable()) # True
print(c.isprintable()) # False 有制表符
print(d.isprintable()) # False 有换行符
print(e.isprintable()) # False
| false |
c3d26fdd5a1810e89100d9c47d8ca269ede69c68 | SkewwG/Python_demo | /demo_str/demo_maketrans.py | 862 | 4.3125 | 4 |
'''
maketrans(x, y=None, z=None, /)
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
'''
print(help(str.maketrans))
from string import maketrans
suchas = maketrans('sm','@$')
s = 'this is sam\'s dog'
print(s)
"this is sam's dog"
print(s.translate(suchas))
"thi@ i@ @a$'@ dog"
print(s.translate(suchas,"dog")) #去除d,o,g字符
"thi@ i@ @a$'@ " | true |
64bb47200ec3c028e25a5a4e3a64aefd567416ad | SkewwG/Python_demo | /demo_dict/demo_forDict.py | 398 | 4.125 | 4 | # 与字典有关的计算问题(zip+sorted对字典的值进行操作)
prices = {
'A':45.23,
'B':612.78,
'C':205.55,
'D':37.20,
'E':10.75
}
keys = prices.keys()
values = prices.values()
# 打印无序的字典
for i in prices:
print(i,prices[i])
# 对字母进行排序
m = sorted(zip(keys,values))
print(m)
# 对数字进行排序
n = sorted(zip(values,keys))
print(n) | false |
ed22943d967d8a0341aea99d25b78883439e8c56 | sanjaykumardbdev/pythonProject_tkinder | /12_dropDown.py | 1,491 | 4.28125 | 4 | # Python GUI Tutorial - 9 - creating drop down menus
from tkinter import *
root = Tk()
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
#1: create instance of Menu class
main_menu = Menu(root)
#============================================================
# File Menu
#============================================================
file_menu_child = Menu(main_menu, tearoff=0)
file_menu_child.add_command(label="New",command=donothing)
file_menu_child.add_command(label="Save",command=donothing)
main_menu.add_separator()
file_menu_child.add_command(label="Save As",command=donothing)
#2: configure main_menu to horizontal bar
root.config(menu=main_menu)
#3: write name of menu bar and associate child menu to named menu;
main_menu.add_cascade(label="File",menu=file_menu_child)
#============================================================
# Edit Menu
#============================================================
edit_menu_child = Menu(main_menu, tearoff=0)
edit_menu_child.add_command(label="Cut",command=donothing)
edit_menu_child.add_command(label="Copy",command=donothing)
edit_menu_child.add_separator()
edit_menu_child.add_command(label="Paste",command=donothing)
root.config(menu=main_menu)
main_menu.add_cascade(label="Edit",menu=edit_menu_child)
#============================================================
# Help Menu
#============================================================
root.mainloop()
| true |
bd168a196fd12dfadcdfaaa9e3b4f2b5c92b2b88 | thierschi/python-exercise | /sheet-1/LTH/exercise-2.py | 2,528 | 4.28125 | 4 | # ------------------------------------------------------------------------------
# Sheet 1 Exercise 2
# Niklas Markert - 1611460 / bt70985
# Lukas Thiersch - 1607110 / bt708626
# ------------------------------------------------------------------------------
# a) What does inf mean? When does it occur in Python?
# The abbreviation inf stands for infinity. While it is technically not possible
# to represent infinity because integers or data stored in a length of bits
# is limited by the length of bits and is therefore not infinite, you can
# represent infinity in python with float('inf') or float('-inf').
# Pythons maths module contains a value for it too: math.inf
# It represents the largest positive or negative number representable by an int
# => 1e1000 or -1e1000
# ------------------------------------------------------------------------------
# b) The expression 3 != 3 is of boolean type.
# Which values can boolean variables have?
# Boolean values in python have two possible values that they can hold:
# - True
# - False
# ------------------------------------------------------------------------------
# c) Write a Python script that asks for two numbers and stores them in the
# variables x and y, respectively. Make sure that x and y are of type float.
# The script should then check whether x equals y. Why is the following code
# not a good idea to do so? Provide a better solution.
# x == y
# Comparing two floats with == is generally not a good idea, because floating
# point numbers are represented as approximations of real numbers (IEEE).
# Comparing the numbers with == would only ever return true if both numbers
# are exactly equal.
# The problem is that when you do arithmetic with floating points you can get
# some weird results. For example:
# The result of the expression 60.34 - 28.58 is 31.760000000000005
# If we would check for equality with 31.76 with == we would get false, although
# we can consider them equal for most cases.
#
# The following script checks 'near equality'
def are_floats_nearly_equal(a, b):
# We check if the percentage of the deviation between a, b
# is less than the tolerated deviation
tolerated_deviation = 0.001
return abs((a - b) / b) < tolerated_deviation
x = float(input('Please provide the first floating point number: '))
y = float(input('Please provide the second floating point number: '))
print("Result of comparison: ", are_floats_nearly_equal(x, y))
# ------------------------------------------------------------------------------
| true |
ea3ed24cc3d869ca71e15159adfdbbe341d87093 | superbe/PythonCrashCourse | /chapter_2/name_cases.py | 1,240 | 4.3125 | 4 | name = 'eric Pearson'
# Упражнение 3.
message = f'Hello {name}, would you like to learn some Python today?'
print(message)
# Упражнение 4.
message = f'Hello {name.lower()}, would you like to learn some Python today?'
print(message)
message = f'Hello {name.upper()}, would you like to learn some Python today?'
print(message)
message = f'Hello {name.title()}, would you like to learn some Python today?'
print(message)
# Упражнение 5.
message = f'Albert Einstein once said, "A person who never made a mistake never tried anything new."'
print(message)
# Упражнение 6.
famous_person = 'Albert Einstein'
message = f'{famous_person.title()} once said, "A person who never made a mistake never tried anything new."'
print(message)
# Упражнение 7.
famous_person = ' \t\nAlbert Einstein \t\n'
print(f'|{famous_person} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.lstrip()} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.rstrip()} once said, "A person who never made a mistake never tried anything new."|')
print(f'|{famous_person.strip()} once said, "A person who never made a mistake never tried anything new."|')
| false |
0a45cfbcc704ded1c92f6e470f6e8b4cb307813f | Laurence-mvt/AutomateTheBoringStuff | /Chapters 1-5/collatz.py | 436 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 19:41:53 2021
@author: laurencefinch
"""
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3*number + 1)
return 3*number + 1
try:
number = int(input("number: "))
except ValueError:
print("you must enter an integer")
while number != 1:
number = collatz(number) | false |
946bb5909b6925e3901ced6c3eb6aa87c7146ec7 | michaelverano/PracticeWithPython | /tablePrinter.py | 1,036 | 4.125 | 4 | #! python3.2
tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose'],
]
def printTable(tableData):
colWidths = [0] * len(tableData) # creates a list of the widths for the inner lists in the table
# Find the longest string in the inner lists.
counter = 0
while counter < len(tableData): #loop through the lists of tableData
biggest_number = 0
for items in tableData[counter]: # find the biggest number per inner list
item_size = len(items)
if item_size > biggest_number:
biggest_number = item_size
# Store largest number in colWidths
colWidths[counter] = biggest_number
counter += 1
# Print the items in a table as per instruction
# This part doesn't work, yet
counter = 0
while counter < len(tableData[0]):
print(
tableData[0][counter].rjust(colWidths[0]) + ' ' +
tableData[1][counter].rjust(colWidths[1]) + ' ' +
tableData[2][counter].rjust(colWidths[2])
)
counter += 1
printTable(tableData) | true |
ace611db7104950c5b7a3d9193b964cfeda6de05 | viniciussalmeida/rice-university | /interactive-python-1/week/0/examples-more-1a_arithmetic_expressions-division.py | 2,161 | 4.25 | 4 | # Arithmetic expressions - numbers, operators, expressions
# Integer vs. Regular division
# Regular division - includes fractional part
# Single division sign
# Used to get exact values
# Ex. 1 What is one third of thirty-two?
print "Ex. 1:", 32.0 / 3.0
# Ex. 2 What is 19 / 24 as a percentage?
print "Ex. 2:", (19.0 / 24.0) * 100, "%"
# Ex. 3 What is the average of 3, 5, 17, and 29?
print "Ex. 3:",(3 + 5 + 17 + 29) / 4.0
print "--------"
# Integer division - rounds down to nearest whole number (floor function)
# Double division sign
# Works the same with integers, but used to get whole numbers from floats
# Ex. 4 If there are 6 triangles in a hexagon, how many complete
# hexagons can be made with 27 triangles?
print "Ex. 4:", 27 // 6.0
# Ex. 5 If 20 people can fit on each bus, how many full busses
# will there be if 59 people are riding in busses?
print "Ex. 5:", 59 // 20.0
# Ex. 6 If Dan can eat one hotdog in 16 seconds, how many
# whole hotdogs can he eat in 3 minutes?
print "Ex. 6:", (3 * 60) // 16.0
print "--------"
# Try changing the number of division signs in the
# problems above to test it out for yourself!
# Note: Integer division is not always the same as
# converting a float to an integer - they round the
# opposite directions when the result is a negative number
print "Same:", 6.0 // 5.0, int(6.0 / 5.0)
print "Same:", 0.0 // 3.0, int(0.0 / 3.0)
print "Different:", -7.0 // 4.0, int(-7.0 / 4.0)
print "--------"
# Warning: Do not divide by 0. It is not allowed in regular
# math, nor is it allowed in Codeskulptor.
#print "Error:", 3 // 0
#print "Error:", 3 / 0
# It is important to make sure that division by zero does
# not occur. The error you get can cause your game or
# program to end prematurely. Be especially careful when
# the denominator of a fraction is an arithmetic expression
# or a changing variable.
# For example:
#print "Error:", 4 / (3 * 4 - 12)
# Although the division by zero is not obvious at first, it
# can still kill your program. Make it a habit to always
# check for this possibility whenever you use division.
| true |
eead277a072e32ecb9307a0bd6bdafc4b64db83a | lfteixeira996/Coding-Bat | /Python/Logic-2/lucky_sum.py | 834 | 4.25 | 4 | import unittest
'''
Given 3 int values, a b c, return their sum.
However, if one of the values is 13 then it does not
count towards the sum and values to its right do not count.
So for example, if b is 13, then both b and c do not count.
lucky_sum(1, 2, 3) -> 6
lucky_sum(1, 2, 13) -> 3
lucky_sum(1, 13, 3) -> 1
'''
def lucky_sum(a, b, c):
res = 0
if a==13:
return 0
elif b==13:
return a
elif c==13:
return (a+b)
else:
return (a+b+c)
class Test_lucky_sum(unittest.TestCase):
def test_1(self):
self.assertEqual(lucky_sum(1, 2, 3), 6)
def test_2(self):
self.assertEqual(lucky_sum(1, 2, 13), 3)
def test_3(self):
self.assertEqual(lucky_sum(1, 13, 3), 1)
if __name__ == '__main__':
unittest.main() | true |
5ff97ddaa635f932c4297b0ee7b9e2bee037383a | lfteixeira996/Coding-Bat | /Python/String-1/first_two.py | 761 | 4.28125 | 4 | import unittest
'''
Given a string, return the string made of its first two chars, so the String "Hello" yields "He".
If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
first_two('Hello') -> 'He'
first_two('abcdefg') -> 'ab'
first_two('ab') -> 'ab'
'''
def first_two(str):
if len(str) < 2:
return str
else:
return str[:2]
class Test_first_two(unittest.TestCase):
def test_1(self):
self.assertEqual(first_two('Hello'), 'He')
def test_2(self):
self.assertEqual(first_two('abcdefg'), 'ab')
def test_3(self):
self.assertEqual(first_two('ab'), 'ab')
if __name__ == '__main__':
unittest.main() | true |
aa6aec27e609b06517e5c1201493206ae5e223c3 | lfteixeira996/Coding-Bat | /Python/Logic-1/alarm_clock.py | 1,091 | 4.125 | 4 | import unittest
'''
Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat,
and a boolean indicating if we are on vacation,
return a string of the form "7:00" indicating when the alarm clock should ring.
Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00".
Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off".
alarm_clock(1, False) -> '7:00'
alarm_clock(5, False) -> '7:00'
alarm_clock(0, False) -> '10:00'
'''
def alarm_clock(day, vacation):
if vacation and (day==0 or day==6):
return 'off'
elif vacation and (day>=1 or day<=5):
return '10:00'
elif day==0 or day==6:
return '10:00'
else:
return '7:00'
class Test_alarm_clock(unittest.TestCase):
def test_1(self):
self.assertEqual(alarm_clock(1, False), '7:00')
def test_2(self):
self.assertEqual(alarm_clock(5, False), '7:00')
def test_3(self):
self.assertEqual(alarm_clock(0, False), '10:00')
if __name__ == '__main__':
unittest.main() | true |
854a333278b79b3624d8fc09b0372b992f06291d | lfteixeira996/Coding-Bat | /Python/List-1/sum2.py | 761 | 4.15625 | 4 | import unittest
'''
Given an array of ints, return the sum of the first 2 elements in the array. If the array length is less than 2, just sum up the elements that exist, returning 0 if the array is length 0.
sum2([1, 2, 3]) -> 3
sum2([1, 1]) -> 2
sum2([1, 1, 1, 1]) -> 2
'''
def sum2(nums):
lenght = len(nums)
if lenght == 0:
return 0
elif lenght < 2:
return nums[0]
elif lenght >= 2:
return nums[0]+ nums[1]
class Test_sum2(unittest.TestCase):
def test_1(self):
self.assertEqual(sum2([1, 2, 3]), 3)
def test_2(self):
self.assertEqual(sum2([1, 1]), 2)
def test_3(self):
self.assertEqual(sum2([1, 1, 1, 1]), 2)
if __name__ == '__main__':
unittest.main() | true |
21ddf13fe94902aea3784ea4bb58bd46f49cc3e8 | lfteixeira996/Coding-Bat | /Python/String-1/left2.py | 628 | 4.15625 | 4 | import unittest
'''
Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end.
The string length will be at least 2.
left2('Hello') -> 'lloHe'
left2('java') -> 'vaja'
left2('Hi') -> 'Hi'
'''
def left2(str):
if len(str) < 2:
return str
return str[2:]+str[:2]
class Test_make_abba(unittest.TestCase):
def test_1(self):
self.assertEqual(left2('Hello'), 'lloHe')
def test_2(self):
self.assertEqual(left2('java'), 'vaja')
def test_3(self):
self.assertEqual(left2('Hi'), 'Hi')
if __name__ == '__main__':
unittest.main() | true |
050731feda7a7f436f18a5aeb364fce52894f89b | pranavmodak/pranav_projects | /reverse.py | 272 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 15:46:06 2020
@author:pranav modak
"""
print("tell me any numbers and I will make it in reverse order")
input = input("Enter numbers: ")
print("Reverse is: ")
for num in range(len(input)-1, -1, -1):
print("" + input[num]) | true |
874fc7596d86a9430d87951c042faa7a3690f446 | pranavmodak/pranav_projects | /alexa practice 8.py | 261 | 4.15625 | 4 | num=int(input("enter a nummber: "))
num1=int(input("enter a nummber: "))
num2=int(input("enter a nummber: "))
num3=int(input("enter a nummber: "))
num4=int(input("enter a nummber: "))
num5 = (num1+num+num2+num3+num4)
print("the average is: "+ str(num5/5)) | false |
f1523718dd15fea63a89087903e580b7d453b925 | vikas-t/practice-problems | /functional-problems/heightOfBinaryTree.py | 294 | 4.1875 | 4 | #!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/height-of-binary-tree/1
def getHeight(root):
"""
Start with 0 height and recurse going down, increasing the levels
"""
if not root:
return 0
return 1 + max(getHeight(root.left), getHeight(root.right)) | true |
cadfdb4bfcdf62b1070fab50f516ccb9e6155e00 | vikas-t/practice-problems | /functional-problems/leftViewOfBinaryTree.py | 691 | 4.1875 | 4 | #!/usr/bin/python
# https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1
def printLeftView(root):
# Get the level order traversal of the tree and print the first node
# of each level
levelOrder = getLevelOrder(root, h={})
for level in levelOrder:
print(levelOrder[level][0], end=" ")
def getLevelOrder(root, level=0, h={}):
# Be careful when you use a default mutable argument in the function
if root:
if level in h:
h[level].append(root.data)
else:
h[level] = [root.data]
getLevelOrder(root.left, level+1, h)
getLevelOrder(root.right, level+1, h)
if level == 0:
return h | true |
064eb4d53da5e05e5f2b038c99fc32bcdc35eb00 | vikas-t/practice-problems | /functional-problems/removeLoopAndLinkedList.py | 676 | 4.21875 | 4 | #!/usr/bin/python3
# https://www.geeksforgeeks.org/detect-and-remove-loop-in-a-linked-list/
def detectLoop(head):
ptr = head
dptr = head
while ptr and dptr and dptr.next:
ptr = ptr.next
dptr = dptr.next.next
if ptr == dptr:
return ptr
# Return the node where the two nodes meet, basically the nodes
# are supposed to meet at the loop node
return False
def removeTheLoop(head):
loopPtr = detectLoop(head)
if not loopPtr:
return 1
ptr = head
while ptr:
if ptr.next == loopPtr:
ptr.next = loopPtr.next
return 1
ptr = ptr.next | true |
5180d1c808d28fb1dc0687b0a7cb6006aa82d02d | vikas-t/practice-problems | /functional-problems/sortStack.py | 410 | 4.28125 | 4 | #!/usr/bin/python3
# https://www.geeksforgeeks.org/sort-a-stack-using-recursion/
# Sorted stack
def insert(stack, v):
if not stack or v > stack[-1]:
stack.append(v)
else:
t = stack.pop()
insert(stack, v)
stack.append(t)
def sort(stack):
if stack:
t = stack.pop()
sort(stack)
insert(stack, t)
# Driver code
x = [7,2,1,9,5]
sort(x)
print(x) | true |
e2c8bd579c333b957fabe47e5ddcb1342bca8b0b | remotephone/lpthw3 | /ex11_20/ex15.py | 728 | 4.4375 | 4 | # Import the modules
from sys import argv
# define the arguments. first one is the name of the script
# Second one is the filename you'll work with.
script, filename = argv
# This is where you open the file for reading and assign it to txt
txt = open(filename)
# Print the file name. The f format lets python know to include variables
print(f"Here's your file {filename}:")
# read is a function to.... read a file.
print(txt.read())
txt.close()
# Prompt the user to put the filename in again.
print("Type the filename again:")
file_again = input("> ")
# read the new varaible which equals the filename again.
txt_again = open(file_again)
# Print it again.
print(txt_again.read())
txt_again.close() | true |
5eb6cc6faeca9dab232a63fabac58347b3885a69 | ethanjensen/Python-Programs-Linear-Algebra | /is_square.py | 234 | 4.15625 | 4 | M = [[1,2,3],[0,1,1],[1,2,0]]
#Determines whether a specified matrix M is square.
def is_square(M):
square = True
for row in M:
if len(row) != len(M):
square = False
return square
print(is_square(M))
| true |
dc821ea43721b504dbee3307fd2840a40d7ccd7a | ikhwan/pythonkungfu | /tutorial/listsAndArrays.py | 466 | 4.25 | 4 | #!/usr/bin/env python
# Array declaration
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
# Second name is the second value of `names' array
second_name = names[1]
# Fill `numbers' array with 1, 2, and 3
numbers.append(1)
numbers.append(2)
numbers.append(3)
# Fill `strings' array with "Hello", and "world"
strings.append("Hello")
strings.append("world")
print(numbers)
print(strings)
print("The second name on the names list is %s" % second_name) | true |
ce2e0da9ffb66ac59f9c4300b06c97b2ccdf4f7d | sme1d1/UMKC_DeepLearning2021 | /ICP/ICP1/source/icp1_2.py | 1,091 | 4.375 | 4 | # sme1d1 Scott McElfresh 1/22/2021
import random
# assign user input to name
name = input("Enter a word: ".lower())
# assign string characters to a list so they can be modified
name_list = list(name)
# pick some random number between 0 and the length of the word
# -1 so we can use the value as an index
x = random.randint(0, len(name)-1)
y = random.randint(0, len(name)-1)
# ensure that we don't pick the same random value
while x == y:
y = random.randint(0, len(name)-1)
print("Removing #%d character: %s" % (x+1, name_list[x]))
print("Removing #%d character: %s" % (y+1, name_list[y]))
#replace list characters
name_list[x] = ''
name_list[y] = ''
#assign list characters to new string
new_name = "".join(name_list)
# print the new reversed word
print("Reversed word with missing characters: ")
print(new_name[::-1])
a = int(input("\nEnter an integer: "))
b = int(input("Enter a second integer: "))
c = a + b
d = a * b
e = a/b
print("The sum of %d and %d, is %d" % (a, b, c))
print("%d multiplied by %d, is equal to %d" % (a, b, d))
print("%d divided by %d, is equal to %f" % (a, b, e))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.