blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
73fe19baa0c07f3f62b6c5ce90c18a948334626e | dky/codepost | /oop-deck-of-cards/deck.py | 1,441 | 4.15625 | 4 | import card
import random
# This class represents a standard Deck of cards. We populate the deck using
# two for loops.
class Deck:
def __init__(self):
# Instance variable
self.cards = []
# Range over the cards
for suit in card.SUITS:
for value in card.VALUES:
# Create a new card object
new_card = card.Card(value, suit)
# Append each card to deck
self.cards.append(new_card)
# num_cards returns a count of all the cards in the deck.
def num_cards(self):
return len(self.cards)
# displays a card's value.
def show_single(self, card):
print("{}, {}".format(card.suit, card.value))
# return the full deck of cards.
def show_full_deck(self):
for i in (self.cards):
self.show_single(i)
# Shuffle the deck and return a random card.
def shuffle(self):
while self.cards:
random_card = random.choice(self.cards)
self.cards.remove(random_card)
return (random_card)
# Pop from beginning of the list?
def peek(self):
if (len(self.cards) != 0):
return self.cards.pop(0)
# Pop but don't return anything?
def draw(self):
self.cards.pop(0)
myDeck = Deck()
print(myDeck.num_cards())
myDeck.show_single(myDeck.shuffle())
myDeck.show_single(myDeck.peek())
myDeck.show_full_deck()
| true |
953693222f0d0cd396538813f42c86476879af24 | KKisly/PrismAssignments | /SalesMan/SalesMan.py | 2,255 | 4.125 | 4 | # This script is to find distance between cities
import csv
import math
from math import pi, log, tan
#loop through csv list
def find (city):
csv_file = csv.reader(open('cc.csv', "rt"), delimiter=",")
for row in csv_file:
if city == row[1]:
finding = row
#print(finding)
return finding
def distance (list1, list2):
x1 = list1[0]
x2 = list2[0]
#sq = ((x1 - x2)**2)
sq = ((list1[0] - list2[0])**2 + (list1[1] - list2[1])**2)
#print(sq)
range = math.sqrt(sq)
return range
def conversion (cityrow):
mapWidth = 30030.000000
mapHeight = 30015.000000
latitude = float(cityrow[2])
longitude = float(cityrow[3])
x = (longitude + 180) * (mapWidth / 360)
#print("x", x)
latRad = latitude * pi / 180
mercN = log(tan((pi / 4) + (latRad / 2)))
y = (mapHeight / 2) - (mapWidth * mercN / (2 * pi))
#print ("y", y)
list = [x, y]
return list
def main():
city = input('Enter first city\n')
city2 = input('Enter second city\n')
city3 = input('Enter third city\n')
Imp_SI = int(input("Would you like output in miles Input (1) or kilometers Input (2)"))
while Imp_SI != 1 and Imp_SI != 2:
Imp_SI = int(input("Please enter correct choice in miles Input (1) or kilometers Input (2)"))
cityrow = find(city)
cityrow2 = find(city2)
cityrow3 = find(city3)
#print(cityrow3)
listcity1 = conversion(cityrow)
# print(listcity1)
listcity2 = conversion(cityrow2)
# print(listcity2)
listcity3 = conversion(cityrow3)
#print(listcity3)
range = distance(listcity1, listcity2)
if Imp_SI == 2:
print("This is distance between", city, "and", city2, "in kilometers:", ("%.2f" % range))
else:
print("This is distance between", city, "and", city2, "in miles:", ("%.2f" % (range/1.609)))
range = distance(listcity2, listcity3)
if Imp_SI == 2:
print("This is distance between", city2, "and", city3, "in kilometers:", ("%.2f" % range))
elif Imp_SI == 1:
print("This is distance between cities", "in miles:", ("%.2f" % (range/1.609)))
if __name__ == "__main__":
main() | false |
31d36a6d28b7f587c29632519bb139a010a0ef42 | dehvCurtis/NSA_Py3_COMP3321 | /Lesson_03/lesson03_sec2_ex2.py | 312 | 4.15625 | 4 | g_list = ['milk','juice','pencils']
def in_grocery_list(grocery_item):
if grocery_item in g_list:
print(f'Yes, {grocery_item} is in the list')
elif grocery_item not in g_list:
print(f'No, {grocery_item} is NOT in the list')
user_item = input('Pick an item: ')
in_grocery_list(user_item) | true |
e59b38b6fdd7016c4296d1487a417a98e7d97ade | ogunsoladebayo/ogunsola-activator | /frameworkshi.py | 2,166 | 4.15625 | 4 | # from password import password
database = {}
plus = True
while plus:
counter = 0
add = counter + 1
index = 'user' + str(add)
new_user = True
while new_user:
first_name = input("Please, enter your first name: ")
last_name = input("Please, enter your last name: ")
email = input("Please, enter your email address: ")
# suggest_password = ""
# password (first_name, last_name):
f_name_spread = list(first_name)
l_name_spread = list(last_name)
import string
import random
f = ''
for i in range(5):
f = f + random.choice(string.ascii_letters)
suggest_password =(f_name_spread[0] + f_name_spread[1] + l_name_spread[-2] + l_name_spread[-1] + f)
print('Welcome ' + first_name + ', Your default password is ' + suggest_password)
# password(first_name, last_name)
details = {"First name" : first_name,
"last name" : last_name,
"email" : email}
password_choice = input("Do you wish to change this password? Type 'Yes' or 'No' only: ")
def password_change(suggest_password):
password_use = True
enter_password = True
while password_use:
if password_choice == "No":
details["password"] = suggest_password
print("Your details have been saved")
password_use = False
elif password_choice == "Yes":
while enter_password:
suggest_password = input("Enter a new password not less than 7 characters: ")
if len(suggest_password) < 6 :
print("Password is less than 7 characters")
# suggest_password = input("Enter a new password longer than or equal to 7 characters: ")
else:
details["password"] = suggest_password
print("Your password has been updated")
enter_password = False
return details
password_change(suggest_password)
database[index] = details
enter_new_user = input("Would you like to enter another user: ")
if enter_new_user == "No":
new_user = False
plus = False
elif enter_new_user == "Yes":
pass
print(database) | true |
5ef5945412e965502c46996f9d8489fbdc62663b | jay6413682/Leetcode | /Odd_Even_Linked_List_328.py | 2,773 | 4.15625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
""" https://leetcode-cn.com/problems/odd-even-linked-list/solution/qi-ou-lian-biao-by-leetcode-solution/ """
if head is None:
return head
odd_pointer = head
even_pointer = even_head = head.next
while even_pointer is not None:
third_pointer = even_pointer.next
if third_pointer is None:
even_pointer.next = None
else:
even_pointer.next = third_pointer.next
odd_pointer.next = third_pointer
even_pointer = even_pointer.next
if odd_pointer.next is not None:
odd_pointer = odd_pointer.next
odd_pointer.next = even_head
return head
"""
# my second try
if not head:
return
if not head.next:
return head
h1 = p1 = head
h2 = p2 = head.next
while p1.next and p2.next:
p1.next = p2.next
p1 = p1.next
p2.next = p2.next.next
p2 = p2.next
p1.next = h2
return h1
"""
"""
# my latest try
if not head or not head.next:
return head
odd_pointer = odd_head = head
even_pointer = even_head = head.next
while True:
if even_pointer:
next_odd = even_pointer.next
else:
odd_pointer.next = even_head
break
if next_odd:
next_even = next_odd.next
else:
odd_pointer.next = even_head
break
odd_pointer.next = next_odd
even_pointer.next = next_even
odd_pointer = odd_pointer.next
even_pointer = even_pointer.next
return odd_head
"""
def oddEvenList2(self, head: ListNode) -> ListNode:
""" https://leetcode-cn.com/problems/odd-even-linked-list/solution/kuai-lai-wu-nao-miao-dong-qi-ou-lian-biao-by-sweet/ """
odd_head = ListNode()
odd_tail = odd_head
even_head = ListNode()
even_tail = even_head
pointer = head
is_odd = True
while pointer is not None:
if is_odd:
odd_tail.next = pointer
odd_tail = pointer
else:
even_tail.next = pointer
even_tail = pointer
pointer = pointer.next
is_odd = not is_odd
odd_tail.next = even_head.next
even_tail.next = None
return odd_head.next
| true |
bea8bc42d9ff727c87a1cf2adb8d6398bf1c3235 | YangChenye/Python-Code | /Python+Algorithm/Sorting-Algorithm/selection_sort.py | 826 | 4.15625 | 4 | # selection_sort 选择排序
# 选择排序算法的实现思路有点类似插入排序,也分已排序区间和未排序区间。但是选择排序每次会从未排序区间中找到最小的元素,将其放到已排序区间的末尾。
import time
def insertion_sort(array):
length = len(array)
if length <= 1:
return
for i in range(length):
min_index = i
min_val = array[i]
for j in range(i, length):
if array[j] < min_val:
min_val = array[j]
min_index = j
array[i], array[min_index] = array[min_index], array[i]
if __name__ == '__main__':
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
start = time.clock()
insertion_sort(array)
print(array)
end = time.clock()
print('用时:', str(end - start)) | false |
072bf8c520b3d2de5f130e9871087dbca8e36d8c | YangChenye/Python-Code | /Python+Algorithm/Geometric/two_point_straight_point.py | 1,070 | 4.40625 | 4 | # 解算出两线段的交点
# 采用 两点确定一条直线,然后两直线求解
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# 用"两点"定义的直线
class Line(object):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
# 求直线的参数,
def get_line_parameter(line):
line.a = line.p1.y - line.p2.y
line.b = line.p2.x - line.p1.x
line.c = line.p1.x * line.p2.y - line.p2.x * line.p1.y
# 解两直线的交点
def get_cross_point(l1, l2):
get_line_parameter(l1)
get_line_parameter(l2)
d = l1.a * l2.b - l2.a * l1.b
cross_point = Point()
cross_point.x = (l1.b * l2.c - l2.b * l1.c) * 1.0 / d
cross_point.y = (l1.c * l2.a - l2.c * l1.a) * 1.0 / d
return cross_point
if __name__ == '__main__':
p1 = Point(0, 1)
p2 = Point(1, 1)
line1 = Line(p1, p2)
p3 = Point(1, 1)
p4 = Point(1, 0)
line2 = Line(p3, p4)
cross_point = get_cross_point(line1, line2)
print("Cross point:", cross_point.x, cross_point.y)
| false |
d49afbf50618198856ce6549262d1bfc53b2f455 | neuxxm/leetcode | /problems/707/test.py | 2,548 | 4.125 | 4 | #16:42AC
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.h = ListNode(0)
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
:type index: int
:rtype: int
"""
h = self.h
p = h.next
ix = 0
while p:
if ix == index:
return p.val
p = p.next
ix += 1
return -1
def addAtHead(self, val):
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
:type val: int
:rtype: None
"""
h = self.h
t = ListNode(val)
t.next = h.next
h.next = t
def addAtTail(self, val):
"""
Append a node of value val to the last element of the linked list.
:type val: int
:rtype: None
"""
h = self.h
p = h.next
while p.next:
p = p.next
p.next = ListNode(val)
def addAtIndex(self, index, val):
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
:type index: int
:type val: int
:rtype: None
"""
h = self.h
if index == 0:
t = ListNode(val)
t.next = h.next
h.next = t
return
p = h.next
ix = 0
while p:
if ix == index-1:
break
p = p.next
ix += 1
if ix != index-1:
return
t = ListNode(val)
t.next = p.next
p.next = t
def deleteAtIndex(self, index):
"""
Delete the index-th node in the linked list, if the index is valid.
:type index: int
:rtype: None
"""
h = self.h
p = h.next
ix = 0
last = h
while p:
if ix == index:
break
last = p
p = p.next
ix += 1
if ix != index:
return
if last.next == None:
return
last.next = last.next.next
| true |
ef45bae5e27cd9fbe9fa60a6368fbfcc80d533ea | whut-leslie/PyLearning | /05_高级数据类型/Ex_09_字典基本使用.py | 362 | 4.15625 | 4 | xiaoming_dict = {"name": "小明"}
# 1.取值
print(xiaoming_dict["name"])
# 在取值的时候,如果指定的key不存在,程序会把报错!
# 2.增加/修改
# 如果key不存在,会新增键值对
xiaoming_dict["age"] = 18
# 如果key存在,会修改
xiaoming_dict["name"] = "小小明"
# 3.删除
xiaoming_dict.pop("name")
print(xiaoming_dict) | false |
788a133ab16187dcc62d1bc9bee26d591ed0ca2e | aashishtamang/assignment_III | /q1.py | 247 | 4.21875 | 4 | #1. Total number of three letter words from shakespeare.txt
import re
file = open('shakespeare.txt','r')
s = file.read()
matchobj = re.findall(r'\b[a-zA-Z]{3}\b',s)
print("The total number of three letter words are ",len(matchobj))
file.close()
| false |
f888ad014b4bd0c36cadb902751b1e7e88775857 | sainikunal90/creating_median_function | /median_function.py | 668 | 4.15625 | 4 | # task was to create a median function without using any inbuilt function.
import numpy
# Taking input of the numbers from CMD Terminal
number_array = list()
number = input("Enter the number of elements you want:")
print ('Enter numbers in array: ')
for i in range(int(number)):
n = input("number :")
number_array.append(int(n))
number_array.sort()
print ('ARRAY: ',number_array)
#Creating a function for Median
def median():
l = number_array
num = len(l)
l.sort()
if num % 2 == 0:
m = (l[int((num/2)-1)] + l[int((num/2))])/2
else:
m = l[int((num/2))]
return m
print('Median of the above array is: ', median())
| true |
d04d00b64364cc57f0d99893403efd34e6dfe9c3 | carlydacosta/whiteboarding | /stacks.py | 878 | 4.40625 | 4 |
### Just talking about a stack and what it does is the abstract data type.
### I give an abstract data type a physical representation as a data structure.
### This is building the data structure.
### Make a class to create an object that responds to things we want it to do with methods.
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
stack = Stack()
print stack.items
print stack.isEmpty()
stack.push(4)
print stack.items
stack.push('dog')
print stack.items
print stack.peek()
stack.push(True)
print stack.items
print stack.size()
print stack.isEmpty()
stack.push(8.4)
print stack.items
print stack.pop()
print stack.pop()
print stack.size()
| true |
392d2f7883af112fbeb1fe54408976d26056b549 | Ruabye/Fluent_Python | /Dict/StrAndIntDict.py | 1,157 | 4.125 | 4 | import collections
class myStrtoIntDict(dict):
"""
自定义字典(映射)类型,直接继承 dict。可以使用字符/数字作为键访问字典里的值
映射类型有__getitem__和__missing__方法
当__getitem__方法没有找到值时,会调用__missing__方法
"""
def __missing__(self, key):
"""
需要判断key是否为字符类型。否则self[str(key)]里调用__getitem__没有找到值时,会再次调用__missing__方法,导致死循环
"""
if isinstance(key, str):
return None
return self[str(key)]
def __contains__(self, item):
"""
实现in关键字。
需要使用self.keys(),直接item in self会再次调用__contains__方法,出现死循环
列表的keys()方法经过优化,访问速度很快
"""
if item in self.keys() or str(item) in self.keys():
return True
return False
if __name__ == "__main__":
#my_dict[3]与my_dict["3"]返回的值是固定的,因为__getitem__会优先执行
my_dict = myStrtoIntDict({"1":10, "2":20,"3":40, 3:20})
print(my_dict[3]) | false |
5a56ba2172e03132b5b3254ff9a95d8543cc565d | berkott/mClasses | /class7.py | 1,109 | 4.34375 | 4 | # 8.13
# Python we always technically pass by reference
# Our "primitive data" types (bool, str, int, floats) are immutable objects
# Many other objects are mutable objects, so be careful
def hot(x):
print(joe is x)
x[1] = "fire"
print(joe is x)
joe = ["super hot", "barbie"]
print(f"Before function: '{joe}'")
hot(joe.copy()) # pass by value
print(f"After function: '{joe}'")
exit()
def hot(x):
print(joe is x)
x[1] = "fire"
print(joe is x)
joe = ["super hot", "barbie"]
print(f"Before function: '{joe}'")
hot(joe) # pass by reference
print(f"After function: '{joe}'")
exit()
def hot(x):
print(joe is x)
x = x + 2
print(joe is x)
joe = 4
print(f"Before function: '{joe}'")
hot(joe) # pass by reference
print(f"After function: '{joe}'")
exit()
# 8.12
a = ["chicken", "bob"]
b = a # assigning the same reference, aka, list object is aliased by both a and b
print(a is b)
b[0] = "x"
print(a)
a = "chicken"
b = a
print(a is b)
b = b + "hi"
print(a)
# 8.11
a = "chicken"
b = "chicken"
print(a is b)
a = ["chicken"]
b = ["chicken"]
print(a is b)
| true |
011b4d7e58616856d844927f685080387af07560 | jmg5219/Virtual_Pet | /pet.py | 2,753 | 4.59375 | 5 | class Pet:
#Using the constructor to build instances
#Self points to the instance to use it's own attribute values
#As with regular functions, we can define default argument values:
def __init__(self, name, fullness=50, happiness=50,hunger=5, mopiness=5):
self.name = name
self.fullness = fullness
self.happiness = happiness
self.hunger = hunger #Configurable
self.mopiness = mopiness
self.toys = []
# But the real power of classes is the ability to define custom methods that make use of those attribute values.
#Each method below modifies the instances attributes accordingly
#the first parameter is self, which is how the body of the method access the instance.
def eat_food(self):
self.fullness += 30
def get_love(self):
self.happiness += 30
def get_toy(self, toy):
self.toys.append(toy)
#Practicing good encapsulation is a matter of deciding the minimum amount of information an object needs to store in its state in order to do its work via its behaviors.
#Modifying be_alive() so that it the amounts are parameterized:
def be_alive(self, hunger, mopiness):
self.fullness -= hunger#Parameterized
self.happiness -= mopiness
for toy in self.toys:
self.happiness += toy.use()
def __str__(self):
return """
%s:
Fullness: %d
Happiness: %d
""" % (self.name, self.fullness, self.happiness)
class CuddlyPet(Pet):
#Super fnction - we can override __init()__ while also reusing the __init__() code from the superclass.
#With this technique, a CuddlyPet could accept additional constructor arguments:
def __init__(self, name, fullness=50, hunger=5, cuddle_level="Extra Cuddly"):
super().__init__(name, fullness, 100, hunger, 1)
self.cuddle_level = cuddle_level
#redefining a method from the parent to have different effect in the child
#By inheritance all other methods are known by the child
def be_alive(self):
self.fullness -= self.hunger
self.happiness -= self.mopiness/2
#New method defined inside the sub-class
def cuddle(self, other_pet):
other_pet.get_love()
#We know that in an instance of CuddlyPet, we have access all the properties and methods of Pet. And now we know that CuddlyPet can implement its own new methods.
# But what if we wanted be_alive() to have a different effect in CuddlyPet than it does in Pet?
#Method overiding to print Extra Cuddly
def __str__(self):
return """
%s:
Fullness: %d
Happiness: %d
Cuddliness: %s
""" % (self.name, self.fullness, self.happiness,self.cuddle_level)
| true |
f66d3b2ab60c042f59ffa498369897621b11fb4c | luksos/iSA_python_basic | /2018.11.21_zajecia_03/homework_03.py | 1,240 | 4.3125 | 4 | """
Program rysujący piramidę o określonej wysokości, np dla 3:
#
###
#####
"""
def instructions():
print("""
Witaj w programie rysującym fantastico piramidki!
Zostań nowym faraonem już dziś...
""")
def height_input():
height = 0
while height == 0:
try:
height = int(input("Podaj wysokość piramidy: "))
except ValueError:
height = 0
continue
if height <= 0:
height = 0
continue
elif height >= 101:
print("Hej, nie przesadzasz? Gdzie ja Ci tą choinkę wydrukuję?")
continue
return height
def draw_pyramid(pyramid_height):
print()
for i in range(pyramid_height):
row = "#" + "#" * i * 2
print(row.center(pyramid_height*2+1))
def main():
instructions()
height = height_input()
draw_pyramid(height)
if height <= 2:
print("\nHmmm... Ale kurduplasta ta piramidka...")
decision = (input("Nie chcesz spróbować zbudować większej? (T/N): ")).lower()
if decision in ('t', 'tak'):
height = height_input()
draw_pyramid(height)
else:
print("\nDo zobaczenia")
main()
| false |
05e4d384a9547d0686dc5d6e9f2a5d1e2b2efd93 | ahussein/algo | /recursion/puzzle.py | 521 | 4.1875 | 4 | """
To keep the description general
enough to be used with other puzzles, the algorithm enumerates and tests all k-
length sequences without repetitions of the elements of a given universe U . We
build the sequences of k elements by the following steps:
1. Recursively generating the sequences of k − 1 elements
2. Appending to each such sequence an element not already contained in it.
"""
def solve_puzzle(k, s, u):
"""
solve puzzel for k length combination for a set 's'
"""
for item in u:
| true |
dd731c1006a8a7d9613e85eaf279a2a994b99052 | gitonga123/Learning-Python | /total_list.py | 612 | 4.4375 | 4 | #This program creates the totals of values in a list.
def main():
#The list with the numbers to be added
print "Enter the size of the List"
size_list = input()
number = [0] * size_list
print ("Enter the Elements of the List")
for x in range(size_list):
number[x] = input()
pass
#The variable to hold the totals in a list
total = 0;
#Using a loop to add the values
for x in number:
total +=x
average = total/size_list
#Diplay the total value
print "The size of the list is: ", len(number)
print "The total: ", total
print "The Average of Values in the Array are: ", average
main() | true |
a464acae26086f63948a32e2a409db760f2928ce | Jeson1g/Dawson | /sort_algorithm/01_merge_sort.py | 1,041 | 4.125 | 4 | def merge_sort(alist):
"""归并排序"""
n = len(alist)
if 1 == n:
return alist
mid = n // 2
# 对左半部分进行归并排序
left_sorted_li = merge_sort(alist[:mid])
# 对右半部分进行归并排序
right_sorted_li = merge_sort(alist[mid:])
# 合并两个有序集合
left, right = 0, 0
merge_sorted_li = []
left_n = len(left_sorted_li)
right_n = len(right_sorted_li)
while left < left_n and right < right_n:
if left_sorted_li[left] <= right_sorted_li[right]:
merge_sorted_li.append(left_sorted_li[left])
left += 1
else:
merge_sorted_li.append(right_sorted_li[right])
right += 1
merge_sorted_li += left_sorted_li[left:]
merge_sorted_li += right_sorted_li[right:]
return merge_sorted_li
if __name__ == '__main__':
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print("before sort: %s" % alist)
sorted_alist = merge_sort(alist)
print("sorted new list: %s" % sorted_alist)
| false |
b77636ba6ea011427db3add8baedec75a0187308 | Rohith-BK/Python-code | /2. Data Types and Sequences.py | 1,289 | 4.28125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Data Types and Sequences
# In[10]:
type('This is a string')
# In[11]:
type(None)
# In[12]:
type(1)
# In[13]:
type(1.0)
# In[14]:
type(add_numbers)
# add_numbers is defined as function in above code before
# In[15]:
# x written in parenthesis is tuple data type
x = (1, 'a', 2 , 'c')
type(x)
# In[18]:
# x written in square bracket is list data type
x = [1, 'a', 2 , 'c']
type(x)
# In[19]:
# append function
x.append(3.4)
print(x)
# In[20]:
for item in x:
print(item)
# In[21]:
# Mathematical Operators - Plus, Multiple
[1, 2] + [3, 4]
# In[22]:
1 * 3
# In[23]:
# in function
1 in (1, 2, 3)
# # Strings
# In[8]:
# String and numeric do not concatenate
# Eg: print('chris' + 2)
# In[3]:
print('Chris' + str(2))
# In[4]:
sales_record = {'price': 3.2,
'num_items': 4,
'person': 'chris'}
sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items'] * sales_record['price']
))
# In[ ]:
| true |
f9f614b9681857c2eedd02965e3bfae674a58c4d | mittersouvik/basic-python-programs | /guessTheNumberGame.py | 777 | 4.125 | 4 | #This is guess the number game
import random
print('Enter your name: ')
name = input()
#print('Please enter a string')
guessedNumber = random.randint(1,20)
print('Hi ' + name + ' start thinking of a number between 1 and 20')
#you will get 6 chances to guess the number
for guessTaken in range(1,7):
print('Take a guess..')
guess = int(input())
if guess > guessedNumber:
print('Your guess is too high')
elif guess < guessedNumber:
print('Your guess is too low')
else:
break #this condition is for correct guess
if guess == guessedNumber:
print('Hi ' + name + ' you have guessed the number in ' + str(guessTaken) + ' guesses')
else:
print('you have lost all your guesses. ' + 'The number is ' + str(guessedNumber))
| true |
00d7fa989ea345d9c928ac72affc70fd2115e659 | muqeetco/dice | /dice.py | 358 | 4.21875 | 4 | import random
print ("This is a Dice game")
num = int(input("Enter a number between 1 and 6: "))
if num>6:
print ("Not a valid input")
elif num<=0:
print ("Not a valid input")
else:
for x in range(6):
game = random.randint(1,6)
print ("The dice returned: " + str(game))
if game == num:
print ("You Won!")
else:
print ("Sorry You Lost!")
| true |
7024c115c54a98432dfebba86fb55dd75d7402a9 | papadavis47/my_sandbox | /Treehouse Python Stuff/new_hello2.py | 729 | 4.21875 | 4 |
# 2nd version with an added conditional statement
first_name = input("What is your first name? ")
print("Hello,", first_name)
if first_name == "John":
print(first_name, "is learning Python.")
elif first_name == "Diego":
print("{} is John Davis' son. He will learn Python when he and his dad buy a Raspberry Pi!\nand work on it together:)".format(first_name))
else: # This is just incase we have a younger user who can't yet read.
age = int(input("How old are you? "))
if age <= 6:
print("Wow, you are {}. If you are confident in your reading ability . . . ".format(age))
print("You should totally learn Python, {}!".format(first_name))
print("Have a great day, {}!".format(first_name))
| true |
d23005373f887fd683309e81f6464b73cd72cc3c | papadavis47/my_sandbox | /Treehouse Python Stuff/masterticket1.py | 816 | 4.3125 | 4 | # I will try to make this my own in some way. 7/18/2018
TICKET_PRICE = 10
tickets_remaining = 100
# Output how many tickets are remaining using the tickets_remaining variable
print("There are {} tickets remaining.".format(tickets_remaining))
# Gather the user's name and assign it to a new variable
user_name = input("What is your name? ")
# Prompt the user by name and ask how many tickets they would like
# Calculate the price ( number of tickets multiplied by the price ) and assign it to a variable
# Output the price to the screen
number_of_tickets = input("Hello {}! How many tickets would you like? ".format(user_name))
number_of_tickets = int(number_of_tickets)
customer_price = TICKET_PRICE * number_of_tickets
print("Your order will cost ${}.".format(customer_price)) | true |
d67cd35a8239e43e753b997afddadcfd082e02eb | MartinMCodazzi/Python | /C3E1.py | 668 | 4.125 | 4 | """
Clase 3 - 28/11/2020
Ejercicio 1 - Manejo de archivos en Python
EducacionIT - Prof. Luciano Pueyo
Martin Nahuel Muñoz Codazzi
29/11/2020
"""
def escrituraArchivo(coleccion):
with open ("archivoPrueba.txt", "w") as archivo:
for elemento in coleccion :
archivo.write(str(coleccion[elemento -1]))
#Hay que hacer casting a String para escribir. El -1 porque me daba error de "out of range"
# No puedo hacer un , + \n en la linea anterior, por eso va la siguiente
archivo.write("\n")
#Sin esta linea, me escribe uno al lado del otro, lástima que writeln no funcione
lista = list(range(1,101))
escrituraArchivo(lista)
| false |
a3e9b381a8c1f3b46a089eda62fe0b04b26673a7 | LYblogs/python | /Python1808/第一阶段/day14-类和对象/05-类的继承.py | 778 | 4.21875 | 4 | """
1.继承
python中的类支持继承,并且支持多继承
python中默认情况是继承自object(object是python中所有类的基类)
(被继承者)(继承者)
父类 和 子类
继承就是让子类直接拥有父类中的内容
b.可以继承哪些内容
对象属性
类的字段
对象方法
__slots__魔法不会被继承
"""
class Person:
num =61
def __init__(self):
self.name ="张三"
self.age =0
self.sex ="男"
def show_message(self):
print("%s你好吗"%self.name)
@classmethod
def people(cls):
print("世界有%d亿人"%cls.num)
#Student类继承Person
class Student(Person):
pass
stu1 =Student()
print(stu1.name)
print(Student.num)
stu1.show_message()
Student.people()
| false |
dd245f6a0b81da0d88d7a8be4ab27e489360a900 | LYblogs/python | /Python1808/第一阶段/day9-函数/06-匿名函数.py | 1,215 | 4.15625 | 4 | """
匿名函数还是函数,除了声明的语法以外,函数其他的语法匿名函数都支持
1.匿名函数的声明
a.语法
函数名 = lambda 参数列表:返回值
b.说明:
函数名 - 变量名
lambda - 关键字
参数列表 -和普通函数的参数列表的作用和要求一样
返回值 - 相当于普通函数return关键字后面的表达式
注意:匿名函数中 : 后面的语句属于函数体
"""
#用匿名函数求两个数的和
def my_num(num1,num2):
return num1+num2
my_sum1 = lambda num1,num2:num1+num2
print(my_sum1(10,20))
#练习:写一个匿名函数,功能是求两个数的最大值
my_max = lambda num1,num2:max(num1,num2)
#补充:python中三目运算符
"""
C中的三目运算符:条件语句?值1:值2 - 条件语句为True,整个表达式的结果是值1,否则是值2
int x =10,y =20;
max =x>y?x:y;
b.python中的三目运算符:值1 if 条件语句 else 值2 -条件语句为True,整个表达式的结果是值1,否则是值2
"""
x = 10
y = 20
print(x if x>y else y)
# 练习:写一个匿名函数,获取字典中指定的key对应的值
my_values = lambda dict,key:dict[key]
print(my_values({"a":100,"b":200},"a")) | false |
2aa5fe847e9343087191b7f425811085deda2e79 | LYblogs/python | /Python1808/第一阶段/day9-函数/05-返回值的应用.py | 427 | 4.3125 | 4 | """
返回值能做的事情,函数调用表达式都可以做
"""
# 1.用函数调用表达式给变量赋值
def func1():
return "hello"
print(func1())
# 2.通过函数调用表达式使用相应的方法
def func2():
return [1,2]
func2() #[1,2]
item = func2().append(3)
print(item)
# func2()=[1,2]
print(func2()[0])
3.#将函数调用表达式作为容器的元素,函数的参数,函数的返回值。
| false |
203dd6869ea062a839a0be03cdd7dd264ac2d5d7 | LYblogs/python | /Python1808/第一阶段/day13-类和对象/04-对象方法.py | 736 | 4.28125 | 4 | """
1.什么是对象方法
直接声明在类里面,并且自带一个self的参数的函数
2.对象方法的调用 - 通过对象调用对象方法
对象.对象方法()
3.self(当前对象)
通过对象调用对象方法的时候,对象方法中的第一个参数self不用传参;
系统会自动将当前对象传给self
哪个对象调用的,self就指向谁。
注意:当前类的对象能做的时候,self都能做,必须是通过对象调用才有用
"""
# 声明Person类
class Person:
"""人类"""
#声明了一个对象方法sleep
def sleep(self):
print("睡觉")
self.run()
def run(self):
print("跑")
#创建一个Person类的对象i
i =Person()
i.sleep()
| false |
fbc40a218809342532ae20e007829dc595d9cdf0 | anjana996/luminarpython | /flowcontrolls/secondlargestnum.py | 603 | 4.15625 | 4 | num1=int(input("Enter a number"))#10
num2=int(input("Enter a number"))#12
num3=int(input("Enter a number"))#13
if((num1>num2)&(num1>num3)):
if(num2>num3):
print("Second largest number is ",num2)
else:
print("Second largest number is ",num3)
elif((num2>num3)&(num2>num1)):
if(num3>num1):
print("Second largest number is ",num3)
else:
print("Second largest number is ",num1)
elif((num3>num2)&(num3>num1)):
if(num2>num1):
print("Second largest number is ",num2)
else:
("Second largest number is ",num1)
else:
print("Fool")
| true |
7b4d452a92c7c1131895983f0156644a2b755488 | anjana996/luminarpython | /operators/Arithmetic.py | 258 | 4.15625 | 4 | num1=int(input("Enter value for num1"))
num2=int(input("Enter value for num2"))
addresult=num1+num2
print("sum=",addresult)
subresult=num1-num2
print("subtraction=",subresult)
multi=num1*num2
print("multiresult=",multi)
div=num1/num2
print("divresult=",div) | false |
dd56d37a944bf61b57681705e55b8078f6459ea6 | toba101/CS101 | /week02/the.py | 2,401 | 4.34375 | 4 | # #--------MAD LIB - WORD GAME Extra---------#
verb = input('choose an verb: ')
adverb = input('choose an adverb: ')
noun = input('choose a noun: ')
noun = input('choose a noun: ')
noun = input('choose a noun: ')
verb = input('choose a verb: ')
verb = input('choose a verb: ')
noun = input('choose a noun: ')
print(f'\n')
# Output user input
print(f'verb: {verb}')
print(f'adverb: {adverb}')
print(f'noun: {noun}')
print(f'noun: {noun}')
print(f'noun: {noun}')
print(f'verb: {verb}')
print(f'verb: {verb}')
print(f'noun: {noun}')
print(f'\n')
# Print out story---Extra Mile----#
print(f"""Your story is: \n \n{verb} your arms {adverb} me and I am {noun}.
You can't go {noun} and change the {noun} but you can {verb} where
you are and {verb} the {noun}.""")
# # Example.
# print(f"""Your story is: \n \nThe other day, I was really in trouble. It all started when I saw a very
# {adjective} {animal} {verb} down the hallway. {exclamatory.upper()}. I yelled. but all I could think
# to do was to {verb} over and over. Miraculously, that caused it to stop, but no
# before it tried to {verb} right in front of my family.!""")
#--------MAD LIB - WORD GAME 02---------#
adjective = input('choose an adjective: ')
nationality = input('choose nationality: ')
name = input('choose a name: ')
noun = input('choose a noun: ')
adjective = input('choose a adjective: ')
noun = input('choose a noun: ')
adjective = input('choose a adjective: ')
adjective = input('choose a adjective: ')
noun = input('choose a noun: ')
noun = input('choose a noun: ')
number = input('choose a number: ')
plural_shape = input('choose a plural shape: ')
food = input('choose a food: ')
food = input('choose a food: ')
print(f'\n')
# Output user input
print(f'adjective: {adjective}')
print(f'nationality: {nationality} ')
print(f'name: {name}')
print(f'noun: {noun}')
print(f'adjective: {adjective}')
print(f'noun: {noun}')
print(f'adjective: {adjective}')
print(f'noun: {noun}')
print(f'noun: {noun} ')
print(f'number: {number}')
print(f'plural shape: {plural_shape}')
print(f'food: {food}')
print(f'food: {food}')
print(f'\n')
# Print out story
print(f"""Pizza is invented by a {adjective} {nationality} chef
named {name}. To make pizza, you need to take a lump of {noun}
and make a thin, round {adjective} {noun}.
Then you cover it with {adjective} sauce {adjective} chesse, and
fresh chopped {noun.upper()}!.""")
| false |
b25d1eb8141d179386fc04c49a22920302b15414 | toba101/CS101 | /week13/sample_function.py | 1,326 | 4.3125 | 4 | import math
def compute_area_square(side):
area = compute_area_rectangle(side, side)
return area
def compute_area_rectangle(length, width):
return length * width
def compute_area_circle(radius):
return math.pi * radius * radius
def compute_area(shape, value1, value2=0):
area = -1
if shape == "square":
area = compute_area_square(value1)
elif shape == "circle":
area = compute_area_circle(value1)
elif shape == "rectangle":
area = compute_area_rectangle(value1, value2)
return area
# The main program starts here...
shape = ""
while shape != "quit":
shape = input("What shape do you have? ")
# Convert it to lower case once, so we don't have to keep converting it
shape = shape.lower()
if shape == "square":
side = float(input("What is the length of the side? "))
area = compute_area(shape, side)
print(f"The area is {area}")
elif shape == "rectangle":
length = float(input("What is the length? "))
width = float(input("What is the width? "))
area = compute_area(shape, length, width)
print(f"The area is {area}")
elif shape == "circle":
radius = float(input("What is the radius? "))
area = compute_area(shape, radius)
print(f"The area is {area}") | true |
105abc52e2693dbf546d402d7074608d5b764ac7 | snachodog/Learning | /control_structures.py | 384 | 4.25 | 4 | # if/else/elif
age = 18
if age >= 18:
print ('is an adult')
elif age >= 12:
print ("is a young adult")
elif age >= 3:
print ('child')
else:
print ('baby')
# ternary
if age >= 21:
old_enough = True
else:
old_enough = False
old_enough = True if age >= 21 else False
# while
while age < 50:
print("not old enough, current age is " +str(age))
age += 1
| false |
ac49f9c5ab2e90bdf7b88938bc23ce38c366c279 | PatrykOlewniak/SPOJ | /PALIN - The Next Palindrome.py | 1,212 | 4.15625 | 4 | """
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left.
For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output.
Numbers are always displayed without leading zeros.
[Input]he first line contains integer t, the number of test cases. Integers K are given in the next t lines.
[Output] For each K, output the smallest palindrome larger than K.
Example:
Input:
2
808
2133
Output:
818
2222
"""
numbers = []
def ask_for_INPUT():
amountOfPalindromes= input()
for number in range(int(amountOfPalindromes)):
newValue = input()
numbers.append(int(newValue))
def number_to_list(number):
return list(str(number))
def isPalindrome(number):
tempList=number_to_list(number)
for k in range(int(len(tempList)/2)+1):
if tempList[k]!=tempList[-k-1]:
return False
return True
def palindrome_from_number(number):
number = number+1
while not(isPalindrome(number)):
number=number+1
return number
ask_for_INPUT()
for i in numbers:
print (palindrome_from_number(i))
| true |
870eaf4abc2bd151381abe3a934358265901d8ed | jvbradley/ATBSwP-v2 | /regexSearch.py | 1,499 | 4.125 | 4 | #! python3
# https://automatetheboringstuff.com/2e/chapter9/
'''
Write a program that opens all .txt files in a folder and searches for any line
that matches a user-supplied regular expression. The results should be printed
to the screen.
'''
def regexSearch():
from pathlib import Path
documentsHome = Path(Path.home(), 'Documents')
if Path.exists(documentsHome) and Path.is_dir(documentsHome):
os.chdir(documentsHome) # Set the current working directory
else:
os.mkdir(documentsHome) # Folder created
os.chdir(documentsHome) # Set the current working directory
textFileList = list(documentsHome.glob('*.txt'))
if len(textFileList) < 1:
infoMessage = ' * I failed to locate text files in the folder ' + documentsHome + '.'
print(infoMessage)
exit()
infoMessage = '\nThis program will search for a line of text in a file ending with the extension \'.txt\'.\n'
print(infoMessage)
textSearch = input('What line of text do you want to seek? ')
for textFile in textFileList:
if Path.is_file(textFile):
print(' * Checking file \'' + textFile.name + '\' ... ')
openTextFile = open(documentsHome / textFile)
textFileContent = openTextFile.readlines()
openTextFile.close()
for line in textFileContent:
if textSearch in line:
print(' * I found this line:')
print('\t' + line)
regexSearch()
| true |
78e1fe5c51062af1e25a22e2ada6e6eee33f9d99 | Insanityandme/python-the-hard-way | /pthway/ex34.py | 1,142 | 4.125 | 4 | animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
# 1. The animal at 1.
# The animal at 1 is a python.
# 2. The third (3rd) animal.
# The third animal is at 2 and is a peacock
# The animal at 2 is the 3rd animal and is a peacock.
# 3. The first (1st) animal.
# The first animal is at 0 and is a bear.
# The animal at 0 is the 1st animal and is a bear.
# 4. The animal at 3
# The fourth animal is at 3 and is a kangaroo
# The animal at 3 is the fourth animal and is a kangaroo
# 5. The fifth (5th) animal
# The fifth animal is at 4 and is a whale.
# The animal at 4 is the fifth animal and is a whale.
# 6. The animal at 2
# The animal at 2 is the third animal and is a peacock
# The third animal is at 2 and is a peacock.
# 7. The sixth (6th) animal
# The sixth animal is a platypus and is at 5.
# The animal at 5 is the sixth animal and is a platypus.
# 8. The animal at 4
# The fifth animal is at 4 and is a whale
# The animal at 4 is the fifth animal and is a whale.
print animals[1]
print animals[2]
print animals[0]
print animals[3]
print animals[4]
print animals[2]
print animals[5]
print animals[4]
| true |
9f4b860aba3f4c126f7324da2a5357b9a5a15b61 | Insanityandme/python-the-hard-way | /pthway/ex15.py | 1,149 | 4.40625 | 4 | # Import the argv module so that we can get
# arguments from the command line.
from sys import argv
# script = argv[0], filename = argv[1]
# argv[0] is the name of the script and
# argv[1] is the first argument given,
# in this case, the file's name.
script, filename = argv
# Opens a file, returning a file object
# in this case we are storing it in the txt variable
txt = open(filename)
# Using print statement and the specifier %r
# we print the filename given in the command line.
print "Here's your file %r: " % filename
# Reads the file object called txt and returns its content as a string.
print txt.read()
# Reads a string from your input and stores it inside second_file
# > is added to simulate a prompt.
print "Type the filename again: "
second_file = raw_input("> ")
# Stores the content of second_file and opens the file object.
txt_again = open(second_file)
# Reads the file object called txt_again and returns its content as a string.
print txt_again.read()
txt.close()
txt_again.close()
# The reason why I think raw_input is better is because you can get
# instructions beforehand, telling you what you need to do.
| true |
a8c3425e028d3a08f80814f007c106c52f191217 | Insanityandme/python-the-hard-way | /pthway/ex6.py | 1,981 | 4.59375 | 5 | # this is simply a variable that stores the string value of "binary"
binary = "binary"
# same as above
do_not = "don't"
# x is assigned a string, inside of it we use the specifier %d to include 10 into the string.
x = "there are %d types of people." % 10
# similar to x BUT this time % takes two arguments, binary and do_not. %d for decimals, %s for strings.
# Strings and Unicode objects have one unique built-in operation: the % operator (modulo).
# Also known as the string formatting or interpolation operator.
y = "Those who know %s and those who %s." % (binary, do_not)
# Example of more complex string formatting
z = '%(language)s has %(number)03d quote types' % {"language": "Python", "number": 2}
# Spits out the content that the variable x and y using the print statement
print x
print y
# %r specifier converts the string using repr().
print "I said: %r." % x
# %s specifier uses str()
print "I also said: '%s'." % y
# Boolean value stored in hilarious
hilarious = False
# again, using the specifier %r (repr()), I don't quite understand why %s isn't used though.
joke_evaluation = "Isn't that joke so funny?! %r"
# spits the values using two variables.
print joke_evaluation % hilarious
# Again storing or "holding" a string value inside of w + e
w = "This is the left side of..."
e = "a string with a right side."
# Printing both out of here.
print w + e
print "\t"
print "### MORE COMPLEX EXAMPLES, READ COMMENTS TO UNDERSTAND"
# for some objects such as integers, they yield the same results,
# but repr() is special in that (for types where this is possible)
# it conventionally returns a result that is valid python syntax,
# which could be used to unambigously recreate the object it represents.
# here's an example, using a date:
import datetime
d = datetime.date.today()
print str(d)
print repr(d)
# Example of more complex string formatting
z = '%(language)s has %(number)03d quote types' % {"language": "Python", "number": 2}
print z
| true |
e29ab2732d03a4ede044dddeb08a0d7346c4cef7 | henriquelorenzini/EstruturaSequencial | /Exercicio05.py | 245 | 4.28125 | 4 | # Faça um Programa que converta metros para centímetros.
metros = float(input('Digite o tamanho em metros: '))
centimetros = metros * 100
print ('o tamanho {:.2f} metros, em centimetros é: {:.0f} centimetros '.format (metros, centimetros)) | false |
f60d61141e7bf19eef4ba3df2ad2a4f824287a83 | henriquelorenzini/EstruturaSequencial | /Exercicio12.py | 730 | 4.1875 | 4 | #Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
#A - o produto do dobro do primeiro com metade do segundo .
#B - a soma do triplo do primeiro com o terceiro.
#C- o terceiro elevado ao cubo.
num1 = float(input('Digite o primeiro valor: '))
num2 = float(input('Digite o segundo valor: '))
num3 = float(input('Digite o terceiro valor: '))
a = (num1 * 2) * (num2 / 2)
b = (num1 * 3) + num3
c = (num3 * num3 * num3)
print('Os valores declarados foram: {:.1f}, {:.1f}, {:.1f}'.format(num1,num2,num3))
print('A - o produto do dobro do primeiro com metade do segundo: ' +str(a))
print('B - a soma do triplo do primeiro com o terceiro: ' + str(b))
print('C- o terceiro elevado ao cubo: ' + str(c))
| false |
b3e2bd4cb00e33f5de744bce2bdc83992548fd9d | xin-liqihua/PythonLearn | /Chapter_5/func.py | 1,852 | 4.1875 | 4 | # 方法定义的练习
def fact(n):
s = 1
for i in range(1, n + 1):
s *= i
return s
a = fact(10)
print(a)
# 可选参数传递
def fact1(n, m = 1):
s = 1
for i in range(1, n + 1):
s *= i
return s // m
b = fact1(10) # n = 10, m = 1
print(b)
c = fact1(10, 5) # n = 10, m = 5
print(c)
# 可变参数传递
def fact2(n, *args):
s = 1
for i in range(1 , n + 1):
s *= i
for item in args:
s *= item
return s
d = fact2(10) # n = 10 args = []
print(d)
e = fact2(10, 3) # n = 10 args = [3]
print(e)
f = fact2(10, 3, 5, 7) # n = 10 args = [3, 5, 7]
print(f)
########################################
# 参数传递的两种方式
########################################
# 位置传递
g = fact1(10, 5) # n = 10, m = 5
print(g)
# 名称传递
h = fact1(m = 5, n = 10)# n = 10, m = 5
print(h)
#######################################
#返回值
#可有可无 有就return XX 没有就 return
###########################################
def fact3(n, m):
s = 1
for i in range(1, n + 1):
s *= i
return s // m, n, m
i,j,k = fact3(10, 5) # i = 725760, j = 10, k = 5
print(i,j,k)
############################################
#变量
#局部变量 和 全局变量
############################################
l = 10
m = 100
def fact4(l):
m = 1
for i in range(1, l + 1):
m *= i
return m
print(fact4(l), m) # fact4(l) = 3628800, m = 100
def fact5(l):
global m
for i in range(1, l + 1):
m *= i
return m
print(fact5(l), m) # fact4(l) = 3628800, m = 3628800
n = ["A", "B"]
def fact6(a):
n.append(a)
return
fact6("C")
print(n) # ['A', 'B', 'C']
o = ["A", "B"]
def fact7(a):
o = []
o.append(a)
return
fact7("C")
print(o) #['A', 'B']
#######################################
#lambda匿名函数
########################################
p = lambda x, y : x + y
print(p(1, 10)) # 11
q = lambda : "呵呵"
print(q()) # 呵呵 | false |
8664e8736f356fffd0a6b8e08f6de32ad07d23a0 | Piyush-Kurkure/Linkedlist | /reverseLL.py | 1,244 | 4.25 | 4 | class Node:
def __init__(self, data):
self.data = data # assisgn data
self.next = None # assign next as NULL
class LinkedList:
def __init__(self): # initialize LL object
self.head = None # assign initial node as NULL
def printlist(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
def push(self, newdata):
newnode = Node(newdata) # 1.Allocate node and 2.put data in it
newnode.next = self.head # 3.Make next of new node as head
self.head = newnode # 4.Move head to new node
def reverse(self):
curr = self.head #initialize the pointer
prev = None
while curr is not None:
forward = curr.next # We need something in front to traverse
curr.next = prev # Change the direction of flow
prev = curr # Increment prev
curr = forward # Increment curr
self.head = prev
if __name__ == '__main__':
linkedlist = LinkedList() # object as empty list
linkedlist.push(1)
linkedlist.push(2)
linkedlist.push(3)
linkedlist.push(4)
linkedlist.reverse()
linkedlist.printlist()
| true |
9aa22fa0ca3a5be3a00a9494791773826fd5a63a | sdlarsen1/cmput175 | /Lab6/skeleton_lab6.py | 640 | 4.46875 | 4 | import turtle
def fractal(myTurtle, depth, size):
"""
implement the recursive draw function
"""
if size > 20 and depth > 0:
myTurtle.forward(size/3)
myTurtle.left(60)
fractal(myTurtle, depth-1, size-100)
myTurtle.forward(size/3)
fractal(myTurtle, depth-1, size-100)
myTurtle.right(120)
myTurtle.forward(size/3)
fractal(myTurtle, depth-1, size-100)
myTurtle.left(60)
fractal(myTurtle, depth-1, size-100)
def main():
myTurtle = turtle.Turtle()
myScreen = turtle.Screen()
myTurtle.color("green")
fractal(myTurtle, 3, 300)
myScreen.exitonclick()
if __name__ == "__main__":
main()
| false |
7dc1fe3ead6200b7f81c41a25b6e06883c0d6cab | Saltytatertot/Old-Python-Files | /Final Program.py | 950 | 4.46875 | 4 | #Final Program
#Tatum Gray
#5/14/2016
#This Program follows the style of a Choose Your Own Adventure Book.
ent = "(Press Enter)"
print("Welcome to -Title-, a Choose Your Own Adventure Story.")
print()
name = input("To get started, what is your name? >> ")
print()
print(name, "is a perfect name to start your story.")
print()
writ = input("""To get yourself familiar with what you'll will have to do,
here is a sample choice; Do you like apples or oranges better?""" + ent)
choiceX = int(input("""
1:Apples \t\t 2:Oranges
"""))
def choose(choice,resp1,resp2,extra): #Resp is a response the program will give.
if choice == 1:
print(resp1)
elif choice == 2:
print(resp2)
else:
print(extra)
choose(choiceX,"I like apples better too.","I prefer the juice to the fruit myself.","Come on get with the program.")
print()
Alright = input("Alright I think you have the hang of it now." + ent)
| true |
8f14fa9878a1054c6f263c531cb8cadfffdcbb5b | Saltytatertot/Old-Python-Files | /Dictionaries.py | 726 | 4.40625 | 4 | #Dictionaries are what we call key value pairs.
#Access these, use key
#converts 3 digit month name to full name
#Dictionary
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
"Aug": "August",
"Sep": "September",
"Oct": "October",
"Nov": "November",
"Dec": "December",
}
print(monthConversions["Nov"])
print(monthConversions["Dec"])
print(monthConversions["Sep"])
print(monthConversions.get("LUV","Ain't here bud. Sorry."))
#Returns None for something not in dictionary
#Can be numbers as long as the keys are unique.
#Useful for assigning values to other values.
| true |
59e6360b5086c7528231c9af8af344862205230c | phz3150/group_assignment-team-2 | /main_program.py | 629 | 4.34375 | 4 | #!/usr/bin/env python
import numpy as np
#create array of x coordinates:
x = -10. + np.arange(0, 20.1, 0.1)
# ask for input R:
R = float(input('R = '))
def volume(R):
"""Calculates the volume of a sphere with a given radius."""
import numpy as np
V = (4 / 3) * np.pi * (R ** 3)
return V
# call the external functions:
y = coordinates(x,R)
D_SA = sphere_properties(R)
V = volume(R)
# print informative statements:
print( 'A sphere of radius %.2f has a diameter of %.2f , a surface area of %.2f , and a volume of %.2f .' %(R, D_SA[0], D_SA[1], V))
print( 'The y-coordinates of a circle with radius', R, ' are \n', y)
| true |
3a184edb6d270e415567fbdcd5f5c7b5b15cabec | kasem777/Python-codeacademy | /Control Flow Challenges/carly's_clippers.py | 2,968 | 4.28125 | 4 | # Carly's Clippers
# You are the Data Analyst at Carly’s Clippers, the newest hair salon on the block.
# Your job is to go through the lists of data that have been collected in the past
# couple of weeks. You will be calculating some important metrics that Carly can use
# to plan out the operation of the business for the rest of the month.
# You have been provided with three lists:
# hairstyles: the names of the cuts offered at Carly’s Clippers
# prices: the price of each hairstyle in the hairstyles list
# last_week: the number of each hairstyle in hairstyles that was purchased last week
hairstyles = [
"bouffant",
"pixie",
"dreadlocks",
"crew",
"bowl",
"bob",
"mohawk",
"flattop",
]
prices = [30, 25, 40, 20, 20, 35, 50, 35]
last_week = [2, 3, 5, 8, 4, 4, 6, 2]
# Iterate through the prices list and add each price to the variable total_price.
total_price = 0
for i in prices:
total_price += i
# After your loop, create a variable called average_price that
# is the total_price divided by the number of prices.
# You can get the number of prices by using the len() function.
average_price = total_price / len(prices)
# Print the value of average_price so the output looks
print(f"Average Haircut Price: {average_price}")
# That average price is more expensive than Carly thought it would be!
# She wants to cut all prices by 5 dollars.
# Use a list comprehension to make a list called new_prices,
# which has each element in prices minus 5.
new_prices = [price - 5 for price in prices]
# Print new_prices.
print(new_prices)
# Carly really wants to make sure that Carly’s Clippers is a profitable endeavor.
# She first wants to know how much revenue was brought in last week.
# Create a variable called total_revenue and set it to 0.
# Use a for loop to create a variable i that goes from 0 to len(hairstyles)
# Hint: You can use range() to do this!
# total_revenue = 0
# Add the product of prices[i] (the price of the haircut at position i)
# and last_week[i] (the number of people who got the haircut at position i)
# to total_revenue at each step.
for i in range(len(hairstyles)):
total_revenue += prices[i] * last_week[i]
# After your loop, print the value of total_revenue
print(f"Total Revenue {total_revenue}")
# Find the average daily revenue by dividing total_revenue by 7.
# Call this number average_daily_revenue and print it out.
average_daily_revenue = total_revenue / 7
print(average_daily_revenue)
# Carly thinks she can bring in more customers by advertising all of the haircuts
# she has that are under 30 dollars.
# Use a list comprehension to create a list called cuts_under_30 that has the entry
# hairstyles[i] for each i for which new_prices[i] is less than 30.
# You can use range() in your list comprehension to make i go from 0 to len(new_prices) - 1.
cuts_under_30 = [hairstyles[i] for i in range(len(new_prices)) if new_prices[i] < 30]
print(cuts_under_30)
| true |
0f737312a7f0b6c357505fa2c7c340ff48688f60 | kasem777/Python-codeacademy | /Control Flow Challenges/UsingBothKeyword&PositionalUnpacking.py | 1,719 | 4.1875 | 4 | ## Using Both Keyword and Positional Unpacking
## This keyword argument unpacking syntax can be used even if the function takes other parameters. However, the parameters must be listed in this order:
## All named positional parameters
## An unpacked positional parameter (*args)
## All named keyword parameters
## An unpacked keyword parameter (**kwargs)
## Here’s a function with all possible types of parameter:
def main(filename, *args, user_list=None, **kwargs):
if user_list is None:
user_list = []
if '-a' in args:
user_list = all_users()
if kwargs.get('active'):
user_list = [user for user_list if user.active]
with open(filename) as user_file:
user_file.write(user_list)
## Looking at the signature of main() we define four
## different kinds of parameters. The first, filename
## is a normal required positional parameter.
## The second,
## *args, is all positional arguments given to a function after
## that organized as a tuple in the parameter args. The third,
## user_list, is a keyword parameter with a default value. Lastly,
## **kwargs is all other keyword arguments assembled as a dictionary
## in the parameter kwargs.
## A possible call to the function could look like this:
main("files/users/userslist.txt",
"-d",
"-a",
save_all_records=True,
user_list=current_users)
## In the body of main() these arguments would look like this:
filename == "files/users/userslist.txt"
args == ('-d', '-a)
user_list == current_users
kwargs == {'save_all_records': True}
## We can use all four of these kinds of parameters to create
## functions that handle a lot of possible arguments being passed to them.
| true |
997db486701bf4ce01d286700b5e362c07960d38 | kasem777/Python-codeacademy | /Loops/count_letters.py | 1,076 | 4.3125 | 4 | # Count Letters:
# Write a function called unique_english_letters that takes the string word as a parameter.
# The function should return the total number of unique letters in the string.
# Uppercase and lowercase letters should be counted as different letters.
# We’ve given you a list of every uppercase and lower case letter in the English alphabet.
# It will be helpful to include that list in your function.
def unique_english_letters(word):
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
count = 0
for char in letters:
if char in word:
count += 1
return count
# Another Answer:
# def unique_english_letters(word):
# letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# uniques = []
# for letter in word:
# if letter in letters and not letter in uniques:
# uniques.append(letter)
# return len(uniques)
# Uncomment these function calls to test your function:
print(unique_english_letters("mississippi"))
# should print 4
print(unique_english_letters("Apple"))
# should print 4
| true |
ac55f1fbdc559004a93f60d10f910f83123c986e | kasem777/Python-codeacademy | /Loops/odd_indices.py | 635 | 4.34375 | 4 | # Odd Indices
# Create a function named odd_indices() that has one parameter named lst.
# The function should create a new empty list and add every element from lst
# that has an odd index. The function should then return this new list.
# For example, odd_indices([4, 3, 7, 10, 11, -2]) should return the list [3, 10, -2].
# Write your function here
def odd_indices(lst):
new_lst = []
for i in range(len(lst)):
if (i % 2) != 0:
new_lst.append(lst[i])
else:
continue
return new_lst
# Uncomment the line below when your function is done
print(odd_indices([4, 3, 7, 10, 11, -2]))
| true |
d4301c5f477e61701a6c96741e348a66d3467f1f | shoeffner/monty | /06_Packages/code/sheet/mazesolver/io.py | 1,529 | 4.375 | 4 | """This module handles the mazesolver's input and output.
Mainly this means printing to the terminal and reading the
starting configurations.
"""
def load_maze(filename):
"""Loads a maze.
Loads a maze from a given filename.
A maze file contains the layout of the maze as rows of numbers separated by
spaces. The numbers encode the following:
0: Empty space.
1: Starting position.
2: Wall space (not accessible).
3: Cheese position.
Note that only exactly one 1 and one 3 are allowed. (This is not checked.)
Args:
filename: The file to be read.
Returns:
A list containing a list per line.
For example if the file contained:
2 2 2 2 2 2
2 1 0 0 3 2
2 2 2 2 2 2
The resulting list would look like this:
[[2, 2, 2, 2, 2, 2],
[2, 1, 0, 0, 3, 2],
[2, 2, 2, 2, 2, 2]]
"""
maze = [[]]
# TODO: Write this function to return what is asked above.
return maze
def print_maze(maze):
"""Prints the maze.
Args:
maze: The maze to print.
"""
for row in maze:
print(' '.join([str(v) for v in row]))
def store_maze(maze, filename):
"""Stores a maze into a file.
The maze is stored in the same layout as described in load_maze(filename).
Args:
maze: A maze as lists of lists.
filename: The file to store the maze in.
"""
# TODO: BONUS: Write the solved maze to a file.
pass
| true |
c118a6c3a8816271e19fd4a755bed37dbaadb689 | AruzhanBazarbai/pp2 | /tsis6/5.py | 254 | 4.375 | 4 | #Write a Python function to calculate the factorial of a number (a non-negative integer).
# The function accepts the number as an argument.
def fact(n):
cnt=1
while n>0:
cnt*=n
n-=1
return cnt
n=int(input())
print(fact(n)) | true |
a1abd3869fed1832beb529760261f14bce608594 | AruzhanBazarbai/pp2 | /tsis6/16.py | 215 | 4.1875 | 4 | #Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included).
def f(n):
a=[]
for i in range(1,n+1):
a.append(i**2)
print(a)
f(30) | true |
e0a2bcf5d6f5ba49cab9b065c4198ebe2d44caf5 | AruzhanBazarbai/pp2 | /tsis6/15.py | 433 | 4.4375 | 4 | #Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically.
def f(s):
res=""
text=s.split('-')
text=sorted(text,key=str)
for word in text:
res+=word+'-'
print(res[:len(res)-1])
f("green-red-yellow-black-white")
"""
items=[n for n in input().split('-')]
items.sort()
print('-'.join(items))
""" | true |
0c77b33b7bdf91cfa48982bfc6ee117320f5b7c3 | AruzhanBazarbai/pp2 | /tsis5/part1/8.py | 607 | 4.4375 | 4 | # Write a python program to find the longest words.
def longest_word(fname):
with open(fname,"r") as f:
words=f.read().split()
max_len=len(max(words,key=len))
return [word for word in words if len(word)==max_len]
print(longest_word("test.txt"))
'''
def f_read(fname):
res=""
res_size=0
a=[]
with open(fname,"r") as f:
for x in f:
a.append(x.split())
for item in a:
#print(len(*item),*item)
n=len(*item)
if n>res_size:
res_size=n
res=item
print(*res)
f_read("test.txt")
''' | true |
49c3b95695adb2af28ef53464aae8c554d9b1488 | dongchen6698/Data_Analysis | /Python/Project_Practice/COMP_6651_Practice/Selection_sort_algorithm.py | 581 | 4.125 | 4 | def selection_sort_algorithm(array, size):
for i in range(size-1): # i = 0, 1, 2, 3, 4, 5 size = 6
iMin = i
# Find the min within the array
for j in range(i+1, size):
if array[j] < array[iMin]:
iMin = j
# Exchange the min with index i
temp = array[i]
array[i] = array[iMin]
array[iMin] = temp
def main():
array = [2, 7, 4, 1, 5, 3, 6]
selection_sort_algorithm(array, len(array))
print(array)
if __name__ == '__main__':
main()
# Time complexity is O(n^2)
| true |
2d70335fc002b40246c9d559f7ca719f83d068be | mar156/Informatorio.Python | /Basicos/SumatoriayPromedio.py | 902 | 4.3125 | 4 | '''' -----------------------------------------------------------------
Ejercicio simple para practicar Estructuras de control.
Para resolver este ejercicio deberá utilizar estructuras
repetitivas.
-----------------------------------------------------------------
EJERCICIO 3:
Cree un programa que pida números hasta que se introduzca un cero.
Debe imprimir la suma total de todos los numeros introducidos y el promedio.
'''
# Coloque la resolución del Ejercicio 3 debajo de esta línea
acumulador = 0
n= 0
numero_consola = int(input('Ingrese por favor un número: '))
print()
while (numero_consola != 0):
n= n+1
acumulador+= numero_consola
print("Suma total de todos los números: ", acumulador)
print("Promedio de todos los números: ", (acumulador/n))
print()
numero_consola = int(input('Ingrese por favor un número: '))
print()
| false |
e6c9bfd141154af38d4623553c1a1068a07d043d | gitbazz/volume_calculator | /volumes.py | 1,019 | 4.25 | 4 | # Import pi for use in ellipsoidVolume function
from math import pi
# Computes the volume of a cube
# @param side is the length of a side of the cube
# @return volume
def cubeVolume(side):
volume = side**3
print("The volume of a cube with side length = %d is: %.2f" %(side, volume))
return volume
# Computes the volume of a pyramid
# @param base is the base length of the pyramid
# @param height is the height of the pyramid
# @return volume
def pyramidVolume(base, height):
volume = (1/3)*(base**2)*height
print("The volume of a pyramid with base length = %d and height = %d is: %.2f" %(base, height, volume))
return volume
# Computes the volume of an ellipsoid
# @param r1 is radius 1 of the ellipsoid
# @param r2 is radius 2 of the ellipsoid
# @param r3 is radius 3 of the ellipsoid
# @return volume
def ellipsoidVolume(r1, r2, r3):
volume = (4/3)*pi*r1*r2*r3
print("The volume of an ellipsoid with r1 = %d, r2 = %d, and r3 = %d is: %.2f" %(r1, r2, r3, volume))
return volume
| true |
08232a2326306d94a44c425c548642a68575abc1 | Ananya9878/Master-PyAlgo | /Topic Wise Questions with Solutions/Array/merge_two_sorted_array_without_extra_space.py | 1,273 | 4.375 | 4 | # Python program to merge two sorted arrays with O(1) extra space.
def merge_array(a1, a2, n, m):
# Iterate through all elements of a2[] starting from the last element
for i in range(m-1, -1, -1):
# Find the smallest element greater than a2[i]. Move all elements one position ahead till the smallest greater
# element is not found
last = a1[n-1]
j=n-2
while(j >= 0 and a1[j] > a2[i]):
a1[j+1] = a1[j]
j-=1
# If there was a greater element
if (j != n-2 or last > a2[i]):
a1[j+1] = a2[i]
a2[i] = last
# main program
n = int(input("Enter length of first array : "))
m = int(input("\nEnter length of second array : "))
a1 = list(map(int,input("\nEnter the elements of first array : ").strip().split()))[:n]
a2 = list(map(int,input("\nEnter the elements of second array : ").strip().split()))[:n]
merge_array(a1, a2, n, m)
print("After Merging \nFirst Array:", end="")
for i in range(n):
print(a1[i] , " ", end="")
print("\nSecond Array: ", end="")
for i in range(m):
print(a2[i] , " ", end="")
''''
Input :
n = 6
m = 4
a1 = [1, 5, 9, 10, 15, 20]
a2 = [2, 3, 8, 13]
output :
After Merging
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity: O(m+n)
The worst case time complexity of code/algorithm is O(m*n).
'''
| true |
19da8272038397d598bac080fd5e1a81b1b5fcee | Ananya9878/Master-PyAlgo | /Graphs/Kruskal's_Algorithm_Implementation.py | 2,491 | 4.125 | 4 | """ Created by @debjitpal5040
Kruskal's Minimum Spanning Tree Algorithm
This program is for set of edges representation of the graph
It is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph.
This means it finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.
The algorithm operates by in each step it adds the next lowest-weight edge that will not form a cycle to the minimum spanning tree.
The algorithm may informally be described as performing the following steps:
Create a forest F (a set of trees), where each vertex in the graph is a separate tree
Create a set S containing all the edges in the graph
While S is nonempty and F is not yet spanning
Remove an edge with minimum weight from S
If the removed edge connects two different trees then add it to the forest F, combining two trees into a single tree
"""
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
def apply_union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskalMST(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = []
rank = []
for node in range(self.V):
parent.append(node)
rank.append(0)
while e < self.V - 1:
u, v, w = self.graph[i]
i = i + 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e = e + 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
for u, v, weight in result:
print(u,"--",v,"\t",weight)
g = Graph(4)
g.add_edge(0, 1, 10)
g.add_edge(0, 2, 6)
g.add_edge(0, 3, 5)
g.add_edge(1, 3, 15)
g.add_edge(2, 3, 4)
print("Edge \tWeight")
g.kruskalMST()
"""
Output
Edge Weight
2 -- 3 4
0 -- 3 5
0 -- 1 10
""" | true |
12558d855e89d3ddd17123f235258c2477a90081 | Ananya9878/Master-PyAlgo | /Topic Wise Questions with Solutions/Recursion/Tower_of_hanoi.py | 818 | 4.125 | 4 | # Program to implement Tower of Hanoi
# Function to demonstrate the number of moves to shift rings from start rod to end rod
def Tower_of_Hanoi(num , start_rod, end_rod, aux_rod):
if num == 1:
print ("Move disk 1 from", start_rod,"to", end_rod)
else:
Tower_of_Hanoi(num-1, start_rod, aux_rod, end_rod)
print ("Move disk", num,"from", start_rod,"to", end_rod)
Tower_of_Hanoi(num-1, aux_rod, end_rod, start_rod)
if __name__ == "__main__" :
num= int(input("Enter the number of rings in the first rod:"))
Tower_of_Hanoi(num,'A','C','B')
'''
Enter the number of rings in the first rod:3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
'''
| false |
0de657f7f608f571b0c4bb29a37b373773ee7fe4 | Ananya9878/Master-PyAlgo | /Topic Wise Questions with Solutions/Array/Spiral_Traversal_of_Matrix.py | 1,030 | 4.1875 | 4 | # In Spiral Traversal of matrix, first you need to traverse in following order top row -> last column -> last row -> first column
# After that second row -> last second column -> last second row -> second column and so on till no elements are left for traversal
def spiral_matrix(m, n, matrix):
k=0
l=0
while (k < m and l < n):
for i in range(l,n):
print(matrix[k][i],end=" ")
k=k+1
for i in range(k,m):
print(matrix[i][n-1],end=" ")
n=n-1
if (k<m):
for i in range(n-1,l-1,-1):
print(matrix[m-1][i],end=" ")
m=m-1
if (l<n):
for i in range(m-1,k-1,-1):
print(matrix[i][l],end=" ")
l=l+1
R=int(input("Enter No of Rows "))
C=int(input("Enter No of Colums "))
print("Add One row at time i.e 1 2 3 4")
matrix=[]
for i in range(0,R):
temp=list(map(int,input().split()))
matrix.append(temp)
spiral_matrix(R, C, matrix)
'''
INPUT:
2
3
1 2 3
4 5 6
OUTPUT:
1 2 3 4 5 6
INPUT:
2
2
1 2
3 4
OUTPUT:
1 2 3 4
Time Complexity: O(R*C)
Space complexity: O(1)
'''
| true |
e905872a4dde7762ed0025c15ee4f8831c35c076 | Ananya9878/Master-PyAlgo | /Algorithms/Sorting/Selection_Sort.py | 733 | 4.5 | 4 | '''
SELECTION SORT
This algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
TIME COMPLEXITY : O(n²)
SPACE COMPLEXITY : O(1)
'''
def selection_sort(array):
size = len(array)
for start in range(size):
minpos = start
for index in range(start, size):
if array[index] < array[minpos]:
minpos = index
array[start], array[minpos] = array[minpos], array[start]
array = list(map(int,input("Enter the elements of Array : ").split()))
selection_sort(array)
print('After running selection_sort : ', array)
'''
OUTPUT
Enter the elements of Array : 43 32 123 67 3 76
After running selection_sort : [3, 32, 43, 67, 76, 123]
''' | true |
26fce279011ac01ff89116165a7c1c7795222b64 | Ananya9878/Master-PyAlgo | /Algorithms/Sorting/Wave_Sort.py | 991 | 4.78125 | 5 | ''' As we understand from the name sort it is a way of sorting that makes the
list of element look like a wave
For example an array after a wave sort will be:
>=arr[1]<=arr[2]>=arr[3]<=
The code for Wave sort: '''
def swap(arr,i,j):
arr[i], arr[j] = arr[j], arr[i]
def WaveSort(arr,n):
for i in range(0,n-1,2):
if i>0 and arr[i-1]>arr[i]:
swap(arr,i,i-1)
if i<n-1 and arr[i]<arr[i+1]:
swap(arr,i,i+1)
return arr
''' Driver code for the function: '''
if __name__=='__main__':
numbers=[]
n=int(input("Length of array: "))
print("Enter the elements: ")
numbers = list(map(int, input().split(",")))
numbers= WaveSort(numbers,n)
print("After Wave Sort: ")
for i in range(n):
print(numbers[i], end=", ")
'''
SAMPLE INPUT:
Length of array: 9
Enter the elements:
10, 20, 5, 17, 46, 35, 29, 59, 70
SAMPLE OUTPUT:
After Wave Sort:
20, 5, 17, 10, 46, 29, 59, 35, 70 ''' | true |
4f552602055ca39b03cdbd1948912f2241b20272 | abhinavmish96/PYTHON | /classesAndObjects.py | 2,241 | 4.75 | 5 | # Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Classes are essentially a template to create your objects.
# A very basic class would look something like this:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
# We'll explain why you have to include that "self" as a parameter a little bit later. First, to assign the above class(template) to an object you would do the following:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
# Now the variable "myobjectx" holds an object of the class "MyClass" that contains the variable and the function defined within the class called "MyClass".
# Accessing Object Variables
# To access the variable inside of the newly created object "myobjectx" you would do the following:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjectx.variable
# So for instance the below would output the string "blah":
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
print(myobjectx.variable)
# You can create multiple different objects that are of the same class(have the same variables and functions defined). However, each object contains independent copies of the variables defined in the class. For instance, if we were to define another object with the "MyClass" class and then change the string in the variable above:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjecty = MyClass()
myobjecty.variable = "yackity"
# Then print out both values
print(myobjectx.variable)
print(myobjecty.variable)
# Accessing Object Functions
# To access a function inside of an object you use notation similar to accessing a variable:
class MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
myobjectx.function() | true |
eacffe99b5221168cb0522fc34c0225dec4d44b5 | abhinavmish96/PYTHON | /loops.py | 2,160 | 4.625 | 5 | # There are two types of loops in Python, for and while.
# The "for" loop
# For loops iterate over a given sequence. Here is an example:
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
# For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange). Note that the range function is zero based.
# Prints out the numbers 0,1,2,3,4
for x in range(5):
print(x)
# Prints out 3,4,5
for x in range(3, 6):
print(x)
# Prints out 3,5,7
for x in range(3, 8, 2):
print(x)
# "while" loops
# While loops repeat as long as a certain boolean condition is met. For example:
# Prints out 0,1,2,3,4
count = 0
while count < 5:
print(count)
count += 1 # This is the same as count = count + 1
# "break" and "continue" statements
# break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples:
# Prints out 0,1,2,3,4
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
# unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If break statement is executed inside for loop then the "else" part is skipped. Note that "else" part is executed even if there is a continue statement.
# Here are a few examples:
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
if(i%5==0):
break
print(i)
else:
print("this is not printed because for loop is terminated because of break but not due to fail in condition") | true |
dbe537bd53ecfa6774f469263d7bfc3133da0ec5 | mvogee/pyMiniProjects | /alarmClock/setup.py | 1,666 | 4.3125 | 4 | from alarmClock import clock
class setup:
def timer():
print("\nussage: hours:minutes:seconds\n\"00:00:00\"\n")
time_length = input("enter timer: ")
try:
# abstract the hours, minutes, and seconds from input
hours = int(time_length[0:2])
minutes = int(time_length[3:5])
seconds = int(time_length[6:8])
# convert all time lengths to seconds for total time
totalseconds = seconds + (minutes * 60) + (hours * 3600)
print("timer set for", time_length)
start = input("type start to start or anything else to exit: ")
if (start.lower() == "start"):
clock.timer(totalseconds)
else:
return
except:
print("please use the format 00:00:00\n")
def alarm():
print ("ussage: hour:minute AM/PM\n\"07:30AM\"\n")
alarm_time = input("enter alarm time: ")
#save the original input string to display once the conversion is done
savetime = alarm_time
try:
#make sure the format is correct
if (int(alarm_time[0:2]) <= 12 and int(alarm_time[3:5]) < 60):
if (alarm_time[5:7].lower() == "am"):
#12 am is the only time we modify AM time
if (alarm_time[0:2] == "12"):
alarm_time = "00" + alarm_time[2:]
elif (alarm_time[5:7].lower() == "pm"):
#noon is the only time we do not add 12 hours to the total
if (not(alarm_time[0:2] == "12")):
alarmt = int(alarm_time[0:2]) + 12
alarm_time = str(alarmt) + alarm_time[2:]
#abstract the real time cutting off the AM or PM
alarm_time = alarm_time[0:5]
print("alarm set for: ", savetime)
clock.alarm(alarm_time);
else:
print("please use the format 12:59AM")
except:
print("please use the format 12:59AM")
| true |
3e5bc2f7bdb09d85d2a73f3906476a7a11b6387f | IchibanKanobee/MyProjects | /Interview/Python/closures/closures.py | 793 | 4.5 | 4 | #A closure is a record storing a function together with an environment
#inner_function is aware of a free variable message
def outer_func():
message = "Hi"
def inner_function():
print (message)
return inner_function()
outer_func()
def outer_func1():
message = "Hi"
def inner_function():
print (message)
return inner_function
my_func = outer_func1()
print(my_func)
my_func()
my_func()
my_func()
#A closure is an inner function that remembers and has access to variables of the outer function, even if the outer funcion is finished executing
def outer_func2(msg):
message = msg
def inner_function():
print (message)
return inner_function
hi_func = outer_func2("Hi")
hello_func = outer_func2("Hello")
hi_func()
hello_func()
| true |
87db602be0c1c34be8885cc215064715c62aacd2 | Blazaca/portfolio | /Crash Course/Lists, Print, and Return.py | 1,360 | 4.15625 | 4 | close_friends = ['Faith', 'Evan', 'Pablo', 'Nick']
# Instead of using print use 'return'
def message_friends(x):
return close_friends[x] + ' is one of my close friends.'
# Because the def for print(close_friends[x] + 'is one of my close friends.'
# has a second line underneath it print will return the second line as 'none'
print(message_friends(0))
print(message_friends(1))
print(message_friends(2))
print(message_friends(3))
# Modes of transportation
# This method not only saves 4 lines of code
# it's faster :D
transport = ['skateboard', 'snowboard', 'boosted board', 'electric car']
for wheels in transport:
print('I would like to own a ' + wheels)
# Changing items in lists
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# this line will change an index
motorcycles[0] = 'ducati'
# when changing a list you can change it to a string, var, bool, etc.
# Appending Lists
# appending a list adds another item to the end of the list
# or if the list is empty it will populate
# motorcycles = ['honda', 'yamaha', 'suzuki']
# motorcycles.append('ducati')
#
# for motorcycle in motorcycles:
# print(motorcycle)
# Inserting items into a list
# motorcycles = ['honda', 'yamaha', 'suzuki']
# motorcycle.insert(0, 'ducati')
# The first variable is the position of insertion
# the second is the item being inserted
| true |
1ff55f7dc391afe08569781a59d2eace67e1a809 | Blazaca/portfolio | /Pre-work class/Python 102/python 102 q-3.py | 1,317 | 4.28125 | 4 | number_list = [13, 14, 66, 77, 64, 333, 7, 98, 5567, 55555, 55556]
number_list2 = [13, 14, 66, 77, 100000000, 2, 4343, 6457]
number_list3 = [1, 22, 33, 44, 55, 666]
number_list_all = [[13, 14, 66, 77, 64, 333, 7, 98, 5567, 55555, 55556],
[13, 14, 66, 77, 100000000, 2, 4343, 6457], [1, 22, 33, 44, 55, 666]]
def max_num_in_list(a_list):
"""
This function uses a for loop to go through a list and compare
each number to max_number which is default set to 0.
It will return the max number.
:param a_list:
:return: Max number in a given list as int
"""
max_number = 0
for number in a_list:
if number > max_number:
max_number = number
return max_number
for list in number_list_all:
print('Checking for a max number with function 1 with list:\n'
+ str(list))
print('Max number is: ' + str(max_num_in_list(list)))
# OR
def max_num_in_list2(a_list):
"""
This function uses the max() function to return the max
number in a given list.
:param a_list:
:return: Max number in given list as int
"""
return max(a_list)
for list in number_list_all:
print('Checking for a max number with function 2 with list:\n'
+ str(list))
print('Max number is: ' + str(max_num_in_list2(list)))
| true |
81b1e26c16780a2d7118dfd77d2cfae0da14bac7 | hengyangKing/python-skin | /Python基础/code_day_5/python中的小坑.py | 466 | 4.15625 | 4 | #coding=utf-8
#1.交换变量
num_1 = 100;
num_2 = 200;
print (num_1,num_2);
num_2,num_1 = num_1,num_2;
print (num_1,num_2);
#2.可变数据类型
def test(par):
par+=par;
print(par);
a = 100;
test(a);
print (a);
print("不可变数据类型的实际参数 不会随着行参的运算而发生改变")
b = [100];
test(b);
print (b);
print ("可变数据类型的实际参数 会随着行参的运算而改变")
print("指针指向的数据类型很关键");
| false |
0244fdbde08ae5fe93638e384d2bde71e8644c40 | mukeshrock7897/List-Programs | /List Programs/2__Program to find the second Largest Number in List.py | 207 | 4.21875 | 4 | a=[]
element=int(input("Enter The Number of Elements::"))
for i in range(element):
b=int(input("Enter the Element::"))
a.append(b)
a.sort()
print("The Second Largest Element of List::",a[element-2])
| true |
09cf2ff5196cbda6e7fbabe8311a1784d3baa736 | Ryan-D-mello/MyCaptain-Projects | /count_letters.py | 463 | 4.1875 | 4 | def most_frequent(string):
for i in range(len(string)):
temp=0
for j in range(len(string)):
if string[i] in string[j]:
temp=temp+1
mydict[string[i]]=temp
print(mydict)
mydict={}
string=input("Enter a string: ")
most_frequent(string)
#I couldn't figure how to print the sorted list(by values) along with their keys.
#Secondly, is there an alternate more efficient logic to this program?
| true |
390b493da24764a10108ce1a0d146e5faaae3720 | gospelin/Python-Programming | /Chapter 2 - Input, Processing and Output/personal_info.py | 579 | 4.25 | 4 | #1. Personal Information
# Write a program that displays the following information:
# • Your name
# • Your address, with city, state, and ZIP
# • Your telephone number
# • Your college major
#Request for personal information
name = input("Enter your full name: ")
address = input("Enter your address: ")
city = input("Enter the city: ")
state = input("Enter the state: ")
major = input("Enter your college major: ")
print(f"\nBelow are your details as submitted:\n Name: {name}\n Address: {address}, {city}, {state}\n College Major: {major}")
| true |
3480f712014e8f7b0701806e71ea662381491760 | YukiT1990/Algorithm-and-Data-Structure-in-Python | /sorts/InsertionSort.py | 859 | 4.15625 | 4 | from typing import MutableSequence
def insertion_sort(a: MutableSequence) -> None:
n = len(a)
for i in range(1, n):
j = i
tmp = a[i]
while j > 0 and a[j - 1] > tmp:
a[j] = a[j - 1]
j -= 1
a[j] = tmp
if __name__ == '__main__':
print('Insertion sort')
num = int(input('The number of the elements: '))
x = [None] * num
for i in range(num):
x[i] = int(input(f'x[{i}]: '))
print(x)
insertion_sort(x)
print('Sorted x in ascending order.')
for i in range(num):
print(f'x[{i}] = {x[i]}')
print(x)
"""
Insertion sort
The number of the elements: 7
x[0]: 6
x[1]: 4
x[2]: 3
x[3]: 7
x[4]: 1
x[5]: 9
x[6]: 8
[6, 4, 3, 7, 1, 9, 8]
Sorted x in ascending order.
x[0] = 1
x[1] = 3
x[2] = 4
x[3] = 6
x[4] = 7
x[5] = 8
x[6] = 9
[1, 3, 4, 6, 7, 8, 9]
"""
| true |
7d20c3075ce77e79ec2a19faa41d20df1df0d47b | acabhishek942/Quora_Algos | /sort.py | 1,988 | 4.21875 | 4 | def quick_sort(array):
less=[]
equal=[]
greater=[]
if len(array)<1:
pivot=array[0]
for x in array:
if x < pivot:
less.append(x)
if x==pivot:
equal.append(x)
if x>pivot:
greater.append(x)
return quick_sort(less)+equal+quick_sort(greater)
else:
return -1
class MergeSort():
def merge(left, right, array):
"""Function to merge the two sub-arrays in the given array"""
nL=len(left)
nR=len(right)
i,j,k=0,0,0
while i<nL and j<nR:
if left[i]<=right[j]:
""" if element of left sub-array is less than or equal to element of right sub-array
then left sub-array element will be copied to element of the main array"""
array[k]=left[i]
i=i+1
else:
""" if the above condition is not satisfied then the element of the right sub-array will be copied to the
main array"""
array[k]=right[j]
j=j+1
k=k+1
""" below two loops ensure that the extra leftover elements in any of the two sub-arrays gets copied as it is
in the main array"""
""" Only one among the two loops will run"""
while i<nL:
array[k]=left[i]
i=i+1
k=k+1
while j<nR:
array[k]=right[j]
j=j+1
k=k+1
def merge_sort(array):
n=len(array)
if n<2:
return 0
mid=int(n/2)
left=[]
right=[]
for i in xrange(0, mid-1):
left.append(array[i])
for i in xrange(mid, n-1):
right.append(array[i])
merge_sort(left)
merge_sort(right)
merge(left, right, array)
| true |
7afa374e0832e59c3b2460b0df43a1c7294f77f4 | Bhavyamadhu2006/Python | /src/Python Statement/ifelse.py | 480 | 4.25 | 4 | # Example for If Elif and Else statements
Job = "Software Engineer"
if (Job == "Teacher"):
print("I'm working as a teacher")
elif (Job == "Doctor"):
print("I'm a surgeon")
elif (Job == "Software Engineer"):
print("I'm a developer")
else :
print("I'm still studying")
# Another Example
Name = " "
if (Name == "Madhu"):
print("Hello Madhu")
elif (Name == "Prayu"):
print("Hello Prayu")
elif (Name == "Bhavya"):
print("Hello Bhavya")
else:
print("Hello Stranger") | false |
085a8323de7cd9e58b1abc65bc3ad74a5753888c | Bhavyamadhu2006/Python | /src/SecondAssessment/test1.py | 1,420 | 4.40625 | 4 | # 1. Create a Statement that will print out words that start with 's'
st = 'Print only the words that start with s in this sentence'
st_list = st.split()
print(st_list)
for item in st_list:
if item[0] == "s":
print(item)
# 2. Print all the even numbers from 0 to 10
my_list1 = list(range(0,11,2))
print(my_list1)
# 3. Create a list of all numbers between 1 and 50 that are divisible by 3
my_list = [num for num in range(1,100) if num%3 == 0]
print(my_list)
# 4. Go through the string below and if the length of a word is even print "even!"
st1 = 'Print every word in this sentence that has an even number of letters'
st1_list = st1.split()
print(st1_list)
for item in st1_list:
if len(item) % 2 == 0:
print(item)
# 5. Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".
for num in range(1,100):
if (num%3 == 0 and num%5 == 0):
print("FizzBuzz")
elif num%3 == 0:
print("Fizz")
elif (num%5 == 0):
print("Buzz")
else:
print(num)
# 6. Create a list of the first letters of every word in the string below
st2 = 'Create a list of the first letters of every word in this string'
st2_list = st2.split()
print(st2_list)
first_letter_list = [item[0] for item in st2_list]
print(first_letter_list) | true |
cd278cb71e1649a7c2f1592cdb9c7db1141ce001 | VinayagamD/PythonTrainingBatch1 | /patterns/pyramid_pattern.py | 602 | 4.21875 | 4 |
def take_user_input():
return int(input("Enter Number for rows for pattern:\n"))
def print_pattern(rows):
"""
require 3 loops
1) Row loop
2) Space loop
3) Column loop
:param rows: Number of rows to print
:return: none
"""
for row in range(1, rows+1):
for space in range(0, (rows-row)):
print(" ", end=" ")
for col in range(0, (2*row)-1):
print("*", end=" ")
print()
def run_pattern_application():
rows = take_user_input()
print_pattern(rows)
if __name__ == '__main__':
run_pattern_application()
| true |
2401fadd26840dbb61dde101c063cdcdc6a36783 | sissialves/IPEAPython | /ListaExec13.py | 854 | 4.1875 | 4 | """
IPEA - Mestrado em Políticas Públicas e Desenvolvimento
3a. turma
Prof. Bernardo Furtado
Aluna: Sissi Alves da Silva
1a Lista de Exercícios
13. Escreva um programa que substitua ‘,’ por ‘.’ e ‘.’ por ‘,’ em uma string. Exemplo: 1,000.54
por 1.000,54.
"""
def substitue_pontuacao(p):
if "," in p:
p2 = str.replace(p,',',':')
if "." in p2:
p3 = str.replace(p2, ".", ",")
if ":" in p3:
p4 = str.replace(p3, ":", ".")
return p4
if __name__ == '__main__':
palavra1 = "1,000.54"
palavra2 = "1.000.540,00"
print('Exemplo 1: A string inicial: ', palavra1)
print('A nova palavra é: ', substitue_pontuacao(palavra1))
print('Exemplo 2: A string inicial: ', palavra2)
print('A nova palavra é: ', substitue_pontuacao(palavra2))
exit(0)
#funcionando! SAS | false |
0240a95147d9213ff3d20d3c4c826a5dde86937c | hookeyplayer/exercise.io | /thinkpython2/笔记3_初级披萨.py | 827 | 4.46875 | 4 | # 存储所点比萨的信息
pizza = {'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'],}
print("You ordered a " +
pizza['crust'] + "-crust pizza " +
"with the following toppings:")
# 字典中嵌套了列表,一个键关联多个值
for topping in pizza['toppings']:
print("\t" + topping)
# 一、单变量披萨配料:创建形参空元组 *toppings
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 二、多变量:披萨尺寸和配料
def make_pizza2(size, *toppings):
print("Your " + str(size) +" inch pizza with toppings:")
for topping in toppings:
print('\t' + topping.title())
make_pizza2(12, 'pepperoni', 'green onions')
| false |
2964dc1f3e1d4e576ea0e0bdaa17cd1cb98e7324 | StaciAF/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,357 | 4.15625 | 4 | #!/usr/bin/python3
"""
This modules divides all elements of a matrix
Matrix must be a list of lists with values of types integer and float
Each matrix row must be the same size
Dividend results should be rounded to 2 decimal places
"""
def matrix_divided(matrix, div):
""" checks matrix as list, checks for value types, returns new matrix
Args:
matrix: matrix given to be divided
div: number given to be divided by, must be int/float
"""
int_error = "matrix must be a matrix (list of lists) of integers/floats"
row_error = "Each row of the matrix must have the same size"
divNum_error = "div must be a number"
zero_error = "division by zero"
if len(matrix) is 0:
raise TypeError(int_error)
if isinstance(matrix, list) is False:
raise TypeError(int_error)
for row in matrix:
if isinstance(row, list) is False:
raise TypeError(int_error)
for x in row:
if isinstance(x, (int, float)) is False:
raise TypeError(int_error)
if isinstance(div, (int, float)) is False:
raise TypeError(divNum_error)
if div is 0:
raise ZeroDivisionError(zero_error)
for row in matrix:
if len(matrix[0]) != len(row):
raise TypeError(row_error)
return[[round(x/div, 2) for x in row] for row in matrix]
| true |
3d57564dd14077c28e189ce1e9da15f7fddcd7bc | StaciAF/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 362 | 4.21875 | 4 | #!/usr/bin/python3
"""
this module creates a method to count lines in a text file
"""
def number_of_lines(filename=""):
""" this method returns the number of lines in a text file """
linecount = 0
with open(filename, 'r') as this_file:
for line in this_file.readlines():
linecount += 1
this_file.closed
return linecount
| true |
079e4482c653631d538f77852431268d2a0ad98a | StaciAF/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/3-say_my_name.py | 570 | 4.46875 | 4 | #!/usr/bin/python3
"""
This module prints 'My name is <first_name> <last_name>'.
Both first_name and last_name must be given as strings
"""
def say_my_name(first_name, last_name=""):
""" checks for both arguments to be strings, prints sentence """
first_error = "first_name must be a string"
last_error = "last_name must be a string"
if isinstance(first_name, str) is False:
raise TypeError(first_error)
if isinstance(last_name, str) is False:
raise TypeError(last_error)
print("My name is {} {}".format(first_name, last_name))
| true |
02f95994c2f5bee9ef56139e306604f5adfc606c | StaciAF/holbertonschool-higher_level_programming | /0x06-python-classes/4-square.py | 1,053 | 4.5625 | 5 | #!/usr/bin/python3
""" no modules imported """
class Square:
""" Defines a Square class """
def __init__(self, size=0):
""" initializes Square with optional value of 0 - size will be private
Args:
size: size of Square
"""
self.__size = size
@property
def size(self):
""" defines properties of size making attribute private
Returns: private instance of size
"""
return self.__size
@size.setter
def size(self, value):
""" defines size setter
Raises:
TypeError: if size/value is not of type int
ValueError: if size/value is less than 0
"""
if not isinstance(value, int):
raise TypeError('size must be an integer')
elif value < 0:
raise ValueError('size must be >= 0')
else:
self.__size = value
def area(self):
""" defines public function to get Square area
Returns: area of current Square
"""
return self.size ** 2
| true |
1c48009c323b496e1cd650fa818a119522f041b1 | IMDCGP105-1819/portfolio-s184286 | /python ex6.py | 533 | 4.15625 | 4 |
name = input("Enter your name: ")
print("Your name is", name, ".")
age = int(input("Enter your age: "))
if age > 18:
print(name, "is", age, "years old.")
height = float(input("Enter your Height(cm):"))
if height > 0:
print("That's a positive size!")
weight = float(input("Enter your Weight(kg):"))
if weight > 0:
print("That's a positive weight!")
eyes = input("Eye colour:")
print ("and your eye color is:"+eyes)
hair = input("Hair colour:")
print ("and your hair color is:"+hair)
| true |
daa567f19d802a8a1e5d608bbb3a9c462675bad5 | prottayislive/mini_projects | /rock_paper_scissor.py | 862 | 4.21875 | 4 | import random
def play():
""" Making initial choice for user and pc"""
print("Enter 'r' for rock, 'p' for paper, 's' for scissor")
user = input("Choose your move: ").lower().strip()
computer = random.choice(['r', 'p', 's'])
print(f"You played {user} and computer played {computer}")
# conditionals to determine winner or loser
if user == computer:
return 'tie'
if is_win(user, computer):
winner = "Congrats! You won!"
return winner
loser = "You Lost!"
return loser
def is_win(player, opponent):
"""Finding winner through logic --> r>s, s>p , p>r"""
# game mechanics to decide who wins
if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') or (
player == 'p' and opponent == 'r'):
return True
print(play())
| true |
bcb4a5fb04bd8b0709dd5388af946c72423f060b | ShravanKumarGodugu/Python_code | /EVEN & ODD.py | 293 | 4.3125 | 4 | ''' Printing EVEN & ODD Numbers
Condition for Even Numbers n(variable)%2==0:
If above is true is even or else it ODD Numbers
'''
N = int(raw_input('Enter a Number '))
if N%2==0:
print("The given number is Even {}" .format(N))
else:
print("The Given Number is ODD {}" .format(N)) | false |
b9c78fbe4e513838cadab7ca04fc4951cfff4534 | liyaSileshi/coding-syntax-spd | /kwords.py | 895 | 4.21875 | 4 | #4, Given a string of text and a number k,
# find the k words in the given text that
# appear most frequently. Return the words
# in a new array sorted in decreasing order.
#input: text= ‘one fish two fish blue fish red fish’ k=2
#find the k(2) most frequent words that are in the text
#histogram of all the words
#sort a dict by the value
def hist_text(text, k):
text_hist = {} #make a histogarm out of the text
text_arr = text.split(' ')
for i in text_arr:
# if i is in the hist
# increment by 1
if i in text_hist:
text_hist[i] += 1
# if not make a key and assign it to 1
else:
text_hist[i] = 1
text_hist = sorted(text_hist.items(), key= lambda x: x[1], reverse=True)
sub_text = text_hist[:k]
return sub_text
text= "one fish two fish blue fish red fish red"
print(hist_text(text, 2)) | true |
cd489b25394f90a37c9913823a4e94a85a8080ac | sharmasubash/python-bootcamp | /calculation_of_pi.py | 519 | 4.15625 | 4 | # -*- coding: utf-8 -*-
# Create the Function to calculate PI using Ramanujam Series
from decimal import Decimal
def fact(n):
fact = 1
if n == 0:
return fact;
else:
while (n>=1):
fact = n * fact
n = n-1
return fact
def ramu_pi(num):
constant = (8**(0.5))/9801 ;
z = 0
for n in range(num):
x = float(constant*(((fact(4*n))/(fact(n)**4)) * ((26390*n) + 1103)/396**(4*n)))
z = z + x;
return z
1/Decimal(ramu_pi(2000)) | false |
2a3fbbacfe4fd50259eea81f1c1c2342543e29e0 | wangxp1994/python_code | /hanyue/code_study/_04_collections_namedtuple.py | 734 | 4.5 | 4 | # collections是Python内建的一个集合模块,提供了许多有用的集合类
"""
namedtuple
它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素.
这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便
"""
from collections import namedtuple
# 定义一个坐标元组
Point = namedtuple("Point", ["X", "Y"])
p = Point(10, 2)
print(p.X, p.Y, type(p))
# 定义一个学生
Student = namedtuple("Student", ["name", "gender", "age", "score"])
s = Student("张三", "男", 23, 100)
print(s.name, s.gender, s.age, s.score) | false |
20964b9f14f1b34b4aa0051f7960bddf52571325 | sherryxiata/SwordOffer | /Recursion&Loop/RectangleCover.py | 728 | 4.3125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/3/4 15:28
# @Author : wenlei
'''矩形覆盖问题
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
'''
#第一块矩形横着放:f(n-2) 第一块矩形竖着放:f(n-1)
def rectCover(number):
# write code here
if number < 0:
return 0
res = [0, 1, 2]
while len(res) <= number:
res.append(res[-1] + res[-2])
return res[number]
if __name__ == '__main__':
print(rectCover(-1))
print(rectCover(0))
print(rectCover(1))
print(rectCover(2))
print(rectCover(3))
print(rectCover(4))
| false |
7dd1a7a6f658bfff0450449dd634c29e1bd492e9 | atharva-01/Python-Lab-Programs | /reverse_pair.py | 364 | 4.5 | 4 | '''
Two words are a 'reverse pair' if each is the reverse of the other. Write a program that finds all the reverse
pairs in the word list.
'''
def reversing_str(word_list):
reverse_pair_list = []
for i in word_list :
r = i[::-1]
reverse_pair_list.append(r)
return reverse_pair_list
print(reversing_str(['one','two','three'])) | true |
bac8dbfae3bbd69cf57a076bc668e2d329d60b04 | atharva-01/Python-Lab-Programs | /exponentation.py | 374 | 4.53125 | 5 | '''
Program to find the exponent of the given number to the power given by user
'''
def get_exp(base ,power):
pow = 1
for i in range(power):
pow = pow * base
return pow
base = float(input('Enter the base :'))
power = int(input('Enter the power :'))
print('The value of number whose base is',base,'and power is',power,'is:',get_exp(base,power)) | true |
a73dc796cce760892ee4fa9272c5c6584f9d1013 | wbrucesc/PythonExercises | /ex2.py | 324 | 4.28125 | 4 |
# Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.
def max_of_three(num1, num2, num3):
if num1 > num2 and num1 > num3:
return num1
elif num2 > num1 and num2 > num3:
return num2
else:
return num3
print(max_of_three(1, 12, 4))
| true |
5d9fbdebecba4b9f4899b1bbf7c268d49d66c434 | wbrucesc/PythonExercises | /ex3.py | 362 | 4.25 | 4 |
# Define a function that computes the length of a given list or string. (It is true that Python has the
# len() function built in, but writing it yourself is nevertheless a good exercise.)
def find_length(string):
length = 0
for i in string:
length += 1
return length
print(find_length("Happy Birthday"))
print(len("Happy Birthday"))
| true |
b388ee991ace7757d809d5feead34838aeb78366 | malhotraguy/List_o_Matic-Function | /Code.py | 1,362 | 4.21875 | 4 | def check_list_o_matic(list_name):
def list_o_matic(list_name,inp):
if inp=="":
return print(list_name.pop(),"popped from list \nLook at the after list: ",list_name)
else:
if inp in list_name:
list_name.remove(inp)
print("\n1 instance of","'"+inp+"'","has been removed from the list")
print("Look at the after list: ",list_name)
else:
list_name.append(inp)
print("\n1 instance of","'"+inp+"'","has been appended to the list")
print("Look at the after list: ",list_name)
while True:
if list_name==[]:
print("\nGOODBYE!!!")
break
else:
print("\nLook at the before list: ",list_name)
inp=input("Enter your Character or 'quit' to end!! : ")
if inp=="quit":
print("GOODBYE!!! \n")
print(list_name)
break
else:
list_o_matic(list_name,inp)
#=====================================================================================================================
#=====================================================================================================================
list_animal=["cat","dog","horse"]
check_list_o_matic(list_animal)
| true |
d3587589e392254b9229172dda1675e8fc542761 | ckopecky/Algorithms | /1-stock_prices/stock_prices.py | 2,396 | 4.125 | 4 | #!/usr/bin/python
import argparse
'''
the list of prices show the variance of price during different times of day. list is sorted by time and not by price.
so the basic problem is to find the maximum profit you can make by buying first and then selling later in the day.
what we need to do is to keep track of the min price so far and the max profit so far.
so we need to have some sort of pointer that starts at the beginning of the array and then a second pointer that starts at the second element in the array.
the first element is automatically the current min price so far and the difference between the second element and the first element is the current max profit so far.
if we do a while loop whose conditional is that i and j are both less than the length of the array, we can keep the while loop going without having nested loops I think.
for the first check, we set i to the initial element in array and we set j to the third element in the array since we have already instantiated the the max profit so far is the difference between elemnt 1 and element 0.
let's check to see if j element - i element is > max profit so far -- if it is update max profit
if not, advance j if there is length left in the array -- if not reset i to i + 1 and reset j to the "new" i + 1.
'''
def find_max_profit(prices):
i = 0
j = 1
max_profit = float('-inf')
while i < len(prices) and j < len(prices):
difference = prices[j] - prices[i]
print(difference)
if difference > max_profit:
max_profit = difference
if j + 1 == len(prices):
#we start over
if i + 1 == len(prices):
break
else:
i += 1
j = i + 1 #new i
else:
j += 1
else:
if j + 1 == len(prices):
#we start over
if i + 1 == len(prices):
break
else:
i += 1
j = i + 1 #new i
else:
j += 1
return max_profit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(profit=find_max_profit(args.integers), prices=args.integers)) | true |
7de2f864bbe75db64c921f1ca790de767e9ab3b9 | grisreyesrios/Coding-Exercises-Challenges | /Project-Euler/Problem1/Solution1.py | 431 | 4.25 | 4 | # Project Euler Problem1
def sum_multiples(x):
total_sum = sum(x for x in range(x) if (x % 3 == 0 or x % 5 == 0))
return total_sum
try:
multiples_range = int(input('Please enter a range to compute the multiples of 3 and 5:'))
total_multiples = sum_multiples(multiples_range)
print(total_multiples)
except ValueError:
print("Invalid input, please introduce only integers and below 1 000 000")
quit()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.