blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2ee9c142a5a92e71db84a593c66519d3fa79f09c | gregor-sudo/my-repository | /TestLoan.py | 996 | 4.21875 | 4 | from Loan import Loan
def main():
# Enter yearly interest rate.
annualInterestRate = float(input
("Enter yearly interest rate, for example, 7.25: "))
# Enter number of years.
numberOfYears = int(input(
"Enter number of years as an integer: "))
# Enter loan amount.
loanAmount = float(input(
"Enter loan amount, for example, 120000.95: "))
# Enter a borrower.
borrower = input("Enter a borrower's name: ")
# Enter reason.
reason = input("Enter a reason for the loan: ")
# Create a Loan object.
loan = Loan(annualInterestRate, numberOfYears,
loanAmount, borrower, reason)
# Display loan date, monthly payment, and total payment.
print("The borrower is", loan.getBorrower(), "for", loan.getReason())
print("The monthly payment is", format(
loan.getMonthlyPayment(), '.2f'))
print("The total payment is", format(
loan.getTotalPayment(), '.2f'))
main() # Call the main function.
| true |
9cbb9d0269379b3c74f41c2a2c3eba47db659547 | Nikhilskaria/python | /flow controls/decision making/sortedorder.py | 262 | 4.15625 | 4 | num1=int(input("enter a number"))
num2=int(input("enter a number"))
num3=int(input("enter a number"))
if(num1>num2&num1>num3)&(num2>num1&num2>num3):
print(n1,n2,n3)
elif(num2>num1&num2>num3)&(num3>num1&num3>num2)
print(n2,n3,n1)
else:
print(
)
| false |
593c69bcd3c7edc74a9b0b5c03b7338f58740107 | ourway/simple-cnn | /feedforward.py | 1,656 | 4.59375 | 5 | #! /usr/bin/env python3
'''
A neuron is a simple function, it get's two inputs,
sum them with some weight and bias and finally pass it
through an activation function.
We'll use a sigmoid function as activation func.
'''
import numpy as np
def sigmoid(x):
'''
>>> raw = sigmoid(7)
>>> round(raw, 4)
0.9991
'''
return 1 / (1 + np.exp(-x))
class Neuron:
'''
this is a sample neuron:
>>> weights = np.array([0,1])
>>> bias = 4
>>> n = Neuron(weights, bias)
>>> x = np.array([2,3])
>>> round(n.feedforward(x), 8)
0.99908895
'''
def __init__(self, weights, bias):
self.weights = weights
self.bias = bias
def feedforward(self, inputs):
total = np.dot(self.weights, inputs) + self.bias
return sigmoid(total)
class Network:
'''
lets test it:
>>> network = Network()
>>> x = np.array([2, 3])
>>> network.feedforward(x)
0.7216325609518421
'''
def __init__(self):
weights = np.array([0, 1])
bias = 0
## now add hiden layers:
## all layers have input value of [2,3]
## so
self.h1 = Neuron(weights, bias) ## hidden layer 1
self.h2 = Neuron(weights, bias) ## hidden layer 2
self.o1 = Neuron(weights, bias) ## output
def feedforward(self, x):
out_h1 = self.h1.feedforward(x)
out_h2 = self.h2.feedforward(x)
out_o1 = self.o1.feedforward(np.array([out_h1, out_h2]))
return out_o1
if __name__ == '__main__':
import doctest
doctest.testmod()
| true |
1b18d492138e4ffa494c5f3b2c684141c210bd1a | MaoningGuan/LeetCode | /LeetCode 热题 HOT 100/rotate.py | 1,516 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
48. 旋转图像
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
"""
from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
方法:转置加翻转
时间复杂度:O(N^2)
空间复杂度:O(1) 由于旋转操作是 就地 完成的。
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix[0])
# transpose matrix
for i in range(n):
for j in range(i, n):
matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]
# reverse each row
print(matrix)
for i in range(n):
matrix[i].reverse()
if __name__ == '__main__':
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix)
solution = Solution()
solution.rotate(matrix)
print(matrix)
| false |
786f21b4220e470cacb11dc8daf47f3c8eeec9cb | MaoningGuan/LeetCode | /软件开发岗刷题(华为笔试准备)/哈希表/intersection.py | 1,026 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
349. 两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
"""
from typing import List
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""
方法二:内置函数
时间复杂度:一般情况下是 O(m+n),最坏情况下是 O(m×n) 。
空间复杂度:最坏的情况是 O(m+n),数组中的所有元素都不同。
:param nums1:
:param nums2:
:return:
"""
s1 = set(nums1)
s2 = set(nums2)
return list(s1 & s2)
if __name__ == '__main__':
nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]
solution = Solution()
print(solution.intersection(nums1, nums2))
| false |
a6fe98652afbce6cec838ef8ce4f00dbba4e4faa | ravikp92/Python-Labs | /Training/11_chapter.py | 2,934 | 4.375 | 4 | # Inheritance
# Single Inheritance
class Employee:
company="Google"
def showdetails(self):
print(f"This is an employee of {self.company}")
class Programmer(Employee):
language="Python"
def getLanguage(self):
print(f"The language is {self.language}")
def showdetails(self):
print(f"This is an programmer of {self.language}")
e=Employee()
e.showdetails()
p=Programmer()
p.getLanguage()
p.showdetails()
print(p.company)
# Multiple Inheritance
class Emp:
company="Visa"
ecode=101
class Freelancer:
company="Fever"
level=1
class Test(Emp,Freelancer):
name="ravi"
p1=Test()
print(p1.name)
print(p1.level)
print(p1.ecode)
print(p1.company) # class Test(Emp,Freelancer): Employee written first . so its company is called
# Multilevel Inheritance and
# and use of super
class Emp1:
company="Visa"
ecode=101
def __init__(self):
print("..Initializing Emp1..")
def takeBreath(self):
print("Emp1 is breathing")
class Freelancer1(Emp1):
company="Fever"
level=1
def __init__(self):
super().__init__()
print("..Initializing Emp1..")
def takeBreath(self):
super().takeBreath()
print("freelancer1 is breathing")
class Test1(Freelancer):
name="ravi"
def takeBreath(self):
# super().takeBreath()
print("test1 is breathing")
a=Emp1()
a.takeBreath()
b=Freelancer1()
b.takeBreath()
c=Test1()
c.takeBreath()
# class method
class Emp2:
company="Visa"
salary=10
@classmethod
def getSalary(cls,salary):
cls.salary=salary
# print("Emp1 is breathing")
t=Emp2()
print(t.salary)
t.getSalary(45)
print(t.salary)
print(Emp2.salary)
# property decorators
class Emp3:
company="Google"
salary=100
salarybonus=10
@property # getter
def totalSalary(self):
return self.salary + self.salarybonus
@totalSalary.setter
def totalSalary(self,val):
self.salarybonus=val-self.salary
q=Emp3()
print(q.totalSalary)
q.totalSalary = 5800
print(q.salary)
print(q.salarybonus)
# Operator Overloading
class Number:
def __init__(self,num):
self.num=num
def __add__(self,num2):
return self.num+num2.num
def __mul__(self,num2):
return self.num*num2.num
def __str__(self):
return f"Number is {self.num}"
def __len__(self):
return 1
n1=Number(5)
n2=Number(4)
print(n1)
print(n2)
print(len(n1))
print(len(n2))
sum=n1+n2
multiply= n1*n2
print("Sum is :",sum)
print("Multiple is :",multiply)
# Complex numbers
class Complex:
def __init__(self,r,i):
self.real=r
self.imaginary=i
def __add__(self,c):
return Complex(self.real+c.real,self.imaginary +c.imaginary)
def __str__(self):
return f"{self.real}+{self.imaginary}i"
c1=Complex(3,4)
c2=Complex(4,5)
print(c1+c2) | true |
c19390294ba95bed9ff61358582413f30f7748a7 | DmitryPukhov/pyquiz | /pyquiz/leetcode/FriendCircles.py | 2,030 | 4.25 | 4 | from typing import List
class FriendCircles:
"""
There are N students in a class. Some of them are friends, while some are not.
Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C,
then A is an indirect friend of C.
And we defined a friend circle is a group of students who are direct or indirect friends.
Given a N*N matrix M representing the friend relationship between students in the class.
If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not.
And you have to output the total number of friend circles among all the students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
Constraints:
1 <= N <= 200
M[i][i] == 1
M[i][j] == M[j][i]
"""
def findCircleNum(self, M: List[List[int]]) -> int:
circle = 2
self.marked_students = set()
for student in range(0, len(M)):
circle += self.mark_friends(M, student, circle)
return circle - 2
def mark_friends(self, m: List[List[int]], student, circle):
if student in self.marked_students:
return 0
found = 0
for other in range(0, len(m)):
if m[student][other] == 0:
continue
if m[student][other] == 1:
found = 1
m[student][other] = m[other][student] = circle
self.mark_friends(m, other, circle)
self.marked_students.add(student)
return found
| true |
fdbccb4a73ad56c8f873b12382223dc7ca6740a4 | DmitryPukhov/pyquiz | /pyquiz/leetcode/LargestRectangleInHistogram.py | 1,446 | 4.125 | 4 | from typing import List
class Solution:
"""
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
Example:
Input: [2,1,5,6,2,3]
Output: 10
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
1 <= heights.length <= 105
0 <= heights[i] <= 104
"""
def largestRectangleArea(self, heights: List[int]) -> int:
stack = [-1]
maxarea = 0
heights.append(0)
# Go through histogram, push to stack or process right bound with popping from stack
for i, h in enumerate(heights):
while stack and heights[stack[-1]] > h:
# Calculate stack rectangle area, update maximum if applicable
i_stack = stack.pop()
height_stack = heights[i_stack]
width_stack = i - stack[-1] - 1
maxarea = max(maxarea, height_stack * width_stack)
stack.append(i)
heights.pop()
return maxarea
| true |
8a2d53a925413a61df9f3da42daedb8e6e44303c | DmitryPukhov/pyquiz | /pyquiz/leetcode/WildcardMatching.py | 1,901 | 4.28125 | 4 | from functools import lru_cache
class Solution:
"""
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Example 4:
Input: s = "adceb", p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".
Example 5:
Input: s = "acdcb", p = "a*c?b"
Output: false
Constraints:
0 <= s.length, p.length <= 2000
s contains only lowercase English letters.
p contains only lowercase English letters, '?' or '*'.
"""
def isMatch(self, s: str, p: str) -> bool:
@lru_cache(None)
def dp(s: str, p: str) -> bool:
# Base case, p is over
if not p:
# If p is over
return not s
# P still exists, check with different p,s moves
if p[0] == '?' and s:
# p is any single character, move both s and p
return dp(s[1:], p[1:])
elif p[0] == '*':
# p is keeny, move s or move p or move both
return dp(s, p[1:]) or (s and (dp(s[1:], p) or dp(s[1:], p[1:])))
else:
# p is just a letter
return s and s[0] == p[0] and dp(s[1:], p[1:])
return dp(s, p)
| true |
0cbe5fca61e05336216f64cbd77aea98419f436f | DmitryPukhov/pyquiz | /test/leetcode/test_GasStation.py | 2,574 | 4.21875 | 4 | from unittest import TestCase
from pyquiz.leetcode.GasStation import GasStation
class TestGasStation(TestCase):
def test_can_complete_circuit_example1(self):
"""
Example 1:
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Output: 3
Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
:return:
"""
self.assertEqual(3, GasStation().canCompleteCircuit(gas=[1, 2, 3, 4, 5], cost=[3, 4, 5, 1, 2]))
def test_can_complete_circuit_example2(self):
"""
Example 2:
Input: gas = [2,3,4], cost = [3,4,3]
Output: -1
Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
"""
self.assertEqual(-1, GasStation().canCompleteCircuit(gas=[2, 3, 4], cost=[3, 4, 3]))
def test_can_complete_circuit_111_121(self):
self.assertEqual(-1, GasStation().canCompleteCircuit(gas=[1, 1, 1], cost=[1, 2, 1]))
def test_can_complete_circuit_111_111(self):
self.assertEqual(0, GasStation().canCompleteCircuit(gas=[1, 1, 1], cost=[1, 1, 1]))
def test_can_complete_circuit_121_211(self):
self.assertEqual(1, GasStation().canCompleteCircuit(gas=[1, 2, 1], cost=[2, 1, 1]))
def test_can_complete_circuit_121_031(self):
self.assertEqual(0, GasStation().canCompleteCircuit(gas=[1, 2, 1], cost=[0, 3, 1]))
def test_can_complete_circuit_5828_6566_3(self):
"""
Input: [5,8,2,8]
[6,5,6,6]
Answer: 3
"""
self.assertEqual(3, GasStation().canCompleteCircuit(gas=[5, 8, 2, 8], cost=[6, 5, 6, 6]))
def test_can_complete_circuit_4_5(self):
self.assertEqual(-1, GasStation().canCompleteCircuit(gas=[4], cost=[5]))
| true |
077ae8fc692ae64eb35a67798bc11a63fc42616d | DmitryPukhov/pyquiz | /pyquiz/leetcode/LargestPerimeter.py | 719 | 4.15625 | 4 | from typing import List
class LargestPerimeter:
"""
Given an array A of positive lengths, return the largest
perimeter of a triangle with non-zero area, formed from 3 of these lengths.
If it is impossible to form any triangle of non-zero area, return 0.
"""
def largestPerimeter(self, A: List[int]) -> int:
# Get largest lengths
A.sort(reverse=True)
# Get first 3 largest lengths which can form triangle
for i in range(0, len(A) - 3 + 1):
if A[i] + A[i + 1] > A[i + 2] and A[i + 1] + A[i + 2] > A[i] and A[i] + A[i + 2] > A[i + 1]:
return sum(A[i:i + 3])
return 0
print(LargestPerimeter().largestPerimeter([2, 1, 2, 3]))
| true |
6481ae2bfbb5f84ebedd515e32c57939c4de5870 | brandonchinn178/text_game | /game/items.py | 1,263 | 4.34375 | 4 | class Item(object):
"""
The base class for every item in the game
"""
def __init__(self, name, description):
"""
Creates a new Item with the given name and description
@param name (String) -- the name of this Item
@param description (String) -- the description for this Item
"""
self.name = name
self.description = description
def __str__(self):
"""
@returns (String) a print-friendly string representing this item
"""
return "<Item: %s>" % self.name
def use(self, game_state):
"""
Every item that does something must overwrite this function. By default, an item
does not do anything when used.
@param game_state (GameState) -- the game state that contains information about the
current game
"""
pass
class ExampleItem(Item):
"""
An example subclass of Item
"""
def __init__(self):
# call the super class's __init__ function
super(ExampleItem, self).__init__(
name='Example Item',
description='This item will be absolutely pointless in the game'
)
def use(self, game_state):
print 'You used an example item!'
| true |
79a7a4cafd2908fc5a2f6d13e6d5fbd65f1c9f65 | ShaliniGupta06/Python-and-Network-Security-Bootcamp-Project | /Project 3.py | 457 | 4.40625 | 4 | # PROJECT 3:
# Python code to generate hashes of string data using MD5
# and adding salting to it
#importing hashlib library
import hashlib
#inputting data
data = input('Enter data:\t')
temp = data
# Adding Salting:
data = data+'123'
data = 'abc'+data
ans = hashlib.md5(data.encode())
# printing the output
print('The MD5 Hash of ',temp,' after salting is : ', ans.hexdigest())
# End of Program
# NOTE: Iteration part not done
| true |
8975aec27b7b8f88c8faf436ee16bae4cefc24fb | SumaiyaShaheen/python_codes | /assignment.py | 1,686 | 4.34375 | 4 | import math
import sys
from datetime import datetime
def assignment1():
print("Q1-> Write a Python program to print the following string in a specific format \n Q2-> Write a Python program to get the Python version you are using \n Q3-> Write a Python program to display the current date and time. \n Q4-> Write a Python program which accepts the radius of a circle from the user and compute the area. \n Q5-> Write a Python program which accepts the user's first and last name and print them in reverse order with a space between them. \n Q6-> Write a python program which takes two inputs from user and print them addition")
choice = int(input(" my choice is "))
if choice==1:
print("Twinkle, twinkle, little star, \n \t How I wonder what you are! \n \t \t Up above the world so high, \n \t \t Like a diamond in the sky. \n Twinkle, twinkle, little star, \n \t How I wonder what you are")
elif choice==2:
print (sys.version)
elif choice==3:
now = datetime.now()
print("Today's date:", now)
curretH=now.time()
print(curretH)
elif choice==4:
radius = int(input("Enter the radius of circle"))
area = math.pi *radius *radius
print(area)
elif choice==5:
first_name = input(" Enter you'r first name ")
second_name = input(" Enter you'r second name ")
name = second_name + " " + first_name
print(name)
elif choice==6:
num_1 = int(input("Enter first number "))
num_2 = int(input("Enter Second number "))
result = num_1 + num_2
print("The addition of ", num_1, " and ", num_2, " is ", result)
assignment1()
| true |
de486e62f69d3b8ae1db6b4aeef35b75b72fbf17 | yckfowa/python_beginner_projects | /random_number_guessing.py | 1,065 | 4.25 | 4 | import random
print("Welcome to the number guessing game! ")
while True:
try:
upper_bound = int(input("Please choose the upperbound of your number: "))
break
except ValueError:
print("Sorry, you have to enter a number instead of characters")
random = random.randint(1,upper_bound)
guesses = None
number_of_guess = 0
while random != guesses:
while True:
try:
guesses = int(input(f"Please guess a random number between 1 and {upper_bound}: "))
break
except ValueError:
print("Sorry, you will have to input numbers, not random character")
if random == guesses:
print(f"Fabulous, you got it!")
number_of_guess += 1
elif guesses > random:
print("Slightly off by a bit, Please reduce the number ")
number_of_guess += 1
elif guesses < random:
print("A bit too much, Please try a smaller number ")
number_of_guess += 1
print(f"The random number is {random} and the total guesses you used were {number_of_guess}")
| true |
b908f25090f57ba924123b8d2d2c1658b0af5aea | PaulAlexInc/Practice-Python | /Exercise_6.py | 341 | 4.25 | 4 |
"""
Ask the user for a string and print out whether this string is a palindrome or not.
(A palindrome is a string that reads the same forwards and backwards.)
https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
"""
string = input("Enter a string :")
s = string[::-1]
print (s)
print("true" if s==string else "false")
| true |
f2d6b63c890ac1aa29fb4264144b01650719712d | peytonbrsmith/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 1,442 | 4.125 | 4 | #!/usr/bin/python3
"""
Create a function def island_pm(grid):
that returns the pm of the island described in grid:
"""
def island_perimeter(grid):
"""
returns the pm of the island described in grid
grid is a list of list of integers:
0 represents a water zone
1 represents a land zone
One cell is a square with side length 1
Grid cells are connected horizontally/vertically
(not diagonally).
Grid is rectangular, width and height don’t exceed 100
Grid is completely surrounded by water, and there is one island
(or nothing).
The island doesn’t have “lakes” (water inside that isn’t connected
to the water around the island).
"""
pm = 0
for row in range(len(grid)):
for column in range(len(grid[row])):
if grid[row][column] == 1:
if column == 0:
pm += 1
elif grid[row][column - 1] == 0:
pm += 1
if column == (len(grid[row]) - 1):
pm += 1
elif grid[row][column + 1] == 0:
pm += 1
if row == 0:
pm += 1
elif grid[row - 1][column] == 0:
pm += 1
if row == (len(grid) - 1):
pm += 1
elif grid[row + 1][column] == 0:
pm += 1
return pm
| true |
edeff79b11447faa493b05a0b35191392c0c9e68 | stephaniewankowicz/bootcamp-coding-worksheets | /03_file_io.py | 2,347 | 4.34375 | 4 | #!/usr/bin/env python2
from pprint import pprint
def part_1(data, tsv_path):
"""
Save the given dictionary to the given file using the tab-separated value
(TSV) format.
You can think of TSV files like Excel spreadsheets because they organize
data into rows and columns. The columns are separated by tabs ('\t') and
the rows are separated by newlines ('\n'). A nice feature of the TSV
format is that Excel understands it, so you can look at your saved data in
Excel to make sure it looks right.
Make one row in your TSV file for each entry in the given dictionary. Save
the keys in the first column and the values in the second.
"""
pass
def part_2(tsv_path):
"""
Load a dictionary from the given TSV file and return it.
This function is exactly the opposite of part_1(). If the TSV file given
to this function was created by part_1(), the dictionary returned by this
function should be identical to the one passed to part_1().
Note that you get strings when you read data from a file, even if the data
are numeric. Use the ``int()`` function to convert a string to a integer
and the ``float()` function to convert a string to a real number.
"""
pass
def part_3(data, pkl_path):
"""
Save the given dictionary to the given pickle (*.pkl) file.
The pickle module can save almost any python object (dicts, lists, dicts of
lists, lists of dicts, tuples, sets, custom classes, etc.) to a file so it
can be loaded back into python later. It's usually much easier to pickle
data than to write your own code to read and write a file.
Read this page to learn how to use the pickle module:
https://docs.python.org/2/library/pickle.html
"""
pass
def part_4(pkl_path):
"""
Load a dictionary from the given pickle file and return it.
"""
pass
word_lens = {
'already': 7,
'audacity': 8,
'crunch': 6,
'formula': 7,
'grieving': 8,
'heartless': 9,
'marble': 6,
}
print "Writing a TSV file..."
part_1(word_lens, 'word_lens.tsv')
print "Reading a TSV file..."
pprint(part_2('word_lens.tsv'))
print "Writing a pickle file..."
part_3(word_lens, 'word_lens.pkl')
print "Reading a TSV file..."
pprint(part_4('word_lens.pkl'))
| true |
1dad811fefc5996cf43940f71435a8860eca1613 | HeyImMatt/springboard-18-1-python-intro | /words.py | 285 | 4.25 | 4 | def print_upper_words(words, must_start_with):
""" Prints all words out in upper case letters """
for word in words:
if word[0] in must_start_with:
print(word.upper())
print_upper_words(["hello", "hey", "goodbye", "yo", "yes"], must_start_with={"h", "y"}) | true |
9d76e50154b3e998c2fc9b777c241d26e13ea06c | almamuncsit/Data-Structures-and-Algorithms | /Data-Structure/14-hash-table.py | 656 | 4.4375 | 4 | # Declare a hashtable using dictionary
hash_table = {'name': 'Mamun', 'age': 26, 'class': 'First Class'}
# Accessing the dictionary with its key
print("hash_table['name']: ", hash_table['name'])
print("hash_table['age']: ", hash_table['age'])
hash_table['age'] = 8 # update existing entry
hash_table['School'] = "DPS School" # Add new entry
print("hash_table['age']: ", hash_table['age'])
print("hash_table['School']: ", hash_table['School'])
print(hash_table)
del hash_table['name'] # remove entry with key 'name'
print(hash_table)
hash_table.clear() # remove all entries in hash_table
print(hash_table)
del hash_table # delete entire dictionary
| false |
502cf400dbe4f706b9e778cbe7f7b70d8d0e6438 | YHACENE/Maths | /fibonacci.py | 1,406 | 4.1875 | 4 | #coding: utf-8
"""
def febonacci(n):
if n == 1:
return 1
elif n == 2:
return 1
elif n > 2:
return febonacci(n - 1) + febonacci(n - 2)
for n in range(1, 101):
print(n, " : ", febonacci(n))
"""
# Amelioration of the algorithm using memorization
"""
fibonacci_cache = {}
def fibonacci_a(n):
#if we have cached the value, then return it
if n in fibonacci_cache:
return fibonacci_cache[n]
#compute the Nth term
if n == 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = fibonacci_a(n - 1) + fibonacci_a(n - 2)
# Cache the value and return it
fibonacci_cache[n] = value
return value
for n in range(1, 1001):
print(n, " : ", fibonacci_a(n))
"""
# Another way to calculate fibonacci sequence
from functools import lru_cache
@lru_cache(maxsize = 1000)
def fibonacci(n):
# Check that the input is a positive integer
if type(n) != int:
raise TypeError("n must be a positive integer")
if n < 1:
raise ValueError("n must be a positive integer")
# Compute the Nth term
if n == 1:
return 1
elif n == 2:
return 1
elif n > 2:
return fibonacci(n - 1) + fibonacci(n - 2)
for n in range(1, 501):
print(n , " : ", fibonacci(n))
# Golden ratio
for n in range(1, 101):
print("Golden ratio: ", fibonacci(n + 1) / fibonacci(n))
| false |
fb523727cedfe720d657a3aca0f59912cfa12304 | piyavishvkarma09/dictionery | /adding_eliment_to_dictionary.py | 2,570 | 4.6875 | 5 | #eg.2
#Adding Elements to a Dictionary:-i
# n a python dictionary we can add only one key value pair at a time.
# To add to a dictionary we mention the key inside square brackets "[ ]"
# and use the equal to "=" operator`` to assign a value
# dic= {
# 'Name': 'RAM',
# 'Age': 17,
# }
# dic['ORGANIZATION'] = "NAV GURUKUL"
# dic['place'] = 'dharamsala'
# dic['state']='himachal'
# print(dic)
# eg.2
# dic= {
# 'Name': 'RAM',
# 'Age': 17,
# }
# dic['student']={
# 'id':22,
# 'place':'dharamsala'
# }
# print(dic)
#Key Exists or not
# We use the in keyword to check whether a given key exists
# or not in a dictionary
# car ={
# "brand": "ford",
# "model": "mustang",
# "year": 1964
# }
# if "model" in car:
# print("Yes, 'model' is one of the keys in the car dictionary.")
# else:
# print("No, 'model' key dictionary mai nahi hai.")
#################################################
#UPDATE DICTIONARY
# Updating Dictionary :-
# To update dictionary ,we can make an entry in it or we can add a key-value pair
# or we can change the value of an existing key. As given in the example explained:-
# person= {'1': 'RAM', '2': 17,}
# person[3] = 'male'
# print(person)
#eg.2 updation
# details={
# 'Name': 'RAM',
# 'Age': 17,
# 'student': {
# 'id': 22,
# 'place': 'dharamsala'
# }
# }
# details['student']['id']=35
# print(details)
#############################
#Copy of Dictionary :-
# We can copy a dictionary in two ways,first method is using copy() and
# second method by using built-in function dict().
# classes ={
# "room1": "6th",
# "room2": "7th",
# "room3": "8th"
# }
# mydict=classes.copy()#to copy a dictionery
# print(mydict)
#########################################################
#Removing Elements from a Dictionary:-We can remove dictionary elements by many methods. Like given below.
# pop() :Using the pop( )
# method we can remove a specified element from the dictionary.
CAR_DETAILS={
"brand": "Ford",
"model": "jason",
"year": 1964
}
CAR_DETAILS.pop("model")
# CAR_DETAILS.pop("year")
print(CAR_DETAILS)
# popitem():-
# The popitem() method removes the last inserted item:
# person={
# 'name':'jack',
# 'id':22,
# 'place':'dharamsala'
# }
# person.popitem()
# print(person)
#del :-
#Using the del keyword we can remove a specified element from the
#dictionary.
# person={
# 'name':'jack',
# 'id':22,
# 'place':'dharamsala'
# }
# del person['place']
# print(person)
| false |
3b17f22c71a5e765ee6fa4734249fed12f295e94 | AnJu3kwla/Python-Special-Concepts | /LambdaExpressions.py | 891 | 4.40625 | 4 | def f(x):
return 3*x + 1
print(f(2))
"""Lambda Expression"""
lambda x : 3*x + 1
#We can't use this function anywhere because it has no name. So we can give it a name and then get use of it
g = lambda x: 3*x + 1
print(g(2))
"""Lambda Expressions with multiple inputs"""
full_name = lambda first_name, last_name : first_name.strip().title() + " " + last_name.strip().title()
print(full_name("pULithA", "AnjANa"))
scifi_authors = ["Issac Asimov", "Ray Bradbury", "Robert Heinlein", "Arthurs C. Clarke", "Frank Herbert", "Orson Scott Card", "Duglas Adams", "H.G.Wells","Leigh Brackett"]
scifi_authors.sort(key = lambda name : name.split(" ")[-1].lower())
print(scifi_authors)
def build_quadratic_function(a,b,c):
"""Returns the function f(x) = ax^2 + bx + x"""
return lambda x:a*x**2 + b*x + c
f = build_quadratic_function(2,3,-5)
print(f(0))
print(f(1))
print(f(2))
print(build_quadratic_function(3,0,1)(2)) | true |
e4717f5fa62c9fdf97fb6b7c923ee173f1463625 | Merovizian/Aula09 | /Aula 09 - Strings.py | 1,943 | 4.34375 | 4 | #Fatiamento
print("Fatiamento:")
fatiamento = "Curso em Video Python"
print(fatiamento[3]) #vai mostrar a str que está no indice 2 do texto fatiamento
print(fatiamento[:5]) #Vai mostrar todas as str do indice 0 até o indice desejado
print(fatiamento[5:12]) #Vai mostrar todas as str pertencentes ao intervalo desejado
print(fatiamento[::2]) #Vai mostrar as str pertencentes ao intervalo desejado pulando de 2 em 2.
print("Curso" in fatiamento) #True or False
print("\n\n")
# Para a criação de menus: utilize print(""" TEXTO GIGANTE """)
print("Utilizando texto grande:")
print ("""Bolchevique (russo: большевик; francesa: "bolchevik"; inglesa: "bolshevik")
é uma palavra da língua russa, e significa "maioritário".
Assim foram chamados os integrantes do Partido Operário Social-Democrata Russo liderada por Lenin. """)
print("\n\n")
#Outras Funçoes:
print ("Outras Funçoes:")
funcoes = "Aprendendo a Programar"
#len(obj) - retorna a quantidade de indices do texto
print(len(funcoes))
#obj.count('') - retorna a quantidade de str indicadas existem destro do texto (Pode ser usada entre um intervalo utilizando ':')
print(funcoes.count('n'))
#obj.find('') - retorna a posição do primeiro str encontrado e retorna -1 se não encontrar.
print(funcoes.find('n'))
#obj.strip() - remove os espaços indesejados antes e depois do objeto [ tem as variaçoes: lstrip() e rstrip()
print(f" {funcoes} ".strip())
#obj.replace('','') - Troca a frase original por uma outra
print(funcoes.replace('Aprendendo', 'Ensinando'))
funcoes = funcoes.replace('Aprendendo','Ensinando')
print(funcoes)
#obj.split() - Cria uma lista de str utilizando como separador um objeto desejado
print(funcoes.split())
print(funcoes.split('a'))
print(funcoes.split()[0][0]) #Dentro da lista criada acha a posição.
#''.join(obj) - Pega uma lista e junta em uma unica str colocando um objeto entre as listas
print('_'.join(funcoes.split()))
| false |
a36f70388eaaa83b3d38079a431083300c04290b | psitronic/Twenty-One | /cards.py | 2,054 | 4.125 | 4 |
from random import randint
class Card(object):
"""
A class to deal with playcard objects
"""
def __init__(self, card_suit, card_value):
"""
A constructor to create a card with suit and value
"""
self.suit = card_suit
self.value = card_value
def get_suit(self):
# return the card suit
return self.suit
def get_value(self):
# returns the card value
return(self.value)
def show(self):
# display cards at the screen
print("%s of %s" % (self.value,self.suit))
class Deck(object):
"""
A class to deal with the deck of cards
"""
def __init__(self):
self.cards = [] # the cards array
self.faces = [] # the array of faces
self.royal = ["J","Q","K","A"] # faces of royal cards
# let's build the deck
self.build()
def build(self):
"""
The function builds a deck of cards
"""
suits = ["Clubs","Hearts","Diamonds","Spades"]
# first add cards with faces from 6 to 10
self.faces = [str(num) for num in range(6,11)]
# now add cards with royal faces
for face in self.royal:
self.faces.append(face)
# build the deck of cards with different faces for four suits
self.cards = [Card(suit,face) for suit in suits for face in self.faces]
def shuffle(self):
"""
Shuffle the cards in the deck
"""
for num in range(len(self.cards)-1,0,-1):
# chose a random card in the deck
new_num = randint(0,num)
# swap two cards in the deck
self.cards[num],self.cards[new_num] = self.cards[new_num],self.cards[num]
def show(self):
"""
The function shows all cards in the deck
"""
for card in self.cards:
card.show()
deck = Deck()
deck.shuffle()
deck.show() | true |
258ea19b222576456f20870647c42403e871982a | timjlittle/Python | /recipe.py | 1,720 | 4.21875 | 4 | recipe = []
recipename = ""
recipeserves = 0
def NewRecipe ():
#This function asks the user to enter the details of a recipe
recipename = input ("Please tell me the name of your recipe")
recipeserves = input("How many does this serve?")
f = open(recipename,'w')
f.write (recipeserves + '\n')
#Ask for new ingredients repeatedly until the users doesn't
#say y to the question (case sensitive)
more = "y"
while (more == "y"):
item = input("Item name")
count = input("how much")
units = input("What are the units?")
#Add a dynamically created list containing the ingredient name,
# how many and what the units are to the recipe list
f.write(item + ',' + count + ',' + units + '\n')
recipe.append([item, count, units] )
more = input("more ingredients?")
f.close()
def ShowRecipe():
#This function displays the list of ingredients for a recipe
#with the quantities adjusted to serve the number specified.
serve = int(input("How many people are coming?"))
print ("you need:")
for ingredient in recipe:
item = ingredient[0]
count = ingredient[1]
units = ingredient[2]
print ( (count/recipeserves) * serve, units, " of ", item)
#Main
choice = ""
while (choice != "q" and choice != "Q"):
print (" 1 Enter the details of a new recipe")
print (" 2 Show the ingredients of an existing recipe")
print (" q Quit this program\n\n")
choice = input ("Please enter 1, 2 or q")
if not (choice in ('1', '2', 'q', 'Q')):
print ("Invalid input.")
elif (choice == '1'):
NewRecipe ()
elif (choice == '2'):
ShowRecipe()
| true |
2532770c48a2fd1b2d61879af5bdaf1c7aa769cf | Ichbini-bot/python-labs | /02_basic_datatypes/2_strings/02_12_Trip_Costs.py | 480 | 4.4375 | 4 | '''
Receive the following arguments from the user:
kilometers to drive
liters-per-kilometer usage of the car
price per liter of fuel
Calculate the cost of the trip and display it to the user in the console.
'''
km = float(input("Pls enter kilometers to drive: "))
usage = float(input("Pls tell the liters-per-km usage of the car: "))
literprice = float(input("Pls advice on price per liter of fuel: "))
costs = km * usage * literprice
print("Your trip will cost you: ", costs) | true |
70a454cbf1caffc2f468cb9dd380e923d2a8e520 | Ichbini-bot/python-labs | /02_basic_datatypes/2_strings/02_09_vowel.py | 918 | 4.3125 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
# Can be solved more elegantly via loops - but thats for later. Question is,
if there is no more better way to use .count method to count vowels (did research it and tried it multiple times, but
coudlnt figure it out)#
'''
# Input sentence from user
# variables that contain vowels
# show results (total_count and individual count)
data = str(input("Pls enter your sentence: "))
sentence = data.lower()
a = sentence.count("a")
e = sentence.count("e")
i = sentence.count("i")
o = sentence.count("o")
u = sentence.count("u")
total_count = a + e + i + o + u
print(total_count)
print("a =", a)
print("e =", e)
print("i =", i)
print("o =", o)
print("u =", u)
| true |
ad2a7eea12c5aa2c7a06549d8822a3ca250a8562 | Ichbini-bot/python-labs | /15_aggregate_functions/15_03_my_enumerate.py | 612 | 4.25 | 4 | '''
Reproduce the functionality of python's .enumerate()
Define a function my_enumerate() that takes an iterable as input
and yields the element and its index
'''
list = ["apple", "pears", "kiwis", "pineapples"]
list2 = [1,2,3,4,5]
def my_enumerate(argument, start = 0):
index = start
for element in argument:
yield index, element #first time using yield. Compared to return, yiel can give back several values - however, needs to be called via a for loop (as iterator)
index +=1
for i in my_enumerate(list):
print(i)
for i in my_enumerate(list2):
print(i)
| true |
a52a3394c353f0aa07726247a154c40972d52766 | Ichbini-bot/python-labs | /03_more_datatypes/2_lists/03_06_product_largest.py | 631 | 4.40625 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it out, otherwise
come back to this task after you have learned about loops)
'''
list = []
for i in range(1,5):
data = int(input("Enter number: "))
list.append(data)
print(list)
list.sort()
print("largest number is: ", list[-1])
total = 1
for i in list:
print(i)
total = total * i
print(total)
| true |
181030fa53a06767560f0d38b91da6a413032b96 | Ichbini-bot/python-labs | /15_aggregate_functions/15_02_sum.py | 339 | 4.125 | 4 | '''
Write a simple aggregate function, sum(), that takes a list and returns the sum.
'''
list = [1,2,3,4]
print("The sum of the list is: ", sum(list))
#Crowbar method:
def summe(argument):
total = 0
for i in argument:
total = total + i
return total
print("The sum of the list is (crowbar method): ", summe(list))
| true |
e7576ffda6fccd4be1b0e29efb9a5d334b24074d | milenabaiao/python-1 | /crescentenaocrescente.py | 239 | 4.1875 | 4 | num1 = input("Digite um número: ")
num2 = input("Digite um número: ")
num3 = input("Digite um número: ")
if ((int(num1) < int(num2)) and (int(num2) < int(num3))):
print("crescente")
else:
print("não está em ordem crescente")
| false |
b8aebde8ad9d00fcb276743dfe15c60fecb2f9da | Ming-Coder/Python | /Chapter4/4-10_ch.py | 237 | 4.15625 | 4 | ch=['a','b','c','d','e','f','g','h','i']
print("The first three items in the list are:")
print(ch[:3])
print("Three items from the middle of the list are:")
print(ch[3:6])
print("The last three items in the list are:")
print(ch[-3:])
| false |
31d5d43e34979ad05d118a012c2d947e3ad66d5e | hikarocarvalho/Python_Wiki | /Exercises/02-Decision-Structure/ex05.py | 805 | 4.25 | 4 | # Faça um programa para a leitura de duas notas parciais de um aluno.
# O programa deve calcular a média alcançada por aluno e apresentar:
# A mensagem "Aprovado", se a média alcançada for maior ou igual a sete;
# A mensagem "Reprovado", se a média for menor do que sete;
# A mensagem "Aprovado com Distinção", se a média for igual a dez.
firstnote = float(input("Enter with the first note: "))
secondnote = float(input("Enter with the second note: "))
middle = (firstnote + secondnote) / 2
if middle == 10:
print("Congratulations you have passed with distintion!! Your note is:",middle)
elif middle >=7:
print("You have pass with",middle,"like your note!")
elif middle <7:
print("You have REPROVED with",middle,"like your note!")
else:
print("Some note has an incorrect value!") | false |
88c9b6b6c92859c7c188478ead68ec953a48edab | hikarocarvalho/Python_Wiki | /Exercises/02-Decision-Structure/ex11.py | 1,716 | 4.5 | 4 | # As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe
# contraram para desenvolver o programa que calculará os reajustes.
# Faça um programa que recebe o salário de um colaborador e o reajuste
# segundo o seguinte critérios, baseado no salário atual:
# salários até R$ 280,00 (incluindo) : aumento de 20%
# salários entre R$ 280,00 e R$ 700,00 : aumento de 15%
# salários entre R$ 700,00 e R$ 1500,00 : aumento de 10%
# salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela:
# o salário antes do reajuste;
# o percentual de aumento aplicado;
# o valor do aumento;
# o novo salário, após o aumento.
# ---------------------------------------------------#
# declare variables
# declara variaveis
salary = float(input("Enter with your salary value: \n"))
# verify with conditions
# verifica condições
if salary <= 280:
print(f'The initial value is: {salary} and apply with 20%')
print(f'The value result from 20% is: {(salary*0.20):.2f}')
print(f'The final value is: {((salary*0.20)+salary):.2f}')
elif salary <= 700 and salary > 280:
print(f'The initial value is: {salary} and apply with 15%')
print(f'The value result from 15% is: {(salary*0.15):.2f}')
print(f'The final value is: {((salary*0.15)+salary):.2f}')
elif salary < 1500 and salary > 700:
print(f'The initial value is: {salary} and apply with 10%')
print(f'The value result from 10% is: {(salary*0.10):.2f}')
print(f'The final value is: {((salary*0.10)+salary)}')
else:
print(f'The initial value is: {salary} and apply with 5%')
print(f'The value result from 5% is: {(salary*0.05):.2f}')
print(f'The final value is: {((salary*0.05)+salary):.2f}') | false |
26c93247ee4200baadf6355f694c14262a0ea35e | hikarocarvalho/Python_Wiki | /Exercises/01-Sequential-Structure/ex06.py | 270 | 4.40625 | 4 | #the user gives the ray value
#o usuário dá o valor do raio
ray = float(input("Enter with the ray value: "))
#calculate the area of a circle
#calcula a área do circulo
area = ray**2 * 3.14
#Show the result
#mostra o resultado
print("The area of this circle is:",area) | false |
2000ff778e51081f48524a57ab084e92e444102d | shaypatricks/Programming-PRG-105-005l | /25.2.py | 875 | 4.125 | 4 | '''
def main():
my_name = get_name()
print('Hello', my_name, 'how may we help today')
def get_name():
name = input('please enter your name: ')
return name
main()
keep_going = 'y'
while keep_going == 'y' or keep_going == 'Y':
income = float(input('Please enter your income to the month: $ '))
bills = int(input('How many bills have you received: $ '))
for bills in range(bills):
total = 0.00
spending_money = income - bills
'''
# get cost from user, pass to calc_cost
def main():
structure_value = float(input('how much would it cost to replace your home: $ '))
calc_cost(structure_value)
# calculate the cost of the insurance using the variable
def calc_cost(value):
insurance = value * .8
print('you should get about $', format(insurance, ',.2f'), 'for your home.')
main()
| true |
d4c1f3023ae6f04a67651d3589cc459b3337218d | shaypatricks/Programming-PRG-105-005l | /Popular names.py | 1,181 | 4.1875 | 4 | """
Write a program that reads the contents of the two files into two separate lists.
The user should be able to enter a boy's name, a girl's name, or both* and the application will display messages
indicating whether the names were among the most popular.
* Entering a name should cause the program to check both lists.
"""
def main():
# start with opening both files
pop_girls = open('GirlNames.txt', 'r')
pop_boys = open('BoyNames.txt', 'r')
user_check = input('Please enter a name: ')
name_1 = pop_girls.readline()
name_2 = pop_boys.readline()
pop_girls.close()
pop_boys.close()
name_g = name_1.rstrip('\n')
name_b = name_2.rstrip('\n')
# now to run a user input
for line in name_g:
line = name_g
if user_check == name_g:
print('This is a popular girls name')
else:
print("This is not a popular girls name")
break
for line1 in name_b:
line1 = name_b
if user_check == name_b:
print('This is a popular boys name')
else:
print('this is not a popular boys name')
break
main()
| true |
405d189b8f12e5955e89d8591eb9c51339492221 | Ryuchi25/pythonintask | /IVTp/2014/task_6_21.py | 1,079 | 4.3125 | 4 | #Задача 6, Вариант 21
#Создайте игру, в которой компьютер загадывает название одной из семи основных #физических единиц, согласно Международной системы единиц , а игрок должен его #угадать.
#Шпенькова А.С.
#11.04.2016
import random
n = random.randint (1,7)
if n==1:
unit = "Метр"
elif n==2:
unit = "Килограмм"
elif n==3:
unit = "Секунда"
elif n==4:
unit = "Ампер"
elif n==5:
unit = "Кельвин"
elif n==6:
unit = "Моль"
elif n==7:
unit = "Кандела"
answer = input('\nНазовите одну из семи основных физических единиц , согласно Международной системы единиц: ')
if answer == unit:
print('\nВы угадали!')
else:
print('\nВы не угадали!!!')
print('Правильный ответ: ', unit)
input("\n\nНажмите Enter для выхода.")
| false |
9b68de9297e7ca7f378d0812e2e2f2eca01ff8bb | madddyr/pg_MR | /listMR.py | 779 | 4.21875 | 4 | name = "Maddy"
subjects = ["English","Math","Science","Spanish","History"]
print("Hello " + name)
for i in subjects:
print("One of my subjects is " + i)
sports = ["soccer","hockey","basketball","lacrossse","field hockey"]
for i in sports:
if i == "field hockey":
print(i + " isn't a sport")
elif i == "hockey":
print(i + " is awesome")
elif i == "soccer":
print(i + " is the best sport")
else:
print("One of my favorite sports is " + i)
food = []
while True:
print("What food do you like? Type 'end' to quit.")
answer = input()
if answer == "end":
break
else:
food.append(answer)
for i in food:
print("One of your favorite foods is " + i)
| false |
a31cfdebf3a5dd61c17d1322c42c319dca4f6b1d | EiSandarWin/PythonSample | /ifstate.py | 1,836 | 4.1875 | 4 | #Week 3A 21.9.2019
#>>> x = int(input("Please enter an integer:"))
#>>> if x < 0:
#... x = 0
#... print('Negative changed to zero')
#... elif x == 0:
#... print('zero')
#... elif x == 1:
#... print('Single')
#... print('More')
#...
#More
#x = int(input("Please enter an integer"))
#if x >= 40 and x <= 75:
# print('Aged go to bagan')
#elif x < 40 and x >= 10:
# print('Youth go to beach')
#elif x <= 10 and x >0:
# print('Go to Playground')
#else:
# print('unlisted')
#int(input("Examination Result:"))
#100 scholar
#70 destination
#50 excellent
#40 pass fail
#10 warning
x = int(input("Please enter your marks"))
if x == 100:
print('You are scholar person', x)
elif x >= 70 and x < 100:
print('You passed with destination', x)
elif x >= 50 and x < 70:
print('You are excellent person', x)
elif x > 40 and x < 50:
print('You passed' ,x )
elif x == 39 :
x = x + 1
print('You are modifation', x)
elif x == 38:
x = x + 2
print('You are modifation', x)
elif x == 37:
x = x + 3
print('You are modifation', x)
elif x == 36:
x = x + 4
print('You are modifation', x)
elif x == 35:
x = x + 5
print('You are modifation', x)
elif x > 5 and x <=10:
print('You try more and more', x)
else:
print('I call your parents', x)
>>> words = ['cat', 'window', 'defenestrate', 'world']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
world 5
>>>
>>> words = ['cat', 'window', 'defenestrate', 'world']
>>> for w in words[:]:
... if len(w) > 6:
... words.append(w)
...
>>> words
['cat', 'window', 'defenestrate', 'world', 'defenestrate']
>>> words = ['cat', 'window', 'defenestrate', 'world']
>>> for w in words[:]:
... if len(w) > 4:
... words.insert(0, w)
...
>>> words
['world', 'defenestrate', 'window', 'cat', 'window', 'defenestrate', 'world'] | false |
01fb71584592ca04a00bf0f9c860d9a770436220 | nutristar/Home_WORK_1 | /4th.py | 432 | 4.1875 | 4 | """. Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции."""
number=91234567
max=0
while number>0:
x=number%10
number = number // 10
if x>max:
max=x
print(f"наибольшая чифра {max}") | false |
f9ad4fcae967d914cf734854964d7aa6c97365c1 | vishalvb/Algorithms | /others/print_bst_levelwise/solution1.py | 1,010 | 4.34375 | 4 | # Python program to print level order traversal using Queue
Time: O(n), n is the number of nodes in the binary tree. At max all the nodes are touched twised, once to push and next to pop
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to print the height of binary tree
def printLevelOrder(root):
if root is None:
return
q = []
q.append(root)
while len(q) > 0:
node = q.pop()
print(node.data),
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
#Driver Program to test above function
root = Node(1)
root.left = Node(3)
#root.right = Node(2)
root.left.left = Node(4)
root.left.right = Node(5)
print "Level Order Traversal of binary tree is -"
printLevelOrder(root)
#This code is contributed by Nikhil Kumar Singh(nickzuck_007)
| true |
d55898e4cc47442bce55ee9cc7e0b7f4120f8416 | TayKristian/Python | /Exercicios_entrada_saida/Lista01 - Questão 01 - Python para Zumbis.py | 364 | 4.375 | 4 | # Questão 01 - Python para Zumbis
# Comentario de uma unica linha
"""
Faça um programa que peça dois números inteiros e imprima a soma desses dois números.
Comentário de multiplas linhas
"""
# n1 -> número 1
n1 = int(input("Digite o 1° número: "))
# n2 -> número 2
n2 = int(input("Digite o 2° número: "))
# s -> soma
s = n1 + n2
print('A soma é', s)
| false |
a28efe2360bc599365fd6756fcd3180b291447fb | jonathanwenan19/Banking_Problem | /Banking_Project.py | 2,485 | 4.21875 | 4 | #Hw
#1. <Menu driven program that can
#a.depositt
#b.addaccount
#c.withdraw
#balance inquiry
#quit
class account:
def __init__(self,balance:float):
self.balance = balance
def getbalnce(self):
print("Your balance is ${} ".format(self.balance))
def deposit(self,amt):
if amt<=self.balance:
resultantbalance= self.balance-amt
print("Here you go!${}.The remaining balance is ${}".format(amt,resultantbalance))
elif amt > self.balance:
print(f'Sorry, we are unable to proceed with the transaction,because you have ${self.balance},which is not enough!')
else:
print('Transaction cancelled! Have a nice day!')
def withdraw(self,amt:float):
resultantbalance= self.balance+amt
print(f'{amt} has been inserted to your bank account! Now you have ${resultantbalance}. Have a nice day!')
class Customer:
customer={}
def __init__(self,firstname:str,lastname:str,account:str):
self.firstname,self.lastname,self.account= firstname,lastname,account
def getfn(self):
return self.firstname
def getln(self):
return self.lastname
def getacc(self):
return self.account
def makeacc(self):
insfname= input('What is your first name?')
inslname= input('What is your last name?')
insnewaccname= input('What will your account name be?')
print(f'Your name is {insfname} {inslname}, with an account name of {insnewaccname}')
self.customer['Account']=insnewaccname
def accmanager():
print('1.Getbalance 2. Deposit 3. Withdraw 4. make an account 5. quit')
action=int(input('What do you want to do?')) #1.Getbalance 2. Deposit 3. Withdraw 4. make an account 5. quit
actionver1,actionver2 = account(500),Customer('Jonathan','Wenan','Blank_Chan7')
if action == 1:
actionver1.getbalnce()
print('Have a nice day!')
if action == 2:
amountdepo=int(input('Type in the amount you want to deposit'))
actionver1.deposit(amountdepo)
print('have a nice day!')
if action == 3:
amountdepo=int(input('Type in the amount you want to Withdraw'))
actionver1.withdraw(amountdepo)
print('Have a nice day!')
if action== 4:
actionver2.makeacc()
print('Have a nice day!')
else:
print('Have a nice day!')
accmanager()
| true |
8c95808005e3900e1162b546be7ef3277425a05c | MashaBltv/CP4 | /2.py | 345 | 4.15625 | 4 | a=float(input('введите первый катет a:'))
b=float(input('введите второй катет b:'))
c=(a ** 2 + b ** 2) ** 0.5
S=(a*b) * 0.5
P=a+b+c
c=str(c)
print('гипотенуза = ' + c)
S=str(S)
print('площадь треугольника = ' + S)
P=str(P)
print('периметр треугольника = '+ P) | false |
e0003a6a89992035e22130f7d00d9bc446fd68ad | LuisMMMTS/Python-ProgrammingFundamentals-exercises | /dictionaries/4. Sort by key.py | 444 | 4.3125 | 4 | """'
Write a Python function `sort_by_key(dict)', ' that, given a dictionary
`dict', ' of colors (key is the color name and value is its hexadecimal
value), returns a list of pairs ordered by color. Note that It is not possible
to sort a dictionary, only to get a representation of a dictionary that is
sorted.
'
"""
def sort_by_key(dict):
l=[]
for key,value in dict.items():
l.append((key,value))
return sorted(l) | true |
c691d108bc26509d5932697b977668ca472572a3 | mohammedsiraj08/python_assignment | /pythonassignment/16thprogram.py | 308 | 4.25 | 4 | # name : sai eshwar reddy kottapally
# rollno : 100519733022
# program to reverse a list without reverse function
L1=[]
n=eval(input("enter the size of the list:"))
for i in range(n):
L1.append(eval(input("enter the values:")))
print("reversed elements of the list")
for i in range(n):
print("",L1[n-1-i],end="")
| false |
10f195942b3c2e3ae16b7f0b80b64be2e926eb37 | isaacmartin1/Texas_Financial_Derivatives | /Week_1_Cirriculum_Pt2.py | 840 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#Value of European option at expiration
price = 75
strike = 70
if price > strike:
payoff = price - strike
else:
payoff = 0
print("the payoff is", payoff)
#What if you have multiple possible prices for an option
import numpy as np
end_prices = [75, 70, 65, 60]
strike = 70
payoffs = []
for x in end_prices:
if x > strike:
payoffs.append(x-70)
else:
payoffs.append(0)
print("the average payoff is", np.average(payoffs))
#Same as above but with definition to do calculations
import numpy as np
end_prices = [75, 70, 65, 60]
strike = 70
payoffs = []
def value(x):
if x > strike:
payoffs.append(x-70)
else:
payoffs.append(0)
for x in end_prices:
value(x)
print("the average payoff is", np.average(payoffs))
# In[ ]:
| true |
8a0fd41ec0089d0eaa2e69730716c014a8b14bc8 | pedroccpimenta/APMIEPol | /comentarios.py | 665 | 4.25 | 4 | # Linha de comentário
# Pedro Pimenta, Outubro 2017
# variáveis numéricas
a = 36
# As instruções podem ser terminadas por ; - obrigatório se quisermos escrever mais do que uma
# instrução na mesma linha
b= 58; c=5.7;
pi=3.1415
vc = 5+1j
print ('a+b=', a+b)
# Quais os tipos das variáveis?
print ('tipo de a=',type(a))
print ('tipo de b=',type(b))
print ('tipo de b=',type(c))
print ('tipo de pi=',type(pi))
print ('tipo de vc=',type(vc))
nome='José Silva'
outro_nome="Maria Silva"
print (nome, outro_nome)
print (len(nome)) # len(<str>) - comprimento, em caracteres, de uma variável <string>
print (len(c))
# len () - não aplicável a variáveis numéricas
| false |
cc68b0436986977ad98ddfe4ec644498b5676832 | pedroccpimenta/APMIEPol | /isprime.py | 448 | 4.15625 | 4 | # Verificar se um dado número é primo
# A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself.
def is_prime(x):
if x<2:
return False
else:
for n in range (2, x-1):
if x%n == 0:
return False
return True
print ('8 is prime?:',is_prime(8))
print ('17 is prime?', is_prime(17))
print ('1 is prime?', is_prime(1)) | true |
8517ddf101ee1e8bbb606b6ae4e3cff869703905 | ANIK-DATTA/Quick-Sort | /quickSort.py | 859 | 4.21875 | 4 | def quickSort(low, high, arr):
if(low<high): #Terminating Condition
pivot = partition(low, high, arr) #Extracting pivot location
quickSort(low, pivot-1, arr)
quickSort(pivot+1, high, arr)
def partition(low, high, arr):
pivot = arr[high]
pivot_index=low-1
for i in range(low, high):
if(arr[i]<=pivot): #Extracting elements smaller than the the pivot
pivot_index+=1
arr[pivot_index], arr[i]= arr[i], arr[pivot_index] #Swapping smaller element with the element at pivot_index
pivot_index+=1
arr[pivot_index], arr[high]= arr[high], arr[pivot_index] #Final swapping to bring the pivot in place
return (pivot_index)
if __name__ == "__main__":
arr=raw_input("Enter the array to be sorted:: ").split() #Splitting the input on spaces
arr=[int(a) for a in arr]
quickSort(0, len(arr)-1, arr) #Start index: 0; End index: length -1;
print(arr) | true |
862efcb8982ffa5e712fb0f27ee6f533b3176f52 | jahan1234/Python | /dictionary.py | 1,250 | 4.21875 | 4 | '''
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
'''
#Loop though dictionary
'''
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
for key in a_dict.keys():
print(key,':',a_dict[key])
'''
#sort dictionary
'''
a_dict = {2:3, 1:89, 4:5, 3:0}
c = {k:a_dict[k] for k in sorted(a_dict.keys())}
print(type(c))
'''
#Datetime
import datetime
currdate = datetime.date(2021,5,5)
prevdate = datetime.date(2020,6,10)
diff = currdate - prevdate
print(diff.days)
tomorrow = currdate + datetime.timedelta(days = 4)
print(tomorrow)
#loop though dates
for day in range((currdate-prevdate).days):
#print(day)
pass
| true |
bef639dc89b593570980843dcb290fc42d32ba0b | LemonLzy/Algorithm_python | /chapter2/SelectSort.py | 1,131 | 4.125 | 4 | # @Author:Lzy
# @Time:2020/8/27
# selectSort
"""
1、一种较慢的排序算法
2、选择的大O表示法为O(n^2)
3、选择排序算法思想:
在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
从剩余未排序元素中继续寻找最小(大元素),然后放到已排序序列的末尾
以此类推,直到所有元素均排序完毕
"""
# 选择排序
def select_sort(array):
length = len(array)
for i in range(length):
smallest_index = i
for j in range(i + 1, length):
if array[j] < array[smallest_index]:
smallest_index = j
array[i], array[smallest_index] = array[smallest_index], array[i]
return array
"""
测试,对给定数组进行排序
"""
if __name__ == '__main__':
my_list = [4, 2, 1, 9, 3, 6, 7]
print(select_sort(my_list))
# # 找出数组中的最小元素
# def findSmallest(array):
# smallest = array[0]
# smallest_index = 0
# for i in range(1, len(array)):
# if array[i] < smallest:
# smallest = array[i]
# smallest_index = i
| false |
67bed49ec8fff4c0788ef51e6f88dcde446bec4c | StjepanPoljak/tutorials | /python/tests/unit-test-ex.py | 1,427 | 4.125 | 4 | #!/usr/bin/env python3
import unittest
def fibonacci_step(prev, curr, step, step_max):
if step == step_max:
return curr
else:
return fibonacci_step(curr, prev+curr, step + 1, step_max)
def fibonacci(n):
return fibonacci_step(0, 1, 1, n)
class SomeTestCase(unittest.TestCase):
"""Tests for fibonacci() function"""
def setUp(self):
self.fibonacci_list = [ 1, 1, 2, 3, 5, 8, 13, 21, 34 ]
# Note: The setUp method will be run first on unittest.main()
def test_fibonacci_first(self):
for index, fib_num in enumerate(self.fibonacci_list, start=1):
self.assertEqual(fibonacci(index), fib_num)
# Note: The opposite of this is assertNotEqual
def test_fibonacci_second(self):
for fib_num in [ fibonacci(n) for n in range(1, len(self.fibonacci_list) + 1) ]:
self.assertIn(fib_num, self.fibonacci_list)
# Note: The opposite of this is assertNotIn
def test_fibonacci_third(self):
fib_list = [ fibonacci(n) for n in range(1, len(self.fibonacci_list) + 1) ]
prev1 = fib_list[0]
prev2 = fib_list[1]
for fib_index in range(2, len(fib_list)):
self.assertTrue(prev1 + prev2 == fib_list[fib_index])
prev1 = prev2
prev2 = fib_list[fib_index]
# Note: The opposite of this is assertFalse
unittest.main()
# Note: Tests will be run for any method starting with test_ prefix
| true |
68b85b06255e13eaaf3533186ffe8bee7c7b34f4 | StjepanPoljak/tutorials | /python/basic/input-ex.py | 741 | 4.15625 | 4 | #!/usr/bin/env python3
name = input("Type in your name: ")
print("Hello, " + name + "!")
age = input("Type in your age: ")
age = int(age)
if age >= 18:
print("You've grown up!")
else:
print("You're still a child!")
# Note: In Python2, input() interprets
# user's input as code and attempts to
# run it; use raw_input() instead
print("Type in a grocery (or q to quit): ")
grocery_list = []
user_input = ""
while user_input != "q":
user_input = input()
if user_input != "q":
grocery_list.append(user_input)
print("You will need to buy:")
while grocery_list:
current_grocery = grocery_list.pop()
print("\t* " + current_grocery)
# Note: You can use 'break' and 'continue'
# like in C/C++ (and similar)
| true |
ba52a8819ee154961584bb410133df06fb765117 | gdpe404/formation_python | /07-modules/02-perso/mypackage/mymodule.py | 2,364 | 4.1875 | 4 | # Docstring
def hello_world():
"""Affiche le message 'Hello world' dans le terminal
"""
print("Hello World !")
def say_hello(prenom):
"""Affiche le message 'bonjour' suivi du prenom
Args:
prenom (str): prenom de l'utilisateur
"""
print(f"Bonjour {prenom} !")
def multiplication(nombre, nombre2):
resultat = nombre * nombre2
print(f"{nombre} x {nombre2} = {resultat}")
def soustraction(nombre, nombre2):
"""Renvoie le resultat d'une soustraction
Args:
nombre (int): Nombre 1
nombre2 (int): Nombre 2
Returns:
int: Resultat de la soustraction
"""
resultat = nombre - nombre2
return resultat
def print_table(nombre, max_=10):
"""Affiche la table de multiplication d'un nombre
Args:
nombre (int): nombre entier
max_ (int, optional): [description]. Defaults to 10.
"""
compteur = 1
while compteur <= max_:
resultat = nombre * compteur
print(f"{nombre} x {compteur} = {resultat}")
compteur += 1
def how_many_minutes(heures, minutes):
return (heures * 60 + minutes)
def find_char(chaine, lettre):
index = 0
taille_chaine = len(chaine)
while index < taille_chaine:
if lettre == chaine[index]:
return "Trouvé"
index += 1
return "Aucun résultat"
def find_char_avec_for(chaine, lettre_rechercher):
for lettre_en_cours in chaine:
if lettre_en_cours == lettre_rechercher:
return "Trouvé"
return "Aucun résultat"
print("__name__ : " + __name__ )
if __name__ == "__main__": # <- ca veut dire qu'on execute le fichier en tant que script.
hello_world()
p = 'John'
say_hello(p)
multiplication(5,2)
multiplication(15,7)
resultat = soustraction(5,2)
print(f"Resultat: {resultat}")
print(f"Resultat: { soustraction(10,4) }")
print_table(7)
print_table(5, 20)
print( how_many_minutes(1, 30) )
resultat = how_many_minutes(2,45)
print(f"Resultat: {resultat}")
print( find_char("Salut tout le monde", 'u') )
resultat = find_char("Salut tout le monde", 'z')
print(f"Resultat: {resultat}")
print( find_char_avec_for("Salut tout le monde", 'u') )
resultat = find_char_avec_for("Salut tout le monde", 'z')
print(f"Resultat: {resultat}") | false |
26c12318ee49babd40bc0a89e370e3dff3844237 | June-fu/python365 | /2020/03march/02.py | 1,382 | 4.28125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: june-fu
# Date : 2020/3/2
"""
Problem 12: Write a program mydoc.py to implement the functionality of pydoc.
The program should take the module name as argument and
print documentation for the module and each of the functions defined in that module.
$ python mydoc.py os
Help on module os:
DESCRIPTION
os - OS routines for Mac, NT, or Posix depending on what system we're on.
...
FUNCTIONS
getcwd()
...
"""
# Hints:
# The dir function to get all entries of a module
#
# The inspect.isfunction function can be used to test if given object is a function
#
# x.__doc__ gives the docstring for x.
#
# The __import__ function can be used to import a module by name
def my_doc(name):
from inspect import isfunction
p = __import__(name)
print('Help on module', name, '\n\nDESCRIPTION\n')
print(p.__doc__)
print('\nFUNCTIONS\n')
for i in dir(__import__(name)):
if isfunction(p.__getattribute__(i)):
print(i + '()')
def my_doc1(name):
from inspect import getmembers, isfunction
p = __import__(name)
print('Help on module', name, '\n\nDESCRIPTION\n')
print(p.__doc__)
print('\nFUNCTIONS\n')
for f in getmembers(p, predicate=lambda x: isfunction(x)):
print(f[0]+'()')
if __name__ == '__main__':
my_doc('os')
| true |
f4eb12af00d64fdfbdc21cc5e20cb4c74f26d83c | June-fu/python365 | /2020/11November/22reductions.py | 1,244 | 4.3125 | 4 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
'''
# @ Author: june-fu
# @ Create Time: 2020-11-22 13:21:45
# @ Modified by: june-fu
# @ Modified time: 2020-11-22 13:21:49
# @ Description:Boolean reductions
You can apply the reductions: empty, any(), all(), and bool() to provide a way to summarize a boolean result
'''
import pandas as pd
import numpy as np
df = pd.DataFrame({
'one': pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
'two': pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
'three': pd.Series(np.random.randn(3), index=['b', 'c', 'd'])
})
print(df)
print("all:\n", (df > 0).all())
print("empty:\n", (df > 0).empty)
print("any:\n", (df > 0).any())
# you can reduce to a final boolean value
print((df >0).any().any())
# you can test if a pandas object is empty, via the empty property
print("test df is empty or not:\n", df.empty)
print(pd.DataFrame(columns=list('ABC')).empty)
# to evaluate single-element pandas objects in a boolean context, use the method bool()
print("evaluate single-element of Series:\n", pd.Series([True]).bool())
print(pd.Series([False]).bool())
print("evaluate single-element of DataFrame:\n", pd.DataFrame([[True]]).bool())
print(pd.DataFrame([[False]]).bool()) | true |
fcc5fa99e98f7068ce8df64dbb8ff94e7036c56a | June-fu/python365 | /2020/09September/05DataFrame-dict-Series.py | 1,304 | 4.21875 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: june-fu
# Date : 2020/9/14
"""
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it
like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.
Like Series, DataFrame accepts many different kinds of input:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it
like a spreadsheet or SQL table, or a dict of Series objects. It is generally the most commonly used pandas object.
Like Series, DataFrame accepts many different kinds of input:
1. Dict of 1D ndarrays, lists, dicts, or Series
2. 2-D numpy.ndarray
3. Structured or record ndarray
4. A Series
5. Another DataFrame
"""
# From dict of Series or dicts
import numpy as np
import pandas as pd
d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
print(df)
print(pd.DataFrame(d, index=['d', 'b', 'a']))
print(pd.DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three']))
# The row and column labels can be accessed respectively by accessing the index and columns attributes:
print(df.index)
print(df.columns)
| true |
a3af4058478e0f5373999b13ecf3d0c181ab93b7 | June-fu/python365 | /2020/02february/02-Factorization.py | 853 | 4.3125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: june-fu
# Date : 2020/2/2
"""
将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
"""
def is_prime2(num):
for i in range(2, num):
if not (num % i):
return False
return True
def factorization(num):
if num < 2:
print('This number should be a positive integer greater than one!')
return
elif is_prime2(num):
print("This number must be composite!")
return
else:
lst = [x for x in range(2, num) if is_prime2(x)]
str1 = ''
while int(num) != 1:
for i in lst:
if not num % i:
str1 += str(i) + '*'
num /= i
return '*'.join(sorted(str1[:-1].split('*')))
if __name__ == '__main__':
print(factorization(90))
| true |
b0f0ee5c19f5481321ea711250f7c760cb96f5e7 | June-fu/python365 | /2020/01january/05.py | 785 | 4.3125 | 4 | # -*- coding: utf-8 -*-
# Author: june-fu
# Date : 2020/1/19
"""
Python Program for array rotation
Write a function rotate(ar[], d) that rotates arr[] by d elements.
Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Output arr[] = [3, 4, 5, 6, 7, 1, 2]
"""
def left_rotate(arr, d):
i = 0
while i < d:
arr.append(arr[0])
del arr[0]
i += 1
return arr
# 递归实现
def left_rotate2(arr, d):
for i in range(d):
left_rotate_one(arr)
return arr
def left_rotate_one(arr):
temp = arr[0]
for i in range(len(arr)-1):
arr[i] = arr[i+1]
arr[len(arr)-1] = temp
if __name__ == '__main__':
arr1 = [1, 2, 3, 4, 5, 6, 7]
print(left_rotate(arr1, 2))
arr2 = [1, 2, 3, 4, 5, 6, 7]
print(left_rotate2(arr2, 2))
| false |
25b44616f930559e0b02e4b6830504074aa00c6e | wnorales/Python | /Loops/For_Loop.py | 506 | 4.28125 | 4 | List = [8, 10, 20, 30, 40, 50, 60, 70, 80, 90, 300]
for n in range(1, 200):
if n in List:
print(n)
"""Example of a for loop. Prints only numbers within the list above. Does not print 300 since its not in the range from 1-200"""
MagicNumber = 60
for n in range(100):
if n is MagicNumber:
print("The magic number is " + str(n))
"""This just an example of a regular for loop"""
List2 = ['917-231-4287', '631-639-9604', '718-474-6892', '552-987-5014']
for n in List2:
print(n) | true |
f2df0299b186d14f3a1aa6cd63e40ea1777910b5 | wnorales/Python | /Data Structure and Algorithms/Arrays.py | 499 | 4.125 | 4 | from array import *
array1 = array('i', [10, 20, 30, 40, 50, 80])
for x in array1:
print(x)
# Printing specific Elements from an Array
print(array1[0])
print(array1[2])
# Inserting Elements into an Array
array1.insert(1, 15)
for x in array1:
print(x)
# Removing from an Array
array1.remove(50)
for x in array1:
print(x)
# Search in an Array, This will return the index of an Element
print(array1.index(15))
# Updating an element in an Array
array1[5] = 90
for x in array1:
print(x) | true |
783e928ca6a2f2e75abdf76ebacaccec0447e5c1 | MuhammadShahzeb1/1.-Python-Beginners-programs-Part1 | /8.WhileStatement/Break.py | 764 | 4.375 | 4 |
# In this program we will learn about the Break Statement
# The main purpose of break statement is that we can stop the loop on our required value or we can stop the infinity loop that never stops
# for imolementing break statement we usually use if statement
#break statement program that never stops or loop that keeps on running because we dant set the limit
"""i=0
while i<45:
print(i) Now this progrsm will keep on executing as limit is not defined so we have to put limit
i=i+1 """
i=0
while i<45:
print(i)
if i==44: # we use if statement and set the limit that when it reaches 44 perform following function
break #this will stop the program execution so after 44 program will be stoped
i=i+1 | true |
61d0e9e558f27d2b869735c6e02be2625e6a7585 | MuhammadShahzeb1/1.-Python-Beginners-programs-Part1 | /3.PythonListFunctions/main.py | 1,659 | 4.59375 | 5 |
# Now in this program we will explore List Data Structures
# Lists are somehow equlanat to arrays
# in list we store multiple values in a single variable
#list
AhleBait=["Muhammad","Ali","Fatima","Hassan","Hussain",]
print(AhleBait)
print(AhleBait[4]) # now in above list we store five names and we can print any name by putting index number
# now we will see lists in case of numbers
rollno=[12,13,15,11,5,8,9]
print(rollno)
# now we will explore functions and methods in list
# These given below functions cange the original list
rollno.sort()
rollno.reverse()
print(rollno)
print(max(rollno)) # will print max/largest number from list
print(min(rollno)) #will print min/smallest number from list
# List Slicing
# List Slicing can not chnage the oroginal list
print(rollno[0:7]) # in this slicing it will show all numbers
print(rollno[:]) # it will show the same results as above bcz if we dont put vale first will consider least and 2nd max
print(rollno[2:5]) # it will show from index 2 to 5
# Extended Slicing
print(rollno[::2]) # will print with the skipping of every 2nd number in the list
print(rollno[::3]) # will print with the skipping of every 3rd number in the list
# Negative slicing is not recommended except -1
print(rollno[::-1]) # it will print reverse direction
print(rollno[1:7:-1]) #print null
#now we will discuss how can we change the item from list
#Mutable can change
#Immutable can not change
#immutable
tp=(1,3,5)
tp[2]=4
print(tp)
#Mutable
#chnaging the value from list
myrollno[2]=4
print(myrollno) #changing value in list from 7 to 4
| true |
0f1d55c670e758518c5969886abfe74c88ba86c0 | Nico34000/API_ong | /functions_panda.py | 2,831 | 4.21875 | 4 | import pandas
#github-action genshdoc
def csv_file():
"""
This function contains datas from csv file. \n
She return : 'id', 'Country', 'year',
'emission', 'values', 'footnote', 'source'.
"""
csv = pandas.read_csv('co2.csv', header=2, names=['id', 'Country', 'year',
'emission', 'values', 'footnote', 'source'])
return csv
def country_list():
"""
This function contains a list of countries we've in CSV.\n
It serves us to have only a list of the countries present in csv.\n
She return : 'China, Hong Kong SAR', 'Guatemala'...
"""
df = csv_file()
country_list = set(df['Country'].tolist())
return country_list
def latest_by_country(country):
"""
This function is used to send back country, year, and emission
for a country.\n
We use .sort_value to return year in ascending order.\n
She return with "France" (for exemple):
'country': 'France', 'year': 2017, 'emissions': 306123.541
"""
df = csv_file()
df = df.loc[df['Country'].isin([country])].sort_values(['year'],
ascending=False)
result = {}
result["country"] = str(df.iloc[0][1])
result["year"] = int(df.iloc[0][2])
result["emissions"] = float(df.iloc[0][4])
return result
def year_list():
"""
This function contains a list of years we've in column year
in csv.\n
She return :["2016", "1985", "2017", "1995", "2005",
"1975", "2010", "2015"]
"""
year_li = ["2016", "1985", "2017", "1995", "2005", "1975", "2010", "2015"]
return year_li
def average_year(year):
"""
This function does the average of values of emission (thousand metric...)
for a given year.\n
She return with "2017" (for exemple):
'year': '2017', 'total': 219666.44571830984
"""
df = csv_file()
df = df.loc[df['year'].isin([year])]
df = df[(df["emission"] == 'Emissions \
(thousand metric tons of carbon dioxide)')]
mean_year = df.mean()['values']
result = {}
result["year"] = year
result["total"] = float(mean_year)
return result
def per_capi(country):
"""
This function return values for emission (Per capital)
of all years for a given country.\n
She return with "France" (for exemple):
1975: 7.845, 1985: 6.209, 1995: 5.773, 2005: 5.887, 2010: 5.233,
2015: 4.5, 2016: 4.515, 2017: 4.565
"""
df = csv_file()
df = df.loc[df['Country'].isin([country])]
df = df[(df["emission"] == 'Emissions \
per capita (metric tons of carbon dioxide)')]
result = {}
longeur = len(df)
for i in range(longeur):
result[int(df.iloc[i][2])] = float(df.iloc[i][4])
return result
| true |
f2612de13621c037e5723cb5abdc69604d1a712e | joshsarath/Spring-12-CSC-280 | /leapYear.py | 883 | 4.25 | 4 | # Josh Sarath
# This program is a leap year calculator
def leapYear(year):
"""
A boolean function that returns True or False according to
whether year is a leap year.
>>> leapYear(2001)
False
>>> leapYear(2004)
True
"""
return year % 400 ==0 or year % 4==0 and year %100 !=0
def leapYears(startYear, endYear):
"""
This function returns a list of boolean values, one for each
year from startYear to endYear (inclusive) indicating whether the
year was a leap year.
>>> leapYears(2001,2004)
[False, False, False, True]
"""
list = []
for i in range(startYear, endYear + 1):
list.append(leapYear(i))
return list
#
# The following are the standard way to ensure easy testing
#
def main():
print('Testing...')
import doctest
doctest.testmod()
if __name__=='__main__':
main()
| true |
8a6ad026c7e4fae25367f8730c9992e86392a065 | xJackpoTx/xJackpoTx | /1.10 conditions.py | 861 | 4.125 | 4 | x = int(input("Невідоме число"))
if x % 2 == 0:
print("Парне")
else:
print("Не парне")
x = int(input("Невідоме число"))
if x % 3 == 0:
print("Ділиме на 3")
elif x % 3 == 1:
print("решта тільки 1")
else:
print("решта 2")
a = int(input())
b = int(input())
if a != b:
if a > b:
print('Перше число більше!')
else:
print('Друге число більше!')
else:
print('Два числа рівні!')
a = int(input())
b = int(input())
if b != 0:
print(a / b)
else:
print('Ділення неможливе')
b = int(input('Потрібно ввести не нульве значення'))
if b == 0:
print('Ви не впоралися!')
else:
print(a / b)
| false |
ed81c1e1b22780f2d566a659d4f541f0b428b419 | castrofj/CourseCodes | /Python/LógicaProgramaçãoAlgoritmos/ClassificadorEnsino.py | 1,764 | 4.28125 | 4 |
## declaração de variáveis.
parar = "N"
nome = ""
idade = 0
niveis_de_ensino = ["Educação Infantil", "Ensino Fundamental I",
"Ensino Fundamental II", "Ensino Médio"]
## while loop para manter o programa em execução após o fim da rotina.
while parar != "S":
## apresentação e captura de informações do usuário para validação.
print("\n===========================================================")
print("Programa para identificar a etapa de ensino. Por gentileza forneça:")
nome = input("Nome do aluno(a): ")
idade = int(input("Idade do aluno(a): "))
## condicionais para validação dos dados inseridos dentro de cada categoria de ensino.
if idade >= 1 and idade <= 5:
print(f"\nEstudante {nome} tem {idade} anos e está no {niveis_de_ensino[0]}.")
print("===========================================================")
elif idade > 5 and idade <= 10:
print(f"\nEstudante {nome} tem {idade} anos e está no {niveis_de_ensino[1]}.")
print("===========================================================")
elif idade > 10 and idade <= 14:
print(f"\nEstudante {nome} tem {idade} anos e está no {niveis_de_ensino[2]}.")
print("===========================================================")
elif idade > 14:
print(f"\nEstudante {nome} tem {idade} anos e está no {niveis_de_ensino[3]}.")
print("===========================================================")
else:
print("Idade não fornecida corretamente.\n")
# condição de avaliação para término de programa.
print("\nDeseja sair do programa? S - Sim Qualquer tecla - Não")
parar = input("Digite sua resposta: ")
if parar == 'S':
break
| false |
7b1528f72dcacce65307ff68049c9e87bea0b4c6 | Avichai-Aziz/Python | /HomeWorks/HomeWork2/dice3.py | 1,228 | 4.28125 | 4 |
#Student: Avichai Aziz
#Assignment no. 3
#Program: dice3.py
#ex 3: rolling three dice
import random
#define variables
n = int(input("Enter the number of games: "))
k = int(input("Enter the number of equal series: "))
n_game = 0 #number of game
equal_series = 0 #numbers of equal series
n_of_tries = 0 #numbers of tries
while n_game <= n and k <= n:
for n_game in range(1,n+1):
#dropping the dice
dice1 = random.randint(1, 6) #first cube
dice2 = random.randint(1, 6) #second cube
dice3 = random.randint(1, 6) #third cube
print(dice1, ',', dice2, ',', dice3)
if dice1 == dice2 == dice3: #if the dice are equals
equal_series += 1 #add 1 to the equal series
n_of_tries = n_game
if n_game == n and equal_series < k:
print("you failed,reached", equal_series, "equal series")
break
elif equal_series >= k and n_game == n:
print("you win! reached", equal_series, "equal series after", n_of_tries, "games")
break
else: #if the user input number of equal series that bigger than the numbers of games or negative numbers
print("error, try again")
| false |
8ceff027869c2481b80ea54b9f96dbae0c6b992f | Git-Good-Milo/Week-3-Python-2.0 | /102_data_types.py | 1,782 | 4.34375 | 4 | # # For more info on all things Python, use: https://docs.python.org/3/library/
# # Numerical data types
# # - int, long, float, complex
# # These are numerical data types whc we can use numerical operators
# # Complex and long numbers we don't use so much
# # Complex brings and imaginary component to a number
# # Long -
#
# # int - Stands for integers
# # Whole numbers
# my_int = 10
# print(my_int)
# print(type(my_int))
#
# # Opperator - add, subtract, multiply, devide
#
# print(5+6)
# print(8*6)
# print(18/3) # Devisions automatically get converted to float
# print(9-7)
#
# # Modules looks for rhe number of remeinders
# # %
# print(22%5) # --> counts how many remainders are left after the devison. Cant be more than the dividing number
#
# # Comaprrison Operators #--> this outputs a boolean value
#
# # == is the comparison operator
# # < / > bigger than, smaller than. Adding
# # <= less than or equal to
# # >= bigger than or equal too
# # != is not equal to
# # is and is not
#
# my_variable_1 = 10
# my_variable_2 = 13
#
# print(my_variable_1 == my_variable_2)
# print(my_variable_1 > my_variable_2)
# print(my_variable_1 < my_variable_2)
# print(my_variable_1 >= my_variable_2)
# print(my_variable_1 is 15)
# print(my_variable_2 is not 56)
#
# # Boolean values
# # These are difined as etither true or false
# print(type(True))
# print(type(False))
# print(0 == False)
# print(1 == True)
#
# # None
# print(None)
# print(type(None))
# Logocal AND & OR
a = True
b = False
# Using *and*, both sides have to be true for it to result in true
print(a and True)
print(1 == 1 and True)
print(1 == 1 and False)
# Using OR, only one side needs to be true
# This will print true
print(True or False)
print(True or 1 == 2)
# This will print false
print(False or 1 == 2)
| true |
76e22d2d0e9dbd4d1071cf135005aeed40cb5eae | rocco722/electric-bugaloo | /Hangman.py | 1,261 | 4.25 | 4 | import random
def hangman():
"""
Elementary form of Hangman. Two options: A) Another user (Player 1) enters a word
B) Uses four preselected words
String -> String
Convert the string into a list than alter the values accordingly
And end up printing a string 'You win' or 'You loose'
"""
guess = ""
# answer = input('Player 1 enter a word: ') Adjustable to the input of another user
words = ["dog","cat","bird","owl"]
answer = words[random.randrange(0,3)]
location_of_guess = 0
real_answer = list(answer)
# num_guesses = 2 * len(answe)
num_guesses = 10
while num_guesses > 0:
guess = input("Please guess a letter: ")
#list(answer)
#num_guesses = len(answer)
if guess in real_answer:
location_of_guess = real_answer.index(guess)
del(real_answer[location_of_guess])
print('Correct')
num_guesses -=1
if len(real_answer) == 0:
print("You Won!")
break
else:
num_guesses -= 1
print("Please try again. Guesses Remaining: ", num_guesses)
if num_guesses == 0:
print('You lost!')
hangman() | true |
9210b3912f4551aad1e871839ce551791aab7e62 | yash-khandelwal/python-wizard | /Complete Developer Course 2021/basics/lists.py | 2,300 | 4.3125 | 4 | # List
# ordered sequece of object
# li = [1, 2, 3, 4, 5]
# li2 = ['a', 'b', 'c']
# li3 = [1, 2, 'a', True, 'kritagya', [1, 2, 3]] # mixed typed data
# for ele in li3:
# print(f'{ele} is of tyle: {type(ele)}')
# # list slicing
# print(li3[4])
# print(li3[:])
# print(li3[::-1])
# # lists are mutable
# li3[2] = 'replaced element'
# print(li3[:])
# # list gotcha
# print("List Gotcha")
# # assignment copy
# print("\nAssignment copy")
# copyList = li3 # copylist would just point to the same memory block
# print(li3)
# print(copyList)
# copyList[0] = 'item replaced in copy list'
# print(li3)
# print(copyList)
# #shallow copy
# print("\nShallow copy")
# shallowcopy = li3[:] # copylist2 would make shallow copy of original li3
# print(li3)
# print(shallowcopy)
# shallowcopy[1] = 'item replaced in copy list 2'
# print(li3)
# print(shallowcopy)
# # BUT
# shallowcopy[-1].append(4)
# print(li3)
# print(shallowcopy)
# # deep copy
# print("\nDeep copy")
# import copy
# deepcopyli3 = copy.deepcopy(li3)
# print(li3)
# print(deepcopyli3)
# deepcopyli3[-1].append('appended in deepcopy')
# print(li3)
# print(deepcopyli3)
# List Methods
#adding
basket = [1, 2, 3, 4, 5]
print(len(basket))
basket.append(6)
print(basket)
basket.insert(4, 100)
print(basket)
basket.extend([1001, 1002])
print(basket)
# removing
popped = basket.pop()
print("popped: ", popped)
print(basket)
popped = basket.pop(1)
print("popped: ", popped)
print(basket)
removed = basket.remove(1001)
print("removed: ", removed) # None
print(basket)
#basket.remove(100234) # throws error 100234 is not in list
index = basket.index(6) # serching the velue and provide the index of that element
print(index)
freq = basket.count(4)
print(freq)
basket.append(4)
freq = basket.count(4)
print(freq)
print(basket)
basket.reverse()
print(basket)
# sorted_basket = sorted(basket)
# print(sorted_basket)
print(basket)
basket.sort()
print(basket)
basket.clear()
# other functionalities
basket = [1, 2, 3, 4, 5]
ispresent = 5 in basket
print(ispresent)
rl = list(range(100))
print(rl)
words = ['Hi,', 'I', 'am', 'kritagya']
delimeter = ' '
sentance = delimeter.join(words)
print(sentance)
# List Unpacking
print("\nList Unpacking")
[a, b, c, *other, d] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a)
print(b)
print(c)
print(other)
print(d)
# | true |
ce207f66b29885c79a529dc2c6925f51e651947c | Arj09/mca101_manisha | /myPred.py | 810 | 4.21875 | 4 | def myIncrement(number):
'''
Objective : To compute the increment of given number.
Input Variables :
number : The number inputted by user.
Return value : Incremented value of given number.
'''
#Approach : Return number+1
return number+1
tempNumber=0
def myPredecessor(value):
'''
Objective : To find the predecessor of given value.
Input Variables :
value : integer - The number inputted by user.
Return value : Predecessor value of given number.
'''
#Approach : Use recursion.
if value==0 or value==1:
return 0
else:
if value==myIncrement(tempNumber):
return tempNumber
else:
myIncrement(tempNumber)
| true |
6f40aaeb15c26ec35bc92eafe5fe8ca18e5efa74 | MateuszSacha/Selection | /development exercise 3+.py | 622 | 4.1875 | 4 | # Mateusz Sacha
# 07-10-2014
# Development Exercise 3
hours = int(input("Enter the number of hours you worked this week:"))
rate_of_pay = int(input("Enter your hourly rate of pay:"))
if hours >= 0 and hours <= 40:
answer = hours * rate_of_pay
print("{0}: This is how much you have earned this week.".format(answer))
elif hours > 40:
answer1 = hours*(rate_of_pay*1.5)
print("{0}: this is how much you've earned adding the extra hours.".format(answer1))
elif hours > 60:
print("Enter a number between 0 and 60.")
elif hours < 0 :
print("Enter a number beween 0 and 60.")
| true |
498d991d73672c915cd28c1595ecc3a30b7d86df | wufanwillan/leet_code | /Binary Tree Paths.py | 1,271 | 4.1875 | 4 | # Given a binary tree, return all root-to-leaf paths.
# For example, given the following binary tree:
# 1
# / \
# 2 3
# \
# 5
# All root-to-leaf paths are:
# ["1->2->5", "1->3"]
# Credits:
# Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
result,path=[],[]
def depth(node,path,result):
if not node:
return
path.append(str(node.val))
if not (node.left or node.right):
pathlist="->".join(path)
result.append(pathlist)
if node.left:
depth(node.left,path,result)
path.pop()
if node.right:
depth(node.right,path,result)
path.pop()
depth(root,path,result)
return result
| true |
51d51b0c3829afb094a332bc198f16217ee47ef7 | alberzenon/Python_basic | /2.-Cadenas/ejercicio2.py | 624 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 24 13:52:06 2021
@author: alberto
Escribir un programa que pregunte el nombre completo del usuario en la consola y después muestre por pantalla
el nombre completo del usuario tres veces, una con todas las letras minúsculas, otra con todas las letras
mayúsculas y otra solo con la primera letra del nombre y de los apellidos en mayúscula.
El usuario puede introducir su nombre combinando mayúsculas y minúsculas como quiera.
"""
nombre= input("Introduce tu nomber completo")
print(nombre.lower())
print(nombre.upper())
print(nombre.title())
| false |
ec4b88670546ac3bc875a8e6f4ba3c0b6bab1703 | alberzenon/Python_basic | /1.TiposDeDatosSImples/Cadenas2_letars.py | 616 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 21:38:11 2021
@author: alberto
Escribir un programa que pregunte el nombre completo del usuario en la consola y después muestre por pantalla el
nombre completo del usuario tres veces, una con todas las letras minúsculas, otra con todas las letras mayúsculas
y otra solo con la primera letra del nombre y de los apellidos en mayúscula. El usuario puede introducir su nombre
combinando mayúsculas y minúsculas como quiera.
"""
nombre= input("¿Cual es su nombre: ")
print(nombre.lower())
print(nombre.upper())
print(nombre.title())
| false |
9586c7d4b09b87dce5e42c8749ea9a91b57ecd70 | Gummy27/Prog | /Assignment_14/question_1.py | 498 | 4.15625 | 4 | def main():
# Finish the function
user_continue = "y"
my_dict = {}
while(user_continue == "y"):
word = input("Input a word: ")
definition = input(f"Enter the definition for {word}: ")
my_dict[word] = definition
user_continue = input("Would you like to add another word and definition (y/n)?: ")
my_list = []
for key in my_dict:
my_list.append((key, my_dict[key]))
print(sorted(my_list))
if __name__ == "__main__":
main() | true |
fd4bd5af28ae587194d335c3a0233603407d0780 | Gummy27/Prog | /Assignment 1/Basic/question_2.py | 234 | 4.25 | 4 | num_int = int(input("Enter a number: ")) # Do not change this line
# Fill in the missing code below
result_int = num_int * 3 + num_int * 4
print("If the input is", num_int, "then the result is", result_int) # Do not change this line | true |
b66329b05b21d70dc4e6eaca9875d07c06e96e86 | Gummy27/Prog | /Assignment 1/Basic/question_5.py | 208 | 4.375 | 4 | d = float(input("What is the diameter?"))
import math
radius = d / 2
volume = (4/3)*math.pi*(radius**3)
volume_of_half_sphere = volume / 2
print("The volume of the half-sphere is", volume_of_half_sphere) | true |
6f30ba25269af58f15e994cb395a438022ff6a2d | Gummy27/Prog | /Assignment_4/question_6.py | 299 | 4.25 | 4 | mb_per_month = int(input("How much data (in Mb) do you get per month?: "))
n = int(input("How many months have you had this plan?: "))
result = 0
for x in range(n):
mb_used = int(input("How much data did you use this month?: "))
result += mb_per_month - mb_used
print(result+mb_per_month)
| false |
fb76470e4d09ba36772d58a9f584702123325eb9 | Gummy27/Prog | /Midterm_exam_2/question_2.py | 2,520 | 4.1875 | 4 | def main():
file_name = input("Enter filename: ")
file_stream = open_file(file_name)
if file_stream is not None:
file_data = readlines_to_list(file_stream)
print_out_file_data_info(file_data)
user_remove_punctuation = input("Remove punctuation (y/n)?: ")
if(user_remove_punctuation == "y"):
no_punct = remove_punctuation(file_data)
print_out_file_data_info(no_punct)
adjective = input("Enter an adjective (positive form): ")
if(user_remove_punctuation == "y"):
adjective_forms_in_file(adjective, no_punct)
else:
adjective_forms_in_file(adjective, file_data)
else:
print("File {} not found!".format(file_name))
# Your functions appear here
def open_file(filename):
"""
This function opens the file and returns it read.
"""
try:
with open(filename, "r") as file:
return file.read()
except:
return None
def readlines_to_list(file_data):
"""
This function erases all newlines and splits the data into a list. It also
lowers all characters.
"""
file_data_list = file_data.replace("\n", " ")
file_data_list = file_data_list.split(" ")
for index in range(len(file_data_list)):
file_data_list[index] = file_data_list[index].lower()
return file_data_list
def print_out_file_data_info(file_list):
"""
This function prints out how many words were found and the raw list.
"""
print(file_list)
print(f"Found {len(file_list)} words")
def remove_punctuation(file_list):
"""
This function removes punctuation from words. If words are all punctuation they
are deleted.
"""
new_list = []
for word in file_list:
new_word = ""
for letter in word:
if(letter.isalnum()):
new_word += letter
if(new_word):
new_list.append(new_word)
return new_list
def adjective_forms_in_file(adjective, file_data):
"""
This function checks if all forms of a specific adjective is in file.
It will print out all the forms that were found.
"""
found_adjectives = ["", "", ""]
forms = ["", "er", "est"]
for index in range(len(forms)):
if(adjective + forms[index] in file_data):
found_adjectives[index] = adjective + forms[index]
print(tuple(found_adjectives))
# Main program starts here
if __name__ == "__main__":
main() | true |
a877234594ed03e14127eea046af956b88f271d7 | Gummy27/Prog | /Assignment_15/question_1.py | 529 | 4.4375 | 4 | def main():
word_set = set()
user_input = input("Enter a word to add to the set: ")
while(user_input != "q"):
word_set.add(user_input)
print_ordered_set(word_set)
print(f"The size of the set is: {len(word_set)}")
user_input = input("Enter a word to add to the set: ")
def print_ordered_set(word_set: set) -> None:
"""
This will print out the set in order.
"""
for x in sorted(word_set):
print(x, end=" ")
print()
if __name__ == "__main__":
main() | true |
4be9c545cad7531f40e9e72f3fe339e68a0533c9 | https-Learn-to-code-com/Python-codes | /LinkedList/Demo.py | 948 | 4.15625 | 4 | class Node:
data = 0
next = None
def __init__(self):
self.data = 0
self.next = None
class LinkedList:
root = None
def insert(self, data):
n = Node()
n.data = data
temp = self.root
if self.root is None:
self.root = n
else:
while temp.next is not None:
temp = temp.next
temp.next = n
def display(self):
temp = self.root
while temp is not None:
print(temp.data, end=" ")
temp = temp.next
print(end="\n")
if __name__ == "__main__":
linkedList = LinkedList()
while True:
ch = int(input("1.insert\n2.Display\nEnter your choice : "))
if ch is 1:
linkedList.insert(int(input("Enter Data : ")))
elif ch is 2:
print("List is : ", end=" ")
linkedList.display()
elif ch is 10:
exit(0)
| true |
b6e8456f54d66e2a2735f8c21fc7c9a6d9b39a34 | lopesofrin28/Django-course | /part1/PYTHON_LEVEL_ONE/controlflow.py | 1,861 | 4.46875 | 4 | ############COMPARISON OPERATORS
#Greater than
1>2
#Less than
1<2
# Greater than or Equal to
1 <= 2
# Less than or Equal to
1 >= 1
# Equality
1 == 1
1 == "1" #not possible
# Inequality
1!=2
##################################LOGICAL OPERAOTRS
# AND
(1>2) and (2<3)
# OR
(1>2) or (2<3)
# Multiple Logical OPERATORS
(1==2) or (2==3) or (4==4)
###############################CONDITIONAL OPERATORS
# IF OPERATOR
if 1<2:
print("yes!")
if 1<2:
if 2<3:
print("true!")
if 1<2:
print("First block!")
if 20<3:
print("Second block!")
# IF ELSE STATEMENT
if 1<2:
print("hola!")
else:
print("Amigo!")
# ELIF LADDER
if 1<2:
print("IF!")
elif 3==3:
print("ELIF!")
else:
print("ELSE!")
########################################LOOPS
################# FOR LOOPS
# seq = [1,2,3,4,5,6]
# for item in seq:
# # Code here EXAMPLE:if item%2==0:
# print(item)
#
#
# d={"sam":1,"frank":2,"dan":3}
# for k in d:
# print(k)
# print(d[k])
#
#
# mypairs=[(1,2),(3,4),(5,6)]
# for items in mypairs:
# print(items)
#
# for (tup1,tup2) in mypairs:
# print(tup1)
# print(tup2)
# print("\n")
# print(tup2)
# print(tup1)
########### WHILE LOOPS
i=1
while i<5:
print("i is: {}".format(i))
i=i+1
# >>> [1,2,3,4,5]
# [1, 2, 3, 4, 5]
# >>> range(0,5)
# range(0, 5)
# >>> list(range(0,5))
# [0, 1, 2, 3, 4]
# >>> list(range(0,20,2))
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# >>>
for item in range(10):
print(item)
x=[1,2,3,4]
out=[]
for num in x:
out.append(num**2)
print(out)
out=[num**2 for num in x]
print(out)
#PROGRAM TO PRINT STAR PATTERN
# print("Program to print half pyramid: ");
# rows = input("Enter number of rows ")
# rows = int (rows)
# for i in range (0, rows):
# for j in range(0, i + 1):
# print("*", end=' ')
# print("\r")
| false |
b9ea360747213e5feb1b808362ebe272b73feb6c | ea-lang/calculator-2 | /reduce_calculator.py | 1,364 | 4.3125 | 4 | # """
# calculator.py
# Using our arithmetic.py file from Exercise02, create the
# calculator program yourself in this file.
# """
from arithmetic import *
# # Your code goes here
def my_reduce(function,calc_list):
for i in range(len(calc_list)):
if i == (len(calc_list))-1:
return calc_list
else:
calc_list[i:i+2] = function(calc_list[i], calc_list[i+1])
while True:
input_string = raw_input("> ")
input_list = input_string.split(" ")
if input_string.lower() == "q" or input_string.lower() == "quit":
break
elif input_list[0] == "+":
print reduce(add, map(int, input_list[1:]))
elif input_list[0] == "-":
print reduce(subtract, map(int, input_list[1:]))
elif input_list[0] == "*":
print reduce(multiply, map(int, input_list[1:]))
elif input_list[0] == "**":
print power(int(input_list[1]), int(input_list[2]))
elif input_list[0] == "%":
print mod(int(input_list[1]), int(input_list[2]))
elif input_list[0] == "/":
print reduce(divide, map(int, input_list[1:]))
elif input_list[0] == "square":
print square(int(input_list[1]))
elif input_list[0] == "cube":
print cube(int(input_list[1]))
else:
print "Not a valid input. Please try again"
| true |
85530dcc3636f82521ba6ced34290b7ab5c46dae | randykinne/intro-to-programming | /programs/Exam Test.py | 760 | 4.125 | 4 | def main():
money = input("Enter the numerical equivalent for currency: ")
print(convertMoney(money))
def convertMoney(money):
if (money == ".01"):
return "Penny"
elif (money == ".05"):
return "Nickel"
elif (money == ".10"):
return "Dime"
elif (money == ".25"):
return "Quarter"
elif (money == "1.00"):
return "Dollar"
elif (money == "5.00"):
return "Five Dollar"
elif (money == "10.00"):
return "Ten Dollar"
elif (money == "20.00"):
return "Twenty Dollar"
elif (money == "50.00"):
return "Fifty Dollar"
elif (money == "100.00"):
return "One Hundred Dollar"
else:
return "ValueError: Incorrect Input"
main()
| false |
940f7631cbc3e850991f42422d408db5a89e9d7f | Emanuellukas/DesafiosPython | /desafio27.py | 296 | 4.15625 | 4 | print("======== Desafio 27 ========")
#Lê o nomme de uma pessoa, mostrando o primeiro e o último nome separadamente
#nome = input("Digite seu nome completo: ")
nome = "Lucas Emanuel da Silva Nunes"
print("Seu primeiro nome é: {}".format(nome.split()[0]))
print("Seu último nome é: {}".format(nome.split()[-1]))
| false |
15def11ccce0dc42aa07ec321c767da708c0157d | joantyry/bc-16-day4 | /MissingNumber.py | 474 | 4.15625 | 4 | def find_missing(a,b):
'''
You are presented with two arrays, all containing positive integers. One of the arrays will have one extra number, see below:
[1,2,3] and [1,2,3,4] should return 4
[4,66,7] and [66,77,7,4] should return 77
'''
a,b = set(a),set(b)
if (len(a) == len (b) or len(a) == 0 or len(b)==0):
return 0
else:
for num in a:
if num not in b:
return num
for num in b:
if num not in a:
return num
| true |
be1c7feab9de39a641020b45d15c8e884e3e7e00 | lightclient/workedExamples | /examples/temperature_convertor/soln.py | 1,193 | 4.46875 | 4 |
def fahrenheit_to_celsius():
# get the fahrenheit temperature from the user
fahrenheit = float(input("Enter Temperature in Fahrenheit : "))
# use the formula to calculate temperature in celsius
celsius = (fahrenheit - 32) * 5.0/9.0
# output with appropriate units
print("Temperature:" + str(fahrenheit) + "F = " + str(celsius) + "C")
def celsius_to_fahrenheit():
# get the celsius temperature from the user
celsius = float(input("Enter Temperature in Celsius : "))
# use the formula to calculate temperature in fahrenheit
fahrenheit = (celsius * 9.0/5.0) + 32
# output with appropriate units
print("Temperature:" + str(celsius) + "C = " + str(fahrenheit) + "F")
def main():
# get the choice from the user
print("1. Fahrenheit to Celsius")
print("2. Celsius to Fahrenheit")
option = int(input("Your choice :"))
# based on the option call the appropriate function
# if the user enters an invalid option print the appropriate response
if option==1:
fahrenheit_to_celsius()
elif option==2:
celsius_to_fahrenheit()
else:
print("INVALID OPTION!")
if __name__ == '__main__':
main()
| true |
2a90fa2be4daa70ef31f7adfe34ddd5d97263041 | hello-moldova/make-a-page | /2_python/15_function.py | 805 | 4.25 | 4 | def plus(a, b): # 'def' is shorthand for 'define', or 'definition'
print("What is %d + %d?" % (a,b))
print(a+b)
plus(3,4)
plus(6,2)
def minus(a, b):
print("What is %d - %d?" % (a,b))
print(a-b)
def do_everything(a, b):
print("I'm gonna do %d + %d and %d - %d!" % (a,b,a,b))
plus(a,b)
minus(a,b)
print() # You know, this is also a function!
do_everything(9, 2)
def f(x):
return 3*x + 4 # A classic linear function
x = 1
y = f(x)
print()
print("x is %d" % (x))
print("y is 3*x + 4 = %d" % (y))
print()
print("Here's a weird thing about functions")
print("functions can be inside a variable!!")
func = plus
print("Let's do func(3,4), after func = plus")
print()
func(3,4)
func = minus
print("Let's do func(3,4), after func = minus")
print()
func(3,4) | true |
6057d185a2eb02029ecc8735f8c4af28842bea1d | dhruvkirangosu/learnpython | /perimeterCalculator.py | 300 | 4.3125 | 4 | # print ("Please enter the length of side 1 : ")
# print ("Please enter the length of side 2 :")
side1 = float(input("Please enter the length of side 1 : "))
side2 = float(input("Please enter the length of side 2 : "))
perimeter = (side1 + side2) * 2
print ("The perimeter is {}".format(perimeter)) | true |
f608e7a600f4f3cf9ff798191c5b24abff534bda | aileentran/coding-challenges | /revlinkedlist.py | 1,161 | 4.125 | 4 | """Write a function that takes the head node of a linked list and returns the head of a new linked list, where the nodes are in the reverse order.
Test case:
>>> ll = Node(1, Node(2, Node(3)))
>>> new_ll = reverse_linked_list(ll)
>>> new_ll.as_string()
'321
"""
# thoughts
# input: head of linked list
# output: head of linked list (reversed)
# create node class w/being able to print linked list as a string
# self.data, self.next
# while loopin and etc.
# function takes in linked list
# make an.. empty node? or set the node to the first value in linked list
# traverse through linked list
# set each node as the head (clean slate)
# once we hit node.next == None --> break loop
# we return the head of the list
class Node(object):
"""Create node."""
def __init__(self, data, next=None):
self.data = data
self.next = next
def as_string(self):
"""Print node and all it's successors as a string."""
out = []
n = self
while n:
out.append(str(n.data))
n = n.next
return "".join(out)
def rev_ll(node):
head = None
while node:
# create a new head node!
head = Node(node.data, head)
node = node.next
return head
| true |
72005defc5253ddfb3b3d3fc3a723a8e11bd0d9e | altonelli/interview-cake | /problems/python/queue_with_two_stacks.py | 1,649 | 4.21875 | 4 |
# Note: Something you learned here was the usage of class variables vs instance variuables in Python
# be thorough when using class variables and knwoing when and when not to use init
class Stack(object):
def __init__(self):
self.stack = []
def pop(self):
popped = self.stack.pop()
return popped
def push(self, value):
self.stack.append(value)
return value
def is_empty(self):
return len(self.stack) == 0
class Queue(object):
def __init__(self):
self.in_stack = Stack()
self.out_stack = Stack()
def enqueue(self, value):
print("in_stack {}".format(str(len(self.in_stack.stack))))
print("out_stack {}".format(str(len(self.out_stack.stack))))
return self.in_stack.push(value)
def dequeue(self):
if self.out_stack.is_empty():
while not self.in_stack.is_empty():
moving_value = self.in_stack.pop()
print("moving {}".format(str(moving_value)))
self.out_stack.push(moving_value)
return self.out_stack.pop()
def is_empty(self):
return len(self.in_stack.stack) + len(self.out_stack.stack) == 0
def main():
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
while not stack.is_empty():
print(stack.pop())
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
print(queue.dequeue())
queue.enqueue(5)
queue.enqueue(6)
while not queue.is_empty():
print(queue.dequeue())
if __name__ == '__main__':
main()
| true |
a64d96aead9f592b6165302b22889ca9e99aaee6 | altonelli/interview-cake | /problems/python/reverse_string_inplace.py | 493 | 4.125 | 4 |
# If not allowed to use the swap, use a temp variable
def reverse_string_inplace(string):
string_list = list(string)
for idx in range(len(string_list) / 2):
print(string_list[idx])
string_list[idx], string_list[len(string_list) - 1 - idx] = string_list[len(string_list) - 1 - idx], string_list[idx]
print(string_list[idx])
return ''.join(string_list)
def main():
print(reverse_string_inplace("reverse_string"))
if __name__ == '__main__':
main()
| true |
4fafd00614fe77f4552057d865cdfe777102fd4f | BrianWW/cc-example | /src/words_tweeted.py | 1,048 | 4.21875 | 4 | #!/usr/bin/python
import sys
from collections import defaultdict
# example of program that calculates the total number of times each word has been tweeted.
#file_input=open("tweet_input/tweets.txt","r")
#file_output=open("tweet_output/ft1.txt","w")
def main():
if len(sys.argv) == 3:
file_input = open(sys.argv[1],"r")
file_output = open(sys.argv[2],"w")
elif len(sys.argv) == 1:
file_input=open("tweet_input/tweets.txt","r")
file_output=open("tweet_output/ft1.txt","w")
else:
print 'usage: ./words_tweeted.py fileinput fileoutput'
sys.exit(1)
wordcount={}
for word in file_input.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for key in sorted(wordcount):
print "%s \t\t %s" % (key.ljust(20), wordcount[key])
file_output.write("%s \t\t %s \n" % (key.ljust(20), wordcount[key]))
file_input.close()
file_output.close()
if __name__ == '__main__':
main()
| true |
90fa605a6498a79484c016a327771e8b403826d6 | BPCao/Assignments | /WEEK 1/WEDNESDAY/palindrome/palindrome.py | 394 | 4.25 | 4 |
class Palindrome:
def palindrome(self, word):
empty = ''
word = word.lower()
reverse = len(word) - 1
while reverse >= 0:
empty = empty + word[reverse]
reverse -= 1
return reverse
# if empty == word:
# print("This word is a palindrome")
# else:
# print("This word is NOT a palindrome")
| true |
862ec16df414182fb08c2e29d317f90c22949a6f | hieule22/artificial-intelligence | /heuristic-search/pitcher.py | 2,907 | 4.15625 | 4 | ### File pitcher.py
### Implements the water pitcher puzzle for state space search
from search import *
class PitcherState(ProblemState):
"""
The water pitcher puzzle: Suppose that you are given a 3 quart
pitcher and a 4 quart pitcher. Either pitcher can be filled
from a faucet. The contents of either pitcher can be poured
down a drain. Water may be poured from one pitcher to the other.
When pouring, as soon as the pitcher being poured into is full,
the pouring stops. There is no additional measuring device and
and the pitchers have no markings to show partial quantities.
Each operator returns a new instance of this class representing
the successor state.
"""
def __init__(self, q3, q4):
self.q3 = q3
self.q4 = q4
def __str__(self):
"""
Required method for use with the Search class.
Returns a string representation of the state.
"""
return "("+str(self.q3)+","+str(self.q4)+")"
def illegal(self):
"""
Required method for use with the Search class.
Tests whether the state is illegal.
"""
if self.q3 < 0 or self.q4 < 0: return 1
if self.q3 > 3 or self.q4 > 4: return 1
return 0
def equals(self, state):
"""
Required method for use with the Search class.
Determines whether the state instance and the given
state are equal.
"""
return self.q3==state.q3 and self.q4==state.q4
def fillq3(self):
return PitcherState(3, self.q4)
def fillq4(self):
return PitcherState(self.q3, 4)
def drainq3(self):
return PitcherState(0, self.q4)
def drainq4(self):
return PitcherState(self.q3, 0)
def pourq3Toq4(self):
capacity = 4 - self.q4
if self.q3 > capacity:
return PitcherState(self.q3-capacity, 4)
else:
return PitcherState(0, self.q4 + self.q3)
def pourq4Toq3(self):
capacity = 3 - self.q3
if self.q4 > capacity:
return PitcherState(3, self.q4-capacity)
else:
return PitcherState(self.q3 + self.q4, 0)
def operatorNames(self):
"""
Required method for use with the Search class.
Returns a list of the operator names in the
same order as the applyOperators method.
"""
return ["fillq3", "fillq4", "drainq3", "drainq4",
"pourq3Toq4", "pourq4Toq3"]
def applyOperators(self):
"""
Required method for use with the Search class.
Returns a list of possible successors to the current
state, some of which may be illegal.
"""
return [self.fillq3(), self.fillq4(),
self.drainq3(), self.drainq4(),
self.pourq3Toq4(), self.pourq4Toq3()]
Search(PitcherState(0,0), PitcherState(0,2))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.