blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e82894a863e7bc24cd1a17432b99630d9cfc604c | Oboze1/UCI_homework | /04-Python2/create_notes_drs.py | 1,446 | 4.25 | 4 | import os
#imports os
#defines the function main to create the folder directory system
def main():
#
#checks to see if the 'CyberSecurity-Notes' directory already exits
#
if os.path.isdir("CyberSecurity-Notes") == False:
#uses 'os.mkdir' to make a directory 'CyberSecurity-Notes'
#
os.mkdir("CyberSecurity-Notes")
#changes the path to the new directory
#
cur_path = os.path.join("CyberSecurity-Notes")
#runs a for loop to create 24 iterations of i
#
for i in range(1,25):
#makes a directory under the 'cur_path' with the name 'Week' + the value of 'i'
#
os.mkdir(cur_path + "/" + "Week " + str(i))
#joins the path into the folder that was just created
#
file_path = os.path.join(cur_path+ "/"+ "Week " + str(i))
#iterates through a range of 1-4 producing 3 lesson folders in the current 'Week' folder
#
for b in range(1, 4):
#makes the new directory with each 'Day'
#
os.mkdir(file_path + "/" + "Day " + str(b))
b +=1 #changes the iterated value
i +=1 #changes the iterated value
#if the directory exits prints out error message and aborts:
else:
print("----------FILE SYSTEM ALREADY EXISTS, CREATION OF FILE SYSTEM ABORTED!!-----------")
#main() | true |
7b39b19ccd500ec83103a1e07e89e55b108079df | timtingwei/prac | /py/corePy/13.1_object_intrudce.py | 2,251 | 4.15625 | 4 | #13.1_object_intrudce.py
#/// instance and class
class MyData(object):
""""
def __init__(self):
self.x = 10
self.y = 20
"""
pass
mathObj = MyData()
mathObj.x = 4 #/// x是实例特有的属性,不是类的属性,是动态的
mathObj.y = 5
print (mathObj.x + mathObj.y)
#9
print (mathObj.x * mathObj.y)
#20
#/// method
class MyDataWithMethod(object): #定义类和方法
def printFoo(self):
print ('You invoked printFoo()!')
myObj = MyDataWithMethod() #创建实例
myObj.printFoo() #调用方法
#You invoked printFoo()!
#create a class
class AddrBookEntry(object):
'address book entry class'
def __init__(self,nm,ph): #///在实例化的时候被调用
self.name = nm
self.phone = ph
print ('Created instance for:',self.name) #打印出介绍,self被实例名替换
def updatePhone(self,newph):
self.phone = newph
print ('Updated phone # for: ',self.name)
#create instance
john = AddrBookEntry('John Doe','408-555-1212')
#Created instance for: John Doe
jane = AddrBookEntry('Jane Doe','650-555-1212')
#Created instance for: Jane Doe
print (john)
#<__main__.AddrBookEntry object at 0x028531D0>
print (john.name) #打印实例的名字
#John Doe
print (john.phone)
#408-555-1212
print (jane.name)
#Jane Doe
print (jane.phone)
#650-555-1212
#call method
john.updatePhone('415-555-1212')
#Updated phone # for: John Doe
print (john.phone)
#415-555-1212
#create subclass
class EmplAddrBookEntry(AddrBookEntry):
'Employee Address Book Entry class'
def __init__(self,nm,ph,id,em):
AddrBookEntry.__init__(self,nm,ph) #super().__init__(self)
self.empid = id
self.email = em
def updateEmail(self,newem):
self.email = newem
print ('Updated e-mail address for:',self.name)
john = EmplAddrBookEntry('John Doe','408-555-1212',42,'jogh@hotmail.com')
#Created instance for: John Doe
print (john)
#<__main__.EmplAddrBookEntry object at 0x02883490>
print (john.name) #John Doe
print (john.phone) #408-555-1212
print (john.email) #jogh@hotmail.com
john.updatePhone('415-555-1212') #Updated phone # for: John Doe
print (john.phone) #415-555-1212
john.updateEmail('john@doe.spam') #Updated e-mail address for: John Doe
print (john.email) #john@doe.spam | false |
55d6f682df04071d77456fefaa8e89e00e6eede9 | SpartaKushK/First | /coin_flip_simulator.py | 816 | 4.1875 | 4 | '''
#Coin Flip Simulation - Write some code that simulates flipping a single coin however many times the user decides.
# The code should record the outcomes and count the number of tails and heads.
'''
import random
def flip_coin():
flip_results = []
total_heads = 0
total_tails = 0
num_of_flips = int(input('How many times do you want to flip the coin? '))
for num in range(num_of_flips):
flip_results.append(random.randint(1,2))
while True:
if flip_results[-1] == 1:
total_heads += 1
break
else:
total_tails += 1
break
print('The order of the sides were (1 = heads and 2 = tails: ' +str(flip_results))
print('There were '+ str(total_heads) + ' head(s) and ' + str(total_tails) + ' tail(s) after doing ' + str(num_of_flips) + ' flips')
flip_coin()
| true |
26041107893579444099238b735b5a2f59f550fa | Garric81/Python | /old_files/lessons2.py | 817 | 4.125 | 4 | #speed = int(input())
print("Система расчёта штрафов")
car_speed = 85
is_town = True
fine_for_20_to_40 = 500
fine_for_40_to_60 = 1000
fine_for_60_to_80 = 2000
fine_for_80_and_more = 5000
town_speed = 60
country_speed = 90
if is_town:
over_speed = car_speed - town_speed
else:
over_speed = car_speed - country_speed
if over_speed < 20:
print("Скорость не превышена или превышена незначительно")
elif over_speed >= 20 and over_speed < 40:
print("Штраф: " + str(fine_for_20_to_40))
elif over_speed >= 40 and over_speed < 60:
print("Штраф: " + str(fine_for_40_to_60))
elif over_speed >= 60 and over_speed < 80:
print("Штраф: " + str(fine_for_60_to_80))
elif over_speed >= 80:
print("Штраф: " + str(fine_for_80_and_more))
| false |
322ea317e128b82eb03ffb98a1501a7b0ddbbd4c | payalbhatia/Machine_Learning | /*Python_Basics/Command_Line_Argument/command_line_argument.py | 478 | 4.125 | 4 | import sys
# check if it has any arguments
print()
arg_num = len(sys.argv)
if arg_num == 1:
print('there are no arguments')
elif arg_num > 1:
# subtract 1 because one of the arguments is the file name
print('there are %d arguments ' % (arg_num-1))
print(sys.argv)
print('first argument is:', sys.argv[1])
# how to combine all arguments without quotations
one_string = " ".join(sys.argv[1:])
print(one_string)
print(type(one_string))
print('done')
print()
| true |
d851d6a26beedfdd9217f92a9d31052d8bcd02e8 | Travis-ugo/pythonTutorial | /Class.py | 801 | 4.3125 | 4 | # A Class in python is like an object constuctor or a blueprint for creating object.
# all classes have function called __init__(), which always executes when the class
# is being initiated.
# use the __init__() function to assign values to object properties, or other operationns
# that are nessesary to do when th object is created
class Person :
def __init__(self, name , age , year) :
self.name = name
self.age = age
self.year = year
def Fun(self) :
print('cally got them boys' + self.name + str(int( self.age)) )
clout = Person(' nana', 27 , 1999)
clout.Fun()
# NOTE: The self parameter is a reference to the current instance of the class,
# and is used to access variablles that belongs to the class .
# it doesnt have to be named "SELF" | true |
e51665d1d889fc309ec96cb7a3357dcdc6b27f90 | devesh37/HackerRankProblems | /Datastructure_HackerRank/Linked List/MergeTwoSortedLlinkedLists.py | 1,620 | 4.1875 | 4 | #!/bin/python3
#Problem Link: https://www.hackerrank.com/challenges/merge-two-sorted-linked-lists/problem
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the mergeLists function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def mergeLists(head1, head2):
newList=SinglyLinkedList()
tmp3=newList.head=SinglyLinkedListNode(0)
tmp1=head1
tmp2=head2
data=0
while(tmp1!=None and tmp2!=None):
if(tmp1.data<tmp2.data):
data=tmp1.data
tmp1=tmp1.next
else:
data=tmp2.data
tmp2=tmp2.next
tmp3.next=SinglyLinkedListNode(data)
tmp3=tmp3.next
while(tmp1!=None):
tmp3.next=SinglyLinkedListNode(tmp1.data)
tmp3=tmp3.next
tmp1=tmp1.next
while(tmp2!=None):
tmp3.next=SinglyLinkedListNode(tmp2.data)
tmp3=tmp3.next
tmp2=tmp2.next
return(newList.head.next)
if __name__ == '__main__': | true |
5cb576a8f9e9891f8046e0f8e0f188f5d98241bd | zepedac6581/cti110 | /P3WH1_ColorMixer_Zepeda.py | 1,563 | 4.34375 | 4 | # A program that allows users to input primary colors as a mix and ouputs
# a secondary color.
# CTI-110-0003
# P3HW1 - Color Mixer
# Clayton Zepeda
# 2-14-2019
#
def main():
# User inputs two primary colors
# Primary colors are red, blue and yellow.
print("The primary colors are red, blue, and yellow.")
primary_color_1 = input('Enter the first primary color to mix: ')
primary_color_2 = input('Enter the second primary color to mix: ')
# if Mixing primary_1 == red and primary_2 == blue:
# print('The secondary color is purple.')
if (primary_color_1 in ("red","Blue","blue","Red")and primary_color_2 in\
("blue","red","Red","Blue")):
print("The secondary color is purple.")
# if else Mixing primary_1 == red and primary_2 == yellow
# print('The secondary color is orange.')
elif (primary_color_1 in("red","Red","Yellow","yellow") and primary_color_2 in\
("yellow","Yellow","Red","red")):
print("The secondary color is orange.")
# if else Mixing primary_1 == blue and primary_2 == yellow
# print('The secondary color is green.')
elif (primary_color_1 in ("blue","Blue","Yellow","yellow") and primary_color_2 in\
("yellow","Yellow","Blue","blue")):
print("The secondary color is green.")
# if user inputs a primary color not equal to primary_1, primary_2 or primary_3
# display 'Error; input color is not a primary.'
else:
print("Error! One color entered is not a primary color.")
main()
| true |
182bb72bf884e6f1678e7fcf5f408c7b521a1900 | alvinwang922/Data-Structures-and-Algorithms | /Strings/Compare-Version-Numbers.py | 1,904 | 4.125 | 4 | """
Given two version numbers, version1 and version2, compare them.
Version numbers consist of one or more revisions joined by a
dot '.'. Each revision consists of digits and may contain
leading zeros. Every revision contains at least one character.
Revisions are 0-indexed from left to right, with the leftmost
revision being revision 0, the next revision being revision 1,
and so on. For example 2.5.33 and 0.1 are valid version numbers.
To compare version numbers, compare their revisions in
left-to-right order. Revisions are compared using their integer
value ignoring any leading zeros. This means that revisions 1
and 001 are considered equal. If a version number does not
specify a revision at an index, then treat the revision as 0.
For example, version 1.0 is less than version 1.1 because their
revision 0s are the same, but their revision 1s are 0 and 1
respectively, and 0 < 1. Return the following:
If version1 < version2, return -1.
If version1 > version2, return 1.
Otherwise, return 0.
"""
class Solution:
def compareVersion(self, version1: str, version2: str):
one = version1.split(".")
two = version2.split(".")
l1, l2 = len(one), len(two)
smaller, larger = min(l1, l2), max(l1, l2)
for i in range(smaller):
if int(one[i]) == int(two[i]):
continue
elif int(one[i]) > int(two[i]):
return 1
else:
return -1
if l1 > l2:
for v in one[smaller:]:
if int(v) != 0:
return 1
elif l1 < l2:
for v in two[smaller:]:
if int(v) != 0:
return -1
return 0
print(compareVersion("1.01", "1.001"))
print(compareVersion("1.0.1", "1"))
print(compareVersion("7.5.2.4", "7.5.3"))
print("The values above should be 0, 1, and -1.")
| true |
3adb0122c6c2190389ffa9c91e2e3013f08310fa | alvinwang922/Data-Structures-and-Algorithms | /Trees/Tree-To-LinkedList.py | 1,529 | 4.21875 | 4 | """
Convert a Binary Search Tree to a sorted Circular Doubly-Linked List
in place. You can think of the left and right pointers as synonymous
to the predecessor and successor pointers in a doubly-linked list.
For a circular doubly linked list, the predecessor of the first element
is the last element, and the successor of the last element is the first
element. We want to do the transformation in place. After the
transformation, the left pointer of the tree node should point to its
predecessor, and the right pointer should point to its successor. You
should return the pointer to the smallest element of the linked list.
"""
# Definition for a Node.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def treeToDoublyList(self, root: 'Node'):
if not root:
return
dummy = Node(0, None, None)
prev = dummy
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
node.left, prev.right, prev = prev, node, node
node = node.right
dummy.right.left, prev.right = prev, dummy.right
return dummy.right
print(treeToDoublyList([]))
print(treeToDoublyList([4, 2, 5, 1, 3]))
print(treeToDoublyList([2, 1, 3]))
print("The linked lists above should be [], [1, 2, 3, 4, 5], \
and [1, 2, 3].")
| true |
e9c31922276c7e2e860cd5716b72e9a7ff0a613b | alvinwang922/Data-Structures-and-Algorithms | /LinkedList/Odd-Even-LinkedList.py | 1,001 | 4.125 | 4 | """
Given a singly linked list, group all odd nodes together followed by the
even nodes. Please note here we are talking about the node number and not
the value in the nodes.
You should try to do it in place. The program should run in O(1) space
complexity and O(nodes) time complexity.
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def oddEvenList(self, head: ListNode):
if not head:
return
odd = head
even = evenHead = head.next
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
odd.next = evenHead
return head
print(oddEvenList(1 -> 2 -> 3 -> 4 -> 5 -> None))
print(oddEvenList(2 -> 1 -> 3 -> 5 -> 6 -> 4 -> 7 -> None))
print("The linkedlists above should be 1->3->5->2->4->None \
and 2->3->6->7->1->5->4->None.")
| true |
63a2c6bd1837d4d68b58bb0b4e7d6767c9e6a6ab | alvinwang922/Data-Structures-and-Algorithms | /DFS/Reconstruct-Itinerary.py | 1,476 | 4.375 | 4 | """
Given a list of airline tickets represented by pairs of
departure and arrival airports [from, to], reconstruct the
itinerary in order. All of the tickets belong to a man who
departs from JFK. Thus, the itinerary must begin with JFK.
Note:
If there are multiple valid itineraries, you should return
the itinerary that has the smallest lexical order when read
as a single string. For example, the itinerary ["JFK", "LGA"]
has a smaller lexical order than ["JFK", "LGB"]. All airports
are represented by three capital letters (IATA code).
You may assume all tickets form at least one valid itinerary.
One must use all the tickets once and only once.
"""
import collections
class Solution:
def findItinerary(self, tickets: List[List[str]]):
targets = collections.defaultdict(list)
for a, b in sorted(tickets)[::-1]:
targets[a].append(b)
route = []
def visit(airport):
while targets[airport]:
visit(targets[airport].pop())
route.append(airport)
visit('JFK')
return route[::-1]
print(findItinerary([["MUC", "LHR"], ["JFK", "MUC"], \
["SFO", "SJC"], ["LHR", "SFO"]]))
print(findItinerary([["JFK", "SFO"], ["JFK", "ATL"], \
["SFO", "ATL"], ["ATL", "JFK"], ["ATL", "SFO"]]))
print("The arrays above should be [\"JFK\", \"MUC\", \
\"LHR\", \"SFO\", \"SJC\"] and [\"JFK\", \"ATL\", \
\"JFK\", \"SFO\", \"ATL\", \"SFO\"].")
| true |
760df47c1a3a8a7cdb8b3353e3ac4b2ff5f34f45 | alvinwang922/Data-Structures-and-Algorithms | /Strings/ZigZag-Conversion.py | 971 | 4.25 | 4 | """
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
P A H N
A P L S I I G
Y I R
Write the code that will take a string and make this conversion given a number of rows
"""
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [""] * numRows
rowTracker = 0
forward = True
for char in s:
rows[rowTracker] += char
if rowTracker == 0:
forward = True
elif rowTracker == numRows - 1:
forward = False
if forward == True:
rowTracker += 1
else:
rowTracker -= 1
return "".join(rows)
print(convert("PAYPALISHIRING", 1))
print(convert("PAYPALISHIRING", 3))
print(convert("PAYPALISHIRING", 4))
print("The strings above should be \"PAYPALISHIRING\", \"PAHNAPLSIIGYIR\", and \PINALSIGYAHRPI\".") | true |
3d937fce84d5cb59a5424014b4d0a42942fb3661 | alvinwang922/Data-Structures-and-Algorithms | /Matrices/Flood-Fill.py | 1,521 | 4.21875 | 4 | """
An image is represented by a 2-D array of integers, each integer representing
the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column) of
the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel, plus any pixels
connected 4-directionally to the starting pixel of the same color as the
starting pixel, plus any pixels connected 4-directionally to those pixels
(also with the same color as the starting pixel), and so on. Replace the
color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
"""
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int):
rows, cols, original = len(image), len(image[0]), image[sr][sc]
def traverse(row, col):
if (0 <= row < rows and 0 <= col < cols) \
and image[row][col] == original:
image[row][col] = newColor
else:
return
for (x, y) in ((1, 0), (0, 1), (0, -1), (-1, 0)):
traverse(row + x, col + y)
if original != newColor:
traverse(sr, sc)
return image
print(floodFill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 1, 2))
print(floodFill([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 1, 2, 3))
print("The matrices above should be [[2, 2, 2], [2, 2, 0], [2, 0, 1]] \
and [[1, 1, 1], [1, 1, 3], [1, 0, 1]].")
| true |
3531a16c7b8ee9a8ed2ee798cbac3c2f49cc759e | I201821180/ALGO | /merge_sort.py | 708 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python implementation for merge sort, complexity O(NlogN)
def merge(A, p, q, r):
L = A[p: q+1]
R = A[q+1: r+1]
L.append(float('inf'))
R.append(float('inf'))
i, j = 0, 0
for k in range(p, r+1):
if L[i] <= R[j]:
A[k] = L[i]
i += 1
else:
A[k] = R[j]
j += 1
def merge_sort(A, p, r):
if p < r:
q = (p+r)//2
merge_sort(A, p, q)
merge_sort(A, q+1, r)
merge(A, p, q, r)
if __name__ == '__main__':
A = [3, 41, 52, 26, 38, 57, 9, 49]
print("Before sort:{}".format(A))
merge_sort(A, 0, 7)
print("After sort:{}".format(A))
| false |
7cbab018f0905dadf19ee3b27ede26839cb27aab | alltej/kb-python | /data_structures/tuples.py | 782 | 4.65625 | 5 |
##TUPLES - A tuple is a one dimensional, fixed-length, immutable sequence.
tup = (1, 2, 3)
print(tup)
#convert to tuple
list_1 = [1,2,3]
tup_1 = type(tuple(list_1))
#create a nested tuple
nested_tup = ([1,2,3],(4,5))
print(nested_tup)
print(nested_tup[0])
# Although tuples are immutable, their contents can contain mutable objects.
print("Modify a tuple's contents:")
nested_tup[0].append(4)
print(nested_tup[0])
print()
print("Concatenate tuples by creating a new tuple and copying objects:")
print((1, 3, 2) + (4, 5, 6))
print()
print("unpack tuples")
a, b = nested_tup
print(a, b)
print()
print("A common use of variable unpacking is when iterating over sequences of tuples or lists:")
seq = [( 1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
print(a, b, c) | true |
1206dbd776ea188e499d301fcb655040e5d6d434 | Jhon112/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 649 | 4.15625 | 4 | #!/usr/bin/python3
"""prints a text with 2 new lines after each of these characters: ., ? and :"""
def text_indentation(text):
"""replace the characters ., ? and : for a 2 blank_lines
Args:
text (str): str that will be modified
Returns:
prints the new text
Raises:
TypeError: if text is not a str
"""
if not isinstance(text, str):
raise TypeError("text must be a string")
replacers = ".?:"
text = text.strip()
for replacer in replacers:
text = text.replace(replacer, "{}\n\n".format(replacer))
print("\n".join([li.strip() for li in text.split("\n")]), end="")
| true |
2e2d6a28de15808f95b8c848338905b202764ec9 | Jhon112/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 1,350 | 4.375 | 4 | #!/usr/bin/python3
"""Test max_integer function"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""class to test max_integer function No attributes are needed
but different methods for differents test cases are.
"""
def test_empty_list(self):
"""
checks that the max_integer function returns None in case list passed
is empty.
"""
self.assertIs(max_integer([]), None)
def test_max_at_end(self):
"""
Test if it returns the correct value (max integer of an int list
"""
self.assertEqual(max_integer([1, 2, 3, 4]), 4)
def test_max_at_beggining(self):
"""test if returns max value when it's at first position"""
self.assertEqual(max_integer([4,3,2]), 4)
def test_max_at_middle(self):
"""test if returns max value when it's at mid position"""
self.assertEqual(max_integer([3, 2, 4, 1, 0]), 4)
def test_unique_element(self):
"""Test list with only one element"""
self.assertEqual(max_integer([4]), 4)
def test_negative_numbers(self):
"""
Test if it returns the correct value (max integer)
on a list with negative numbers
"""
self.assertEqual(max_integer([-1, -2, -3, -4]), -1)
| true |
e6e4a29ab2520be59425f9651c40d6e49866d720 | ik2y/recode-beginner-python | /materials/week-4/src/solveTogether-bmi.py | 649 | 4.28125 | 4 | # The formula is BMI = weight(kg) / height (m) ^ 2
# - Underweight: < 18.5
# - Normal: 18.5 - 24.9
# - Overweight: 25 - 29.9
# - Obese: > 30
userWeight = input("Insert your weight in KG: ")
userWeight = float(userWeight)
userHeight = input("Insert your height in meters: ")
userHeight = float(userHeight)
bmiValue = userWeight / (userHeight * userHeight)
status = ""
if(bmiValue < 18.5):
status = "underweight"
elif(bmiValue >= 18.5 and bmiValue <= 24.9):
status = "normal"
elif(bmiValue >= 25 and bmiValue <= 29.9):
status = "overweight"
else:
status = "obese"
print("Your BMI is: " + str(bmiValue))
print("You are " + status) | true |
e01a7b6001470bf28970a96664e8a212033d22d6 | ik2y/recode-beginner-python | /materials/week-7/src/takeHomeChallenge-wordCounter/app.py | 1,101 | 4.15625 | 4 | ###############################################################
# do not modify the code in here ##############################
from helper.TxtReader import TxtReader
import helper.Utility import clearScreen
DATA_PATH = "text.txt"
# load data
txtReader = TxtReader(DATA_PATH)
rawSentence = txtReader.load()
# do not delete the code in here ##############################
###############################################################
# 1. find a way to split a stirng variable into a list of words. We split them by a space
# eg. "I love pepperoni pizzas" -> ["I", "love", "peperoni", "pizzas"]
# HINT: use google to help you
# 2. Initialise an empty dictionary and give it the name `wordsSummary`
# 3. Write a loop through the list of words you made in (1). If the dictionary key does not exists, create new key
# and assign the value of 1 to it
# 4. Otherwise, update the value of this key by adding itself by 1
# 5. Write a function to print a dictionary nicely.
# 6. Call this function at the end of your program
def printDictionary(wordDictionary):
...
## word counting logic goes here | true |
57e5e4ff4c6ed09c3c4902bdd182b373c4686422 | srisivan/python | /divisibility.py | 396 | 4.3125 | 4 |
# To find divisible numbers for 3.
divisors = []
my_num = int(input("Enter the desired number : "))
for i in range (1, (my_num + 1)):
if my_num % i == 0:
divisors.append(i)
length = len(divisors)
if length == 2:
print("%s is a prime number" % my_num)
else:
print("%s is a composite number" % my_num)
print(divisors)
print("The number of divisors is %s" % length)
| true |
57b2759986521a7435beed8922aafc8a19b25f75 | nikolaosmparoutis/Algorithms_and_Data_Structures_Python | /breadth_first_search.py | 920 | 4.3125 | 4 | # Implementation of breadth first search using queue. Add children then BFS the tree
# from left to right. Input an empty array where the return from the BFS will fill it with the nodes.
# T=O(V+E) traverse the nodes + for each node traverse its edges(children),
# space O(V)
class Node:
def __init__(self, name):
self.children = []
self.name = name
def addChild(self, name):
self.children.append(Node(name))
return self # return reference to the instance object it was called(the class object).Used for chaining in unittest.
def breadthFirstSearch(self, array):
queue = [self] # reference of the instance object of the class, Node(name)
while len(queue) > 0:
current = queue.pop(0)
array.append(current.name)
for child in current.children:
queue.append(child)
print(array)
return array
| true |
1495c305585fd90afb2967e3a753e7bfd89e69d0 | Stanislav144/python | /rekord.py | 1,411 | 4.15625 | 4 | # Programm record
#
scores = []
choice = None
while choice != "0":
try:
print(
"""
0- Exit
1- View record
2- Add record
3- Delete record
4- Sorted list
"""
)
choice = input('Enter position: ')
print()
# Exit
if choice == '0':
print("Goodbay")
input("\n\nPress Enter for Quit")
# View records
elif choice =="1":
print ("Records\n")
print("Name\tResult")
for entry in scores:
score, name=entry
print (name, "\t", score)
#Add record
elif choice=="2":
name=input("Input name: ")
score=int(input("Input your new record: "))
entry=(score, name)
scores.append(entry)
scores.sort(reverse=True)
score=scores[:5]
#Delete record
elif choice=='3':
name=input("Input name for delete: ")
score = input("Input record for delete: ")
if score and name in scores:
scores.remove(name, score)
else:
print("Record",score,"or",name,"wrong")
#Sorted scores
elif choice=="4":
scores.sort(reverse=True)
else:
print ("Sorry, your choise is wrong!")
except:
print('Erorre, Press Enter for choice')
continue
| true |
d9b99b09041ae56608107cf6993b6cc1665120ff | jc98924/Metis-Data-Science-Prework | /lessons/python_intro/calc_row_value.py | 837 | 4.59375 | 5 | #!/usr/bin/python
import os
import sys
def calc_row_value(input_string):
"""
This function takes a string input, converts it to an integer value and
then outputs a "new value".
---
args:
input_string(str): input string
returns:
calc_value (int): output value
"""
if type(input_string) != str:
raise ValueError("input_string must be a string type!")
str_conv = [int(d) for d in input_string if d.isdecimal()]
calc_value = 0
for index, digit in enumerate(str_conv):
num_index = index + 1
if num_index % 2 != 0:
calc_value += digit * num_index
else:
calc_value -= digit * 5
return calc_value
input_string = input("Please enter a number to convert:\n")
print("The converted number is:",calc_row_value(input_string))
| true |
95cf841c5a27979c0b573a29f32dae17b6ddc562 | olegpolivin/AlgorithmsSpecializationStanford | /01_Divide_and_Conquer/Week01/RecIntMult.py | 1,214 | 4.34375 | 4 | print('Welcome to exercise 1: Stanford Algorithms')
print('Input: two n-digit positive integers x and y')
print('Assumption: n is a power of 2')
from math import ceil
x = input('Enter first integer: ')
y = input('Enter second integer: ')
n = max(len(x), len(y))
n1, n2 = len(x), len(y)
assert n1 % 2 == 0, 'Number of digits in the first number is not power of 2'
assert n2 % 2 == 0, 'Number of digits in the second number is not power of 2'
def RecIntMultiplication(x,y,n):
"""
Function to multiply two n-digits recursively
"""
if n == 1 :
x = int(x)
y = int(y)
return x * y
else :
k = ceil(n/2)
a = x[0:-k]
b = x[-k:]
if len(a) == 0:
a = '0'
c = y[0 : -k]
d = y[-k:]
if len(c)==0:
c = '0'
ac = RecIntMultiplication(a,c,k)
ad = RecIntMultiplication(a,d,k)
bc = RecIntMultiplication(b,c,k)
bd = RecIntMultiplication(b,d,k)
return 10**n * ac + 10**(k)*(ad+bc) + bd
res = RecIntMultiplication(x,y,n)
print('Result of recursive multiplication: ', res)
print('Calculation is correct: ' , res == int(x)*int(y)) | false |
8fef04cee7bd39d7a23c2e9f74b5e741f424bf61 | serre-lab/smart-playroom-kalpit | /kinectpath/source/utils/misc.py | 1,385 | 4.21875 | 4 | """Miscellaneous helper functions required for calculations
"""
import numpy as np
def calc_line_point_distance(line, point):
"""Function to calculate the distance of a point from a line
Parameters
----------
line : list
(x1, y1, z1, x2, y2, z2) - the endpoints of the line segment
point : list
(x, y, z) - the point whose distance from line has to be calculcated
Returns
-------
int
The distance of the given point from the line represented by the
list of endpoints
"""
x1 = np.float32(np.asarray(line[:3]))
x2 = np.float32(np.asarray(line[3:]))
x = np.float32(np.asarray(point))
numerator = np.linalg.norm(np.cross((x - x1), (x - x2)))
denominator = np.linalg.norm((x2 - x1))
dist = (numerator / denominator)
#slope = ((line[1] - line[3]) / (line[0] - line[2]))
#y_intercept = line[1] - slope * line[0]
#b = -1.0
#a = slope
#return np.abs(a*point[0] + b*point[1] + y_intercept) / (np.sqrt(a**2 + b**2))
return dist
def calc_distance(p1, p2):
# p1 and p2 are 1D vectors
p1 = np.float32(np.asarray(p1))
p2 = np.float32(np.asarray(p2))
return np.sqrt(np.sum(np.square(p1-p2)))
def reject_outliers(data, m=1.5):
X=abs(data - np.mean(data, axis=0)) < 1.5 * np.std(data, axis=0)
Y=np.logical_and(X[:,0],X[:,1],X[:,2])
return data[Y, :]
| true |
4e27bf1d7ec0a4f8d87c8f01e47577029413c4fe | mndimitrov92/Python3_deep_dive | /Functional_Closure_decorators/decorators_with_attributes.py | 1,063 | 4.25 | 4 | """
Decorators which can contain additional attributes that can be accessed.
"""
from functools import wraps
def my_decorator(fn):
my_var = {}
@wraps(fn)
def wrapper(*args, **kwargs):
print("Decorating...")
result = fn(*args, **kwargs)
print("Finished")
return result
def my_helper_func():
print("Help called")
return my_var
# Inner decorator that can be accessed for storing function instances
def another_dec(some_key):
def inner(fn):
print("Inner decorator called")
my_var[some_key] = fn
return fn
return inner
# In order to access the function, it needs to be attached to the returned wrapper function
wrapper.saved = my_helper_func()
wrapper.add_me = another_dec
return wrapper
# Initial decoration of the function
@my_decorator
def test_func():
print("Hello")
return 5
print(test_func.saved)
# Then the the inner decorator from the decoarated function can be used to decorate other functions.
@test_func.add_me("my_func2")
def test_func2():
print("Hello again")
return 10
test_func2()
print(test_func.saved) | true |
9e3a4323ce922225209ba8eb326ce434a9c6e77c | Somesh1501/Codes | /sort_method.py | 229 | 4.3125 | 4 | #sort method is used for sorting element in a list
#sorted function
animals = ['dog','fox','cow','cat']
animals.sort(reverse = True)
print(animals)
''' print(sorted(animals))
x=(sorted(animals))
x.reverse()
print(x)'''
| true |
e5701d4e69fba20f6478ec1ab94a57e567d2a82d | peninah-odhiambo/andela-day4 | /missing_number.py | 401 | 4.125 | 4 | def find_missing (list1, list2):
""" The lists represent two different lists"""
# list1 = set (list1)
# list2 = set (list2)
if len(list1) > len(list2):
for number in list1:
if number not in list2:
return number
else:
for number in list2:
if number not in list1:
return number
"""set gets rids of duplicates in the lists"""
print(find_missing([1,2,2,3,4], [1,2,3,4,5])) | true |
072c2b2b60dc5e4e056742228f14a85902a2b83e | ninarobbins/astr-119-session-2 | /dictionaries.py | 376 | 4.125 | 4 | # dictionaries have key:value for elements
example_dict = {
'class' : 'Astr 119',
'prof' : 'Brant',
'awesomeness' : 10
}
print(type(example_dict))
#get value with key
course = example_dict['class']
print(course)
#change a value via key
example_dict['awesomeness'] += 1 #increase awesomeness
print(example_dict)
for x in example_dict.keys():
print(x, example_dict[x])
| true |
b83bb0e5c7c7c284c9b5d7dce366b3b626856f9a | VINEETHREDDYSHERI/Python-Deep-Learning | /ICPLab2/src/Question1.py | 879 | 4.1875 | 4 | studentCount = int(input("Enter No.of Students: ")) # Asking the User to provide count of students
studentHeightsInFeet = []
studentHeightsInCM = []
for i in range(studentCount):
height = float(input("Enter the Student-{} height in Feet ".format(i))) # Accepting Height of the each student
# from user and converting into Float
studentHeightsInFeet.append(float("{:.1f}".format(height))) # adding height of student to list and converting to
# 1 decimal float format
studentHeightsInCM.append(float("{:.1f}".format(height * 30.48))) # adding height of student to list after
# converting it to Centimeter and converting to 1 decimal float format
print("Student's Height in Feet", studentHeightsInFeet) # printing student height in feet metric
print("Student's Height in centimeter", studentHeightsInCM) # printing student height in Centimeter metric
| true |
0951e9e5237eed56918ae45dafeac20298d25c11 | grumm1728/SFcubestepdown | /Dandy.Candies.py | 749 | 4.125 | 4 | import math
while 1==1:
#input
n = input("How many candies? n=")
n = int(n)
s1_0 = int(math.floor(n ** (1 / 3.0)))
print("s1_0 = ", s1_0)
s1 = s1_0
while n % s1 > 0:
s1 = s1 - 1
print(s1)
print("Side 1 = ",s1)
s1quot = int(n/s1) # quotient of candies divided by first side
s2_0 = int(math.floor(math.sqrt(n/s1)))
print("s2_0 = ", s2_0)
s2 = s2_0
while s1quot % s2 > 0:
s2 = s2 - 1
print(s2)
print("Side 2 = ",s2)
s3 = int(n / (s1 * s2))
print("Side 3 = ",s3)
SA = 2*(s1*s2 + s1*s3 + s2*s3)
print("\n {",s1,", ",s2,", ",s3,"} with Surface Area =", SA)
print("\n===== End =====\n")
| false |
eb7c7f0fc65acc343f1867aa1606d4b0e3caf3f0 | isabellabvo/Design-de-Software | /Listando todos os sufixos de uma string.py | 417 | 4.125 | 4 | #---------ENUNCIADO---------#
'''
Escreva uma função que recebe uma string e devolve uma lista com todos os seus sufixos.
Um sufixo é qualquer substring que se encontra no final da string original.
O nome da sua função deve ser lista_sufixos.
'''
#----------CÓDIGO-----------#
def lista_sufixos(palavra):
a = []
for i in range(len(palavra)):
t = palavra[i:]
a.append(t)
return a
| false |
2c53a2ebfa484658215e3a119ac8c82436feb2a2 | isabellabvo/Design-de-Software | /Lista caracteres.py | 415 | 4.28125 | 4 | #---------ENUNCIADO---------#
'''
Faça uma função que recebe uma string e devolve uma lista contendo os caracteres dessa string, sem repetição.
Ex: 'abacate' deve devolver ['a', 'b', 'c', 't', 'e'].
O nome da sua função deve ser lista_caracteres.
'''
#----------CÓDIGO-----------#
def lista_caracteres(string):
j = []
for i in string:
if i not in j:
j.append(i)
return j
| false |
4017d35f2bf0dc692fd02770510ca0aeba71ccbd | isabellabvo/Design-de-Software | /Diferença de listas.py | 698 | 4.34375 | 4 |
#---------ENUNCIADO---------#
'''
Faça uma função que recebe 2 listas e retorna uma nova lista com os elementos da primeira lista que não estão na segunda lista.
Exemplo: para a entrada lista1 = [2, 7, 3.1, 'banana'] e lista2 = [2, 'banana', 'carro'] sua função deve devolver a lista [7, 3.1].
Atenção, esse é só um exemplo, sua função deve conseguir lidar com quaisquer listas de entrada e não apenas com as do exemplo.
O nome da sua função deve ser subtracao_de_listas.
'''
#----------CÓDIGO-----------#
def subtracao_de_listas (lista1,lista2):
listafinal = lista1
for i in lista1:
if i in lista2:
listafinal.remove(i)
return listafinal
| false |
647a55a85639fb849c9feb2e2086a31fa4777fc8 | isabellabvo/Design-de-Software | /Jogo da roleta simplificado.py | 1,816 | 4.3125 | 4 |
#---------ENUNCIADO---------#
'''
Faça um programa em Python que implementa o jogo da roleta simplificado, o usuário começa com 100 dinheiros, e o programa fica em loop até que o dinheiro acabe:
O programa mostra a quantidade de dinheiro disponível (obrigatório o uso de print)
O usuário aposta um valor (se o valor for zero o programa para)
Posteriormente o programa pergunta se a aposta é em um número ou paridade (par/ímpar)
Se o usuário digitar a opção 'n' o usuário digita o número de 1 a 36, caso ganhe ele recebe 35 vezes o que apostou.
Por exemplo, se ele tinha 100 e apostou 10 ele passará a ter 100+35⋅10=450, se ganhar, ou 100−10=90, se perder.
Se o usuário digitar a opção 'p' o usuário escolhe se par (opção 'p') ou ímpar (opção 'i'), caso ganhe ele recebe o mesmo que apostou.
Por exemplo, se ele tinha 100 e apostou 10 ele passará a ter 100+10=110, se ganhar, ou 100−10=90, se perder.
Será feito um sorteio de 0 (zero) a 36 (trinta e seis) e na sequência o pagamento das apostas
Utilize a função random.randint.
'''
#----------CÓDIGO-----------#
from random import randint
rdn = randint (1,36)
i=100
while i>= 0:
print (i)
a = input("A aposta é um número ou paridade? (n/p)")
if a == "n":
ch = int(input('Número de 1 a 36: '))
if ch == 0:
return False
elif ch == rdn:
i += 35 *ch
else:
i -= ch
elif a == "p":
ch = int(input("Número de 0 a 36: "))
k = input("É par ou ímpar?: (p/i)")
if ch == 0:
return False
elif k == "p":
if rdn%2 == 0:
i += ch
elif k == "i":
if rdn%2 != 0:
i+=ch
else:
i -= ch
print (i)
| false |
811d5e93df6669d787ddd75713785ec4d9d6f006 | livsmith77/Reading-text-files | /MAP_REDUCE_FILTER.py | 1,751 | 4.15625 | 4 |
1. Temperature conversions
def fahrenheit(t):
return ((float(9)/5)*t + 32)
def celsius(t):
return (float(5)/9*(t - 32))
def to_fahrenheit(values):
return map(fahrenheit, values)
def to_celsius(values):
return map(celsius, values)
2. Return maximum value from list
def max(values):
return reduce(lambda a,b: a if (a>b) else b, values)
3. Return minimum value from list
def min(values):
return reduce(lambda a,b: a if (a<b) else b, values)
4. Return sum of values in list
def add(values):
return reduce(lambda a,b: a+b, values)
5. Return value obtained by subtracting consecutive values in list from value of first item
def sub(values):
return reduce(lambda a,b: a-b, values)
6. Return product of values in a list
def mul(values):
return reduce(lambda a,b: a*b, values)
7. Return average of values in a list
def ave(values):
return reduce(lambda a,b: (a+b)/2, values)
8. Return value obtained by dividing consecutive values in list from value of first item - using reduce
def div(values):
return reduce(lambda a,b: a/float(b) if (b != 0 and a != 'Nan') else 'Nan', values)
9. Return even values from list
def is_even(values):
return filter(lambda x: x % 2 == 0, values)
10. Return odd values from list
def is_odd(values):
return filter(lambda x: x % 2 , values)
11. Iterator
def get_triplets(n):
for x in range(1, n):
for y in range(x,n):
for z in range(y,n):
if x**2 + y**2 == z**2:
yield (x,y,z)
12. Fibonacci iterator
def fibonacci(n):
"""Fibonacci numbers generator, first n"""
a, b, counter = 0, 1, 0
while True:
if (counter > n): return
yield a
a, b = b, a + b
counter += 1
| true |
c54ee7da573fab0b4fe1f9c8b93d90cfb0b7d17f | arnab0000/StartUps | /CaseStudy/solution1.py | 2,762 | 4.34375 | 4 | # 1. Your Friend has developed the Product and he wants to establish the product startup and he is searching for a perfect location where
# getting the investment has a high chance. But due to its financial restriction, he can choose only between three locations - Bangalore,
# Mumbai, and NCR. As a friend, you want to help your friend deciding the location. NCR include Gurgaon, Noida and New Delhi.
# Find the location where the most number of funding is done. That means, find the location where startups has received funding maximum
# number of times. Plot the bar graph between location and number of funding. Take city name "Delhi" as "New Delhi".
# Check the case-sensitiveness of cities also. That means, at some place instead of "Bangalore", "bangalore" is given.
# Take city name as "Bangalore". For few startups multiple locations are given, one Indian and one Foreign.
import pandas as pd
import matplotlib.pyplot as plt
startUp = pd.read_csv("startup_funding.csv", encoding='utf-8', skipinitialspace=True)
df = startUp.copy()
df['CityLocation'].dropna(inplace=True)
def splitColumn(city):
return city.split('/')[0].strip()
df['CityLocation'] = df['CityLocation'].apply(splitColumn)
df['CityLocation'].replace("Delhi", "New Delhi", inplace=True)
df['CityLocation'].replace("bangalore", "Bangalore", inplace=True)
df = df[(df['CityLocation'] == 'Bangalore') | (df['CityLocation'] == 'Gurgaon') | (df['CityLocation'] == 'Mumbai') | (df['CityLocation'] == 'Noida') | (df['CityLocation'] == 'New Delhi')]
type_funding = df.groupby('CityLocation').size().sort_values(ascending = False)[0:5]
# print(type_funding)
location = type_funding.index
number = type_funding.values
for i in range(len(location)):
print(location[i], number[i])
plt.bar(location, number)
plt.title('Max number of Fundings')
plt.ylabel('Funding frequency')
plt.xlabel('Cities')
plt.show()
# import numpy as np
# import pandas as pd
# import matplotlib.pyplot as plt
# data=pd.read_csv("startup_funding.csv",skipinitialspace=True)
# data.head()
# data.CityLocation.dropna(inplace=True)
# data.CityLocation.replace("Delhi","New Delhi",inplace=True)
# data.CityLocation.replace("bangalore","Bangalore",inplace=True)
# cities=["Bangalore","Mumbai","Gurgaon","Noida","New Delhi"]
# tno_invest={}
# for i in data.CityLocation:
# i=i.split("/")
# for city in i:
# if city.strip() in cities:
# tno_invest[city.strip()]=tno_invest.get(city.strip(),0)+1
# tno_city=list(tno_invest)
# tno_value=list(tno_invest.values())
# for i in range(len(tno_city)):
# print(tno_city[i], tno_value[i])
# #graph plotting
# #bar graph
# plt.bar(tno_city,tno_value)
# plt.show()
# print(tno_invest) | true |
414bb0784c697fde373f95670fcb9ff2abfb98f3 | belarminobrunoz/BYUI-CSE-110 | /week 07/w08_loops.py | 588 | 4.46875 | 4 |
# #Aqui estou criando umma variavel chamada 'name' e fazendo o loop em cima desse array
# for name in ['bruno', 'fran']:
# print(name)
# #Aqui estou criando um range onde coloco o numero inicial, neste caso 0 e a quantidade de numeros neste range, que no caso é 3
# for index in range(0,3):
# print(index)
# #Looping with a condition
# names = ['bruno', 'fran', 'caio']
# index = 0
# while index < len(names):
# print(names[index])
# #change the condition
# index = index +1
names = ['bruno', 'fran', 'caio']
for name in names:
print("My name is: " + name) | false |
ebef709fb875dbccc987fb7fc94ac1474bbd9f56 | AwsafAlam/Python_Problems | /Basics/List_Pract.py | 2,395 | 4.53125 | 5 | courses = ['Datastructures' , 'AI' , 'Micro' , 'Assembly']
print(courses)
print(courses[0])
print(courses[len(courses) - 1]) # or, we can use negative indexes
print(courses[-1]) ## So, we can traverse in reverse as well
print(courses[0:3]) ## starting at 0 , and upto but not including 3 (ie, < 3 )
print(courses[:2]) # starts at beginning by default
print(courses[1:]) # goes to the end by default
## (This is lnown as slicing)
courses.append('art') ## adds at end of list
print(courses)
courses.insert(1 , 'Music') ## adds music at position 1.
print(courses)
nested = ['CSE 322' , 'CSE 221']
courses.extend(nested) ## Adds values from second list to the first at the end
print(courses)
courses.insert(0 , nested) # creates a list within a list
print(courses)
courses.remove('Datastructures') ## removes the specified element
print(courses)
popped = courses.pop() # removes the last element. useful when implementing a stack or queue
print(courses ,"Popped -->" ,popped)
courses.reverse() ## reverses our list
print(courses)
nested_list = courses.pop() ## cannot sort nested lists. so, we remove the last element, which is a list
courses.sort() ## sorts in alphabetical order. ## For Numbers, sorts by ascending order
print(courses)
courses.sort(reverse=True) ## sorts in **Reverse**alphabetical order.
print(courses)
sorted_list = sorted(courses) # sorting without changing the original array
print("sorted ->" ,sorted_list)
print(courses.index('art')) # position of element in list
print('art' in courses) # To get a true or false value
for item in courses:
print(item)
for idx , item in enumerate(courses):
print(idx, "->" ,item)
print("--------------------------------")
for idx , item in enumerate(courses , start = 2):
print(idx, "->" ,item)
courses_str = ', '.join(courses) ## turns into a single comma separated string
print(courses_str)
new_list = courses_str.split(', ')
print("New List =", new_list)
## Lists are mutable (modifiable),
# Tuples are not mutable (not modifyable)
list_1 = ['History' , 'Math' , 'Physics']
list_2 = list_1
list_1[0] = 'Art'
print(list_1)
print(list_2) ## so, values in both lists are changed, since they are referenced
#Immutable
tuple_1 = ('History' , 'Math' , 'Phy')
tuple_2 = tuple_1
# tuple_1[0] = 'Art' -> not possible, since it is immutable. (So, we cannot change a list)
print(tuple_1)
print(tuple_2)
| true |
49c8c5504bf0d1932ef3f7b3a294e7577fd1be7b | antoni-g/programming-dump | /vgg/manhattan.py | 875 | 4.25 | 4 | # The following method get the manhatten distance betwen two points (x1,y1) and (x2,y2)
def manhattan_distance(x1, y1, x2, y2):
return abs(x1 - x2) + abs(y1 - y2)
def convert(l):
try:
l[0] = float(l[0])
l[1] = float(l[1])
except ValueError:
print("An input character was not a number.")
exit()
# Enter your code here. Read input from STDIN. Print output to STDOUT
point1AsAString = input().strip()
point2AsAString = input().strip()
# Need to parse each point and find the distance between them using the supplied manhattan_distance method
l1=point1AsAString.split(" ")
l2=point2AsAString.split(" ")
# verify
if (len(l1) != 2 or len(l2) != 2):
print ("Invalid number of arguments for coordinates. Need x and y space separated with one point per line")
exit()
#convert and verify
convert(l1)
convert(l2)
print(manhattan_distance(l1[0],l1[1],l2[0],l2[1]))
| true |
93e74790f44f6720f7778dd243943bd3115289d7 | andersondev96/Curso-em-Video-Python | /Ex014.py | 228 | 4.21875 | 4 | # Escreva um programa que converta uma temperatura digitada em ºC para ºF
celsius = float(input('Digite uma temperatura em ºC: '))
fareheit = 9 * celsius/5 + 32
print('{}ºC equivale a {:.1f}ºF.' .format(celsius, fareheit)) | false |
8f028989552dda6b9bd311d060593842a0ff2a59 | andersondev96/Curso-em-Video-Python | /Ex031.py | 572 | 4.125 | 4 | """
Desenvolva um programa que pergunte a distância de uma viagem em Km.
Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de
até 200Km e R$0,45 parta viagens mais longas.
"""
distancia = float(input('Digite a distancia da viagem: '))
print('Você está prestes a começar uma viagem de {}Km.'.format(distancia))
passagem = distancia * 0.50 if distancia <= 200 else distancia * 0.45
'''if distancia <= 200:
passagem = 0.50 * distancia
else:
passagem = 0.45 * distancia'''
print('E o preço da sua passagem será de R${:.2f}'.format(passagem)) | false |
657a00ade5ec77aa9c1941825188b32b10eb8146 | choroba/perlweeklychallenge-club | /challenge-200/sgreen/python/ch-2.py | 1,017 | 4.1875 | 4 | #!/usr/bin/env python3
import sys
def print_row(line, numbers):
row = []
for n in numbers:
if type(line) == str:
# We want to show a solid line
if line in n:
row.append('-------')
else:
row.append(' ')
else:
# We have a left side and right side
left = '|' if line[0] in n else ' '
right = '|' if line[1] in n else ' '
row.append(f'{left} {right}')
print(*row, sep=' ')
def main(n):
# Turn the numbers into a list of strings to show
truth = 'abcdef bc abdeg abcdg bcfg acdfg acdefg abc abcdefg abcfg'.split(
' ')
numbers = [truth[int(i)] for i in n]
# Define the lines we want to show
lines = [
'a',
['f', 'b'],
['f', 'b'],
'g',
['e', 'c'],
['e', 'c'],
'd'
]
for line in lines:
print_row(line, numbers)
if __name__ == '__main__':
main(sys.argv[1])
| false |
2b609dccec107322e639da52fcaa496e1be3200f | choroba/perlweeklychallenge-club | /challenge-228/pokgopun/python/ch-1.py | 698 | 4.125 | 4 | ### Task 1: Unique Sum
### Submitted by: Mohammad S Anwar
### You are given an array of integers.
###
### Write a script to find out the sum of unique elements in the given array.
###
### Example 1
### Input: @int = (2, 1, 3, 2)
### Output: 4
###
### In the given array we have 2 unique elements (1, 3).
### Example 2
### Input: @int = (1, 1, 1, 1)
### Output: 0
###
### In the given array no unique element found.
### Example 3
### Input: @int = (2, 1, 3, 4)
### Output: 10
###
### In the given array every element is unique.
def sumOfUniqElem(tup): return sum(tuple(filter(lambda x: tup.count(x)==1, tup)))
for tup, s in ((2,1,3,2), 4), ((1,1,1,1), 0), ((2,1,3,4), 10): assert sumOfUniqElem(tup)==s
| true |
0410ee45731cc27f26fd509d21b5e8c37e7fcd0f | choroba/perlweeklychallenge-club | /challenge-025/lubos-kolouch/python/ch-2.py | 2,635 | 4.59375 | 5 | def chaocipher_encrypt(message: str) -> str:
"""
Encrypts a message using the Chaocipher algorithm.
Chaocipher is a symmetric encryption algorithm that uses two mixed alphabets to
perform a double substitution on each letter of the plaintext. The two alphabets
are predetermined and fixed.
Args:
message: The message to be encrypted.
Returns:
The encrypted message.
"""
# Define the Chaocipher alphabets
left_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
right_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
ciphertext = ""
left_index = 0
right_index = 0
# Loop through each character in the message
for char in message.upper():
if not char.isalpha():
# Ignore non-alphabetic characters
ciphertext += char
continue
# Find the index of the character in the left alphabet
left_char_index = left_alphabet.index(char)
# Swap the left and right indices
left_index, right_index = right_index, left_index
# Find the corresponding character in the right alphabet
right_char_index = (left_char_index + right_index) % 26
right_char = right_alphabet[right_char_index]
# Append the encrypted character to the ciphertext
ciphertext += right_char
return ciphertext
def chaocipher_decrypt(ciphertext: str) -> str:
"""
Decrypts a message that has been encrypted using the Chaocipher algorithm.
Args:
ciphertext: The message to be decrypted.
Returns:
The decrypted message.
"""
# Define the Chaocipher alphabets
left_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
right_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
plaintext = ""
left_index = 0
right_index = 0
# Loop through each character in the ciphertext
for char in ciphertext.upper():
if not char.isalpha():
# Ignore non-alphabetic characters
plaintext += char
continue
# Find the index of the character in the right alphabet
right_char_index = right_alphabet.index(char)
# Swap the left and right indices
left_index, right_index = right_index, left_index
# Find the corresponding character in the left alphabet
left_char_index = (right_char_index - right_index) % 26
left_char = left_alphabet[left_char_index]
# Append the decrypted character to the plaintext
plaintext += left_char
return plaintext
# Example usage
message = "Hello World!"
ciphertext = chaocipher_encrypt(message)
print(f"Ciphertext: {ciphertext}")
plaintext = chaocipher_decrypt(ciphertext)
print(f"Plaintext: {plaintext}")
| true |
8c7d82cd01beb8066fb38276e41783c950a5027d | choroba/perlweeklychallenge-club | /challenge-208/lubos-kolouch/python/ch-2.py | 1,435 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import List, Tuple, Union
def find_missing_and_duplicate(nums: List[int]) -> Union[Tuple[int, int], int]:
"""
Finds the duplicate and missing integer in a given sequence of integers.
Args:
nums (List[int]): A list of integers with one missing and one duplicate.
Returns:
Union[Tuple[int, int], int]: If both a missing and duplicate integer are found, returns a tuple
containing the duplicate integer followed by the missing integer. If none are found, returns -1.
Example:
>>> find_missing_and_duplicate([1, 2, 2, 4])
(2, 3)
>>> find_missing_and_duplicate([1, 2, 3, 4])
-1
>>> find_missing_and_duplicate([1, 2, 3, 3])
(3, 4)
"""
count = {}
missing = 0
duplicate = 0
for num in nums:
count[num] = count.get(num, 0) + 1
if count[num] > 1:
duplicate = num
for i in range(1, len(nums) + 2):
if i not in count:
missing = i
break
if missing and duplicate:
return (duplicate, missing)
else:
return -1
# Run the tests
def test_find_missing_and_duplicate():
assert find_missing_and_duplicate([1, 2, 2, 4]) == (2, 3)
assert find_missing_and_duplicate([1, 2, 3, 4]) == -1
assert find_missing_and_duplicate([1, 2, 3, 3]) == (3, 4)
test_find_missing_and_duplicate()
| true |
67e59949be5273b74bd40126657c52ad8022feec | choroba/perlweeklychallenge-club | /challenge-212/manfredi/python/ch-1.py | 1,080 | 4.125 | 4 | #!/usr/bin/env python3
# Python 3.9.2 on Debian GNU/Linux 11 (bullseye)
print('challenge-212-task1')
# Task 1: Jumping Letters
# You are given a word having alphabetic characters only, and a list of positive integers of the same length
# Write a script to print the new word generated after jumping forward each letter in the given word by the integer in the list.
# The given list would have exactly the number as the total alphabets in the given word.
def jumping_letters(word: str, jump: list[int]) -> None:
lower = [ c.islower() for c in word ]
ascii = [ ord(c.upper()) for c in word ]
ascii_ord = [ (o + jump[i]) if (o + jump[i]) < ord('Z') else ((o + jump[i]) + ord('A') - 1 ) % (ord('Z')) for i, o in enumerate(ascii) ]
res = ''.join([ str(chr(c)).lower() if lower[i] else str(chr(c)) for i, c in enumerate(ascii_ord)])
print(f"{word}, '{jump}': {res}")
def main():
word, jump = 'Perl', [2, 22, 19, 9]
jumping_letters(word, jump)
word, jump = 'Raku', [24, 4, 7, 17]
jumping_letters(word, jump)
if __name__ == '__main__':
main()
| true |
e0fc6f2aaee11b9eb1cf92e1db5a0030d047aec9 | choroba/perlweeklychallenge-club | /challenge-206/spadacciniweb/python/ch-1.py | 1,732 | 4.25 | 4 | # Task 1: Shortest Time
# Submitted by: Mohammad S Anwar
#
# You are given a list of time points, at least 2, in the 24-hour clock format HH:MM.
# Write a script to find out the shortest time in minutes between any two time points.
#
# Example 1
# Input: @time = ("00:00", "23:55", "20:00")
# Output: 5
#
# Since the difference between "00:00" and "23:55" is the shortest (5 minutes).
#
# Example 2
# Input: @array = ("01:01", "00:50", "00:57")
# Output: 4
#
# Example 3
# Input: @array = ("10:10", "09:30", "09:00", "09:55")
# Output: 15
import re
import sys
from itertools import combinations
def get_minutes(t):
return 60 * int(t[0:2]) + int(t[3:5])
def get_diff_minutes(m1, m2):
res = abs(m1-m2)
if (res >= 720): # 12h * 60 = minutes
return 1440 - res # 24h * 60 = minutes
return res
if __name__ == "__main__":
input = sys.argv[1:]
if (len(input) < 2
or
len(list(filter(lambda x: re.search(r'\d\d:\d\d', x), input))) != len(input)
or
len(list(filter(lambda x: x > '24:00', input))) != 0 ):
sys.exit("Input error")
minutes = [get_minutes(x) for x in input]
comb = combinations(range(len(input)), 2)
h_minutes = {
'val': None,
'pair': None
}
for pair in list(comb):
diff_minutes = get_diff_minutes(minutes[pair[0]], minutes[pair[1]])
if h_minutes['val'] == None or h_minutes['val'] > diff_minutes:
h_minutes['val'] = diff_minutes
h_minutes['pair'] = pair
print(h_minutes['val'])
print("Since the difference between \"{:s}\" and \"{:s}\" is the shortest ({:d} minutes).".format(input[ h_minutes['pair'][0] ], input[ h_minutes['pair'][1] ], h_minutes['val'] ))
| true |
c8ca87012b85e47b31c3de061e2f614fc3c0b936 | choroba/perlweeklychallenge-club | /challenge-034/lubos-kolouch/python/ch-2.py | 1,111 | 4.40625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Define a function to add two numbers
def add(a, b):
return a + b
# Define a function to subtract two numbers
def subtract(a, b):
return a - b
# Define a function to multiply two numbers
def multiply(a, b):
return a * b
# Define a function to divide two numbers
def divide(a, b):
return a / b
# Define a dispatch table that maps operation names to functions
operation_table = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
# Define a function that takes an operation name and two numbers, and performs the operation
def perform_operation(operation, a, b):
if operation in operation_table:
return operation_table[operation](a, b)
else:
raise ValueError(f"Unknown operation '{operation}'")
# Test the dispatch table by performing some operations
print(perform_operation("add", 2, 3)) # Output: 5
print(perform_operation("subtract", 5, 1)) # Output: 4
print(perform_operation("multiply", 4, 6)) # Output: 24
print(perform_operation("divide", 10, 2)) # Output: 5
| true |
0d747cbd92407a75a2bc104bf5dbe0968dc9e372 | choroba/perlweeklychallenge-club | /challenge-023/lubos-kolouch/python/ch-2.py | 1,466 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from typing import List
def prime_decomposition(n: int) -> List[int]:
"""
Compute the prime factors of a number.
Args:
n: An integer greater than or equal to 2.
Returns:
A list of prime factors of the input number.
Raises:
ValueError: If the input number is less than 2.
"""
if n < 2:
raise ValueError("Number should be greater than or equal to 2")
factors = []
d = 2
# Divide the number by prime factors
while n > 1:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if d * d > n and n > 1:
factors.append(n)
break
return factors
# Test cases
def test_prime_decomposition():
assert prime_decomposition(228) == [2, 2, 3, 19]
assert prime_decomposition(131) == [131]
assert prime_decomposition(101) == [101]
try:
prime_decomposition(1)
except ValueError:
pass
else:
assert False, "Expected ValueError for input 1"
if __name__ == '__main__':
# Parse command line argument
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <number>")
sys.exit(1)
n = int(sys.argv[1])
# Compute the prime decomposition
factors = prime_decomposition(n)
# Print the prime factors
print(", ".join(str(f) for f in factors))
# Run tests
test_prime_decomposition()
| true |
9f5bef0b4d288b4f35fa4f7dd3e300ea5cdf95e2 | choroba/perlweeklychallenge-club | /challenge-228/spadacciniweb/python/ch-1.py | 868 | 4.125 | 4 | # Task 1: Unique Sum
# Submitted by: Mohammad S Anwar
#
# You are given an array of integers.
# Write a script to find out the sum of unique elements in the given array.
#
# Example 1
# Input: @int = (2, 1, 3, 2)
# Output: 4
#
# In the given array we have 2 unique elements (1, 3).
#
# Example 2
# Input: @int = (1, 1, 1, 1)
# Output: 0
#
# In the given array no unique element found.
#
# Example 3
# Input: @int = (2, 1, 3, 4)
# Output: 10
#
# In the given array every element is unique.
import re
import sys
if __name__ == "__main__":
input = sys.argv[1:]
if (len(input) < 1
or
len(list(filter(lambda x: re.search(r'[^\-\d]', x), input))) != 0):
sys.exit("Input error\n")
ints = list(map(int, input))
freq = dict((i, ints.count(i)) for i in set(ints))
print( sum( list(filter(lambda x: freq.get(x) == 1, freq.keys())) ) )
| true |
3a5da53de265165f484f3df00a716bd2f67b2577 | HelmuthMN/python-studies | /begginer_projects/acronym.py | 227 | 4.25 | 4 | print("Enter the full meaning and we provide the acronym.")
acronym = " "
meaning = input("Full Meaning: ")
phrase = (meaning.replace('of', '')).split()
for word in phrase:
acronym = acronym + word[0].upper()
print(acronym) | true |
5386874a6d1a078920d9f974deef7ad565d4e9f7 | ssoto/five-programming-problems-1hour | /00_first/00-for-loop.py | 962 | 4.3125 | 4 | #!/bin/python
# -*- coding: utf-8 -*-
# starts at 20:28 sun 10 may
# end at 21:12 sun 10 may
# DO IT FOR-EACH WAY:
# METHOD=0
# WHILE WAY:
# METHOD=1
# RECURSIVE WAY:
# METHOD=2
METHOD=2
def for_loop (array):
for element in array:
print "element " , array.index(element) , " => " , str(element)
def while_loop (array):
for i in range (0, len(array)+1):
print array[i]
def for_recursive(array, depth=0):
if len(array) == 1:
print array[0]
elif len(array) == 2:
for_recursive( [array[0]], depth)
for_recursive( [array[1]], depth)
else:
for_recursive( [array[0]], depth)
for_recursive( array[1:len(array)-1], depth)
if __name__ == "__main__":
array = (0,1,2,3,4,5)
if METHOD == 0:
for_loop (array)
elif METHOD == 1:
for_loop (array)
elif METHOD == 2:
for_recursive(array)
else:
print "Error. Method only can be 0,1 or 2"
| false |
f13d007eea6e94814615fc1c33abd4eb5f3df379 | JoseSerrano22/basic-calculator-recursion | /main.py | 1,473 | 4.1875 | 4 | import art
print(art.logo)
def add(n1,n2):
result = n1+n2
return result
def substract(n1,n2):
result = n1-n2
return result
def mult(n1,n2):
result = n1*n2
return result
def div(n1,n2):
result = n1/n2
return result
operations = { #dictionary of funcions
"+": add,
"-": substract,
"*": mult,
"/": div
}
def calculator():
num1 = float(input("What is your first number?: "))
for key in operations: #print operations
print(key)
symbol = input("Which operation you gonna use from above?: ")
num2 = float(input("What is your second number?: "))
function = operations[symbol]
result = function(num1,num2) #result of the user's operation
print(f"{num1} {symbol} {num2} = {result}")
again = input(f"Type 'y' to continue with calculating {result}, or 'n' to have new slate: ")
if again == "y": #if true repeat with the result
while True:
for key in operations:
print(key)
symbol = input("Which operation you gonna use from above?: ")
num2 = float(input("What is your second number?: "))
function = operations[symbol]
result = function(result,num2)
print(f"{result} {symbol} {num2} = {result}")
again = input(f"Type 'y' to continue with calculating {result}, or 'n' to have a new slate: ")
if(again == "n"): #if no repeat the calculator again from zero
calculator() # recursion for a new slate
elif again == "n":
calculator()
calculator() | true |
45e80eb9a45952dc622f98a4fc1afd5c20d49a4b | z875759270/Learning-Python-100-Days | /day6/day6.py | 1,786 | 4.125 | 4 | # %%
""" 定义一个函数
def add(a,b):
return a+b
print(add(1,5))
"""
# %%
""" 重载的另一种实现(指定参数的默认值)
def two(a=1,b=2):
return a+b
print(two())
print(two(2,3))
"""
# %%
""" 不确定参数个数时可以使用可变参数 (在参数名前面添加 ‘ * ’)
def three(*args):
sum=0
for x in args:
sum+=x
return sum
print(three())
print(three(1,3,5,8))
"""
# %%
""" 不同模块(模块即文件)可以存在相同名字的函数
# 区分方法1(个人推荐)
import demo1 as d1
import demo2 as d2
d1.ccc()
d2.ccc()
# 区分方法2(顺序很重要)
from demo1 import ccc
ccc()
from demo2 import ccc
ccc()
"""
# %%
""" 导入模块时会执行该模块的代码 当我们不希望如此时可以使用 if __name__ =='__main__': 详见demo3
import demo3
"""
# %%
""" test1 实现计算求最大公约数和最小公倍数的函数
def gcd(x, y):
# 求最大公约数
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor
def lcm(x, y):
#求最小公倍数
return x * y // gcd(x, y)
"""
# %%
""" test2 实现判断一个数是不是回文数的函数 """
def is_hws(a):
temp=a
hws=0
while temp>0:
hws=hws*10+temp%10
temp //= 10
return hws==a
# %%
""" 实现判断一个数是不是素数的函数 """
def is_prime(num):
for i in range(2,num):
if num%i==0:
return False
return True
# %%
""" 判断输入的正整数是不是回文素数 """
if __name__=="__main__":
num=int(input('请输入正整数:'))
if is_hws(num) and is_prime(num):
print('%d是回文素数' % num)
else:
print('%d不是回文素数' % num) | false |
a699bb554458b43e6a6418f8e1eff32feb139eaa | maxthemouse/myhpsc | /homework/homework2/hw2a.py | 1,143 | 4.125 | 4 | """
Demonstration script for quadratic interpolation.
Update this docstring to describe your code.
Modified by: M. Adam Webb
"""
import numpy as np
import matplotlib.pyplot as plt
from numpy.linalg import solve
# Set up linear system to interpolate through data points:
# Data points:
xi = np.array([-1., 1., 2])
yi = np.array([0., 4., 3.])
# It would be better to define A in terms of the xi points.
# Doing this is part of the homework assignment.
A = np.array([[1., -1., 1.], [1., 1., 1.], [1., 2., 4.]])
b = yi
# Solve the system:
c = solve(A, b)
print "The polynomial coefficients are:"
print c
# Plot the resulting polynomial:
x = np.linspace(-2, 3, 1001) # points to evaluate polynomial
y = c[0] + c[1] * x + c[2] * x ** 2
plt.figure(1) # open plot figure window
plt.clf() # clear figure
plt.plot(x, y, 'b-') # connect points with a blue line
# Add data points (polynomial should go through these points!)
plt.plot(xi, yi, 'ro') # plot as red circles
plt.ylim(-2, 8) # set limits in y for plot
plt.title("Data points and interpolating polynomial")
plt.savefig('hw2a.png') # save figure as .png file
| true |
62f7db3c1ef8193c9ab4a786f20e9ee36090d51a | broccoli-farm/master | /01/08.py | 1,024 | 4.15625 | 4 | """
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
英小文字ならば(219 - 文字コード)の文字に置換
その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
"""
#ord()関数で英小文字をUnicodeコードポイントに変換
#chr()関数に219-(取得した数値)で暗号処理を行う。
def cipher(text):
ans = ""
for i in text:
if i.islower(): #すべての文字が小文字かどうか判定 ※文字列型じゃ無いと無理?
ans += chr(219 - ord(i))
else:
ans += i
return ans
t = input("暗号化,複合化をします.文字列を入れてね")
a = cipher(t)
print("暗号化 " + a)
f = cipher(a)
print("復号化 " + f)
"""
文字列apple
暗号化 zkkov
復号化 apple
暗号化,複合化をします.文字列を入れてねI am Sakura
暗号化 I zn Szpfiz
復号化 I am Sakura
"""
| false |
15304d525c86ddae9436c54cabd2c0360d0cddab | AlyoshaS/codes | /startingPoint/01-EstruturasCondicionais/exercicios_resolvidos/00.py | 539 | 4.125 | 4 | """
**00** - Faça um programa que receba quatro notas de um aluno, calcule e mostre a média aritmética das notas e a
mensagem de aprovado ou reprovado, considerando para aprovação média 7.
"""
nota1 = int(input("Digite a primeira nota: "))
nota2 = int(input("Digite a segunda nota: "))
nota3 = int(input("Digite a terceira nota: "))
nota4 = int(input("Digite a quarta nota: "))
media = (nota1 + nota2 + nota3 + nota4) / 4
print("Média aritmética: ", media)
print("aprovado" if media >= 7 else "Reprovado")
| false |
095b75f2c665593faf6c469773742a99b02bf2b5 | AlyoshaS/codes | /startingPoint/02-EstruturaSequencial/Exercicios_Propostos/21.py | 442 | 4.1875 | 4 | #!/usr/bin/python
# coding: latin-1
"""21 - Faça um programa que receba um número real, calcule e mostre:
- a parte inteira desse número;
- a parte fracionária desse número;
- o arredondamento desse número"""
num = float(input("Digite o numero: "))
i = int(num)
f = num - i
a = round(num)
print("A parte inteira desse número: ", i, "\nA parte fracionária desse número: ", f, "\nO arredondamento desse número: ", a)
| false |
c07fba06c649594cee345c31c1a69a387ef8ea6e | AlyoshaS/codes | /Python/PORRA DE EXERCÍCIO/exerciciofb.py | 2,281 | 4.28125 | 4 | """
Faça um programa para uma loja de tintas:
O programa deverá pedir o tamanho em metros quadrados da área a ser pintada.
Considere que a cobertuta da tinta é de 1 litro para cada 6 metros quadrados e que a tinda é vendida em:
latas de 18 litros, que custam R$ 80,00 ou em galões da 4 litros, que custam R$ 25,00.
Informe ao usuário as quantidades de tinta a serem compradas e os respectivos preços em 3 situações:
comprar apenas latas de 18 litros;
comprar apenas galões de 4 litros;
misturar latas e galões, de forma que o preço seja o menor.
Acrescente 10% de folga e sempre arredonde os valores para cima, isto é, considere latas cheias!
Dica: Você usará Int(), //, % e if.
"""
# Recebe os dados do usuario:
metros_quadrados = int(input("Digite a área a ser pintada em metros quadrados(m²): "))
# Define a folga de tinta, quantidade de litros por área, de latas, galões e o preco da lata e do galao:
litros = metros_quadrados / 6
folga = .10
total_litros = int(litros + (litros * folga))
preco_lata = 80.00
preco_galao = 25.00
# Define total de litros a ser utilizado:
if total_litros %6 > 0:
litros_total = litros + 1
total_litros = int(litros + (litros * folga))
print("A quantidade de litros a ser utilizada: ", total_litros)
# Define a quantidade de tinta a comprar apenas em latas e seu respectivo valor:
latas = total_litros // 18
if total_litros %18 > 0:
quantidade_de_latas = latas + 1
preco_total_latas = round(quantidade_de_latas * preco_lata, 2)
print("Você precisará de ", quantidade_de_latas, "latas de 18 litros e o valor será de R$", preco_total_latas)
# Define a quantidade de tinta a comprar apenas em galoes e seu respectivo valor:
galoes = total_litros // 4
if total_litros %4 > 0:
quantidade_de_galoes = galoes + 1
preco_total_galoes = round(quantidade_de_galoes * preco_galao, 2)
print("Você precisará de ", quantidade_de_galoes, "galões de 4 litros e o valor será de R$", preco_total_galoes)
# Define a quantidade de tinta a comprar em galoes e latas e seus respectivos valores:
if total_litros %18 > 0:
if
total_latas = latas
total_litros % 18
print(total_galoes)
| false |
d54a3e576cc0b2990fb41f48d436d26842acda20 | AlyoshaS/codes | /startingPoint/01-EstruturasCondicionais/exercicios_resolvidos/18.py | 638 | 4.125 | 4 | """
18 - Faça um programa que receba a altura e o sexo de uma pessoa; calcule e mostre seu peso ideal, utilizando as seguintes fórmulas
(onde h é a altura):
* para homens: (72.7 * h) - 58.
* para mulheres: (62.1 * h) - 44.7.
"""
height = float(input("Digite a sua altura: "))
sex = input("Digite o seu sexo(M para mulher ou H para homem): ")
if sex == 'M':
print("O peso ideal para mulheres com altura %.2fm é de %.2fKg." % (height, ((62.1 * height) - 44.7)))
elif sex == 'H':
print("O peso ideal para homens com altura %.2fm é de %.2fKg." % (height, ((72.7 * height) - 58)))
else:
print("Opção incorreta!")
| false |
ab070412a6de8c1479c984d904b2a387e21f0dec | AlyoshaS/codes | /startingPoint/01-EstruturasCondicionais/exercicios_propostos/04.py | 848 | 4.1875 | 4 | """ 4. Faça um programa que receba três números obrigatoriamente em ordem crescente e um quarto número que não siga essa regra,
Mostre, em seguida, os quatro números em ordem decrescente. Suponha que o usuário digitará quatro números diferentes.
"""
n1, n2, n3 = [int(x) for x in input("Digite três números em ordem crescente: ").split()]
n4 = int(input("Digite o número (fora de ordem): "))
if n4 > n3:
print("a ordem decrescente é: {0} - {1} - {2} - {3}".format(n4, n3, n2, n1))
if n4 > n2 and n4 < n3:
print("a ordem decrescente é: {0} - {1} - {2} - {3}".format(n3, n4, n2, n1))
if n4 > n1 and n4 < n2:
print("a ordem decrescente é: {0} - {1} - {2} - {3}".format(n3, n2, n4, n1))
if n4 < n1:
print("a ordem decrescente é: {0} - {1} - {2} - {3}".format(n3, n2, n1, n4))
| false |
0bdf7f0dca7a10df9aa02dacd85424532380af57 | AlyoshaS/codes | /startingPoint/01-EstruturasCondicionais/exercicios_resolvidos/13.py | 1,504 | 4.1875 | 4 | """
**13** - Faça um programa que receba o salário de um funcionário e, usando a tabela a seguir, calcule e mostre o novo salário.
| FAIXA SALARIAL | % DE AUMENTO |
|----------------------------------------|--------------------------------------|
| Até R$ 300,00 | 50% |
| R$ 300,00 °----* R$ 500,00 | 40% |
| R$ 500,00 °----* R$ 700,00 | 30% |
| R$ 700,00 °----* R$ 800,00 | 20% |
| R$ 800,00 °----* R$ 1.000,00 | 10% |
| Acima de R$ 1.000,00 | 5% |
"""
salario = float(input("Digite o valor do salário atual: "))
if (salario < 300):
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.50)))
elif (salario <= 500):
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.40)))
elif (salario <= 700):
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.30)))
elif (salario <= 800):
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.20)))
elif (salario <= 1000):
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.10)))
else:
print("Seu salário líquido será de R$ %.2f." % (salario + (salario * 0.05)))
| false |
40f93e67e8d94aee7f80fdbe458d237f5cbac464 | AlyoshaS/codes | /startingPoint/02-EstruturaSequencial/Exercicios_Resolvidos/02.py | 403 | 4.125 | 4 | # 3. Faça um programa que receba dois números, calcule e mostre a divisão do primeiro número pelo segundo. Sabe-se que o segundo
# número não pode ser zero, portanto, não é necessário se preocupar com validações.
n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número diferente de 0: "))
div = n1 / n2
print("O resultado da divisão é: ", div)
| false |
962115d2a0262c8911c90a2461a8c3b26888aead | AlyoshaS/codes | /startingPoint/02-EstruturaSequencial/Exercicios_Resolvidos/11.py | 676 | 4.15625 | 4 | """
12. Faça um programa que receba o ano de nascimento de uma pessoa e o ano atual, calcule e mostre:
a idade dessa pessoa em anos;
a idade dessa pessoa em meses;
a idade dessa pessoa em dias;
a idade dessa pessoa em semanas.
"""
ano_nasc, ano_atual = [int(x) for x in input("Digite seu ano de nascimento e o ano atual: ").split()]
idade_anos = ano_atual - ano_nasc
idade_meses = idade_anos * 12
idade_dias = idade_meses * 30
idade_semanas = idade_dias / 7
print("A idade em anos é: ", idade_anos)
print("A idade em meses é: ", idade_meses)
print("A idade em dias é: ", idade_dias)
print("A idade em semanas é: ", idade_semanas)
| false |
b895d5454fc57a6796174a3fdd135ed64ec9bd84 | Cyb3rKn1gh7/Python | /HCF-LCM.py | 307 | 4.125 | 4 | #HCF and LCM calculator python
n = float(input("Enter the First Number : "))
n1 = float(input("Enter the Second Number : "))
a,b=n,n1
while(n1 != 0):
t = n1
n1 = n % n1
n = t
lcm=(a*b)/n
print("HCF of {0} and {1} = {2}".format(a, b, n))
print("LCM of {0} and {1} = {2}".format(a, b, lcm))
| false |
536c642ab2156d9eb572b0d2123c6828cd6d4ae6 | Marist-CMPT120-FA19/-Gabi-Gervasi--Lab-3 | /tree.py | 329 | 4.21875 | 4 | def tree():
print("How many branches in the tree")
print()
height = input("Number of Branches : ")
length = int(height)*2-1
space = (length-1)/2
x=1
while x <= int(height):
print (" "* (int(space)- x +1 ), "#"*(2*x-1))
x=x+1
print(" "*(int(height) -1), "#")
tree()
| true |
3302367ec4353353bb979e91bef07b02b8749dcf | FarkasAlex170/siw | /siw-fibonacci.py | 206 | 4.1875 | 4 | how_many = int(input("How many numbers would you like to see?: "))
a = 0
b = 1
fib = 0
for i in range(how_many):
print("#", i + 1, "a=", a, "b=", b, "fib=", a + b)
fib = a + b
a = b
b = fib | false |
b5268fb1ecee82958548337949e83a396dc63a3a | nguyendatvn/DATACAMPPYTHON | /Intermediate Python for Data Science/Dictionaries & Pandas/ex2.py | 800 | 4.5 | 4 | # Definition of countries and capital
countries = ['spain', 'france', 'germany', 'norway']
capitals = ['madrid', 'paris', 'berlin', 'oslo']
# Get index of 'germany': ind_ger
ind_ger = countries.index("germany")
# # Use ind_ger to print out capital of Germany
# print(capitals[ind_ger])
# From string in countries and capitals, create dictionary europe
europe = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo'}
# # Print europe
# print(europe)
#
# # Print out the keys in europe
# print(europe.keys())
#
# # Print out value that belongs to key 'norway'
# print(europe['norway'])
# Add italy to europe
europe['italy'] = 'rome'
# # Print out italy in europe
# print('italy' in europe)
# Add poland to europe
europe['poland'] = 'warsaw'
# # Print europe
# print(europe)
| false |
49eb017ae455509a32fda6f5073bf032b79334e2 | kawing13328/Basics | /My Homework/Ex_9-3.py | 1,634 | 4.84375 | 5 | """9-3: Users
1. Make a class called User. Create two attributes called first_name and last_name,
and then 2. create several other attributes that are typically stored in a user profile.
3. Make a method called describe_user() that prints a summary of the user’s information.
4. Make another method called greet_user() that prints a personalized greeting to the user.
5. Create several instances representing different users, and call both methods for each user."""
class User(): # step 1.
"""Represent a simple user profile."""
def __init__(self, first_name, last_name, username, email, location, age: int):
"""Initialize the user."""
self.first_name = first_name.title() # Step 2. (Line12 to Line 17)
self.last_name = last_name.title()
self.username = username
self.email = email
self.location = location.title()
self.age = age
def describe_user(self): # Step 3.
"""Display a summary of the user's information."""
print("Profile as follows:")
print(f"\n {self.first_name} {self.last_name}")
print(f" Username: {self.username}")
print(f" Email: {self.email}")
print(f" Location: {self.location}")
print(f" Age:{self.age}")
def greet_user(self): # Step 4.
"""Display a personalized greeting to the user."""
print("\nWelcome back, " + self.username + "!")
albert = User('albert', 'joes', 'a_joes', 'a_joes@example.com', 'brooklyn', 18)
albert.describe_user()
albert.greet_user()
bonnie = User('bonnie', 'greenman', 'bgreen', 'bgreen@example.com', '', 30)
bonnie.describe_user()
bonnie.greet_user()
| true |
9fb1a32d7c0817bca54b6c4caa894821950f70f0 | kawing13328/Basics | /My Homework/Ex_6-7.py | 2,226 | 4.46875 | 4 | countries = ['usa', 'russia', 'spain']
cities = ['new york', 'moscow', 'barceloca']
companies = ['level up', 'abc company', 'ola company']
customers =[companies, cities, countries]
# 6-7. People: Start with the program you wrote for Exercise 6-1 (page 102). first_name, last_name, age, city they live
# Make two new dictionaries representing different people, and store all three dictionaries in a list called people.
# Loop through your list of people. As you loop through the list, print everything you know about each person.
print("***** Ex 6-7 *****")
friend1 = {'first_name': 'mathew', 'last_name': 'cheung', 'age': 38, 'city': 'toronto'} #dict1
friend2 = {'first_name': 'marcus', 'last_name': 'sujan', 'age': 40, 'city': 'hong kong'} #dict2
friend3 = {'first_name': 'robert', 'last_name': 'white', 'age': 20, 'city': 'paris'} #dict3
people = { #3 sub-dicts in 1 big dict
'friend1' : {'first_name': 'mathew', 'last_name': 'cheung', 'age': 38, 'city': 'toronto'},
'friend2' : {'first_name': 'marcus', 'last_name': 'sujan', 'age': 40, 'city': 'hong kong'},
'friend3' : {'first_name': 'robert', 'last_name': 'white', 'age': 20, 'city': 'paris'}
}
print(people) # all details in people
print(friend1.keys())
for key, value in people.items():
print(key)
print(value)
print (people['friend1']['last_name'])
print("***** Model Answer *****")
# Make an empty list to store people in.
people = []
# Define some people, and add them to the list.
person = {
'first_name': 'eric',
'last_name': 'matthes',
'age': 43,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'ever',
'last_name': 'matthes',
'age': 5,
'city': 'sitka',
}
people.append(person)
person = {
'first_name': 'willie',
'last_name': 'matthes',
'age': 8,
'city': 'sitka',
}
people.append(person)
# Display all of the information in the dictionary.
for person in people:
name = person['first_name'].title() + " " + person['last_name'].title()
age = str(person['age'])
city = person['city'].title()
print(f' {name}; He / She is from {city} who is {age} years old.') | false |
3e7903b6dec9f72cf5e9f88ec4abcdc9499fc5c6 | rraj29/ProgramFlow | /searching2.py | 1,004 | 4.25 | 4 | shopping_list = ["milk", "pazzta", "eggs","spam", "bread", "rice"]
item_to_find = "albatross"
#The next initialization is important if the item is not found in the list. Otherwise we'll get error.
found_at = None
#we are searching for something, we need to find the index at which it is located
#for index in range(6)
# for index in range(len(shopping_list)):
# if shopping_list[index] == item_to_find:
# found_at = index
# break
#Python has some inbuilt functions that make it a good language. An example of that shown below:
if item_to_find in shopping_list:
found_at = shopping_list.index(item_to_find)
if found_at is not None:
print("Item found at position {0}".format(found_at))
else:
print("{0} not found".format(item_to_find))
#BREAK gets us out of the loop completely. and staright away moves to print statement.
#This saves a lot of time, suppose the list was 1000 variables long,
#then iterating over it even after we found the position would be useless. | true |
b0784098e30c43588a5dcd5535006eb7f8b44ef1 | kajili/interview-prep | /src/cracking_the_coding_interview/ch_01_arrays_and_strings/Q1_04_PalindromePermutation.py | 1,178 | 4.25 | 4 | # CTCI Question 1.4 Palindrome Permutation
# Given a string, write a function to check if it is a permutation of a palindrome.
# A palindrome is a word or phrase that is the same forwards and backwards.
# A permutation is a rearrangement of letters.
# The palindrome does not need to be limited to just dictionary words.
# EXAMPLE
# Input: Tact Coa
# Output: True (permutations: "taco cat", "atco eta", etc.)
def palindromePermutation(string):
# preprocess the string to all lowercase and remove spaces
string = string.lower().replace(' ', '')
# generate hash table with characters as keys and number of occurrences as values
palindrome_hash_map = {}
for char in string:
if char not in palindrome_hash_map:
palindrome_hash_map[char] = 1
else:
palindrome_hash_map[char] += 1
# iterate through hash table and store a countOddValue counter, if it goes above 1 then return False
countOddValue = 0
for char in palindrome_hash_map:
isOdd = palindrome_hash_map[char] % 2 != 0
if isOdd:
countOddValue += 1
if countOddValue > 1:
return False
return True
| true |
6e223b5094b02006b3c9e7275b414e114bd4130b | mouday/SomeCodeForPython | /test_from_myself/测试练习/面向对象/1.创建类.py | 2,055 | 4.21875 | 4 | # 创建类
class Employee(object):
"""所有员工的基类"""
empCount = 0 # 类变量
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name: %s Salary: %d" % (self.name, self.salary))
# 创建 Employee 类的对象
employeeA = Employee("Tom", 2000)
employeeB = Employee("Jack", 2500)
employeeC = Employee("Jimi", 3000)
# 访问数据成员
# 访问类变量
print(Employee.empCount) # 使用类名称访问类变量 3
# 访问实例变量
# 添加,删除,修改类的属性
employeeA.age = 23 # 添加
employeeA.age = 24 # 修改
del employeeA.age # 删除
setattr(employeeB, "age", 25) # 设置属性,不存在则新建
print(hasattr(employeeB, "age")) # 检查属性存在 True
print(getattr(employeeB,"age")) # 访问对象属性 25
delattr(employeeB, "age") # 删除属性
# 访问对象方法
employeeA.displayCount() # Total Employee 3
employeeA.displayEmployee() # Name: Tom Salary: 2000
employeeB.displayEmployee() # Name: Jack Salary: 2500
employeeC.displayEmployee() # Name: Jimi Salary: 3000
# 内置类属性
print(Employee.__doc__) # 打印类文档 所有员工的基类
print(Employee.__name__) # 类名 Employee
print(Employee.__module__) # 类定义所在的模块 __main__
print(Employee.__base__) # tuple 类的所有父类<class 'object'>
print(Employee.__dict__) # dict 类的属性(由类的数据属性组成)
"""
{
'__dict__': <attribute '__dict__' of 'Employee' objects>,
'__init__': <function Employee.__init__ at 0x0000000001263A60>,
'__weakref__': <attribute '__weakref__' of 'Employee' objects>,
'__module__': '__main__',
'__doc__': '所有员工的基类',
'empCount': 3,
'displayCount': <function Employee.displayCount at 0x0000000001263AE8>,
'displayEmployee': <function Employee.displayEmployee at 0x0000000001263E18>
}
"""
| false |
9f102c93e36f09140eb08ab9954101c59a229de9 | mouday/SomeCodeForPython | /test_from_myself/leetcode/760. Find Anagram Mappings.py | 1,178 | 4.125 | 4 | """
760. Find Anagram Mappings
Given two lists Aand B, and B is an anagram of A.
B is an anagram of A means B is made by randomizing the order of the elements in A.
We want to find an index mapping P, from A to B.
A mapping P[i] = j means the ith element in A appears in B at index j.
These lists A and B may contain duplicates. If there are multiple answers, output any of them.
For example, given
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
We should return
[1, 4, 3, 2, 0]
as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.
Note:
A, B have equal lengths in range [1, 100].
A[i], B[i] are integers in range [0, 10^5].
"""
class Solution:
def anagramMappings(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
c = []
for i in A:
index = B.index(i)
c.append(index)
return c
# return [B.index(a) for a in A]
if __name__ == '__main__':
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
s = Solution()
res = s.anagramMappings(A, B)
print(res) | true |
a3547b570eda2bc5890118e8813abac1104dedd6 | mouday/SomeCodeForPython | /test_from_myself/测试练习/dict简单数据库.py | 564 | 4.125 | 4 | #dict简单数据库.py
#使用人名作为字典的键,每个人又用另一个字典表示
people={
"Alice":{
"phone":"2341",
"addr":"foot drive 23"
},
"Beth":{
"phone":"9012",
"addr":"bar street 42"
},
"Cecil":{
"phone":"3154",
"addr":"Baz avenue 90"
}
}
#描述性标签
labels={
"phone":"phone number",
"addr":"address"
}
name=input("Name:")
request=input("查找带电话(p)还是地址(a)?")
if request[0]=="p": key="phone"
if request[0]=="a": key="addr"
if name in people:
print("%s %s is %s"%(name,labels[key],people[name][key]))
| false |
8669143fd6031d8032ee958845f5623f5e473974 | mouday/SomeCodeForPython | /test_from_myself/设计模式/2.简单工厂模式.py | 1,193 | 4.625 | 5 | # 设计模式之简单工厂模式
# http://mp.weixin.qq.com/s/3J0hq3I95iKnbT5YjniZVQ
"""
简单工厂模式:
专门定义一个 工厂类 来负责创建 产品类 的实例,被创建的产品通常都具有共同的父类。
三个角色:
简单工厂(SimpleProductFactory)角色
抽象产品(Product)角色
具体产品(Concrete Product)角色
"""
# 抽象产品
class Fruit(object):
def produce(self):
print("Fruit is prodeced")
# 具体产品
class Apple(Fruit):
def produce(self):
print("Apple is produced")
class Banana(Fruit):
def produce(self):
print("Banana is produced")
# 简单工厂
class Factory(object):
def produceFruit(self, fruit_name):
if fruit_name == "apple":
return Apple()
elif fruit_name == "banana":
return Banana()
else:
return Fruit()
if __name__ == '__main__':
factory = Factory()
apple = factory.produceFruit("apple")
apple.produce()
banana = factory.produceFruit("banana")
banana.produce()
fruit = factory.produceFruit("fruit")
fruit.produce()
"""
Apple is produced
Banana is produced
Fruit is prodeced
""" | false |
d4a618dbff9c023f636126babb245f533da50a08 | abmish/pyprograms | /100Py/Ex37.py | 282 | 4.125 | 4 | """
Define a function which can generate and print a list where the values are square of numbers between 1 and 20
(both included).
"""
def num_square_list(num):
sq_list = list()
for i in range(1, num+1):
sq_list.append(i ** 2)
print sq_list
num_square_list(20) | true |
be8d6f2cc44daeca5e03c98ff560e8eccb351f5c | abmish/pyprograms | /100Py/Ex2.py | 556 | 4.1875 | 4 | """
Write a program which can compute the factorial of a given list of comma-separated numbers.
The results should be printed in a comma-separated sequence on a single line.
Suppose the following input is supplied to the program:
8,5
Then, the output should be:
40320,120
"""
def factorial(num):
if num ==0:
return 1
return num * factorial(num - 1)
output = []
user_in = raw_input("Please input a comma-separated list of integers").split(",")
for element in user_in:
output.append(str(factorial(int(element))))
print ",".join(output) | true |
4026f1f3ceba0ae5ac94b3af49de6529209c4222 | abmish/pyprograms | /intermediate/I5.py | 1,870 | 4.21875 | 4 | """
PALPRIM - Palindromic Primes
A Palindromic number is a number without leading zeros that remains the same when its digits are reversed. For instance
5, 22, 12321, 101101 are Palindromic numbers where as 10, 34, 566, 123421 are not. A Prime number is a positive integer
greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 31, 97 are Prime numbers but 1, 10,
25, 119 are not. A Palindromic Prime number is both palindromic and prime at the same time. 2, 3, 131 are Palindromic
Prime numbers but 6, 17, 3333 are not. Given a positive integer N, output the largest palindromic prime number not greater
than N.
Input
The first line contains an integer T denoting the number of test cases.
Each of the subsequent T lines contain a single integer N without leading/trailing spaces.
Output
Print T lines.
For each test case, print a single integer denoting the largest palindromic prime number which does not exceed N.
Constraints
1 <= T <= 10^6
2 <= N <= 10^13
"""
from sys import stdin, stdout
def is_palindrome(num_str):
for i in range(len(num_str)/2 +1):
if num_str[i] != num_str[-i-1]:
return False
return True
def is_prime(num):
for i in range(2, num/2+1):
if num%i==0:
return False
return True
def get_max_floor(tlist, num):
i = 0
list_len = len(tlist)
while tlist[i] <= num and i < list_len-1:
i += 1
return str(tlist[i-1])
if __name__ == '__main__':
T = int(stdin.readline())
N = list()
palprim = list()
for i in range(T):
N.append(int(stdin.readline()))
max_N = sorted(N)[-1]
for i in range(max_N +1):
if is_palindrome(str(i)):
if is_prime(i):
palprim.append(i)
palprim.append(0)
for each in N:
print ""
stdout.write(get_max_floor(palprim, each))
| true |
5c74dc0f564824fd35817728941b6c82381f952a | abmish/pyprograms | /100Py/Ex86.py | 252 | 4.1875 | 4 | """
By using list comprehension, please write a program to print the list after removing numbers which are divisible
by 5 and 7 in [12,24,35,70,88,120,155]
"""
tlist = [12,24,35,70,88,120,155]
print [num for num in tlist if num%5 == 0 and num%7 == 0] | true |
1b3ddb739a4cbd02e853f3312fa0b08c3bd0cd18 | abmish/pyprograms | /100Py/Ex44.py | 280 | 4.53125 | 5 | """
Write a program which accepts a string as input to print "Yes" if the string is "yes" or "YES" or "Yes", otherwise
print "No".
"""
input_str = raw_input("input yes variation:")
if input_str=="yes" or input_str=="YES" or input_str=="Yes":
print "Yes"
else:
print "No"
| true |
c49a758c98c06b5f3d4d631310a59e1fcadd5169 | abmish/pyprograms | /100Py/Ex71.py | 310 | 4.25 | 4 | """
Please write a program which accepts basic mathematical expression from console and print the evaluation result.
If the following string is given as input to the program:
35+3
Then, the output of the program should be:
38
"""
user_exp = raw_input("Input a mathematical expression :")
print eval(user_exp)
| true |
e11fd9c5ef073e8e0636346f15adb29c87d9562d | abmish/pyprograms | /euler/e30.py | 659 | 4.125 | 4 | """
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^4
8208 = 8^4 + 2^4 + 0^4 + 8^4
9474 = 9^4 + 4^4 + 7^4 + 4^4
As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
"""
def digit_powers(num, power):
total = 0
while num >= 1:
digit = num %10
num = num /10
total = total + pow(digit, power)
return total
print sum(num for num in xrange(2000, 200000) if digit_powers(num, 5) ==num)
| true |
632395e421c68037fa58d4876a541be446d4428a | abmish/pyprograms | /100Py/Ex24.py | 663 | 4.3125 | 4 | """
Python has many built-in functions, and if you do not know how to use it, you can read document online or find some
books. But Python has a built-in document function for every built-in functions. Please write a program to print some
Python built-in functions documents, such as abs(), int(), raw_input()
And add document for your own function
"""
print abs.__doc__
print int.__doc__
print raw_input.__doc__
def square(num):
'''
Return the square value of the input int
:param num: integer
:return: integer, square of num
'''
return num ** 2
user_in = int(raw_input("Input an integer :"))
print square(user_in)
print square.__doc__
| true |
f7a07ea2f7fb455ea2afddea71e9405f23a70d5b | google/google-ctf | /third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Demo/scripts/fact.py | 1,182 | 4.4375 | 4 | #! /usr/bin/env python
# Factorize numbers.
# The algorithm is not efficient, but easy to understand.
# If there are large factors, it will take forever to find them,
# because we try all odd numbers between 3 and sqrt(n)...
import sys
from math import sqrt
def fact(n):
if n < 1:
raise ValueError('fact() argument should be >= 1')
if n == 1:
return [] # special case
res = []
# Treat even factors special, so we can use i += 2 later
while n % 2 == 0:
res.append(2)
n //= 2
# Try odd numbers up to sqrt(n)
limit = sqrt(n+1)
i = 3
while i <= limit:
if n % i == 0:
res.append(i)
n //= i
limit = sqrt(n+1)
else:
i += 2
if n != 1:
res.append(n)
return res
def main():
if len(sys.argv) > 1:
source = sys.argv[1:]
else:
source = iter(raw_input, '')
for arg in source:
try:
n = int(arg)
except ValueError:
print arg, 'is not an integer'
else:
print n, fact(n)
if __name__ == "__main__":
main()
| true |
2cd2be0282ef81f0cec9624f819b0edb1fc6d79c | StoneRiverPRG/Python_Study | /22 continue-break.py | 1,822 | 4.125 | 4 | # break
# continue
# まずはbreakの使い方
i = 0
while True:
# 無限ループ
print(i, end=" ")
if i == 5:
print("i==5なのでwhileループをbreakします")
break
# breakがあると無限ループから抜ける
i += 1
print("whileループ終了しました")
# 0 1 2 3 4 5 i==5なのでwhileループをbreakします
# whileループ終了しました
# continue
for j in range(5):
print("j = " + str(j), end=", ")
if j == 2:
print()
continue
# contineuでループ1回飛ばし
print("j * j = " + str(j * j))
# continueされたループ(j == 2)ではj*jのprintが実行されない
# j = 0, j * j = 0
# j = 1, j * j = 1
# j = 2,
# j = 3, j * j = 9
# j = 4, j * j = 16
# 2重ループでのbreak
for x in range(5):
# x ループ
for y in range(5):
# y ループ
print("x, y : " + str(x) + ", " + str(y))
break
# yループはbreakによりprint関数は最初の1回しか実行されない(y==0だけ)
# 当然xループはbreakされない。あくまでそのループだけ
# x, y : 0, 0
# x, y : 1, 0
# x, y : 2, 0
# x, y : 3, 0
# x, y : 4, 0
# 2重ループでのcontinue, break
for x in range(5):
# x ループ
for y in range(5):
# y ループ
if x == 2 or x == 3:
continue
# x = 2か,x = 3の時continueの為、
# 下記プリント関数が実行されない
# あくまでループ飛ばされるのはyループのみ
print("x, y : " + str(x) + ", " + str(y))
# x, y : 0, 0
# x, y : 0, 1
# x, y : 0, 2
# x, y : 0, 3
# x, y : 0, 4
# x, y : 1, 0
# x, y : 1, 1
# x, y : 1, 2
# x, y : 1, 3
# x, y : 1, 4
# x, y : 4, 0
# x, y : 4, 1
# x, y : 4, 2
# x, y : 4, 3
# x, y : 4, 4
| false |
b7855277caad219b7e696201229ca46c036d84ff | sufairahmed/Udacity-Introduction-to-Python-Practice | /sum_of_series.py | 520 | 4.21875 | 4 |
def sum_of_series(num_series):
total = 0
for i in range(0, num_series):
total = total + i
print("The sum of the series {} = {}".format(num_series, total))
def sum_of_square_series(num_series):
total = 0
total = (num_series * (num_series + 1) * (2 * num_series + 1 )) / 6
print("The sum of the square series {} = {} ".format(num_series, total))
len_series = int(input("Enter the len of series: "))
sum_of_series(len_series)
sum_of_square_series(len_series)
| true |
a8a8e8c4a092e9712c897f670590a74e27adffc6 | sufairahmed/Udacity-Introduction-to-Python-Practice | /list.py | 323 | 4.25 | 4 | # my_list = [23, 43, 'sufair','ahmed',90, 100, 'taslima',13]
# print(my_list)
# print(my_list[ :-1])
#month = 8
month =int (input('enter a month no: '))
days_in_month = [31,28,31,30,31,30,31,31,30,31,30,31]
# use list indexing to determine the number of days in month
num_days = days_in_month[month - 1]
print(num_days)
| false |
2794354be8ee3d2752b336ac79eee4b5c6be5f11 | lxyshuai/Algorithm-primary-class-python | /1/bubble_sort.py | 732 | 4.1875 | 4 | # coding=utf-8
def bubble_sort(array):
# type: (list[int]) -> None
"""
冒泡排序
时间复杂度:O(N^2)
额外空间复杂度:O(1)
第一轮把最大的数冒泡到最后
第二轮把第二大的数冒泡到最后
...
最后一轮把最小的数放到第一
@param array:
@return:
"""
if not array:
return
for i in reversed(range(0, len(array) - 1)):
for j in range(0, i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
if __name__ == '__main__':
alist = [54, 26, 93, 77, 44, 31, 44, 55, 20]
print("原列表为:%s" % alist)
bubble_sort(alist)
print("新列表为:%s" % alist)
| false |
4d047a7ac0be12375caece8284ebaae753043612 | lxyshuai/Algorithm-primary-class-python | /4/zig_zag_print_matrix.py | 1,857 | 4.25 | 4 | # coding=utf8
"""
“之”字形打印矩阵
【题目】
给定一个矩阵matrix,按照“之”字形的方式打印这个矩阵,例如:
1 2 3 4
5 6 7 8
9 10 11 12
“之”字形打印的结果为:1,2,5,9,6,3,4,7,10,11,8,12
【要求】
额外空间复杂度为O(1)。
"""
def print_diagonal(matrix, top_row, top_column, down_row, down_column, direction):
"""
打印对角线
@param matrix:
@type matrix:
@param top_row:
@type top_row:
@param top_column:
@type top_column:
@param down_row:
@type down_row:
@param down_column:
@type down_column:
@return:
@rtype:
"""
if direction:
# 从上往下对角线遍历
while top_row != down_row + 1 and top_column != down_column - 1:
print matrix[top_row][top_column]
top_row += 1
top_column -= 1
else:
while down_row != top_row - 1 and down_column != top_column + 1:
print matrix[down_row][down_column]
down_row -= 1
down_column += 1
def print_matrix_zig_zag(matrix):
top_row = 0
top_column = 0
down_row = 0
down_column = 0
end_row = len(matrix) - 1
end_column = len(matrix[0]) - 1 if end_row != 0 else 0
direction = False
while top_row != end_row + 1:
print_diagonal(matrix, top_row, top_column, down_row, down_column, direction)
top_row = top_row + 1 if top_column == end_column else top_row
top_column = top_column if top_column == end_column else top_column + 1
down_column = down_column + 1 if down_row == end_row else down_column
down_row = down_row if down_row == end_row else down_row + 1
direction = not direction
if __name__ == '__main__':
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print_matrix_zig_zag(matrix)
| false |
385df9987fa2baa4709aa28d27c190371b134f3a | DavidBlazek18/Python-Projects | /python_Polymorphism_Assignment_P193.py | 2,891 | 4.15625 | 4 |
#Parent class
class Airline_Passenger:
name = "Chuck Yeager"
email = "Yeager@gmail.com"
password = "1234abcd"
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_password = input("Enter your password: ")
if entry_email == self.email and entry_password == self.password:
print("Welcome to SpaceForce Airlines, {}".format(entry_name))
else:
print("Please enter the correct email or password.")
#Child class Frequent Flyer
#This gives a 20% discount and asks for an additional code so the
#passenger can identify as a frequent flyer
class Frequent_Flyer(Airline_Passenger):
miles_flown = 50000
frequent_flyer_discount = 0.2
frequent_flyer_code = "Mach1"
#This is the same method as in the Parent class "Airline_Passenger".
#The difference is instead of using password the person uses frequent_flyer_code.
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_frequent_flyer_code = ("Enter your Frequent Flyer code: ")
if (entry_email == self.email and entry_frequent_flyer_code == self.frequent_flyer_code):
print("Congratulations, {}, you have earned a 20% discount!".format(entry_name))
else:
print("Thanks for flying SpaceForce Airlines. Your miles will be added to your Frequent Flyer account.")
#Child class Stratosphere Flyer
#This gives a 30% discount and asks for an additional code so the
#passenger can identify as a frequent flyer
class Stratosphere_Flyer(Airline_Passenger):
miles_flown = 100000
stratosphere_flyer_discount = 0.3
stratosphere_flyer_code = "Mach2"
#This is the same method as in the Parent class "Airline_Passenger".
#The difference is instead of using password the person uses stratosphere_flyer_code.
def getLoginInfo(self):
entry_name = input("Enter your name: ")
entry_email = input("Enter your email: ")
entry_stratosphere_flyer_code = ("Enter your Stratosphere Flyer code: ")
if (entry_email == self.email and entry_stratosphere_flyer_code == self.stratosphere_flyer_code):
print("Congratulations, {}, you have earned a 30% discount and admittance to the executive Lounge!".format(entry_name))
else:
print("Thanks for flying SpaceForce Airlines. Your miles will be added to your Stratosphere Flyer account.")
#THe following code invokes the method for the Airline Passenger as well as
#Frequent FLiers and Stratosphere Fliers
patron = Airline_Passenger()
patron.getLoginInfo()
frequent_flyer = Frequent_Flyer()
frequent_flyer.getLoginInfo()
stratosphere_flyer = Stratosphere_Flyer()
stratosphere_flyer.getLoginInfo()
| true |
0286c74096a35d30aebee609727ca21e66bada45 | ICS3U-Programming-JonathanK/Unit5-01-Python | /temp_convert.py | 838 | 4.28125 | 4 | #!/usr/bin/env python3
# Created by: Jonathan Kene
# Created on: June 1, 2021
# The program will use one for loop and one if statement,
# outputting five integers per line with each separated by a space.
def fahrenheit():
user_string = input("Enter the Temperature (°C): ")
print("")
# make sure if the user types anything but an integer, it's not valid
try:
user_int = int(user_string)
print("")
except ValueError:
print("{} is not a integer" .format(user_string))
# convert the tempertature in celsius from user into fahrenheit
else:
temp_to_f = (9/5)*user_int + 32
print("{}°C is equal to {}°F". format(user_int, temp_to_f))
finally:
print("")
# call the function fahrenheit()
def main():
fahrenheit()
if __name__ == "__main__":
main()
| true |
c5524e0f95241287a34536f24fefa49a60136e53 | uniquearya70/Python_Practice_Code | /q15_odd.py | 464 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 16:49:35 2018
@author: arpitansh
"""
'''
Use a list comprehension to square each odd number in a list. The list is input
by a sequence of comma-separated numbers.
Suppose the following input is supplied to the program:
1,2,3,4,5,6,7,8,9
Then, the output should be:
1,3,5,7,9
'''
inp =input('Enter input here: ').split(',')
num = [x for x in inp if int(x)%2 != 0]
print(','.join(num))
| true |
8e1b506f8b585879cfe91b215aa660c75598e03e | uniquearya70/Python_Practice_Code | /q42_lambda.py | 429 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 00:40:29 2018
@author: arpitansh
"""
'''
Write a program which can filter even numbers in a list by using filter function.
The list is: [1,2,3,4,5,6,7,8,9,10].
'''
'''
li = [1,2,3,4,5,6,7,8,9,10]
evenNumber = filter(lambda x: x%2==0, li)
print(evenNumber)
'''
li = [1,2,3,4,5,6,7,8,9,10]
evenNumbers = filter(lambda x: x%2==0, li)
print (evenNumbers)
| true |
da2116af1f80d95c24399be57ebf10219e9cba51 | uniquearya70/Python_Practice_Code | /q61.py | 747 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 13:54:37 2018
@author: arpitansh
"""
'''
The Fibonacci Sequence is computed based on the following formula:
f(n)=0 if n=0
f(n)=1 if n=1
f(n)=f(n-1)+f(n-2) if n>1
Please write a program using list comprehension to print the Fibonacci Sequence
in comma separated form with a given n input by console.
Example:
If the following n is given as input to the program:
7
Then, the output of the program should be:
0,1,1,2,3,5,8,13
'''
def fibo(n):
if n==0:
return 0
elif n==1:
return 1
else:
return fibo(n-2)+fibo(n-1)
n = int(input('Enter value of n: '))
value = [str(fibo(x)) for x in range (0,n+1)]
print(','.join(value))
| true |
fe4c37e3083ffd64145d3177ac205dc94a719164 | uniquearya70/Python_Practice_Code | /q40.py | 362 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 00:08:41 2018
@author: arpitansh
"""
'''
Write a program to generate and print another tuple whose values are even numbers
in the given tuple (1,2,3,4,5,6,7,8,9,10).
'''
tp=(1,2,3,4,5,6,7,8,9,10)
lst=list()
for i in tp:
if tp[i]%2==0:
lst.append(tp[i])
tp2=tuple(lst)
print (tp2) | true |
c1805d558362add81db3e79c33335eb8b537b100 | uniquearya70/Python_Practice_Code | /q21_leftrigtupdn.py | 1,052 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 17 13:57:52 2018
@author: arpitansh
"""
'''
A robot moves in a plane starting from the original point (0,0). The robot can
move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot
movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
¡
The numbers after the direction are steps. Please write a program to compute the
distance from current position after a sequence of movement and original point.
If the distance is a float, then just print the nearest integer.
'''
import math
pos = [0,0]
print('Give directions and input here: ')
while True:
s = input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction=="UP":
pos[0]+=steps
elif direction=="DOWN":
pos[0]-=steps
elif direction=="LEFT":
pos[1]-=steps
elif direction=="RIGHT":
pos[1]+=steps
else:
pass
print (int(round(math.sqrt(pos[1]**2+pos[0]**2)))) | true |
af2e45c06a6b024e20d8da0d8887c45f4cf1aec5 | shubhamsahu02/cspp1-assignments | /M22/assignment1/read_input.py | 288 | 4.28125 | 4 | '''
Write a python program to read multiple lines of text input and store the input into a string.
'''
STR_ING = ""
S_1 = int(input())
for i in range(S_1):
STR_ING += input() +'\n'
i += 1
print(STR_ING)
def main():
'''main function'''
if __name__ == '__main__':
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.