blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b5d3beb20cc86479f91f35db74f4f4a87bd54dc4 | KishoreMayank/CodingChallenges | /Interview Cake/Stacks and Queues/MaxStack.py | 821 | 4.3125 | 4 | '''
Max Stack:
Use your Stack class to implement a new class MaxStack with a
method get_max() that returns the largest element in the stack.
'''
class MaxStack(object):
def __init__(self):
self.stack = []
self.max = []
def push(self, item):
"""Add a new item to the top of our stack."""
self.stack.append(item)
if not self.max or item >= self.max[-1]: # add if empty or if greater
self.max.append(item)
def pop(self):
"""Remove and return the top item from our stack."""
item = self.stack.pop()
if item == self.max[-1]: # pop if the same element
self.max.pop()
return item
def get_max(self):
"""The last item in max is the max item in our stack."""
return self.max[-1]
| true |
c7a5d62ff9c478f7430982313345c1f0adb82459 | kanatnadyrbekov/Ch1Part2-Task-31 | /task31.py | 470 | 4.28125 | 4 | # Напишите функцию которая подсчитает количество строк, слов и букв в текстовом
# файле.
text = """Hello my name is Kanat, and I study in Maker's course
mjdbvzjk zkjvasukz ksbvzu ubvu jbvab ajbvuzb """
string = text.count("\n")
print(f"Text has: {string + 1} string")
words = ' '
a = text.count(words)+1
print(f"Text has: {a} words")
letter = len(text)-a +1
print(f"Text has: {letter} letters")
| false |
158b7350e9ad0138b32882cc0f3e1cee08ddde6f | wakabayashiryo/Library | /python/Practice/function.py | 1,071 | 4.125 | 4 | #動物の最高速度を辞書型で定義
animal_speed_dict = {
"チーター":110,"トナカイ":80,
"シマウマ":60,"ライオン":58,
"キ リ ン":50,"ラ ク ダ":30,
}
#東京から各都市までの距離を辞書型で定義
distance_dict = {
"静 岡":183.7,
"名古屋":350.6,
"大 阪":507.5,
}
#時間を計算する関数を定義
def calc_time(dist,speed):
t = dist /speed
t = round(t,1)
return t
#動物の各都市までの時間を計測する関数を定義
def calc_animal(animal,speed):
res = "|"+animal
for city in sorted(distance_dict.keys()):
dist = distance_dict[city]
t = calc_time(dist,speed)
res += "|{0:>6}".format(t)
return res + "|"
print("+--------+------+------+------+")
print("|動物名前",end="")
for city in sorted(distance_dict.keys()):
print("|"+city,end="")
print("|")
print("+--------+------+------+------+")
for animal,speed in animal_speed_dict.items():
s = calc_animal(animal,speed)
print(s)
print("+--------+------+------+------+")
| false |
95b549c39072f6cc6ad2cab9602f9522ff012079 | tamanna-c/Python-Internship | /Day2.py | 1,490 | 4.25 | 4 | #Task-1
"""print("Hello World")"""
''' This is an example of multiline comment'''
""" This is also an example of multiline comment"""
#Task-2
"""
a=10
b=20.5
c="Tamanna"
print(a)
print("Value of b is:",b)
print("My name is",c)"""
#Task-3
"""name="Tamanna"
print("Name is:",name)
#assigning a new value
name="Tamanna.com"
print("Name is:",name) """
#Task-4
"""a,b,c=20,10.5,"Orange"
print(a)
print("Value of b is:",b)
print("Fruit name is:",c) """
#Task-5
"""b=c=d=900
print("Value of b=",b)
print("Value of c=",c)
print("Value of d=",d) """
#Task-6
"""n1=100
print(n1,"is of type", type(n1))
n2=20.6
print(n2,"is of type", type(n2))
print(n2, "is complex number?", isinstance(10.5,int))
n3=1+3j
print(n3, "is complex number?", isinstance(1+3j,complex)) """
#Task-7
"""name="Tamanna Choithani"
print("Name is :",name)
print(name [0])
print(name [2:5])
print(name[2:])
print(name[:4])
print(name*2)
print (name + " Hello") """
#Task-8
"""list1 = [10, 20, 30, "Akash", 40, 50, "Technolabs", 60]
print(list1)
print (list1[2])
print(list1[0:3])
print (list1 [5:])
print (list1[:3])
print(type(list1)) """
#Task-9
"""d = { 1: 'Satoru',2: 'Suguru', 'key': 10 }
print (type(d))
print ("d[1] = ", d[1])
print ("d[2] = ", d[2])
print ("d[key] = ", d['key']) """
#Task-10
"""l1 = (10, 20, 30, "Akash", 40, 50, "Technolabs", 60)
print(l1)
print (l1[2])
print(l1[0:3])
print (l1 [5:])
print (l1[:3])
print(type(l1)) """ | false |
047638de234a37c895d55b1aa6f571f72d2c9f4c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex16.py | 877 | 4.3125 | 4 | '''Reading and writing files'''
from sys import argv
script, filename = argv
print "We're going to erase %r."%filename
print "If you don't want that, hit CTRL-C(^C)."
print "If you don't want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
#when you open the file in write mode,you dont need to truncate.
#write erases the contents of the already existing file
print "Truncating the file. Goodbye!"
target.truncate()
print "Now am going to ask you for three lines."
line1 = raw_input("line1: \n")
line2 = raw_input("line2: \n")
line3 = raw_input("line3: \n")
print "I'm going to write these to the file."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#alternatively:
#SEE HOW TO WRITE USING ONE COMMAND
print "And finally we close it."
target.close() | true |
e670461879bb35a19b25ef3b8ca5364d2fd3c007 | stellakaniaru/practice_solutions | /dict_learn.py | 266 | 4.15625 | 4 | '''
A program that iterates through dict items and prints them out.
'''
classmates = {'Mary :' : ' Sweet but talks too much',
'stella :' : ' cool,calm and collected',
'Mark :' : ' code ninja on the block'}
for k, v in classmates.items():
print(k + v)
| false |
b1025eb52f8c374fecd1458fe6e151f38eb8ec1a | stellakaniaru/practice_solutions | /overlapping.py | 500 | 4.1875 | 4 | '''
Define a function that takes in two lists and returns True
if they have one member in common.False if otherwise.
Use two nested for loops.
'''
#function definition
def overlapping(list1, list2):
#loop through items in first list
for i in list1:
#loop through items in second list
for j in list2:
#check if any of the items in list1 are equal to any of the items in list2
if i == j:
return True
#outside loop to ensure its not caught up in any loop conditions
return False
| true |
5b49cf35ea8a0c178691c729f4275a93519be37c | stellakaniaru/practice_solutions | /learn-python-the-hard-way/ex7.py | 849 | 4.40625 | 4 | '''more printing'''
#prints out a statement
print 'Mary had a little lamb.'
#prints out a statement with a string
print 'Its fleece was as white as %s.'%'snow'
#prints out a statement
print 'And everywhere that Mary went.'
print '.' * 10 #prints a line of ten dots to form a break
#assigns variables with a character each
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
#prints out the variables by adding them together to form a name
#experiment with the comma
#when you remove the comma,python inteprates the next command to be executed on the next line.
#the comma tells python that execution of the following line of code should occur on the current line
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12 | true |
053d3a417ab0f05a201f9999917babd870869561 | stellakaniaru/practice_solutions | /years.py | 664 | 4.25 | 4 | '''
Create a program that asks the user to enter their name and
age. Print out a message addressed to them that tells them
the year they will turn 100 years old.
'''
from datetime import date
#ask for user input on name and age
name = input('Enter your name: ')
age = int(input('Enter your age: '))
num = int(input('Enter a number to show how many times the output should be printed: '))
#generates the current year
years = date.today().year
#generates the year of birth
diff = years - age
#generates the year the individual will turn 100 years
a_100 = diff + 100
#outputs the results
print("%s, you will be a 100yrs in the year %s\n" %(name, a_100) * num) | true |
1f42e53223e2ec4d0ce3f185cf5e4919985e0f0c | stellakaniaru/practice_solutions | /max_three.py | 364 | 4.3125 | 4 | '''
Define a function that takes in three numbers as
arguments and returns the largest of them.
'''
#function definition
def max_of_three(x,y,z):
#check if x if the largest
if x > y and x > z:
return x
#check if y is the largest
elif y > x and y > z:
return y
#if the first two conditions arent met,z becomes the largest by default
else:
return z
| true |
d3b3b842686d62d102ef89dfdffb0fefdc834343 | prabhatpal77/Adv-python-oops | /refvar.py | 475 | 4.1875 | 4 | # Through the reference variable we can put the data into the object, we can get the data from the object
# and we can call the methods on the object.
# We can creste a number of objects for a class. Two different object of a same class or different classes
# does not contain same address.
class Test:
"""sample class to test object"""
def display(self):
print("welcome")
print(Test.__doc__)
t1=Test()
print(t1)
t1.display()
t2=Test()
print(t2)
t2.display()
| true |
80d0dafe8c5f6604e94c34dca7d6aeefc9acbf9b | prabhatpal77/Adv-python-oops | /abstraction4.py | 543 | 4.125 | 4 | # We can access the hidden properties of a super class within the subclass through special syntax.
class X:
__a=1000
def __init__(self):
self.__b=2000
def __m1(self):
print("in m1 of x")
class Y(X):
__c=3000
def __init__(self):
self.__d=4000
super().__init__()
def __m2(self):
print("in m2 of y")
def display(self):
print(Y.__c)
print(self.__d)
self.__m2()
print(self._X__a)
print(self._X__b)
self._X__m1()
y1=Y()
y1.display()
| false |
69996ed2547992a8a7b8eb86e554740f0ac3647b | IrinaVladimirTkachenko/Python_IdeaProjects_Course_EDU | /Python3/TryExcept/else_finaly.py | 855 | 4.34375 | 4 | # If we have an error - except block fires and else block doesn't fire
# If we haven't an error - else block fires and except block doesn't fire
# Finally block fires anyway
#while True:
# try:
# number = int(input('Enter some number'))
# print(number / 2)
#except:
# print('You have to enter a number!')
#else:
# print('Good job! This is a number!')
# break
#finally:
# print('Finally block')
#print('Code after error handling')
def divide(x, y):
try:
return x / y
except ZeroDivisionError as a:
print('You can\'t divide by zero!')
print(e)
except TypeError as e:
print('x and y must be numbers')
print(e)
else:
print('x has divided by y')
finally:
print('finally block')
print(divide(4, 0))
# print(divide(4, 'w')) | true |
b7c8c1f93678be20578422e02e01adeba36041f9 | Ballan9/CP1404-pracs | /Prac01/asciiTable.py | 420 | 4.25 | 4 | LOWER = 33
UPPER = 127
print("Enter a character:")
character = input()
print("The ASCII code for g is", ord(character))
number = int(input("Enter a number between {} and {}:".format(LOWER,UPPER)))
if number < LOWER or number > UPPER:
print("Invalid number entered")
else:
print("The Character for {} is ".format(number), chr(number))
for i in range (LOWER,UPPER+1):
print("{:<3}, {:>3}".format(i, chr(i)))
| true |
82b1b76a67d899523d77c2ee9d6fdea0812cbd67 | catherinelee274/Girls-Who-Code-2016 | /Python Projects/fahrenheittocelsius.py | 356 | 4.28125 | 4 | degree = input("Convert to Fahrenheit or celsius? For fahrenheit type 'f', for celsius type 'c'")
value = input("Insert temperature value: ")
value =int(value)
if degree == "c":
value = value-32
value = value/1.8
print(value)
elif degree == "f":
value = value*1.8 + 32
print(value)
else:
print("Insert a valid value")
| true |
77a30e9dc9d474a27928153ebef45acfccfcbbfa | kononeddiesto/Skillbox-work | /Module20/07_sort_function/main.py | 306 | 4.25 | 4 | def sort(some_tuple):
for i_int in some_tuple:
if type(i_int) != int:
return some_tuple
elif type(i_int) == int and i_int == some_tuple[-1]:
new_tuple = sorted(list(some_tuple))
return tuple(new_tuple)
my_tuple = (4, 3, 2, 1)
print(sort(my_tuple))
| false |
c42c463b4cc15dce457eb07ff2338d8e9c52c391 | kononeddiesto/Skillbox-work | /Module18/13_anagram/main.py | 384 | 4.125 | 4 | first_word = list(input('Введите 1 слово:'))
second_word = input('Введите 2 слово:')
for i in second_word:
if i in first_word:
first_word.remove(i)
if not first_word:
print('Слова являются анаграммами друг друга')
else:
print('Слова не являются анаграммами друг друга')
| false |
3775cb6c2e02e1b142b14ef88f2cadd57fd47d3e | blakerbuchanan/algos_and_data_structures | /datastructures/datastructures/queues.py | 697 | 4.1875 | 4 | # Impelement a queue in Python
# Makes use of the list data structure inherent to Python
class Queue:
def __init__(self):
self.Q = []
def remove(self):
try:
self.Q.pop(0)
except:
print("Error: queue is empty.")
def add(self, item):
self.Q.append(item)
def peek(self):
return self.Q[0]
def isEmpty(self):
if len(self.Q) == 0:
return True
else:
return False
if __name__ == '__main__':
queue = Queue()
queue.remove()
print(queue.isEmpty())
queue.add("bird")
queue.add("alligator")
print(queue.Q)
print(queue.peek())
print(queue.isEmpty()) | true |
54785e654145533309b1197a6f17aea09a8d7b28 | go1227/PythonLinkedLists | /DoubleLinkedList.py | 1,655 | 4.1875 | 4 | __author__ = "Gil Ortiz"
__version__ = "1.0"
__date_last_modification__ = "4/7/2019"
__python_version__ = "3"
#Double Linked List
class Node:
def __init__(self, data, prev, next):
self.data = data
self.prev = prev
self.next = next
class DoubleList:
head = None
tail = None
def append(self, data): #append new value to the end of the list + add pointer prev pointing to the node before the last
new_node = Node(data, None, None)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
#new_node.next = None
self.tail.next = new_node
self.tail = new_node
def remove(self, node_value):
this_node = self.head
while this_node is not None:
if this_node.data == node_value:
if this_node.prev is not None:
#re-link pointers to the point we simply "skip" the current node
this_node.prev.next = this_node.next
this_node.next.prev = this_node.prev
else:
self.head = this_node.next
this_node.next.prev = None
this_node = this_node.next
def show(self):
print("FULL Double Linked List:")
this_node = self.head
tmp = ""
while this_node is not None:
tmp = tmp + str(this_node.data) + " -> "
this_node = this_node.next
tmp = tmp + "None"
print(tmp)
d = DoubleList()
d.append(5)
d.append(8)
d.append(50)
d.show()
d.remove(8)
d.show() | true |
56bfaaa56ffb54a986b9d7ea862cb670405b785e | carloslorenzovilla/21NumberGame | /main.py | 2,291 | 4.34375 | 4 | """
Created on Sun Jul 14 10:17:48 2019
@author: Carlos Villa
"""
import numpy as np
# This game is a take on a 21 Card Trick. 21 numbers are randomly placed
# in a 7x3 matrix. The player thinks of a number and enters the column that
# the number is in. This step is repeated three times. Finally, the number
# that the user was thinking of is revealed.
class NumberTrick:
def __init__(self):
pass
@staticmethod
def shuffCards(grid, turn):
# Prompt for player input
if turn == 1:
col = int(input('Pick a number. What column it is in (1, 2, or 3)?: '))
print('\n')
else:
col = int(input('What column is your number in now (1, 2, or 3)?: '))
print('\n')
# Stays in loop until user provides valid entry
while col == 0 or col > 3:
col = int(input('That is not a valid column! Try again genius (1, 2, or 3): '))
print('\n')
# Elements in columns are aranged in reverse, and the selected coulumn
# is aranged between the other two columns. The newly aranged matrix is
# flattened into 1-D array by columns.
if col == 1:
numbers = np.array([grid[::-1,1],grid[::-1,col-1],grid[::-1,2]])
elif col == 2:
numbers = np.array([grid[::-1,0],grid[::-1,col-1],grid[::-1,2]])
else:
numbers = np.array([grid[::-1,0],grid[::-1,col-1],grid[::-1,1]])
numbers = numbers.flatten()
return numbers
def start(self):
#Create array from 1-21, shuffle
numbers = np.arange(1,22)
np.random.shuffle(numbers)
#Round 1
turn = 1
grid_1 = numbers.reshape(7,-1)
print('\n',grid_1)
numbers_1 = self.shuffCards(grid_1, turn)
#Round 2
turn += 1
grid_2 = numbers_1.reshape(7, -1)
print(grid_2)
numbers_2 = self.shuffCards(grid_2, turn)
#Round 3
turn += 1
grid_3 = numbers_2.reshape(7, -1)
print(grid_3)
numbers_3 = self.shuffCards(grid_3, turn)
#Result
print('Your number is {}!'.format(numbers_3[10]))
NumberTrick().start()
| true |
f7e6ef2007bcea37aa7aa2d7ba71a125b0bde471 | yulyzulu/holbertonschool-web_back_end | /0x00-python_variable_annotations/7-to_kv.py | 442 | 4.15625 | 4 | #!/usr/bin/env python3
"""Complex types"""
from typing import Tuple, Union
def to_kv(k: str, v: Union[int, float]) -> Tuple[str, float]:
""" type-annotated function to_kv that takes a string k and an
int OR float v as arguments and returns a tuple. The first element
of the tuple is the string k. The second element is the square of the
int/float v and should be annotated as a float."""
return (k, v ** 2)
| true |
5e1816ef1384ba6d66df4cd9639bbcd08a4e4805 | jaeheon-lee/pre-education | /quiz/pre_python_02.py | 1,010 | 4.15625 | 4 | """"2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오
예시
<입력>
첫 번째 수를 입력하세요 : 10
두 번째 수를 입력하세요 : 15
어떤 연산을 하실 건가요? : *
<출력>
150
"""
def calculator(a,b,c):
if c == '*':
print(a*b)
elif c =='/':
if b == 0:
print('0으로 나눌 수 없습니다.')
b= int(input('두 번째 수를 입력하세요.:'))
calculator(a,b,c)
print(a/b)
else:
print(a / b)
elif c =='+':
print(a+b)
elif c =='-':
print(a-b)
else:
print('연산기호를 잘 못 입력 하셨습니다.')
c = input('어떤 연산을 하실 건가요? :')
calculator(a,b,c)
a = int(input('첫 번째 수를 입력하세요 : '))
b = int(input('두 번째 수를 입력하세요 : '))
c = input('어떤 연산을 하실 건가요? : ')
calculator(a,b,c)
| false |
d4d47e92f11fbac4d36867562b0616dd8fad565e | je-castelan/Algorithms_Python | /Python_50_questions/10 LinkedList/merge_sorted_list.py | 1,009 | 4.1875 | 4 | """
Merge two sorted linked lists and return it as a new sorted list.
The new list should be made by splicing together the nodes of the first two lists.
"""
from single_list import Node
def mergeTwoLists(l1, l2):
newList = Node(0,None)
pos = newList
while (l1 and l2):
if l1.value < l2.value:
pos.next = l1
pos = pos.next
l1 = l1.next
else:
pos.next = l2
pos = pos.next
l2 = l2.next
while l1:
pos.next = l1
pos = pos.next
l1 = l1.next
while l2:
pos.next = l2
pos = pos.next
l2 = l2.next
return newList.next #Not neccesary to use first node with "0"
if __name__ == '__main__':
n = Node (7, None)
m = Node (5, n)
c = Node (4, m)
b = Node (3, c)
a = Node (1, b)
f = Node (6, None)
e = Node (4, f)
d = Node (2, e)
newlist = mergeTwoLists(a, d)
x= newlist
while x:
print(x.value)
x = x.next
| true |
42ea8bfbfab0cda471b19eb65d3981a235888341 | je-castelan/Algorithms_Python | /Python_50_questions/19 Tree Graphs/max_path_sum.py | 1,457 | 4.125 | 4 | """
A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.
The path sum of a path is the sum of the node's values in the path.
Given the root of a binary tree, return the maximum path sum of any path.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def __init__(self):
self.res = -float("inf")
def maxPathSum(self, root):
self._navigate(root)
return self.res
def _navigate(self, root):
if not root:
return 0
# The following recursion check the subpaths on left and right
left = self._navigate(root.left)
right = self._navigate(root.right)
#Maxside check only the node and the max side
maxside = max(root.val, max(left, right) + root.val)
# Then, it will check sumarizing the node and BOTH sides
maxtop = max(maxside, left + right + root.val)
#Having two sides, it check if it is the max path
self.res = max (self.res, maxtop)
# It will return only the max side (not top) in order to check
# upper on the tree
return maxside
| true |
6c8974807d165228b8465c8fbf0f469b7d6ac8c6 | dmoncada/python-playground | /stack.py | 1,359 | 4.1875 | 4 | class Stack:
'''A simple, generic stack data structure.'''
class StackNode:
def __init__(self, item, next_node):
self.item = item
self.next = next_node
class EmptyStackException(Exception):
pass
def __init__(self):
'''Initializes self.'''
self.top = None
self.count = 0
def __len__(self):
'''Returns len(self).'''
return self.count
def push(self, item):
'''push(item) -> None -- Pushes item to the top.'''
t = self.StackNode(item, self.top)
self.top = t
self.count += 1
def pop(self):
'''pop() -> item -- removes and returns the item at the top.
Raises EmptyStackException if the stack is empty.'''
if not self.top:
raise self.EmptyStackException('stack is empty')
item = self.top.item
self.top = self.top.next
self.count -= 1
return item
def peek(self):
'''peek() -> item -- returns (without removing) the item at the top.
Raises EmptyStackException if the stack is empty.'''
if not self.top:
raise self.EmptyStackException('stack is empty')
return self.top.item
def is_empty(self):
'''is_empty() -> boolean -- asserts if the stack is empty.'''
return not self.top
| true |
c122d2a776f88be7797cfbd7768db9be8e54e8a3 | murthyadivi/python-scripts | /Prime number check.py | 864 | 4.1875 | 4 | # returns the number input by user
def input_number(prompt):
return int(input(prompt))
# Checks if the given number is a primer or not
def check_prime(number):
#Default primes
if number == 1:
prime = False
elif number == 2:
prime = True
#Test for all all other numbers
else:
prime = True
for check_number in range(2, (number // 2)+1):
if number % check_number == 0:
prime = False
break
return prime
def display_prime(number):
prime = check_prime(number)
if prime:
check = ""
else:
check = "not "
print("The given number, ", number," is ", check, "prime.", sep = "", end = "\n\n")
while 1 == 1:
display_prime(input_number("Enter a number to check. Ctl-C to exit: "))
| true |
da4be3a59e10efd46c69195b9f9839561e9039de | TaoCurry/Basic_Python3 | /高阶函数/埃拉托色尼筛选法.py | 499 | 4.15625 | 4 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
def _is_odd():
n = 1
while True:
n = n + 2 #筛选出奇数
yield n
def _not_divisible(n): #筛选函数
return lambda x: x % n > 0
def primes():
yield 2
it = _is_odd() #初始序列,3开始的奇数
while True:
n = next(it) #返回序列的第一个数
yield n
it = filter(_not_divisible(n), it)
for n in primes():
if n < 1000:
print(n)
else:
break | false |
e2fdeb9dfe2706ee3eee86e871f49b4df3c8ae92 | yuanyuanzijin/Offer-in-Python | /排序算法/insertion_sort.py | 1,142 | 4.28125 | 4 | """
插入排序(Insertion Sort)
插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
算法描述
一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:
从第一个元素开始,该元素可以认为已经被排序;
取出下一个元素,在已经排序的元素序列中从后向前扫描;
如果该元素(已排序)大于新元素,将该元素移到下一位置;
重复步骤3,直到找到已排序的元素小于或者等于新元素的位置;
将新元素插入到该位置后;
重复步骤2~5。
"""
def insertion(array):
for i in range(1, len(array)):
c = array[i]
for j in range(i-1, -1, -1):
if c < array[j]:
array[j+1] = array[j]
if j == 0:
array[0] = c
else:
array[j+1] = c
continue
return array
a = [5, 4, 6, 5, 2, 3, 10, 9, 8, 6]
print(insertion(a))
| false |
eba206f339e529b0c09661825ef6b4d24a36808a | AlexHoang2012/hoangtheduong-python-D4E12 | /Session2/Homeworks/Homework2.py | 356 | 4.15625 | 4 | print("BMI calculation")
h = int(input("Please input your height (cm): "))
w = int(input("Please input your weight (kg): "))
BMI= w/(h*h/10000)
print("Your BMI is: ",BMI)
if(BMI<16):
print("Severely underweight")
elif(BMI<18.5):
print("underweight")
elif(BMI<25):
print("Normal")
elif(BMI<30):
print("Overweight")
else:
print("Obese")
| false |
3e8715e64fe0540e8b00d7c28567773c3a8b178c | Krishan00007/Python_practicals | /AI_ML_visulizations/ML_linear_regression.py | 1,873 | 4.15625 | 4 | import warnings
warnings.filterwarnings(action="ignore")
# Practical implementation of Linear Regression
# -----------------------------------------------
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
def get_data(filename):
dataframe = pd.read_csv(filename)
print( dataframe)
x_parameters = []
y_parameters = []
for single_square_feet, single_price in zip(dataframe['square_feet'], dataframe['price'] ):
x_parameters.append( [single_square_feet] )
y_parameters.append( single_price )
# once we got the data, return it to main program
return x_parameters, y_parameters
#sandeepsingla sandeepsingla11:16 AM
def linear_model_main(x_parameters, y_parameters, quest_value):
# create Linear Regression Object
regr = LinearRegression()
regr.fit(x_parameters, y_parameters)
predicted_ans = regr.predict([[quest_value]])
print("Output From Machine = ", predicted_ans)
predictions = {}
print("After Training via Sklearn : Model Parameters")
print("m= ", regr.coef_)
print("c= ", regr.intercept_)
plt.scatter(x_parameters, y_parameters, color="m", s=30, marker="o")
all_predicted_Y=regr.predict( x_parameters)
plt.scatter(x_parameters, all_predicted_Y, color="b", s=30, marker="o")
plt.plot(x_parameters, all_predicted_Y, color="g")
plt.scatter(quest_value, predicted_ans, color="r")
plt.show()
def startAIAlgorithm():
#Collect the training data from external CSV file
x, y = get_data('sample_data/LR_House_price.csv')
print("Formatted Training Data : ")
print("x = ", x)
print("y = ", y)
question_value = 700 #This is the question data
linear_model_main(x, y, question_value)
if __name__ == "__main__":
startAIAlgorithm() | true |
61c414f192b860ad7fd4f392ce611b22d58d0f98 | Krishan00007/Python_practicals | /practical_6(2).py | 2,141 | 4.28125 | 4 | """
Write a GUI-based program that allows the user to convert temperature values between degrees Fahrenheit
and degrees Celsius. The interface should have labeled entry fields for these two values. These components
should be arranged in a grid where the labels occupy the first row and the corresponding fields occupy the
second row. At start-up, the Fahrenheit field should contain 32.0, and the Celsius field should contain
0.0. The third row in the window contains two command buttons, labeled >>>> and <<<. When the user presses
the first button, the program should use the data in the Fahrenheit field to compute the Celsius value,
which should then be output to the Celsius field. The second button should perform the inverse function.
"""
#!/usr/bin/env python3
from tkinter import *
def convert_fahr():
words = fbtext.get()
ftemp = float(words)
celbox.delete(0, END)
celbox.insert(0, '%.2f' % (tocel(ftemp)))
return
def convert_cel():
words = cbtext.get()
ctemp = float(words)
fahrbox.delete(0, END)
fahrbox.insert(0, '%.2f' % (tofahr(ctemp)))
def tocel(fahr):
return (fahr-32) * 5.0 / 9.0
def tofahr(cel):
return cel * 9.0 / 5.0 + 32
Convertor = Tk()
Convertor.title('Temperature converter')
fahrlabel = Label(Convertor, text = 'Fahrenheit')
fahrlabel.grid(row = 0, column = 0, padx = 5, pady = 5, sticky = E)
cellabel = Label(Convertor, text = 'Celsius')
cellabel.grid(row = 1, column = 0, padx = 5, pady = 5, sticky = E)
fbtext = StringVar()
fbtext.set('')
fahrbox = Entry(Convertor, textvariable=fbtext)
fahrbox.grid(row = 0, column = 1, padx = 5, pady = 5)
cbtext = StringVar()
cbtext.set('')
celbox = Entry(Convertor, textvariable=cbtext)
celbox.grid(row = 1, column = 1, padx = 5, pady = 5)
fgobutton = Button(Convertor, text = 'convert_far to cel', command = convert_fahr)
fgobutton.grid(row = 3, column = 0, padx = 5, pady = 5, sticky = N+S+E+W)
cgobutton = Button(Convertor, text = 'convert_cel to far', command = convert_cel)
cgobutton.grid(row = 3, column = 2, padx = 5, pady = 5, sticky = N+S+E+W)
Convertor.mainloop()
| true |
d8c97706c79eaeff2111524b111e3a25753176b7 | Krishan00007/Python_practicals | /AI_ML_visulizations/value_fill.py | 1,035 | 4.34375 | 4 | # Filling a null values using interpolate() method
#using interpolate() functon to fill missing values using Linear method
import pandas as pd
# Creating the dataframe
df = pd.DataFrame(
{ "A": [12, 4, 5, None, 1],
"B": [None, 2, 54, 3, None],
"C": [20, 16, None, 3, 8],
"D": [14, 3, None, None, 6]
}
)
# Print the dataframe
print( df )
#Let’s interpolate the missing values using Linear method.
# Note that Linear method ignore the index and treat the values as equally spaced.
# To interpolate the missing values
#df2 = df.interpolate(method ='linear', limit_direction ='forward')
#print( df2 )
#As we can see the output, values in the first row could not get filled as the direction of filling
# of values is forward and there is no previous value which could have been used in interpolation.
df3 = df.interpolate(method ='linear', limit_direction ='backward')
print( df3 ) | true |
23c50555c6cf85b3157b30c463e390d4b374d50c | Krishan00007/Python_practicals | /practical_3(1).py | 2,229 | 4.78125 | 5 | """
A bit shift is a procedure whereby the bits in a bit string are moved to the left or to the right.
For example, we can shift the bits in the string 1011 two places to the left to produce the string 1110.
Note that the leftmost two bits are wrapped around to the right side of the string in this operation.
Define two scripts, shiftLeft.py and shiftRight.py, that expect a bit string as an input.
The script shiftLeft shifts the bits in its input one place to the left, wrapping the leftmost
bitto the rightmost position. The script shiftRight performs the inverse operation. Each script
prints the resulting string.
"""
val = int(input("Enter 1 for Leftshift , 2 for Rightshift:"))
if(val==1):
num=input("Enter the number you want to left shift: ")
n=input("enter number of digits you want to shift: ")
while True:
if not (num.isnumeric() and n.isnumeric()):
if not num.isnumeric():
num=input("Sorry!! Enter a correct number: ")
else:
n=input("Sorry!! Enter number of digits: ")
else:
num=int(num)
n=int(n)
binary=bin(num)
print("The binary equivalent of the number is: ",binary)
leftShift=num<<n
print("the binary equivalent of the resultant is: ",bin(leftShift))
print("and the dedial equivalent is: ",leftShift)
break
elif(val==2):
num=input("Enter the number you want to right shift: ")
n=input("enter number of digits you want to shift: ")
while True:
if not (num.isnumeric() and n.isnumeric()):
if not num.isnumeric():
num=input("Sorry!! Enter a correct number: ")
else:
n=input("Sorry!! Enter number of digits: ")
else:
num=int(num)
n=int(n)
binary=bin(num)
print("The binary equivalent of the number is: ",binary)
rightShift=num>>n
print("the binary equivalent of the resultant is: ",bin(rightShift))
print("and the dedial equivalent is: ",rightShift)
break
else :
print("Enter a valid value!") | true |
14c47f156cf416431864448d62d3f27918d5226b | PNai07/Python_1st_homework | /02_datatypes.py | 1,888 | 4.5625 | 5 | # Data Types
# Computers are stupid
#They doi not understand context, and we need to be specific with data types.
#Strings
# List of Characters bundled together in a specific order
#Using Index
print('hello')
print(type('hello'))
#Concatenation of Strings - joining of two strings
string_a = 'hello there'
name_person = 'Juan Pier'
print (string_a + ' ' + name_person)
#Useful methods
#Length
print (len(string_a))
print (len(name_person))
#Strip = Removes trailing white spaces
string_num = ' 90323 '
print(type(string_num))
print(string_num)
print(string_num.strip())
#.split - a method for strings
#It splits in a specific location and output a list (data type)
string_text = 'Hello I need to go to the loo'
split_string =string_text.split(' ')
print(split_string)
#Capturing User Input - capture and display user input
#user_input_first_name = input('What is your first name')
#print (user_input_first_name)
# get user input and print first and last name
# 1) get user input/ first name
# save user input to variable
first_name = input ('What is your first name')
# get user last name
# and save it to variable
last_name = input ('what is your last name?')
#user_input_last_name = input('What is your last name')
#print (user_input_last_name)
# join two and
# Let us use concactenation
# Let us use interpolation
# print
full_name = first_name +' ' +last_name
print (full_name)
#Let us use interpolation
welcome_message = f"Hi {full_name} you are very welcome!"
print(welcome_message)
# Count /lower/ upper/ capitalize
text_example = "Here is some text, with lot's of text"
#Count
print(text_example.count('e'))
print(text_example.count('text'))
#lower
print(text_example.lower())
#Upper
print(text_example.upper())
#Capitalize
print(text_example.capitalize())
print('PIZZAHUT'.strip().capitalize())
print('PizzaHut'.capitalize())
print('pizza hut'.capitalize())
| true |
9908be12de460b5cb7a690eae3b9030e8422e8a2 | PNai07/Python_1st_homework | /06_datatypes_booleans.py | 1,426 | 4.5625 | 5 | # Booleans
# Booleans are a data type that is either TRUE or FALSE
var_true = True
var_false = False
#Syntax is capital letter
print(type(var_true))
print(type(var_false))
# When we equate/ evaluate something we get a boolean as a response.
# Logical operator return boolean
# == / ! / <> / >= / <=
weather = 'Rainy'
print(weather =='Sunny')
print (weather== 'Rainy')
#Logical **AND** & ** OR **
# evaluate two sides, BOTH have to be true for it to return True
print ('<Testing logical and: ')
print(weather== 'Rainy') and (weather== 'Sunny')
print(True and False)
#True
print ('<Testing logical and: ')
print(weather== 'Rainy') and (weather== 'Rainy')
print(True and True)
#Logical OR - One of the side
# Some methods or functions can return booleans
potential_number = '10'
print('hey')
print(potential_number.isnumeric())
print(potential_number.isinteger())
print ('location in code!')
print (potential_number.isnumeric())
print ('Location in code 2')
text = 'Hello World'
print(text[0] =='H')
print(text.startswith('h'))
print(text.startswith('H'))
print ('Testing. endswith.(arg)')
print (text[-1]== '!') # Strings are list of characters. -1 represents the last index in said list
print(text.endswith('!'))
print(text.endswith('?'))
#Booleans and Numbere
print("printing bool values of numbers")
print (bool(13))
print (bool(-1))
print (bool(3.14))
print (bool(1+3j))
#Value of None
print (bool(None))
| true |
53e2fc8c6c8ba4b78ad525d40a369a082611cb30 | Parth731/Python-Tutorial | /Quiz/4_Quiz.py | 264 | 4.125 | 4 |
# break and continue satement use in one loop
while (True):
print("Enter Integer number")
num = int(input())
if num < 100:
print("Print try again\n")
continue
else:
print("congrautlation you input is 100\n")
break
| true |
9641bd85b9168ca13ea4e70c287dd703d3f7c19c | Parth731/Python-Tutorial | /Exercise/2_Faulty_Calculator.py | 920 | 4.1875 | 4 | #Exercise 2 - Faulty Calculator
# 45*3 = 555, 56+9 = 77 , 56/6 = 4
# Design a caluclator which will correctly solve all the problems except
# the following ones:
# Your program should take operator and the two numbers as input from the user and then return the result
print("+ Addition")
print("- Subtraction")
print("* Multiplication")
print("/ Division")
op = input("choose the option +, -, *, /")
print("Enter the number 1")
a = int(input())
print("Enter the number 2")
b = int(input())
if op == '+':
if a == 56 and b == 9:
print("77")
else:
print(a+b)
elif op == '-':
if a == 55 and b == 10:
print("60")
else:
print(a - b)
elif op == '*':
if a == 45 and b == 3:
print("555")
else:
print(a * b)
elif op == '/':
if a == 56 and b == 6:
print("4")
else:
print(a / b)
else:
print("Error ! please check your input")
| true |
0a5b0d751a1fcbfa086452b6076527668aa4fcbc | shrobinson/python-problems-and-solutions | /series (2,11).py | 365 | 4.28125 | 4 | #Given two integers A and B. Print all numbers from A to B inclusively, in ascending order, if A < B, or in descending order, if A ≥ B.
#Recommendation. Use for loops.
#For example, on input
#4
#2
#output must be
#4 3 2
A = int(input())
B = int(input())
if A < B:
for i in range(A, B+1):
print(i)
else:
for i in range(A, B-1,-1):
print(i)
print()
| true |
bb4b6083ef0eca3abca1627acfab5a77dd0bc485 | shrobinson/python-problems-and-solutions | /length_of_sequence (2,4).py | 394 | 4.1875 | 4 | #Given a sequence of non-negative integers, where each number is written in a separate line. Determine the length of the sequence, where the sequence ends when the integer is equal to 0. Print the length of the sequence (not counting the integer 0).
#For example, on input
#3
#2
#7
#0
#output should be
#3
n = int(input())
count = 0
while n > 0:
count += 1
n = int(input())
print(count)
| true |
608a587c0123d50950fb43f3321572f01a2450e2 | shrobinson/python-problems-and-solutions | /countries_and_cities (3,18).py | 855 | 4.28125 | 4 | #First line of the input is a number, which indicates how many pairs of words will follow (each pair in a separate line). The pairs are of the form COUNTRY CITY specifying in which country a city is located. The last line is the name of a city. Print the number of cities that are located in the same country as this city.
#Hint. Use dictionaries.
#For example, on input:
#6
#UK London
#US Boston
#UK Manchester
#UK Leeds
#US Dallas
#Russia Moscow
#Manchester
#output must be:
#3
city_dict = {}
dict_count = int(input())
while dict_count > 0:
user_input = input()
value, key = user_input.split(" ")
city_dict[key] = value
dict_count = dict_count - 1
key_input = input()
check_value = city_dict[key_input]
value_count = 0
my_list = list(city_dict.values())
for i in my_list:
if i == check_value:
value_count += 1
print(value_count)
| true |
28150f1848962980561507ee3bf9a41804f3e564 | shrobinson/python-problems-and-solutions | /leap_year (1,13).py | 508 | 4.15625 | 4 | #Given the year number. You need to check if this year is a leap year. If it is, print LEAP, otherwise print COMMON.
#The rules in Gregorian calendar are as follows:
#a year is a leap year if its number is exactly divisible by 4 and is not exactly divisible by 100
#a year is always a leap year if its number is exactly divisible by 400
#For example, on input
#2000
#output must be
#LEAP
year = int(input())
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("LEAP")
else:
print("COMMON")
| true |
40861b19351648b058fee1f74ff2ce0d236808ab | chiefmky/ArrayAndStringProblem | /StringCompression.py | 798 | 4.1875 | 4 | #Implement a method to perform basic string compression using count of repeated characters
#input:aabcccccaaa
#output:a2b1c5a3
def compression(astr):
# aabcccccaa
ch = astr[0]
count = 1
ans = ""
for i in range(1, len(astr)):
if ch == astr[i]:
count += 1
else:
ans += ch + str(count)
count = 1
ch = astr[i]
ans += ch + str(count)
return ans
def compression2(astr):
count = 0
siz = len(astr)
arr = []
for i in range(siz):
count += 1
if i + 1 >= siz or astr[i] != astr[i + 1]:
arr.append(astr[i])
arr.append(count)
count = 0
return "".join(str(ch) for ch in arr)
if __name__ == '__main__':
s = "aabcccccd"
print(compression2(s)) | false |
a7a8ba21ad69cd68dc8ab7d57faf2cd40681524f | Get2dacode/python_projects | /quickSort.py | 1,180 | 4.15625 | 4 |
def quicksort(arr,left,right):
if left < right:
#splitting our array
partition_pos = partition(arr,left,right)
quicksort(arr,left, partition_pos - 1)
quicksort(arr,partition_pos+1,right)
def partition(arr,left,right):
i = left
j = right -1
pivot = arr[right]
while i < j:
while i < right and arr[i] < pivot:
i += 1
while j > left and arr[j] >= pivot:
j -= 1
if i < j:
arr[i],arr[j] = arr[j],arr[i]
if arr[i] > pivot:
arr[i],arr[right] = arr[right],arr[i]
return i
def display(list):
print('Unsorted:')
print(list)
quicksort(list,0,len(list)-1)
print('sorted')
print(list)
def rando(num):
import random
empty = []
while len(empty) < num:
number_generator = random.randint(0,100)
empty.append(number_generator)
if len(empty) >= num:
print(display(empty))
#test
Knicks_roster = ['RJ Barrett','Alec Burks','Evan Fournier','Taj Gibson','Quentin Grimes','Rokas Jokubaitis','Kevin Knox II','Miles McBride','Nerlens Noel','Immanuel Quickley','Julius Randle','Mitchell Robinson','Derrick Rose','Aamir Simms','Jericho Sims','Obi Toppin','Luca Vildoza','Kemba Walker','MJ Walker']
#display(Knicks_roster)
rando(13)
| true |
e10519c39e2ee2eb03adf844eda3d6ea6c0ed891 | soumyaracherla/python-programs | /tenth.py | 662 | 4.28125 | 4 | fruits=['mango', 'apple', 'banana']
print(fruits)
print(fruits[2])
print(fruits[-2]) # list
print(fruits.index("apple"))
fruits.append('grapes')
print(fruits) # append operation
vegetables=['onion', 'carrot', 'beetroot', 'tomato']
fruits.extend(vegetables)
print(fruits) # extend operation
fruits.insert(2,'pineapple')
print(fruits) # insert operation
vegetables.remove('carrot')
print(vegetables) # remove operation
vegetables.pop(1)
print(vegetables) # pop operation
vowels=['a', 'e', 'i', 'o', 'u']
print(vowels)
print(vowels[ :3])
print(vowels[2:])
print(vowels.count('a')) #count operation
fruits.sort()
print(fruits) # sort method
| false |
7b145f2578ad8e7a8b78b3230f38631bdc1f76c7 | aadilkadiwal/Guess_game | /user_guess.py | 651 | 4.15625 | 4 | # Number guess by User
import random
def user_guess(number):
random_number = random.randint(1, number)
guess = 0
guess_count = 0
while guess != random_number:
guess = int(input(f'Guess the number between 1 and {number}: '))
guess_count += 1
if guess > random_number:
print('Sorry, guess again, Too High')
elif guess < random_number:
print('Sorry, guess again. Too Low')
print(f'Great Job! You guess {random_number} number in {guess_count} guesses. ')
print('Selecting a range of number from 1 to ....')
number = int(input('Enter a last number: '))
user_guess(number) | true |
b4f271e3a902188ce99905547ebcf43d52261f50 | niloy-biswas/OOP-Data-structure-Algorithm | /oop.py | 2,673 | 4.15625 | 4 | class Person:
def __init__(self, name: str, age: int, birth_year: int, gender=None):
self.name = name # Person has a name // has a relation with instance
self.__age = age
self.__birth_year = birth_year # Private variable / Data encapsulation
self.gender = gender
def get_name(self):
return self.name
def set_name(self, new_name):
if self.__has_any_number(new_name):
print("Sorry, Name can't have number")
return
self.name = new_name
def get_birth_year(self):
return self.__birth_year
def __has_any_number(self, string): # private method. It can't be callable by outside of this class
# If anyone directly access the value then we can't check the validity of
# that new data. So that we use method for accessing instance
return "0" in string
def get_summery(self):
return f"Name: {self.name}, Age: {self.__age}, BirthYear: {self.__birth_year}, Gender: {self.gender}"
person1 = Person("Niloy", 22, 1999)
person2 = Person("Akib", 24, 1997)
print(person1.name) # Access directly without function
print(person2.get_name()) # Access with function
person2.set_name("Akib Bin Khodar Khashi") # override the value of name using set
print(person2.get_summery())
person1.name = "Niloy Biswas" # Access variable directly / for stop is use private variable
print(person1.get_name())
person1.set_name("00NIloy")
print(person1.get_name())
person_list = [Person("Mahi", 23, 1998),
Person("Riaz", 23, 1998, "Male"),
Person("Moon", 50, 1970, "Male")]
for person in person_list:
if person.get_birth_year() >= 1990:
print(person.get_summery())
class Student(Person): # Inheritance / Person is the super class
# Student is a Person / is a relation between sub and supper class
def __init__(self, name: str, age: int, birth_year: int, student_id: str):
super().__init__(name, age, birth_year)
self.student_id = student_id
def get_summery(self):
return f"Name: {self.get_name()}, BirthYear: {self.get_birth_year()}, ID: {self.student_id}"
student1 = Student("Tomi", 25, 1995, "171-35-239")
print(student1.get_summery())
student1.set_name("Tanvir")
print(student1.get_summery())
class Teacher(Person): # Teacher is a Person
def __init__(self, name: str, age: int, birth_year: int, dept: str):
super().__init__(name, age, birth_year)
self.department = dept
all_person_list = [
Person("Niloy", 22, 1999),
Student("Taz", 26, 1994, "171-35-241"),
Teacher("BIkash", 30, 1990, "SWE")
]
for p in all_person_list:
print(p.get_summery())
| true |
2c758cd5b6825ae199112690ac55dc7e229f782d | ritopa08/Data-Structure | /array_rev.py | 867 | 4.375 | 4 | '''-----Arrays - DS: An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ).
Given an array, , of integers, print each element in reverse order as a single line of space-separated integers.------'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the reverseArray function below.
def reverseArray(a):
n=len(a)
return a[n::-1]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input())
arr = list(map(int, input().rstrip().split()))
res = reverseArray(arr)
fptr.write(' '.join(map(str, res)))
fptr.write('\n')
fptr.close()
| true |
a87621ac4cb9c506b514ee5c6f69796330c92237 | pratibashan/Day4_Assignments | /factorial.py | 261 | 4.25 | 4 |
#Finding a factorial of a given no.
user_number =int(input("Enter a number to find the factorial value: "))
factorial = 1
for index in range(1,(user_number+1)):
factorial *= index
print (f"The factorial value of a given number is {factorial}") | true |
6671ca404f704cf143d719c60f030eddf9a48b8d | vasudhanapa/Assignment-2 | /assignment 2.py | 750 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# 1. Write a program which accepts a sequence of comma-separated numbers from console and generate a list.
# 1. Create the below pattern using nested for loop in Python.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
#
# In[1]:
num1 = 1
num2 = 5
for i in range(0,2*num2):
if i<4:
print(('*'*num1))
num1 = num1 + 1
else:
print(('*'*num1))
num1 = num1 - 1
# 2. Write a Python program to reverse a word after accepting the input from the user. Sample Output:
# Input word: ineuron
# Output: norueni
#
# In[2]:
word = input("enter a word to reverse:")
for i in range(len(word)-1,-1,-1):
print(word[i],end = "")
# In[ ]:
| true |
9709680af1eeef88c1b8472142c5f85b9003114c | AmitAps/advance-python | /generators/generator7.py | 860 | 4.5 | 4 | """
Understanding the Python Yield Statement.
"""
def multi_yield():
yield_str = "This will print the first string"
yield yield_str
yield_str = "This will print the second string"
yield yield_str
multi_obj = iter(multi_yield())
while True:
try:
prt = next(multi_obj)
print(prt)
except StopIteration:
break
# print(next(multi_obj))
#
# print(next(multi_obj))
# print(next(multi_obj))
"""
Take a closer look at that last call to next(). You can see that execution has blown up with a
traceback. This is because generators, like all iterators, can be exhausted. Unless your
generator is infinite, you can iterate through it one time only. Once all values have been
evaluated, iteration will stop and the for loop will exit. If you used next(),
then instead you’ll get an explicit StopIteration exception.
"""
| true |
9f311f33adbc0a2fb31ffc1adb014bb66de0fb2b | AmitAps/advance-python | /oop/class2.py | 337 | 4.15625 | 4 | class Dog:
#class attribute
species = 'Canis familiaris'
def __init__(self, name, age):
self.name = name
self.age = age
"""
Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one
instance to another.
"""
| true |
42f8e41488f1de16d53ced9f76053374fe5ce4a3 | AmitAps/advance-python | /instance_class_and_static_method/fourth_class.py | 1,073 | 4.15625 | 4 | import math
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
def __repr__(self):
return (f'Pizza({self.radius!r}, '
f'{self.ingredients!r})')
def area(self):
return self.circle_area(self.radius)
@staticmethod
def circle_area(r):
return r ** 2 * math.pi
"""
Flagging a method as a static method is not just a hint that a method won’t modify class or instance state — this restriction is also enforced by the Python runtime.
Instance methods need a class instance and can access the instance through self.
Class methods don’t need a class instance. They can’t access the instance (self) but they have access to the class itself via cls.
Static methods don’t have access to cls or self. They work like regular functions but belong to the class’s namespace.
Static and class methods communicate and (to a certain degree) enforce developer intent about class design. This can have maintenance benefits.
"""
| true |
a4a9466ca29261aff4264cd4d2c565df7c19a0fa | AmitAps/advance-python | /dog-park-example.py | 703 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 09:25:55 2020
@author: aps
"""
class Dog:
species = "Canis familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
# Another instance method
def speak(self, sound):
return f"{self.name} says {sound}"
def __str__(self):
return f"{self.name} is {self.age} years old"
"""
Remember, to create a child class, you create new class with its own name and then put the name of the parent
class in parentheses.
"""
class JackRussellTerrier(Dog):
pass
class Dachshund(Dog):
pass
class Bulldog(Dog):
pass
| true |
c977f10079c4c36333dfc1b33635945b2e469c29 | Ayselin/python | /candy_store.py | 1,014 | 4.125 | 4 | candies = {
'gummy worms': 30,
'gum': 40,
'chocolate bars': 50,
'licorice': 60,
'lollipops': 20,
}
message = input("Enter the number of the option you want to check?: \n1. To check the stock. \n2. How many candies have you sold? \n3. Shipment of new stock.")
if message == '1':
for candy, amount in candies.items():
amount = int(amount)
print(f"{candy}: {amount}")
elif message == '2':
# for candy, amount in candies.items():
items = input("Please enter the product you want to check: ")
sold = input("How many candies have you sold?: ")
sold = int(sold)
candies[items] = candies[items] - sold
print(f"{candies[items]}")
elif message == '3':
# for candy, amount in candies.items():
product = input("Please enter the product you want to check: ")
received = input("How many items were delivered?: ")
received = int(received)
candies[product] = candies[product] + received
print(f"{candies[product]}")
| true |
1788d7fb0349eebc05ab37f91754b18e6ce66b3f | SeshaSusmitha/Data-Structures-and-Algorithms-in-Python | /SelectionSort/selection-sort.py | 423 | 4.3125 | 4 | def insertionSort(array1,length):
for i in range(0, length ):
min_pos = i;
for j in range(i+1, length):
if array1[j] < array1[min_pos]:
min_pos = j;
temp = array1[i];
array1[i] = array1[min_pos];
array1[min_pos] = temp;
array1 = [2, 7, 4, 1, 5, 3];
print "Array before Selection sort"
print(array1);
length = len(array1);
insertionSort(array1, length);
print "Array after Selection sort"
print(array1); | true |
4b414735cbd1563ac59a6598279f7a4863723828 | zaidITpro/PythonPrograms | /inseritonanddeletionlinklist.py | 1,106 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,data):
if(self.head==None):
self.head=Node(data)
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(data)
def insert_at_beg(self,data):
newnode=Node(data)
newnode.next=self.head
self.head=newnode
def delete_at_beg(self):
current=self.head
self.head=current.next
del current
def printlist(self):
current=self.head
while(current!=None):
print(current.data)
current=current.next
myLinkList=LinkedList()
myLinkList.insert(25)
myLinkList.insert(45)
myLinkList.insert(78)
print("\n\nCreated Linked List is: \n")
myLinkList.printlist()
print("\n\nEnter the element you want to insert at the beginning: ")
element=int(input())
myLinkList.insert_at_beg(element)
print("\n\nThe updated Linked List after insertion at beginning: \n")
myLinkList.printlist()
print("\n\nThe updated Linked List after deletion at beginning:\n")
myLinkList.delete_at_beg()
myLinkList.printlist() | true |
c239eddac5bd840e8c73c44e1da8e3c5e6e794ea | dxn19950918/dxn | /demo2.py | 542 | 4.125 | 4 | #循环语句:有规律切重复操作的语句
#列表
# a = [1,2,3,4]
# for i in a : # for 中的in不是判断
# print(i)
# #元组
# b = ("123",1,3,4)
# for i in b:
# print(i)
# #字符串变量
# c = "儿童节快乐"
# for i in c:
# print(i)
#字典
d = {"username":"张三","password":"123456"}
for i in d:
print(i) #i 第一次循环是username
#print(d[i]) #下标key值方式取值
print(d.get(i)) #get的方式取值
print("========")
#如果键值对不存在,get取空值,key值会报错 | false |
b5ddce8fc3ec17161f57cd3b0c51bc964105e383 | Raise-hui/Sorting-algorithm | /堆排序.py | 2,534 | 4.375 | 4 | '''
根据升序降序选取不同的堆,一般升序选取大根堆,降序选取小根堆。
1.先将无序的序列构建成一个堆,根据升序降序的需求选取大根还是小根堆。
2.将堆顶元素和末尾元素交换,这样最大的元素就会沉底
3.重新调整结构,使其满足堆的特性。继续交换堆顶和末尾元素,直到整个序列有序。
'''
# 每次在顶更新元素
def push_down(heap, size, u):
'''
:param heap: 堆
:param size: 堆的长度
:param u: 当前元素
:return:
'''
# t 存的是最大值的索引,即根节点和左右儿子之间的最大值。
# 这里默认heap 索引号从1开始
t, left, right = u, u * 2, u * 2 + 1
if left <= size and heap[t] < heap[left]:
t = left
if right <= size and heap[t] < heap[right]:
t = right
# 若if成立则说明根要和儿子换位置了
if t != u:
heap[u], heap[t] = heap[t], heap[u]
# 继续往下递归直到形成一个堆
push_down(heap, size, t)
return heap
# 每次在尾更新元素,每个元素和父节点比较大小
def push_up(heap, u):
# 如果父节点存在且父节点的值小于子节点的值,就交换位置
while (u // 2 and heap[u // 2] < heap[u]):
heap[u // 2], heap[u] = heap[u], heap[u // 2]
u //= 2
return heap
# 若每次在中间更新元素,两个函数都调用一下
# push_down()
# push_up()
# 插入一个元素的操作,插到最后一个元素
def insert(heap, size, x):
size += 1
heap[size] = x
push_up(heap, size, x)
# 删除堆顶元素的操作,然后自顶向下调整
def remove_top(heap, size):
heap[1] = heap[size]
size -= 1
push_down(heap, size, 1)
def heap_sort(nums, size):
# 构建堆自底向上
for i in range(1, size + 1):
nums = push_up(nums, i)
# 调整堆堆自顶向下,每次将堆顶的数和堆尾的数交换
for i in range(1, size + 1):
nums[1], nums[size] = nums[size], nums[1]
size -= 1
# 每改动一次堆都要重新调整一次
nums = push_down(nums, size, 1)
return nums[1:]
if __name__ == '__main__':
size = int(input('需要排序的个数:'))
# 数组索引是从零开始的,而堆的序号是从1开始的,故将数组设置成(size+1)维度.
nums = [0 for _ in range(size + 1)]
for i in range(1, size + 1):
nums[i] = int(input('输出数值:'))
res = heap_sort(nums, size)
print(res)
| false |
294e065c455c87506bc42384c7b95f5c55df9dc6 | petr-tik/lpthw | /ex40.py | 766 | 4.125 | 4 | """ classes in python:
class name_of_class(object):
def __init__(self):
self.tangerine = "And now a thousand years between"
def apple(self):
print "I am classy APPLES!"
by instantiating you create objects from classes
and you create a mini module, which you can assign to a variable,
so you can work with it
"""
class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song([ "Happy birthday to you",
"I don't want to get sued",
"So I'll stop here."])
bulls_on_parade = Song(["They rally around tha family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
print'--' * 10
bulls_on_parade.sing_me_a_song() | false |
e2c32f8e48cb84d2c52db49f4559746ac7a56eae | petr-tik/lpthw | /ex30.py | 779 | 4.15625 | 4 | #-*- coding=utf-8 -*-
people = 30
cars = 40
trucks = 15
if cars > people:
print "We should take the cars."
elif cars < people:
print "We should not take the cars."
else:
print "we cannot decide"
if trucks > cars:
print "That's too many trucks"
elif trucks < cars:
print "maybe we could take the trucks"
else:
print "we still cannot decide"
if people > trucks and cars == trucks:
print "people can choose between cars or trucks"
else:
print "there are either more trucks than people or the number of cars doesn't equal the number of trucks"
# if, elif (maybe multiple) and else assess which block of code should be run
# the elif statement with TRUE boolean value executes the block below it
lines = [raw_input("line %d: " % i) for i in range (1,5)]
print lines | true |
92fee0692d9bfd860c4235c13ca639065c0bb7ee | petr-tik/lpthw | /ex4.py | 1,281 | 4.25 | 4 | # assign the variable 'cars' a value of 100
cars = 100
# assign the variable 'space_in_a_car' a floating point value of 4.0
space_in_a_car = 4
# assign the variable 'drivers' a value of 30
drivers = 30
# assign the variable 'passengers' a value of 90
passengers = 90
# assign the variable 'cars_not_driven' a value equaling the difference between the number of cars and drivers
cars_not_driven = cars - drivers
# the variable cars_driven is equal to the number of drivers
cars_driven = drivers
# the variable for carpool capacity is calculated as the product of cars driven and space in a car
carpool_capacity = cars_driven * space_in_a_car
# the variable for average passengers per car is the result of division of the number of passengers by the number of cars driven
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available"
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
# = assigns a value to a variable
# == checks if two values/variables are equal
# x = 100 is better than
# x=100
| true |
7e4d07ccaffd2671193f8d011a8c209e15a02552 | plooney81/python-functions | /madlib_function.py | 887 | 4.46875 | 4 | # create a function that accepts two arguments: a name and a subject
# the function should return a string with the name and subject inerpolated in
# the function should have default arguments in case the user has ommitted inputs
# define our function with default arguments of Pete and computer science for name and subject respectively
def madlib(name="Pete", subject="computer science"):
return f'{name}\'s favorite subject is {subject}'
# prompt the user for name and subject
print('\nPlease input your name')
user_name = input('> ')
print('\nPlease input your favorite subject')
user_subject = input('> ')
# call the madlib function with the two user inputs as the parameters, then we save
# the return of that function into a new variable named string output, which we will then print below
string_output = madlib(user_name, user_subject)
print(f'\n\n{string_output}\n\n')
| true |
b41ce62b8a50afdc1fb0fecb58bfe7de4c59d9cd | psukalka/morning_blues | /random_prob/spiral_matrix.py | 2,073 | 4.4375 | 4 | """
Date: 27/06/19
Program to fill (and optionally print) a matrix with numbers from 1 to n^2 in spiral form.
Time taken: 24min
Time complexity: O(n^2)
*) Matrix formed with [[0]*n]*n will result in n copies of same list. Fill matrix elements individually instead.
"""
from utils.matrix import print_matrix
def fill_spiral(n):
'''
There are total four directions. Left to right (LR), Top to Bottom (TB), Right to left (RL) or Bottom to Top (BT).
To fill a spiral matrix, we need to change directions at either boundary of the matrix or if the element is already filled.
:param n: width of the box
'''
direction = "LR"
start_x = 0
start_y = -1
count = 1
matrix = []
for i in range(0, n):
row = []
for j in range(0, n):
row.insert(j, 0)
matrix.insert(i, row)
while count <= n * n:
if direction == "LR":
i = start_x
for j in range(start_y + 1, n):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_y = j
direction = "TB"
if direction == "RL":
i = start_x
for j in range(start_y - 1, -1, -1):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_y = j
direction = "BT"
if direction == "TB":
j = start_y
for i in range(start_x + 1, n):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_x = i
direction = "RL"
if direction == "BT":
j = start_y
for i in range(start_x - 1, -1, -1):
if matrix[i][j] != 0:
break
matrix[i][j] = count
count += 1
start_x = i
direction = "LR"
return matrix
matrix = fill_spiral(4)
print_matrix(matrix)
| true |
26a29fa5956b9ef81041c2d0496c26fd4eb0ad08 | psukalka/morning_blues | /random_prob/matrix_transpose.py | 1,037 | 4.4375 | 4 | """
Given a matrix, rotate it right by 90 degrees in-place (ie with O(1) extra space)
Date: 28/06/19
Time Complexity: O(n^2)
Time taken: 30 min
"""
from utils.matrix import create_seq_matrix, print_matrix
def transpose_matrix(mat):
"""
Rotate a matrix by 90 degrees to right.
Ex:
Original:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Rotated:
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4
:param mat: Matrix to be rotated
:return: transpose of matrix
"""
rows = len(mat)
for col in range(0, int(rows / 2)):
for i in range(col, rows - col - 1):
temp = mat[rows - i - 1][col]
mat[rows - i - 1][col] = mat[rows - col - 1][rows - i - 1]
mat[rows - col - 1][rows - i - 1] = mat[i][rows - col - 1]
mat[i][rows - col - 1] = mat[col][i]
mat[col][i] = temp
return mat
matrix = create_seq_matrix(4)
print_matrix(matrix)
matrix = transpose_matrix(matrix)
print_matrix(matrix)
| true |
34c5432be9c10152035e994aa7aed5bcc09c28ef | SawonBhattacharya/Python | /dictionary.py | 400 | 4.3125 | 4 | #consists of elements in key value pair form
car={"Name": "Ravi", "USN": 102 ,"address": "xcf"}
print(car)
print(car["USN"])
print(car.get("USN"))
#updating value
car["USN"]=103
print(car)
for x in car.values():
print(x)
for x in car:
print(x)
for x in car.items():
print(x)
for x,y in car.items():
print(x,y)
print(len(car))
car["Age"]=23
print(car)
| false |
54053e477ab116aa59c4a4e52bb3744d28fe56b8 | storans/as91896-virtual-pet-ajvl2002 | /exercise_pet.py | 2,167 | 4.25 | 4 | # checks if the number entered is between 1-5 or 1,3 or whatever has been stated
# check int function
def check_int(question, error, low, high):
valid = False
# while loop
while valid == False:
number = input("{}".format(question))
try:
number = int(number)
if low <= number <= high:
return number
else:
print(error)
except ValueError:
print(error)
# puts stars or exclamation points around words if the formatter is used
def formatter(character, output):
print(character * (len(output) + 4))
print("{} {} {}".format(character, output, character))
print(character * (len(output) + 4))
# show items function
def show_items(dictionary_name):
number = 1
for item in dictionary_name:
print("{}. {}".format(number, item.title()))
number += 1
# choose item function
def choose_item(list_name):
choice = check_int("Please choose an option from the following forms of exercise:", "Please choose a number between 1 and 3.", 1, 3)
choice = choice - 1
chosen_item = list_name[choice][1]
return chosen_item
# weight
# calculates the pets weight function
def weight_calc(current_weight, choice, list_name):
total_weight = current_weight - choice
return total_weight
# Main Routine
start_weight = 1.5
EXERCISE_DICTIONARY = {"hop": 0.2, "run": 0.3, "walk": 0.1}
EXERCISE_LIST = [["hop", 0.2], ["run", 0.3], ["walk", 0.1]]
# main_menu
formatter("*", "Virtual pet")
print()
print("Main menu:")
print("1. Check your virtual pet's weight\n"
"2. feed your virtual pet\n"
"3. Exercise your virtual pet\n"
"4. Help\n"
"5. Exit virtual pet\n")
# checks if the number entered is between 1-5
menu_choice = check_int("Please enter the number of the option you wish to do:", "Please choose a number between 1 and 5.", 1, 5)
print()
# if menu choice equals 3 do this...
if menu_choice == 3:
show_items(EXERCISE_DICTIONARY)
exercise = choose_item(EXERCISE_LIST)
weight = weight_calc(start_weight, exercise, EXERCISE_LIST)
print("Your pet weighs {}kgs".format(weight))
| true |
0dba230b503ad68b4fa1c6185a947637633ba7a6 | SimonLundell/Udacity | /Intro to Self-Driving Cars/Bayes rule/numpy_examples.py | 638 | 4.375 | 4 | # but how would you print COLUMN 0? In numpy, this is easy
import numpy as np
np_grid = np.array([
[0, 1, 5],
[1, 2, 6],
[2, 3, 7],
[3, 4, 8]
])
# The ':' usually means "*all values*
print(np_grid[:,0])
# What if you wanted to change the shape of the array?
# For example, we can turn the 2D grid from above into a 1D array
# Here, the -1 means automatically fit all values into this 1D shape
np_1D = np.reshape(np_grid, (1, -1))
print(np_1D)
# We can also create a 2D array of zeros or ones
# which is useful for car world creation and analysis
# Create a 5x4 array
zero_grid = np.zeros((5, 4))
print(zero_grid)
| true |
2c55e90b57860b41171344fcc2d3d1a7e69968b1 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /NumberRelated/DivisbleBy3And5.py | 522 | 4.3125 | 4 | # Divisible by 3 and 5
# The problem
# For a given number, find all the numbers smaller than the number.
# Numbers should be divisible by 3 and also by 5.
try:
num = int(input("Enter a number : "))
counter = 0
for i in range(num):
if i % 15 == 0:
print(f"{i} is divisible by 3 and 5.")
counter += 1
print(f"There are {counter} numbers between 0 and {num}(not inclusive) "
f"that are divisible by 3 and 5")
except ValueError:
print("Input must be an integer")
| true |
66af1aa9f857197a90b5a52d0d7e83a5a56f1d35 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /Reverse/ReverseNumber.py | 376 | 4.3125 | 4 | # Reverse a number
# The problem
# Reverse a number.
def reverse_number(num: int) -> int:
reverse_num = 0
while num > 0:
reverse_num = reverse_num * 10 + num % 10
num //= 10
return reverse_num
try:
n = int(input("Enter a number : "))
print(f"Reverse of {n} is {reverse_number(n)}")
except ValueError:
print("Input must be a number")
| true |
4a31afea4a442fef55f57d261d0f93298e056efd | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /PrimeNumber/AllPrimes.py | 530 | 4.1875 | 4 | # All Prime Numbers
# the problem
# Ask the user to enter a number. Then find all the primes up to that number.
try:
n, p = int(input("Enter a number : ")), 2
all_primes = [False, False]
all_primes.extend([True] * (n - 1))
while p ** 2 <= n:
if all_primes[p]:
for i in range(p * 2, n + 1, p):
all_primes[i] = False
p += 1
all_primes = [i for i in range(len(all_primes)) if all_primes[i]]
print(all_primes)
except ValueError:
print("Input must be a number")
| true |
e2f84b0a47c1b9c39d804cd95e53820c1e99c47e | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /EasyOnes/TemporaryVariables.py | 745 | 4.5 | 4 | # Swap two variables
# The problem
# Swap two variables.
#
# To swap two variables: the value of the first variable will become the value of the second variable.
# On the other hand, the value of the second variable will become the value of the first variable.
#
# Hints
# To swap two variables, you can use a temp variable.
var1 = input("Enter variable 1 : ")
var2 = input("Enter variable 2 : ")
# without using temporary variables
print(f"Before swapping : A = {var1}, B = {var2}")
var1, var2 = var2, var1
print(f"After swapping <py way> : A = {var1}, B = {var2}")
var1, var2 = var2, var1
print(f"Before swapping : A = {var1}, B = {var2}")
temp = var1
var1 = var2
var2 = temp
print(f"After swapping <temp variable> : A = {var1}, B = {var2}")
| true |
bc0cdadda198a60507364154b43e3a9088605e08 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /LoopRelated/SecondSmallest.py | 848 | 4.25 | 4 | # Second smallest element
# The problem
# For a list, find the second smallest element in the list
try:
size = int(input("Enter the size of the array : "))
user_list = []
unique_ordered = []
if size <= 0:
raise ValueError("Size of array must be a non-zero positive integer")
if size > 1:
for _ in range(size):
user_list.append(float(input("Enter the number : ")))
unique_ordered = sorted(list(set(user_list)))
smallest = unique_ordered[0]
second_smallest = unique_ordered[1]
else:
smallest = unique_ordered[0]
second_smallest = unique_ordered[0]
print("User list : ", str(user_list))
print(f"The smallest number : {smallest}")
print(f"The second smallest number : {second_smallest}")
except ValueError:
print("List items must be numbers")
| true |
0bf8f3f1388fc54ef3956e91899841438aca7482 | kanuos/solving-https-github.com-ProgrammingHero1-100-plus-python-coding-problems-with-solutions | /PrimeNumber/SmallestPrimeFactor.py | 770 | 4.1875 | 4 | # Smallest prime factor [premium]
# The problem
# Find the smallest prime factor for the given number.
def is_prime(number):
number = abs(number)
if number == 0 or number == 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
def all_factors(number):
number = abs(number)
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors
try:
n = int(input("Enter a number : "))
print(f"The factors of {n} are : {all_factors(n)}")
prime_factors = [x for x in all_factors(n) if is_prime(x)]
print(f"The prime factors of {n} are : {prime_factors}")
except ValueError:
print("Input must be a number")
| true |
6fef789f70be17b87b1d40a9116dd018b0da6274 | code-v1/list_exercise | /exercise_one.py | 309 | 4.40625 | 4 | #Create list named 'students'
#print out second and last student name
students = {
'student1':'berry',
'student2':'pickle',
'student3':'wilder',
'student4':'benny',
'student5':'doddy'
}
print ('Second student:', students.get('student2'))
print ('Last student', students.get('student5')) | false |
7bcb73db98b3c593be479799b1c548e8d83bbfed | ParkerCS/ch18-19-exceptions-and-recursions-elizafischer | /recursion_problem_set.py | 2,681 | 4.125 | 4 | '''
- Personal investment
Create a single recursive function (or more if you wish), which can answer the first three questions below. For each question, make an appropriate call to the function. (5pts each)
'''
#1. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY, so MPR is APR/12). Assuming you make no payments for 6 months, what is your new balance? Solve recursively.
money = 10000
apr = 20
monthly_apr = apr/12
#print(monthly_apr)
def one(money, month):
apr = 0.20
monthly_apr = apr / 12
money += money * monthly_apr
if month < 7:
one(money, month + 1)
if month == 6:
money = round(money,2)
print("You have $" + str(money), "after 6 months.")
print("\nProblem #1")
one(money, 1)
print()
#2. You have $5000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). You make the minimum payment of $100 per month for 36 months. What is your new balance? Solve recursively.
def two(money, month):
monthly_apr = 0.20 / 12
money += money * monthly_apr
money -= 100
#if month < month + 1
if month < 37:
two(money, month +1)
if month == 36:
money = round(money,2)
print("You have $" + str(money), "after 36 months of paying the minimum of $100 a month.")
print("Problem #2")
two(5000, 36)
print()
#3. You have $10000 on a high interest credit card with an APR of 20.0% (calculated MONTHLY). If you make the minimum payment of $100 per month, how many months will it take to pay it off? Solve recursively.
def three(money, month, done):
monthly_apr = 0.20 / 12
money += money * monthly_apr
money -= 100
money = round(money, 2)
print(money)
if month < 100 and not done:
three(money, month +1, False)
if money <= 0:
done = True
print("Your debt was paid off after" , month, "month(s).")
print("Promblem #3 doesn't work because you will never pay off your debt:")
three(10000, 1, False)
print()
#4 Pyramid of Cubes - (10pts) If you stack boxes in a pyramid, the top row would have 1 box, the second row would have two, the third row would have 3 and so on. Make a recursive function which calculates the TOTAL NUMBER OF BOXES for a pyramid of boxes n high. For instance, a pyramid that is 3 high would have a total of 6 boxes. A pyramid 4 high would have 10.
def four(n_height, boxes, index):
boxes += n_height
if n_height != 0:
four(n_height - 1, boxes, index + 1)
elif n_height == 0:
print("There would be", boxes, "boxes for that number of rows")
n_height = int(input("Enter a number of rows (height): "))
four(n_height, 0, 0) | true |
41b46b0cbd0b3b8e5a8be106469a82bcfa096b60 | koakekuna/pyp-w1-gw-language-detector | /language_detector/main.py | 933 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""This is the entry point of the program."""
from languages import LANGUAGES
def detect_language(text, languages=LANGUAGES):
"""Returns the detected language of given text."""
# create dictionary to store counters of words in a language
# example --> counters = {"spanish": 29, "german": 3, "english": 0}
counters = {}
for language in LANGUAGES:
counters[language["name"]] = 0
# iterate through each word in text,
# compare to common words in each dictionary
# if it matches, then add +1 to the counter for the language
for word in text.split():
for language in LANGUAGES:
name = language['name']
commonwords = language['common_words']
if word in commonwords:
counters[name] += 1
# return the highest value of all keys in the counter dictionary
return max(counters, key=counters.get) | true |
d9ed893d4df5e5a5fb5819868aab00fc5feaa18e | databoy/processing.py-book | /chapter-08-dictionaries_and_json/dictionaries/dictionaries.pyde | 1,438 | 4.25 | 4 | student = ['Sam', 24]
student = {'name': 'Sam', 'age': 24}
# accessing dictionaries
print(student['age']) # displays: 24
print(student['name']) # displays: Sam
print(student) # {'name': 'Sam', 'age': 24}
if 'age' in student:
print(student['age'])
# modifying dictionaries
student['age'] = 25
print(student) # {'name': 'Sam', 'age': 25}
student['id'] = 19950501
print(student) # {'name': 'Sam', 'id': 19950501, 'age': 25}
del student['age']
print(student) # {'name': 'Sam', 'id': 19950501}
# nesting dictionaries and lists
students = {
'names': ['Sam', 'Lee'],
'ids': [19950501, 19991114]
}
print(students['names'][1]) # Lee
students = [
{'name': 'Sam', 'id': 19950501},
{'name': 'Lee', 'id': 19991114}
]
print(students[1]['name']) # Lee
# combining loops and dictionaries
courses = {
'game development': 'Prof. Smith',
'web design': 'Prof. Ncube',
'code art': 'Prof. Sato'
}
# iterating keys
#for course in courses:
for course in sorted(courses):
print(course)
print(sorted(courses.keys())) # ['code art', 'game development', 'web design']
# iterating values
for prof in courses.values():
print(prof)
# iterating items
print(courses.items())
for kv in courses.items():
print(kv)
#for course, prof in sorted(courses.items()):
for course, prof in reversed(sorted(courses.items())):
print('{} coordinates the {} course.'.format(prof, course))
| false |
f70add96e7e82cf95f9f6a8df4f00a25b2a8f17d | ankity09/learn | /Python_The_Hard_Way_Codes/ex32.py | 596 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 8 18:40:47 2019
@author: ankityadav
"""
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters' ]
for number in the_count:
print("This is count {}".format(number))
for fruit in fruits:
print("A fruit of type: {}".format)
for i in change:
print("I got {}".format(i))
elements = []
for i in range(0, 6):
print("Adding {} to the list.".format(i))
elements.append(i)
for i in elements:
print("Element was: {}".format(i))
| true |
eba680e70f99c565a0b95c2d230061034bf24291 | tdominic1186/Python_Crash_Course | /Ch_3_Lists/seeing_the_world_3-5.py | 833 | 4.40625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 20:56:36 2018
@author: Tony_MBP
"""
places = ['new zealand', 'canada', 'uk', 'australia', 'japan']
print(places)
#use sorted to to print list alphabetically w/o modifying list
print(sorted(places))
#show list is still in same original order
print(places)
#use sorted to print list in reverse alpha w/o modifying list
print(sorted(places, reverse = True))
#show list is still in same order
print(places)
#use reverse to to change order of list and print
places.reverse()
print(places)
#use reverse to change order back
places.reverse()
print(places)
#use sort to change list to alpha and print to show changed order
places.sort()
print(places)
#use sort to change list to reverse alpha and print to show changed order
places.sort(reverse = True)
print(places) | true |
7e9f1fe1a143bd90aea5e8478c703ec8bc980a59 | tdominic1186/Python_Crash_Course | /Ch_9_Classes/number_served.py | 2,193 | 4.5 | 4 | '''
Start with your program from Exercise 9-1 (page 166).
Add an attribute called number_served with a default value of 0. x
Create an instance called restaurant from this class. x
Print the number of customers the restaurant has served, and then change this value and print it again. x
Add a method called set_number_served() that lets you set the number of customers that have been served. Call this method with a new number and print the value again. x
Add a method called increment_number_served() that lets you increment
the number of customers who’ve been served. Call this method with any number you like that could represent how many customers were served in, say, a day of business. x
p171
'''
class Restaurant():
"""A simple model for a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and cuisine type attributes"""
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
"""Describes the restaurant's name and cuisine type."""
print("\nThe restaurant's name is " + self.restaurant_name.title() + " and the cuisine type is " + self.cuisine_type.title() + ".")
def open_restaurant(self):
"""Inidcates if the restaurant is open."""
print(self.restaurant_name.title() + " is open!")
def set_number_served(self, customer_number):
"""Set number of customers that have been served."""
self.number_served = customer_number
def increment_number_served(self, additional_customers):
"""Add the given amount of customers to the Number Served"""
self.number_served += additional_customers
restaurant = Restaurant("the cheesesteak house", "american")
restaurant.describe_restaurant()
restaurant.open_restaurant()
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.number_served = 25
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.set_number_served(30)
print("\nNumber Served: " + str(restaurant.number_served))
restaurant.increment_number_served(55)
print("\nNumber Served: " + str(restaurant.number_served))
| true |
fe45487f19bd0c0e402cd04b572741b9087d54ab | tdominic1186/Python_Crash_Course | /Ch_9_Classes/login_attempts.py | 2,013 | 4.125 | 4 | """
9-5. Login Attempts:
Add an attribute called login_attempts to your User class from Exercise 9-3 (page 166). x
Write a method called increment_login_attempts() that increments the value of login_attempts by 1. x
Write another method called reset_login_attempts() that resets the value of login_attempts to 0.x
Make an instance of the User class and call increment_login_attempts()
several times. x
Print the value of login_attempts to make sure it was incremented properly, and then call reset_login_attempts(). x
Print login_attempts again to make sure it was reset to 0.x
p171
"""
class User():
def __init__(self, first_name, last_name, age, favorite_color, favorite_band):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.favorite_color = favorite_color
self.favorite_band = favorite_band
self.login_attempts = 0
def describe_user(self):
"""Describes user's attributes."""
print(self.first_name.title() + " " + self.last_name.title() + "'s age is " + str(self.age) + ". Their favorite color is " + self.favorite_color + " and their favorite band is " + self.favorite_band.title() + ".")
def greet_user(self):
"""Greets user by formatted first and last name."""
print("Hello, " + self.first_name.title() + " " + self.last_name.title() + "!")
def increment_login_attempts(self):
"""Increments login_attempts from the user by 1"""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets the value of login_attempts to 0."""
self.login_attempts = 0
jc = User("jessica", "colliver", 29, "purple", "nsync")
jc.increment_login_attempts()
jc.increment_login_attempts()
jc.increment_login_attempts()
jc.increment_login_attempts()
print("\nThe number of times user has attempted to log in: " + str(jc.login_attempts))
jc.reset_login_attempts()
print("\nThe number of times user has attempted to log in: " + str(jc.login_attempts)) | true |
153b1a2153121b5d00b452484b9f88d344b73ed6 | tdominic1186/Python_Crash_Course | /Ch_8_Functions/unchanged_magicians_8-11.py | 1,514 | 4.53125 | 5 | """
5/21/18
8-11. Unchanged Magicians: Start with your work from Exercise 8-10. Call the
function make_great() with a copy of the list of magicians’ names. Because the
original list will be unchanged, return the new list and store it in a separate list.
Call show_magicians() with each list to show that you have one list of the original
names and one list with 'the Great' added to each magician’s name.
p150
"""
def show_magicians(magician_names):
"""
Prints the formatted names of a list of magicians
"""
while magician_names:
for magician_name in magician_names:
magician_name = magician_names.pop()
print(magician_name.title())
def copy_list(magician_names):
"""
Makes a copy of list 'magician_names'
"""
clone = magician_names[:]
return clone
def make_great(magician_names):
"""
Creates a new list to hold each magician that has been made 'great'
Appends 'the Great' to each magician's name
Returns the modified names to the 'magician_names' list
"""
# great_names = []
while magician_names:
name = magician_names.pop()
great_name = name + ' the Great'
great_names.append(great_name)
# for great_name in great_names:
# magician_names.append(great_name)
# return magician_names
magician_names = ['houdini', 'david copperfield', 'david blaine']
great_names = copy_list(magician_names)
#make_great(great_names)
print(magician_names)
print(great_names)
| true |
d7d65a0c5695274842767e20e5a337db4640d113 | tdominic1186/Python_Crash_Course | /Ch_5_if_Statements/stages_of_life_5-6.py | 522 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 18 11:58:03 2018
5-6 Stages of life - Write an if-elif-else chain that determines a person's
stage of life.
@author: Tony_MBP
"""
age = 65
if age < 2:
print("You're a baby.")
elif age >= 2 and age < 4:
print("You're a toddler.")
elif age >= 4 and age < 13:
print("You're a kid.")
elif age >= 13 and age < 20:
print("You're a teenager.")
elif age >= 20 and age < 65:
print("You're an adult.")
else:
print("You're an elder.")
| true |
cbc38a58be400e83c18324be9acba86971729545 | vladn90/Data_Structures | /heaps/heap_sort_naive.py | 797 | 4.15625 | 4 | """ Naive implementation of heap sort algorithm using Min Heap data structure.
"""
import random
from min_heap_class import MinHeap
def heap_sort_naive(array):
""" Sorts an array in non-descending order using heap. Doesn't return anything.
Time complexity: O(n * lg(n)). Space complexity: O(n), n is len(array).
"""
heap = MinHeap()
for element in array: # put all array elements into heap
heap.insert(element)
for i in range(len(array)): # extract min element from the heap, update array
array[i] = heap.pop_min()
if __name__ == "__main__":
array = [random.randrange(-10, 10) for i in range(10)]
print(f"original array: {array}")
heap_sort_naive(array)
assert array == sorted(array) # self-check
print(f"sorted array: {array}")
| true |
7c1249777a1cdf09f1da6fb492cc70e85d092ac0 | AnjanaPradeepcs/guessmyno-game | /guessmyno.py | 541 | 4.28125 | 4 | import random
number=random.randrange(1,10)
guess=int(input("guess a number between 1 and 10))
while guess!= number:
if guess>number:
print("guess a lesser number.Try again")
guess=int(input("guess a number between 1 and 10))
else:
print("guess a higher number.Try again")
guess=int(input("guess a number between 1 and 10))
print("your guess is correct and You won the game") | true |
8aee1e37b8d65fb372d200a9fd173abc719d6443 | gloriasalas/GWC-Summer-Immersion-Program | /TextAdventure.py | 1,549 | 4.1875 | 4 | start = '''You wake up one morning and find yourself in a big crisis.
Trouble has arised and your worst fears have come true. Zoom is out to destroy
the world for good. However, a castrophe has happened and now the love of
your life is in danger. Which do you decide to save today?'''
print(start)
done = False
print(" Type 'Flash to save the world' or 'Flash to save the love of his life' ")
user_input = input()
while not done:
if user_input == "world":
print (" Flash has to fight zoom to save the world. ")
done = True
print("Should Flash use lightening to attack Zoom or read his mind?")
user_input = input()
if user_input == "lightening":
print("Flash defeats Zoom and saves the world!")
done = True
elif user_input == "mind":
print("Flash might be able to defeat Zoom, but is still a disadvantage. ")
done = True
print("Flash is able to save the world.")
elif user_input == "love":
print ("In order to save the love of his life, Flash has to choose between two options. ")
done = True
print("Should Flash give up his power or his life in order to save the love of his life?")
user_input = input()
if user_input == "power":
print("The Flash's speed is gone. But he is given the love of his life back into his hands. ")
done = True
elif user_input == "life":
print("The Flash will die, but he sees that the love of his life is no longer in danger.")
done = True
print("No matter the circumstances, Flash is still alive. ") | true |
58578e34604e68fc5b8fd9315959316a62a94c21 | lward27/Python_Programs | /echo.py | 240 | 4.125 | 4 | #prec: someString is a string
#times is a integer
#postc:
#prints someString times times to the screen
#if times <=0, nothing prints.
def repeat(someString, times):
if times <= 0:
return
print someString
repeat(someString, times - 1)
| true |
f6c9d0c94a80bbaa9db1e9bedc041baf70c2f6fd | jjulch/cti110 | /P4HW3_NestedLoops_JeremyJulch.py | 356 | 4.3125 | 4 | # Making Nested Loops
# 10-17-2019
# CTI-110 PH4HW3-Nested Loops
# Jeremy Julch
#
# Making the first loop
for row in range(6):
print('#', end='', sep='')
# Making the nested loop to create the spaces between the #
for spaces in range(row):
print( ' ', end='', sep='')
# Making the second #
print('#', sep='')
| true |
e37676e882c196756d7af562c25b8fcb53643f0b | cliffjsgit/chapter-10 | /exercise108.py | 795 | 4.15625 | 4 | #!/usr/bin/env python3
__author__ = "Your Name"
###############################################################################
#
# Exercise 10.8
#
#
# Grading Guidelines:
# - Variable "answer" should be the answer to question 1: If there are 23
# students in your class, what are the chances that two of you have the
# same birthday?.
#
# This exercise pertains to the so-called Birthday Paradox, which you can read
# about at http://en.wikipedia.org/wiki/Birthday_paradox .
#
# 1. If there are 23 students in your class, what are the chances that two of you
# have the same birthday? You can estimate this probability by generating random
# samples of 23 birthdays and checking for matches.
#
# Hint: you can generate random birthdays with the randint function in the
# random module.
#
| true |
5dbe2a4b8ff9eb3db18c2031b4205362b7164b18 | babuhacker/python_toturial | /Variables/Variables.py | 769 | 4.15625 | 4 | # Global Variables
PI = 3.4
# print(PI)
# one = 1
# two = 2
# three = 3
one, two, three = 1, 2, 3
# print(one)
# print(two)
# print(three)
two = 4
# print(two)
# print(one)
Decimal = 1.1
# print(Decimal)
StringVar = "Hello" + "1"
# print(StringVar)
def FunctionName():
newVar = "World"
# print(newVar)
return
FunctionName()
# print(newVar)
# left = What you are giving value to
# right = What the Value is
Five = 5
# print(Five)
count = 0
print(count)
count = count + 1
print(count)
# or
count += 1
print(count)
count = count * 3
print(count)
# or
# count *= 3
# print(count)
#
# count = count / 3
# print(count)
# # or
# count /= 3
# print(count)
#
# count = count - 3
# print(count)
# # or
# count -= 3
# print(count)
count += 1
print(count)
| false |
26c421b5e6c299b69a7ff93badb3b01463acbe33 | Avenger-py/MiniProjects | /AreaOfPolygon.py | 1,338 | 4.125 | 4 | def polygon():
q=input("Are number of sides of polygon finite? (y/n): ")
s=float()
pi=3.141592
if q=="y":
a=int(input("Enter number of sides of polygon: "))
if a==0 or a==1 or a==2 or a>4:
print("Am i a joke to you?")
else:
if a==3:
print("Enter the sides: \n")
b=float(input("First side: "))
c=float(input("Second side: "))
d=float(input("Third side: "))
if b+c>d and c+d>b and b+d>c:
s=(b+c+d)/2
print("Area = {}".format((s*(s-b)*(s-c)*(s-d))**0.5))
else:
print("This triangle cannot exist")
if a==4:
print("Enter the sides: \n")
B=float(input("First side: "))
C=float(input("Second side: "))
D=float(input("Third side: "))
E=float(input("Fourth side: "))
if B==D and C==E:
print("Area = {}".format(B*D))
else:
print("Coming Soon!")
else:
print("Its a cicle LOL.\n")
r=float(input("Now enter the radius: "))
print("Area = {}".format(pi*(r**2)))
| false |
b06a2e53ae982a0d013b38968b99d0406aaaffc0 | MrSameerKhan/Machine_Learning | /practice/reverse_list.py | 1,288 | 4.40625 | 4 |
def reverse_a_list():
my_list = [1,2,3,566,6,7,8]
original_list = my_list.copy()
list_length = 0
for i in my_list:
list_length += 1
for i in range(int(list_length/2)):
main_value = my_list[i]
mirror_value = my_list[list_length-i-1]
my_list[i] = mirror_value
my_list[list_length-i-1] = main_value
print(f"Before reversing {original_list} After revesring {my_list}")
def remove_multiple():
# Python program to remove multiple
# elements from a list
# creating a list
list1 = [11, 5, 17, 18, 23, 50]
# Iterate each element in list
# and add them in variale total
for ele in list1:
if ele % 2 == 0:
list1.remove(ele)
# printing modified list
print("New list after removing all even numbers: ", list1)
def count_occurence():
# Python code to count the number of occurrences
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
# Driver Code
lst = [8, 6, 8, 10, 10, 8, 20, 10, 8, 8]
x = 8
print('{} has occurred {} times'.format(x, countX(lst, x)))
if __name__ == "__main__":
# reverse_a_list()
# remove_multiple()
count_occurence() | true |
2c6fb1c822384688dab0f4f14bce369c01a029fb | tretyakovr/Lesson-01 | /Task-04.py | 1,246 | 4.15625 | 4 | # Третьяков Роман Викторович
# Факультет Geek University Python-разработки
# Основы языка Python
# Урок 1
# Задание 4:
# Пользователь вводит целое положительное число. Найдите самую большую цифру в числе.
# Для решения используйте цикл while и арифметические операции.
# В теоретической части преподаватель проговорился про функцию max, применимую к строкам
# Отсюда решение задачи может быть таким:
# get_num = input('Введите целое положительное число: ')
# print(f'Самая большая цифра в числе {get_num} равна {max(get_num)}')
# Если следовать строго тексту задания, то...
number = int(input('Введите целое положительное число: '))
max_digit = 0
while number != 0:
digit = number % 10
if digit > max_digit:
max_digit = digit
number = number // 10
print(f'Самая большая цифра во введенном числе равна {max_digit}')
| false |
2a18cc8fd70105eee7c47def0f4c4b8d1202fd04 | weiiiiweiiii/AP-statistic-graphs | /Sources-For-Reference/Programs/Poisson.py | 1,155 | 4.4375 | 4 | # -*- coding: utf-8 -*-
from scipy.stats import poisson
import numpy as np
import matplotlib.pyplot as plt
import mpld3
#print "Welcome!"
#print "This is a program that can help you plot graphs for poisson distributions"
#Using poisson.pmf to create a list
#rate = raw_input("Please enter the rate(rate should be an integer), rate = " )
#o = raw_input("Please enter the maximum number of incidents(o should be an integer), o = ")
rate = int(5)
o = int(500)
n = np.arange(0,o+1)
y = poisson.pmf(n, rate)
#Plotting the poisson distribution for users
plt.plot(n,y, 'o-')
plt.title('Poisson: rate=%i' %(rate), fontsize = 20)
plt.xlabel('Number of incidents', fontsize = 15)
plt.ylabel('Probability of happenning', fontsize = 15)
poisim = poisson.rvs(rate, loc = 0, size = 1000)
print ("Mean: %g" % np.mean(poisim))
print ("SD: %g" % np.std(poisim, ddof=1))
#plt.figure()
plt.hist(poisim,bins = 9, normed = True)
plt.xlim(0,10)
plt.xlabel("Number of incidents")
plt.ylabel("density")
plt.show()
#fig = plt.figure(1, figsize=(9, 6))
#fig.savefig('Poisson.png', bbox_inches='tight')
fig = plt.figure(1, figsize=(9, 6))
print(mpld3.fig_to_html(fig))
| true |
3118d09cf3963b943a81b04a96e9729cece878f6 | ProfessorJas/Learn_Numpy | /ndarray_shape.py | 302 | 4.46875 | 4 | import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)
print()
# This resize the array
a = np.array([[1, 2, 3], [4, 5, 6]])
a.shape = (3, 2)
print(a)
print()
# Numpy also provides a reshape function to resize an array
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a.reshape(3, 2)
print(b) | true |
bbf33249764feef08abaade1f3a30dec14229b28 | KELETOR/health-insurance-costs | /Health care comps.py | 1,946 | 4.125 | 4 | # create the initial variables below
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# Add insurance estimate formula below
insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500
print(f"This Persons insurance cost is {insurance_cost} dolars\n")
# Age Factor
age += 4
new_insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500
print(f"This Persons insurance cost is {new_insurance_cost} dolars")
change_in_insurance_cost = new_insurance_cost - insurance_cost
print (f"The change in cost of insurance after increasing the age by 4 years is {change_in_insurance_cost} dollars\n")
# BMI Factor
age = 28
bmi += 3.1
new_insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500
print(f"This Persons insurance cost is {new_insurance_cost} dolars")
change_in_insurance_cost = new_insurance_cost - insurance_cost
print (f"The change in cost of insurance after increasing the BMI by 3.1 is {change_in_insurance_cost} dollars\n")
# Male vs. Female Factor
bmi = 26.2
sex = 1
new_insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500
print(f"This Persons insurance cost is {new_insurance_cost} dolars")
change_in_insurance_cost = new_insurance_cost - insurance_cost
print (f"The change in cost of insurance after changing sex to male is {change_in_insurance_cost} dollars\n")
# Extra Practice
sex = 0
smoker = 1
new_insurance_cost = (250 *age) - (128 * sex) + (370 *bmi) + (425 * num_of_children) + (24000 * smoker) - 12500
print(f"This Persons insurance cost is {new_insurance_cost} dolars")
change_in_insurance_cost = new_insurance_cost - insurance_cost
print (f"The change in cost of insurance after to a smoker is {change_in_insurance_cost} dollars\n")
| false |
4e3b1fbdfe12194e77d28b3dcebd47fae42e44c8 | dongheelee1/oop | /polymorphism.py | 592 | 4.4375 | 4 |
#Polymorphism:
#Example of Method Overriding
class Animal(object):
def __init__(self, name):
self.name = name
def talk(self):
pass
class Dog(Animal):
def talk(self):
print("Woof")
class Cat(Animal):
def talk(self):
print("Meow")
cat = Cat('KIT')
cat.talk()
dog = Dog('EDDY')
dog.talk()
#Example of method overloading
def add(typ, *args):
if typ == 'int':
result = 0
if typ == 'str':
result = ''
for i in args:
result += i
return result
add('int', 1, 2, 3)
add('str', 'i', 'love', 'python')
| true |
e1aa34deed827d162257d8f4c3bbe65c2bdc7d4e | xuyagang/pycon | /base/001_NameSpace.py | 1,148 | 4.28125 | 4 | # 1.若函数内部有和全局变量的同名变量被赋值,则函数内部的为局部变量,函数外的为全局变量
# 此时函数内和全局变量同名的局部变量一定要先赋值再调用,否则会报错,如例1所示
# (UnboundLocalError: local variable 'a' referenced before assignment)
# 例1
# def fun():
# print(a)
# a = 'xyz'
# print(a)
# a = 'abc'
# fun()
# 结果:
# 直接报错
# -------------------------------------------
# 例2
# 作为参数传入后,没有了局部变量,变成了全局变量在函数内的重新赋值
# def fun(a):
# a = '123'
# print(a)
# a = 'abc'
# print(a)
# a = 'xyz'
# fun(a)
# 结果:
# 123
# abc
# -------------------------------------------
# 2.当函数内有一变量名和某个外部函数同名,在该函数内部调用外部同名函数可使用globals,
# globals() 和 locals() 提供了基于字典的访问全局和局部变量的方式
def a():
return 'it is a'
# print('it is a')
def fun():
a = 'it is fun'
f1 = globals()['a']()
print(a)
print(f1)
print(globals())
print(locals())
fun() | false |
ca9e22821f53b36efb8ce3efd97eb82516fa379a | MatPorter/Programowanie-IR | /Zestaw 1/fib_it.py | 304 | 4.25 | 4 | n = int(input("n = "))
def fibonacci(n):
f_i_2 = 1
f_i_1 = 1
i = 3
if n == 1 or n == 2:
return 1
else:
while i in range(3, n+1):
f_i = f_i_1 + f_i_2
f_i_2 = f_i_1
f_i_1 = f_i
i+=1
return f_i
print(fibonacci(n)) | false |
ad56dc7b368603b7d2592573ed26503dcce41e4b | moncefelmouden/python-project-ui-2018 | /dbDemo.py | 1,594 | 4.21875 | 4 | import sqlite3
import os.path
def initDatabase():
db=sqlite3.connect('dbDemo.db')
sql="create table travel(name text primary key,country text)"
db.execute(sql)
sql="insert into travel(name,country) values('Korea Ski-ing Winter Tour','Korea')"
db.execute(sql)
db.commit()
db.close()
def readData():
db=sqlite3.connect('dbDemo.db')
sql="select * from travel"
db.row_factory = sqlite3.Row
rows=db.execute(sql)
for data in rows:
print(data['name']+" -- "+data['country'])
db.close()
def insertData(name,country):
db=sqlite3.connect('dbDemo.db')
sql="insert into travel(name,country) values(?,?)"
db.execute(sql,(name,country))
db.commit()
db.close()
#Exercise...
def deleteData(name):
print("Delete...")
db=sqlite3.connect('dbDemo.db')
sql="delete from travel where name=?"
db.execute(sql,(name,))
db.commit()
db.close()
#create a database when it does not exist
if not os.path.exists("dbDemo.db"): #cannot find file dbDemo.db
initDatabase()
userInput=""
while userInput!="Q":
userInput=input("Enter R to display Data or I to insert Data or D to delete Data or Q to quit")
userInput = userInput.upper()
if userInput=="R":
readData()
elif userInput=="I":
name=input("Enter the name of travel package:")
country=input("Enter the Country:")
insertData(name,country)
elif userInput=="D":
name=input("Enter the name of tour package to Delete")
deleteData(name)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.