blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
1ec4bcaf1bc0ce36c63b85550a43ff73a25cada7 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/unique_paths.py | 1,433 | 4.15625 | 4 | """
62. Unique Paths
A robot is located at the top-left corner
of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of
the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Example 3:
Input: m = 7, n = 3
Output: 28
Example 4:
Input: m = 3, n = 3
Output: 6
Constraints
1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 109.
"""
import unittest
from collections import defaultdict
def unique_paths(m, n):
visited = defaultdict(int)
for i in range(1, m + 1, 1):
for j in range(1, n + 1, 1):
if i == 1 or j == 1:
visited[(i, j)] = 1
continue
if not visited[(i, j)]:
visited[(i, j)] = visited[(i, j - 1)] + visited[(i - 1, j)]
return visited[(m, n)]
class TestUniquePaths(unittest.TestCase):
def test_unique_paths_leetcode1(self):
self.assertEqual(28, unique_paths(3, 7))
def test_unique_paths_leetcode2(self):
self.assertEqual(6, unique_paths(3, 3))
| true |
df439ada7c1e5616bc8812c5abc7ed7ce2fae406 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/symmetric_tree.py | 2,995 | 4.3125 | 4 | """
101. Symmetric Tree
Given a binary tree, check whether
it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
"""
import unittest
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def symmetric_tree_rec(root):
if not root:
return True
return symmetric_tree_rec_aux(root.left, root.right)
def symmetric_tree_rec_aux(left, right):
if not left and not right:
return True
if not left or not right:
return False
left_right_check = symmetric_tree_rec_aux(left.left, right.right)
right_left_check = symmetric_tree_rec_aux(left.right, right.left)
return left.val == right.val and left_right_check and right_left_check
def symmetric_tree_iter(root):
if not root:
return True
queue = [root, root]
while len(queue) > 0:
left = queue.pop()
right = queue.pop()
if not left and not right:
continue
if not left or not right:
return False
if left.val != right.val:
return False
queue.append(left.left)
queue.append(right.right)
queue.append(left.right)
queue.append(right.left)
return True
class TestSymmetricTreeRec(unittest.TestCase):
def test_symmetric_tree_empty(self):
self.assertEqual(symmetric_tree_rec(None), True)
def test_symmetric_tree_leetcode1(self):
tree = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)))
self.assertEqual(symmetric_tree_rec(tree), True)
def test_symmetric_tree_leetcode2(self):
tree = TreeNode(1, TreeNode(2, None, TreeNode(3)), TreeNode(2, None, TreeNode(3)))
self.assertEqual(symmetric_tree_rec(tree), False)
def test_symmetric_tree_leetcode3(self):
tree = TreeNode(1, TreeNode(2, TreeNode(2)), TreeNode(2, TreeNode(2)))
self.assertEqual(symmetric_tree_rec(tree), False)
class TestSymmetricTreeIter(unittest.TestCase):
def test_symmetric_tree_empty(self):
self.assertEqual(symmetric_tree_iter(None), True)
def test_symmetric_tree_leetcode1(self):
tree = TreeNode(1, TreeNode(2, TreeNode(3), TreeNode(4)), TreeNode(2, TreeNode(4), TreeNode(3)))
self.assertEqual(symmetric_tree_iter(tree), True)
def test_symmetric_tree_leetcode2(self):
tree = TreeNode(1, TreeNode(2, None, TreeNode(3)), TreeNode(2, None, TreeNode(3)))
self.assertEqual(symmetric_tree_iter(tree), False)
def test_symmetric_tree_leetcode3(self):
tree = TreeNode(1, TreeNode(2, TreeNode(2)), TreeNode(2, TreeNode(2)))
self.assertEqual(symmetric_tree_iter(tree), False) | true |
3b7856ab73bc783a93a51fbfe62ec3ae546574e2 | GhimpuLucianEduard/CodingChallenges | /challenges/leetcode/reverse_linked_list.py | 2,662 | 4.1875 | 4 | """
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
import unittest
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list_rec(head):
if head is None:
return None
if head.next is None:
return head
return reverse_linked_list_rec_aux(head, None)
def reverse_linked_list_rec_aux(head, prev):
if head is None:
return prev
tmp = head.next
head.next = prev
return reverse_linked_list_rec_aux(tmp, head)
def reverse_linked_list_iter(head):
if head is None:
return None
if head.next is None:
return head
prev = None
while head is not None:
tmp = head.next
head.next = prev
prev = head
head = tmp
return prev
class TestReverseLinkedListRec(unittest.TestCase):
def test_reverse_linked_list_rec_empty(self):
self.assertEqual(reverse_linked_list_rec(None), None)
def test_reverse_linked_list_rec_single(self):
l1 = ListNode(1, None)
l2 = reverse_linked_list_rec(l1)
self.assertEqual(l2.val, 1)
self.assertEqual(l2.next, None)
def test_reverse_linked_list_rec_leetcode(self):
l1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, None)))))
l2 = reverse_linked_list_rec(l1)
self.assertEqual(l2.val, 5)
self.assertEqual(l2.next.val, 4)
self.assertEqual(l2.next.next.val, 3)
self.assertEqual(l2.next.next.next.val, 2)
self.assertEqual(l2.next.next.next.next.val, 1)
self.assertEqual(l2.next.next.next.next.next, None)
class TestReverseLinkedListIter(unittest.TestCase):
def test_reverse_linked_list_iter_empty(self):
self.assertEqual(reverse_linked_list_iter(None), None)
def test_reverse_linked_list_iter_single(self):
l1 = ListNode(1, None)
l2 = reverse_linked_list_iter(l1)
self.assertEqual(l2.val, 1)
self.assertEqual(l2.next, None)
def test_reverse_linked_list_iter_leetcode(self):
l1 = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, None)))))
l2 = reverse_linked_list_iter(l1)
self.assertEqual(l2.val, 5)
self.assertEqual(l2.next.val, 4)
self.assertEqual(l2.next.next.val, 3)
self.assertEqual(l2.next.next.next.val, 2)
self.assertEqual(l2.next.next.next.next.val, 1)
self.assertEqual(l2.next.next.next.next.next, None) | true |
4fc04b7cec358f3946f318aa120ae8276c56e0f1 | ellynhan/challenge100-codingtest-study | /hall_of_fame/lysuk96/List/LTC_49.py | 1,467 | 4.1875 | 4 | '''
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 104
0 <= strs[i].length <= 100
strs[i] consists of lowercase English letters.
'''
from typing import List
import collections
def groupAnagrams(strs: List[str]) -> List[List[str]]:
sort = [sorted(word) for word in strs]
words = collections.defaultdict(list)
for index, value in enumerate(sort):
word = ''
for i in range(len(value)):
word += value[i]
words[word].append(index)
ans =[]
for key in words:
tmp = [strs[index] for index in words[key]]
ans += [tmp]
return ans
strs = ["eat","tea","tan","ate","nat","bat"]
print(groupAnagrams(strs))
# 답지와 비교 :
# 정렬하여 dict에 추가하는 부분을 한문장으로 줄일 수 있다.
# 걸린 시간 : 30분
# 내 풀이:
# Runtime: 141 ms, faster than 28.16% of Python3 online submissions for Group Anagrams.
# Memory Usage: 20 MB, less than 8.05% of Python3 online submissions for Group Anagrams.
# 답지 풀이: | true |
39cff954f66ca2d3c6ef3b2b628c2acdf51adaed | HrutvikPal/MyCompletedPrograms | /PrimeNumberChecker.py | 1,385 | 4.21875 | 4 | print("Prime Number Checker")
print("This calculator tells you if the number you entered is a prime or not.")
def checker():
while True:
try:
number = (input("Enter the number:"))
number = int(number)
break
except ValueError:
print("Error 19a1 - You have entered a unrecognizable value. Please enter only an integer.")
if number == 2:
print("2 is a prime number.")
elif number == 1:
print("1 is not a prime number or composite number. It is a unique number.")
else:
for primenum in range(2,number):
if number % primenum == 0:
print(number,"is not a prime number. It is a composite number.")
break
else:
print(number,"is a prime number.")
checker()
while True:
try:
rerun = (str(input("Do you want to rerun the checker?(yes/no):")))
while rerun in ("yes","Yes"):
checker()
rerun = (str(input("Do you want to rerun the checker?(yes/no):")))
if rerun in ("no","No"):
print("Thank you for using the checker.")
break
else:
print("Error 9a - Invalid input. Please enter only yes or no.")
except Exception:
print("Error 1 - Unknown exception. A problem has occurred.")
| true |
1b1e0d49e78ca1ee05757c973948a8634e5f5efe | Lobanova-Dasha/my_python | /hackerrank/classes.py | 2,821 | 4.34375 | 4 | #! python3
# classes.py
import math
# Classes: Dealing with Complex Numbers
# you are given two complex numbers,
# and you have to print the result of their
# addition, subtraction, multiplication, division and modulus operations.
# The real and imaginary precision part should be correct up to
# two decimal places.
class Complex(object):
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
'''addition'''
def __add__(self, no):
real = self.real + no.real
imaginary = self.imaginary + no.imaginary
return Complex(real, imaginary)
'''subtraction'''
def __sub__(self, no):
real = self.real - no.real
imaginary = self.imaginary - no.imaginary
return Complex(real, imaginary)
'''multiplication'''
def __mul__(self, no):
real = self.real*no.real - self.imaginary*no.imaginary
imaginary = self.real * no.imaginary + self.imaginary * no.real
return Complex(real, imaginary)
'''division'''
def __div__(self, no):
x = float(no.real**2 + no.imaginary**2)
y = self * Complex(no.real, -no.imaginary)
real = y.real/x
imaginary = y.imaginary/x
return Complex(real, imaginary)
'''modulus operations'''
def mod(self):
real = math.sqrt(self.real**2 + self.imaginary**2)
return Complex(real, 0)
def __str__(self) :
return '{0:.2f}{1:+.2f}i'.format(self.r,self.j)
# Class 2 - Find the Torsional Angle
# Task. You are given four points A,B,C and D in a
# 3-dimensional Cartesian coordinate system.
# You are required to print the angle between
# the plane made by the points A,B,C and B,C,D in degrees(not radians).
# Let the angle be PHI.
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, no):
x = self.x-no.x
y = self.y-no.y
z = self.z-no.z
return Points(x, y, z)
def dot(self, no):
x = self.x*no.x
y = self.y*no.y
z = self.z*no.z
return x+y+z
def cross(self, no):
x = self.y*no.z - self.z*no.y
y = self.z*no.x - self.x*no.z
z = self.x*no.y - self.y*no.x
return Points(x, y, z)
def absolute(self):
return pow((self.x**2 + self.y**2 + self.z**2), 0.5)
if __name__ == '__main__':
points = []
for i in range(4):
a = map(float, input().split())
points.append(a)
a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3])
x = (b-a).cross(c-b)
y = (c-b).cross(d-c)
angle = math.acos(x.dot(y) / (x.absolute() * y.absolute()))
print('{0:.2f}'.format(math.degrees(angle)))
| true |
7ea118afbecab6b19273e8ccd34ede14e5448e6e | raelasoul/python-practice | /ex19.py | 1,846 | 4.3125 | 4 | # FUNCTIONS & VARIABLES
#
# Variables in the function are different from others that are listed below
# cheese_count and boxes_of_crackers can accept values that are assigned to
# variables. (i.e., cheese_count can be passed the value that is assigned to amount_of_cheese)
# define function, indicate arguments
# indicate what is performed in this function
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You have {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a party!")
print("Get a blanket.\n")
# Method 1:
# directly gives the function the numbers
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
# uses variables to pass to the function
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
# ---------------------------------
# Method 2:
# function is called and variables are the arguments of the function
# this will print:
# "You have {10} cheeses (amount_of_cheese = 10)
# You have {50} boxes of crackers (amount_of_crackers = 50)
# Man that's enough for a party!
# Get a blanket."
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# ---------------------------------
#Method 3:
# using math and passing to function
# this will plug in the calculations in function
# 10 + 20 = amount_of_cheese
# 5 + 6 = amount_of_crackers
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
# ---------------------------------
# Method 4:
# uses variables and math
# this will take 110 (amount_of_cheese + 100)
# and 1050 (amount_of_crackers + 1000) and plug into
# {cheese_count} and {boxes_of_crackers}
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) | true |
ecac4825a12c77f37ea529c9ccf44492f7aacf22 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - eliminate vowels .py | 1,125 | 4.59375 | 5 | # The continue statement is used to skip the current block and move ahead to the next iteration, without executing the statements inside the loop.
# It can be used with both the while and for loops.
# Your task here is very special: you must design a vowel eater! Write a program that uses:
# a for loop;
# the concept of conditional execution (if-elif-else)
# the continue statement.
# Your program must:
# ask the user to enter a word;
# use userWord = userWord.upper() to convert the word entered by the user to upper case
# use conditional execution and the continue statement to "eat" the following vowels A, E, I, O, U from the inputted word;
# print the uneaten letters to the screen, each one of them on a separate line.
# userWord = input("Enter your word: ")
# userWord = userWord.upper()
userWord = input("Enter your word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
else:
print(letter) | true |
c28ca6c77cf0a37dc9fe4f2714387083e68f02cd | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - Eliminate vowels 2.py | 1,328 | 4.53125 | 5 | # Your task here is even more special than before: you must redesign the (ugly) vowel eater from the previous lab (3.1.2.10) and create a better, upgraded (pretty) vowel eater! Write a program that uses:
# a for loop;
# the concept of conditional execution (if-elif-else)
# the continue statement.
# Your program must:
# ask the user to enter a word;
# use userWord = userWord.upper() to convert the word entered by the user to upper case;
# use conditional execution and the continue statement to "eat" the following vowels A, E, I, O, U from the inputted word;
# assign the uneaten letters to the wordWithoutVovels variable and print the variable to the screen.
# Look at the code in the editor. We've created wordWithoutVovels and assigned an empty string to it. Use concatenation operation to ask Python to combine selected letters into a longer string during subsequent loop turns, and assign it to the wordWithoutVovels variable.
wordWithoutVowels = ""
userWord = input("Enter your word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "I":
continue
elif letter == "O":
continue
elif letter == "U":
continue
else:
wordWithoutVowels += letter
print(wordWithoutVowels) | true |
9ae70ab4d13fff5d34956e75254312ecd297c505 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt - Exercise - Calculate pyramid height.py | 537 | 4.34375 | 4 | # Listen to this story: a boy and his father, a computer programmer, are playing with wooden blocks. They are building a pyramid.
# Their pyramid is a bit weird, as it is actually a pyramid-shaped wall - it's flat. The pyramid is stacked according to one simple principle: each lower layer contains one block more than the layer above.
blocks = int(input("Enter the number of blocks: "))
height = 0
inlayer = 1
while inlayer <= blocks:
height += 1
blocks -= inlayer
inlayer += 1
print("The height of the pyramid:", height) | true |
924a0f5b9132067a5568993d54fa925b9bfd9471 | Catalincoconeanu/Python-Learning | /Python apps&practice/Entry level/Prompt Simple IF - ELSE statement.py | 325 | 4.21875 | 4 | #Sample of simple if - else statement
#This app will ask you for a nr then compare it with nr 5, if is bigger then 5 will print first block of code if not will print the second.
x = input("Enter a nr: ")
y = int(x)
if y > 5:
print("The nr is greater then 5")
else:
print("The nr is smaller then 5")
print("All Done!") | true |
60c08f8f81efe91b31b48d81ee5f0b1f2c392f57 | ilyaLihota/Homework | /4/like.py | 608 | 4.21875 | 4 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
"""Describes amount of likes."""
def likes(*arr: str) -> str:
if len(arr) == 0:
return "no one likes this"
elif len(arr) == 1:
return "{} likes this".format(*arr)
elif len(arr) == 2:
return "{} and {} like this".format(*arr)
elif len(arr) == 3:
return "{}, {} and {} like this".format(*arr)
else:
return "{}, {} and {} others like this".format(*arr[:2], len(arr)-2)
if __name__ == "__main__":
amount_of_likes = likes("Alex", "Jacob", "Mark", "Max")
print(amount_of_likes) | true |
dca174b710bca78ba469904b35f3c18518bc6c80 | gautam-balamurali/Python-Programs | /alternating.py | 608 | 4.21875 | 4 | #Define a Python function "alternating(l)" that returns True if the values in the input list alternately go up and down (in a strict manner).
#For instance:
#>>> alternating([])
#True
#>>> alternating([1,3,2,3,1,5])
#True
#>>> alternating([3,2,3,1,5])
#True
#>>> alternating([3,2,2,1,5])
#False
#>>> alternating([3,2,1,3,5])
#False
def alternating(l):
if (len(l)==0 or len(l)==1):
return True
d=l[0]>l[1]
for i in range(len(l)-1):
if d:
if not l[i]>l[i+1]:
return False
else:
if not l[i]<l[i+1]:
return False
d=not d
return True
k=input("enter list ")
print alternating(k)
| false |
8aa0b06eaaf38499b0b84acb870c114def3fa7bb | dirham/pyhton-hard-way | /ex2.py | 527 | 4.25 | 4 | print "i will count my chickern :"
print "hens ", 25 + 30 / 2
print "Roosters ", 100 - 25 * 3 / 4
print "now i will count the egs :"
print 2 + 3 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is true that 3 + 2 < 5 - 7 ?"
print 3 + 2 < 5 - 7
print "What is 3 + 2 ?", 2 + 3
print "What is 5 - 7 ?", 5 - 7
print "oh, that's why is false "
print "How about so more ?"
print "Is it greater?", 5 > -2
print "is it greater or equal ?", 5 >= -2
print "is it less or equal ?", 5 <= -2
print 7 / 4, "'7 / 4 compare with 7.0 / 4.0 '", 7.0 / 4.0
| false |
e793c31d5aad2b6bade7b2be47bce8272974789d | ReynaCornelio/Computacional1 | /Actividad 2/programa4.py | 562 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 20:34:57 2016
@author: Reyna
"""
n = int(input("Enter an integer: " ))
if n%2==0:
print("even")
else:
print("odd")
print ("Enter two integers, on even, one odd.")
m = int(input("Enter the first integer: 1") )
n = int(input("Enter the second integer: "))
while (m+n)%2==0:
print ("One must be even the other odd.")
m = int(input("Enter the first integer: " ))
n = int(input("Enter the second integer: "))
print("The numbers you chose are",m,"and",n)
| true |
f506fee048da6fafd27321c7ed60b55423c9d0b5 | Johnathanseymour696/Python | /check.py | 1,707 | 4.15625 | 4 | #This is a check/review to make sure nothing was "lost" over break
#Johnathan Seymour
#P1
#Variable declaration and assignment
#example
myVar = "hello"
# Try to , declare two variables 1 string and 1 a number, and assign values
myNum = 1
#while loop
# Example
x = 11
while x > 0:
print(x)
x = x - 1
# you try, print your name 100 times
myNumber = 100
while myNumber > 0:
print("Johnathan Seymour" + str(myNumber))
myNumber = myNumber -1
#String concatenation
#Example
name = "Johnathan"
print("Hello " + name)
#make a variable with your favorite move
#print "My favorite movie is " and then the value stored in the variable
fmovie = "The Terminal"
print("My favorite movie is " + fmovie)
myName = input("What is your name :")
print("Your name is " + myName)
# prompt for favorite song and print your favorite song is: ""
song = input("What is you favorite song ? :")
print("Your favorite song is " + song)
# casting: Changing the type of variable
myMath = 40
print("My Number is " + str(myMath))
num1 = input("Enter a number: ")
num1 = int(num1) + 10
print("num1 + 10= "+ str(num1))
#ask for two numbers add them together and print the result
num2 = input("What is your first number ?: ")
num3 = input("What is your second number ?: ")
num4 = int(num2) + int(num3)
print("First number + Second number = " + str(num4))
#if/else
#example
num = int(input("Type a number: "))
if num > 100:
print("Your number is more than 100")
elif num1 == 100:
print("Your number is equal to 100")
else:
print("Your number is less then 100")
#ask if today is your birthday, if it is print happy birthday
birthday = input("Is it your birthday today (yes/no) ?")
if birthday == | true |
05d858ffea04704c16191ad260c24a728b1df156 | jTCode2408/Intro-Python-I | /src/14_cal.py | 2,309 | 4.5625 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
##2 args
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
##if NO INPUT SPECIFIED, print CURRENT month(DATETIME)
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
##if MONTH ONLY, print MONTH PASSED IN for CURRENT year(datetime)
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
##if BOTH month and year, render calendar for THAT MONTH/YEAR inputted
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
##NO INPUT GIVEN, print message prompting for args
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
import sys
import calendar
from datetime import datetime
#check for input values in term
inputs = sys.argv
now = datetime.now()
month = now.month
year = now.year
#if input not specified, return current month only
if len(inputs) == 1:
print(month) ##should return this month
pass
#if 1 arg given, assume to be month. return that month AND ADD CURRENT year
elif len(inputs) == 2:
month=int(inputs[1]) #index 1, should be month position
#if BOTH, redner both
elif len(inputs) == 3:
month = int(inputs[1])
year=int(inputs[2]) #index 2, shold be year positon
#if NO ARGS, prompt
else:
print("format expected: 14_cal.py [month] [year]")
#print cal in term
cal = calendar.TextCalendar()
cal.prmonth(year, month) | true |
1b3cc20b4d0abdb6af7442bc574a9819b12695b5 | LennyBoyatzis/compsci | /problems/inflight_entertainment.py | 1,017 | 4.34375 | 4 | from typing import List
def can_two_movies_fill_flight(movie_lengths: List,
flight_length: int) -> bool:
"""Determines whether there are two movies whose length is equal to flight
length
Args:
flight_length: Length of the flight in minutes
movie_lengths: List of movie durations
Returns: Boolean indicating whether there are two movies whose length is
equal to that of the flight
"""
movie_lengths_seen = set()
# O(n) solution
for first_movie_length in movie_lengths:
matching_second_movie_length = flight_length - first_movie_length
# O(1) lookup to see if already in set
# Set is just a hash map without a value (only a key)
if matching_second_movie_length in movie_lengths_seen:
return True
movie_lengths_seen.add(first_movie_length)
return False
if __name__ == "__main__":
result = can_two_movies_fill_flight([4, 3, 2], 5)
print("result {}".format(result))
| true |
caea37fde1f2b0f8871ae93802951fcc9b439fc7 | LennyBoyatzis/compsci | /problems/reverse_words.py | 1,112 | 4.25 | 4 | from typing import List
def reverse_words(message: List) -> List:
"""Reverses words in a message
Args:
message: lists of words to be reversed
Returns:
Reversed words in a list
"""
return ''.join(message).split(' ')[::-1]
def reverse_chars_in_place(message: List) -> List:
"""Reverses chars in a message in place
Args:
message: lists of chars to be reversed
Returns:
Reversed chars in a list
"""
left = 0
right = len(message) - 1
while left < right:
message[left], message[right] = message[right], message[left]
left += 1
right -= 1
return message
def reverse_words_in_place(message: List) -> List:
"""Reverses words in a message in place
Args:
message: lists of words to be reversed
Returns:
Reversed words in a list
"""
pass
if __name__ == "__main__":
message = ['c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
's', 't', 'e', 'a', 'l']
result = reverse_words_in_place(message)
print("result", result)
| true |
b1be35f0320b213d35ab5434c7d985d290c08a94 | LennyBoyatzis/compsci | /problems/get_max_profit.py | 840 | 4.1875 | 4 | from typing import List
def get_max_profit(stock_prices: List) -> int:
"""Calculates the max profit for a given set of stock prices
Args:
List of stock prices
Returns: Maximum profit
"""
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
for current_time in range(1, len(stock_prices)):
current_price = stock_prices[current_time]
potential_profit = current_price - min_price
max_profit = max(max_profit, potential_profit)
min_price = min(min_price, current_price)
return max_profit
if __name__ == "__main__":
prices = [1, 5, 3, 2]
result = get_max_profit(prices)
assert result == 4
print("result: {}".format(result))
| true |
ef0b085234cd62c3bf843989e43843be82f5116d | pranali0127/Python-AI-Ml | /Python_program_3_list.py | 1,092 | 4.3125 | 4 | #List
#let's first create demo list
numbers = [1,2,3,4,5,6,7,8,9,10]
#printing a list
print(numbers)
#method 1 : append(value)
# add new elements to the list
# can only add one element at a time
numbers.append(11)
print(numbers)
#method 2 : extend(values)
# add one or more than one element at a time
new = [12,13,14]
numbers.extend(new)
print(numbers)
#method 3 : insert(index,value)
#inserts spectific value to the index given
numbers.insert(0,0)
print(numbers)
#method 3 : sum(list)
#calculates the sum of all the elements of List
#this only sums the numeric values otherwise throw TypeError
print( sum(numbers) )
#method 4 : count()
#calculates total occurrence of given element of list
print( numbers.count(11) )
#method 5 : len(list)
#calculates total length of the list
print( len(numbers) )
#method 6 : index()
#Returns the index of first occurrence.
#Start and End index are not necessary parameters.
print( numbers.index(4) )
#method 7 : min()
#calculates minimun of the list
print( min(numbers) )
#method 8 : max()
#calculates maximum of the list
print( max(numbers) )
| true |
ccd0b3314bfbd668bc1ad44b72a130eeca0611aa | dbialon/LPTHW | /ex20.py | 1,905 | 4.3125 | 4 | from sys import argv, exit
script, input_file = argv
## print the whole file f using .read()
## could use this instead
## print open(input_file).read()
## but we want to use the file globally
## not just in this function
def print_all(f):
print(f.read())
## we're using .seek to go back to a line in file
## .seek(offset[, whence])
## offset is the 'distance' from current position 'whence'
## whence is set to 0 as default and can be ommitted
## 0 begining of file
## 1 current position, 2 end of file
def rewind(f):
f.seek(0)
## prints just one line
## .readline reads a line in current position
## and after sets position in the next line
## line_count just counts the lines
## .readline() moves the cursor to the next line
## .strip() removes '\n' at the end of each line
def print_a_line(line_count, f):
print(line_count, " ---> ", f.readline().strip())
## opens the input file
current_file = open(input_file, 'r')
print("\nFirst let's print the whole file:\n")
## prints the whole file, now position is at the end of the file
## so we need to rewind to the beginning
print_all(current_file)
print("\nNow let's rewind, kind of like a tape.\n")
## rewind to the beginning, position 0
rewind(current_file)
print("""
Let's print three lines:"
LC ---> .readline()
""", end="")
## we're in 0 position, .readline prints line 1 of current_file
## and sets position in line 2
current_line = 1 ## current line = 1
print_a_line(current_line, current_file)
## here it prints line 2 and goes to line 3
current_line += 1 ## current line = 2
print_a_line(current_line, current_file)
## here it prints line 3 and after it runs
## sets position at the end of the file
## because there are only 3 lines
current_line += 1 ## current line = 3
print_a_line(current_line, current_file)
## close the file
current_file.close()
exit(0) | true |
1c71fa4139919cc9960dee2e49b0f7d0961569fa | igoroya/igor-oya-solutions-cracking-coding-interview | /crackingcointsolutions/chapter1/excersisenine.py | 1,097 | 4.125 | 4 | '''
Created on 11 Aug 2017
String rotation: Assume you have a method isSubstring which checks if one word is a substring
of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one
call to isSubstring (e.g. "waterbottle" is rotation of "erbottlewat)
@author: igoroya
'''
def is_substring(string, substring):
return substring in string
def is_rotation(s1, s2):
if len(s1) is not len(s2):
return False
#pick 1st word of s1, loop over str2 until found
chars_start = ''
ref_char = s1[0]
for i in range(len(s2)):
if s2[i] is ref_char:
chars_end = s2[i+1:len(s2)]
break
else:
chars_start += s2[i]
compare = chars_end + chars_start
return is_substring(s1, compare)
if __name__ == '__main__':
s1 = "aeiou"
s2 = "ouaei"
print(is_rotation(s1, s2))
s1 = "william"
s2 = "wallace"
print(is_rotation(s1, s2))
s1 = "waterbottle"
s2 = "erbottlewat"
print(is_rotation(s1, s2))
s1 = "a"
s2 = "22"
print(is_rotation(s1, s2))
| true |
416d4b5679807fff1a1d780250cb43e25dd6445e | Kulchutskiyyura/Yura | /classwork/classwork.py | 1,507 | 4.125 | 4 |
try:
number=int(input("enter nymber: "))
if number%2==0:
print("парне")
else:
print("непарне")
except ValueError:
print("некоректні дані")
def chack(age):
if age<=0:
raise ZeroDivisionError("That is not a positive number!")
while 1:
try:
age = int(input("enter your age: "))
chack(age)
if age%2==0:
print("парне")
else:
print("непарне")
except ZeroDivisionError as e:
print(e)
except ValueError:
print("некоректні дані")
else:
break
while 1:
data=input("enter number: ")
try:
firt_number=float(data[0])
second_number=float(data[2])
if(data[1]!=","):
raise ValueError("you should enter , between number")
except ZeroDivisionError as e:
print(e)
except ValueError as e:
print(e)
else:
m=firt_number/second_number
print(m)
break
finally:
print("good")
dict_week={1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"}
while 1:
try:
number=int(input("enter number: "))
print(dict_week[number])
except ValueError:
print("you enter wrong data")
except KeyError:
print("your number is out of range")
else:
n=input("do you want enter one more number: ")
if n=="n":
break
| false |
e6e5292490e46de3c51faa44ca7d88a7cdc51c64 | Kulchutskiyyura/Yura | /Multiples_of_3_or_5/Multiples_of_3_or_5.py | 252 | 4.25 | 4 | def find_sum_of_multiples_3_5(number):
sum=0
for i in range(number):
if(i%3==0):
sum+=i
print(i)
elif(i%5==0):
sum+=i
print(i)
return sum
print(find_sum_of_multiples_3_5(10))
| false |
d623377f72ea7bcb440d001b456e676a39cd642c | gungorahmet/algorithm-practices | /question_4/solution_4/division_without_divide_solution.py | 1,932 | 4.28125 | 4 | #!/usr/bin/python3
'''
Applied PEP8 (pycodestyle)
Author: Ahmet Gungor
Date : 03.01.2020
Description : This problem was asked by Nextdoor.
Implement integer division without using the
division operator. Your function should return a tuple of (dividend, remainder)
and it should take two numbers, the product and divisor.
For example, calling divide(10, 3) should return (3, 1) since the divisor is 3
and the remainder is 1.
Bonus: Can you do it in O(log n) time? --> Bitwise solution is O(log n) but slower.
Status = Completed
'''
import sys
class Division():
def __init__(self, product, divisor):
self.product = product
self.divisor = divisor
print(f"\n{self.product} {self.divisor}\n")
def divide(self):
self.dividend = 0
self.remainder = 0
if self.divisor == 0:
print("0 division error")
sys.exit(1)
if self.product == 0:
tuple_result = (self.product, self.remainder)
return tuple_result
multiply_of_values = self.find_value_sign(self.product) * self.find_value_sign(self.divisor)
self.product = abs(self.product)
self.divisor = abs(self.divisor)
while self.product > 0:
if self.product < self.divisor:
self.remainder = self.product
break
self.product -= self.divisor
self.dividend += 1
tuple_result = (self.dividend * multiply_of_values, self.remainder)
return tuple_result
def find_value_sign(self, num):
if num > 0:
return 1
elif num < 0:
return -1
else:
return 0
if __name__ == "__main__":
product = 22
divisor = -3
instance = Division(product, divisor)
tuple_result = instance.divide()
print(tuple_result)
| true |
6aa200771edd89a5c97c301512a6fedc2c608fbe | shitalmahajan11/letsupgrade | /Assingment2.py | 2,854 | 4.25 | 4 |
# LetsUpgrade Assignment 2
1. Back slash:- it is continuation sign.
Ex. print*("hello \
welcome")
2. triple Quotes:-represent the strings containing both single and double quotes to eliminate the need of escaping any.
Ex:- print("""this is python session""")
3.String inside the quotes:-there are 2 way to declared on string inside the quotes.
Ex. 1) print('hello world')
2) print("python's World")
4. Escape Sequence of String:- the backslash "\" is a special character, also called the "escape" character.and"\t" is a tab, "\n" is a newline, and "\r" is a carriage return are used.
Ex:- print("hello\tworld")
print("welcome\nhome")
5.Formatted output:- There are several ways to present the output of a program, data can be printed in a human-readable form, or written to a file for future use.
Ex:- name=ABC
age=24
print("the name of person is", name," age is",age)
# variable:- variables means linking of the data to name or A Python variable is a reserved memory location to store values.
Ex:- a=20
# Rules to variable
1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
# python Operator:-
there are 7 type of operator
1. Arithmatic operator
2. Comparison Operator
3. Assignment Operator
4. Bitwise Operator
5. Logical operator
6. Membership Operator
7. Identity Operator
# Arithmatic Operator:- Arithmetic operators are used with numeric values to perform common mathematical operations.
1. + Addition
2. - Subtraction
3. * Multiplication
4. / Division
5. % Modulus
6. ** Exponentiation
7. // Floor division
# Comparision Operator:-Comparison operators are used to compare two values.
1. == Equal
2. != Not equal
3. > Greater than
4. < Less than
5. >= Greater than or equal to
6. <= Less than or equal to
# Assignment Operator:-Assignment operators are used to assign values to variables.used = operator.
# Bitwise operators are used to compare (binary) numbers:-
1. & AND
2. | OR
3. ^ XOR
4. ~ NOT
5. << Zero fill left shift
6. >> Signed right shift
# Logical operator:-Logical operators are used to combine conditional statement.
1. and
2. or
3. not
# Membership Operator:-Membership operators are used to test if a sequence is presented in an object.
1. in
2. not in
# Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory locationIdentity Operator.
1. is
2. is not
| true |
eb1289f5ae2fc5e25f5bc827eadf37748b35953b | ShantanuJhaveri/LM-Python_Basics | /learning_modules/learning_Expressions&Operators/experssions&operators_A1.py | 2,673 | 4.1875 | 4 | # Shantanu Jhaveri, sj06434@usc.edu
# ITP 115, Spring 2020
# Assignment 1
# Description:
# This program creates a Mad Libs story that was generated through an interview with a 10 year old cousin.
# The text generated is what he wanted.
# The code takes an input from the user and prints output, which in this case is the Mad Lib.
# 5 strings requirement
print("\n\n\nPlease refrain from entering spaces after the \":\" and after your input.\n\n\n")
name = str(input("Enter a name:").capitalize())
name1_gender = str(input("Enter the gender of " + '"{}"'.format(name) + " by stating his or her:").lower())
name2 = str(input("Enter another name:").capitalize())
name2_gender = str(input("Enter the gender of " + '"{}"'.format(name2) + " by stating his or her:").lower())
animal = str(input("Enter an animal (singular):").lower())
animal2 = str(input("Enter another animal (singular):").lower())
adjective1 = input("Enter an adjective:").lower()
adjective2 = input("Enter another adjective:").lower()
verb = input("Enter a verb:").lower()
gerund = input("Enter a verb ending in 'ing':").lower()
# 3 numbers requirement
number = int(input("Enter a number:"))
number2 = int(input("Enter a second number:"))
number3 = int(input("Enter a third number:"))
# 1 float requirement
decimal = float(input("Enter a number with a decimal:"))
# spaces
print("\n\n\n")
# Madlib story
print('"{}"'.format(name) + ", the " + '"{}"'.format(adjective1) + " " + '"{}"'.format(animal) + ", loved it when " +
'"{}"'.format(name2) + ", the " + '"{}"'.format(adjective2) + " " + '"{}"'.format(animal2) + ", would gargle the "
+ '"{}"'.format(number) + " tons of saliva in " + '"{}"'.format(name2_gender) + " mouth.")
print("Sometimes, " + '"{}"'.format(name) + " would push " + '"{}"'.format(name2) + " to the limit by adding " +
'"{}"'.format(number2) + " additional tons to the mix. That meant " + '"{}"'.format(name2) + " would have " +
'"{}"'.format(number + number2) + " tons of saliva in his mouth. I know, " + '"{}"'.format(name) +
" is a pretty crazy guy, right...")
print("Anyways, I think we should " + '"{}"'.format(verb) + " in a cave with " + '"{}"'.format(name) +
" to end this madness before it's too late. This way " + '"{}"'.format(name2) + " can continue " +
'"{}"'.format(gerund) + " in piece, ya feel. We will give " + '"{}"'.format(name2) + " approximately " +
'"{}"'.format(decimal) + " oz of water to gargle to prevent withdrawals from past habits.")
print("We will probably have to " + '"{}"'.format(verb) + " with " + '"{}"'.format(name) + " for at least " +
'"{}"'.format(number3) + " years before this weird interaction is over.")
| true |
110ef2545cbf3634c0caf1c0dec15d50f7f15567 | jhcoolidge/AffineCipher | /main.py | 1,700 | 4.28125 | 4 |
def encrypt(message, magnitude, shift):
encrypted_message = ""
for index in range(len(message)):
character = ord(message[index])
encrypted_char = character * magnitude
encrypted_char = encrypted_char + shift
encrypted_char = chr((encrypted_char % 26) + 65) # Mod 26 to stay in the alphabet, + 65 for ASCII Table
encrypted_message = encrypted_message + encrypted_char
return encrypted_message
def decrypt(encrypted_message, magnitude, shift):
decrypted_message = ""
for index in range(len(encrypted_message)):
character = ord(encrypted_message[index])
decrypted_char = character - shift
decrypted_char = decrypted_char * (find_inverse(magnitude))
decrypted_char = chr((decrypted_char % 26) + 65) # Mod 26 to stay in the alphabet, + 65 for ASCII Table
decrypted_message = decrypted_message + decrypted_char
return decrypted_message
def find_inverse(num):
i = 1
while True:
check = num * i
if check % 26 is 1:
return i
i = i + 1
def main():
x = 3
y = 6
message = input("Enter the message to encrypt!\n")
check = input("Do you want to choose a magnitude (a) and shift(b)? (y/n)")
if check is "y":
x = int(input("Enter magnitude(a). "))
y = int(input("Enter shift(b). "))
encrypted_message = encrypt(message, x, y)
print("The encrypted message is: " + encrypted_message)
decrypted_message = decrypt(encrypted_message, x, y)
print("The decrypted message is: " + decrypted_message)
return
if __name__ == "__main__":
main()
| true |
7286241364f3ae973ef2f71a2d5d8e0835eaf24f | Catalin-Ioan-Sapariuc/Pet-Python-projects | /quadraticeqsolver.py | 1,769 | 4.4375 | 4 | ## this code solves the quadratic equation : a*x^2+b*x+c=0
## for modularization, we solve the problem in a function: quadraticeqsolver(a,b,c) , which returns (as a list)
## the solution of the quadratic equation a*x^2+b*x+c=0
## a, b and c are inputted by the user, they could be hard coded as well
## by Ioan Sapariuc, July 5, 2021
import math as m
##a = 1.
##b=2.
##c=1.
def quadraticeqsolver(a, b, c):
solution = []
if (a ==0):
print(f"Since a is {a}, the equation is linear, not quadratic, therefore no solution will be provided")
else:
d = b**2-4.*a*c
if ( d > 0 ):
x1 = (-b + m.sqrt(d))/(2*a)
x2 = (-b - m.sqrt(d))/(2*a)
solution = [ x1, x2]
print(f"The quadratic equation: {a} x^2 +{b} x + {c} =0 has two real distinct roots ")
elif (d ==0 ):
xs = (-b)/(2*a)
print(f"The quadratic equation: {a} x^2 +{b} x + {c} =0 has a double root ")
solution = [xs]
else:
real = (-b)/(2*a)
imaginary = m.sqrt(-d)/(2*a)
print(f"The quadratic equation {a} x^2 +{b} x + {c} =0 has two complex roots: {real} + i *{imaginary} "),
print(f" and {real} - i *{imaginary}; the real and the imaginary parts of the solution are returned "),
print(f"in this order: [real , imaginary]")
solution = [real , imaginary]
return solution
print(f"This code solves the quadratic equation a*x^2 +b*x + c =0 for any values of a, b and c")
a=float(input("Enter the value of a for your quadratic equation "))
b=float(input("Enter the value of b for your quadratic equation "))
c=float(input("Enter the value of c for your quadratic equation "))
solution = quadraticeqsolver(a,b,c)
print(f" The solution of the quadratic equation {a} x^2 +{b} x + {c} =0 is " ),
print(solution)
| true |
1aa2ae45a863d872aacd544e677ed69a48899842 | VishalVema/Python-Automation | /ceasar cipher.py | 1,295 | 4.5 | 4 | import pyperclip
message = 'this is my secret message '
key = 13
mode = 'encrypt'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated = ''
message = message.upper()
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol) #this function is used to find and return index of value by comparing with symbol with in LETTERS,,,,
#this will return index values of message found in LETTERS just comparing it between LETTERS and message
#print (LETTERS.find(symbol))
if mode == 'encrypt':
num = num + key #this will add(+) 13 to every value from letters which was obtained from find funtion
elif mode == 'decrypt':
num = num - key
if num >= len(LETTERS):
num = num - len(LETTERS) # this is used when the value exceed the index obtained by adding 13 (encrypting) to the values
print (str(num ) + ' this is if statement')
elif num < 0:
num = num + len(LETTERS)
#print (str(num ) + ' this is elif statement')
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print(translated)
pyperclip.copy(translated)
| true |
a7d117a1c0df7b2a3012f9d6b76379a5ab60c1dd | talhabalaj/card-game | /server/src/GameLogic.py | 872 | 4.15625 | 4 | from random import shuffle
class Card:
CARD_TYPES = ["PAN", "PATI", "DIL", "DIAMOND"]
CARD_NUMBERS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
def __init__(self, number, card_type):
assert number >= 1 and number <= 13, 'Card number not valid'
assert card_type in Card.CARD_TYPES, 'Card type not valid'
self.number = number
self.card_type = card_type
# when we print an object, this function is
# used to convert it to printable form
# https://stackoverflow.com/questions/4912852/how-do-i-change-the-string-representation-of-a-python-class
def __str__(self):
return f"{Card.CARD_NUMBERS[self.number]} of ${self.card_type}"
class Deck:
def __init__(self):
self.cards = []
for i in Card.CARD_TYPES:
for j in Card.CARD_NUMBERS:
self.cards.append(Card(j, i))
def shuffle(self):
shuffle(self.cards)
| true |
c4e6f649990badfa983138498f18aab6828509c7 | hmunduri/MyPython | /datatype/ex14.py | 276 | 4.15625 | 4 | # Python program that accepts a comma serperate sequence of words as input and prints the unique words in sorted form
import sys
items = raw_input("Input comma seperated sequence of words")
words = [word for word in items.split(",")]
print(",".join(sorted(list(set(words)))))
| true |
891e45c0720ad58c8a116bf0b8197f14f419340a | hmunduri/MyPython | /datatype/ex8.py | 309 | 4.34375 | 4 | #python function that takes a list of words and returns the length of the longest one
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][1]
print(find_longest_word(["PHP", "EXCERCISE", "Eventually"]))
| true |
92ec5004591291e5c1f4a8d1054cc13de2360120 | misscindy/Interview | /Bit_Manipulation/Bit_Manipulation_Notes.py | 2,758 | 4.5 | 4 | '''
Basic Facts
The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x & y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
x | y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
~ x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
x ^ y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0,
and it's the complement of the bit in x if that bit in y is 1.
Just remember about that infinite series of 1 bits in a negative number, and these should all make sense.
https://wiki.python.org/moin/BitManipulation
https://wiki.python.org/moin/BitArrays
'''
def tricks():
x = 11
print "^ ops, 0 retrieve a bit, 1 gets complement of a bit"
print "x ^ 0s : x", x ^ 0, bin(x)
print "x ^ 1s : ~x", x ^ (15), bin(x ^ (15))
print "x ^ x : 0", x ^ x
print "============================================="
print "& ops, 0 clears a bit, 1 keeps the bit"
print "x & 0s : 0", x & 0, bin(x & 0)
print "x & 1s : x", x & (15), bin(x & (15))
print "x & x : x", x & x
print "============================================="
print "| ops, 0 keeps the bit, 1 set the bit to 1"
print "x | 0s : x", x | 0, bin(x | 0)
print "x | 1s : 1", x | (15), bin(x | (15))
print "x | x : x", x | x
########################################
# OPS #
########################################
# Get bit
def get_nth_bit(x, n):
# zeroth
# 1 1 0 1 1 0
# 1 0 0 0
# 0 0 0 0 0 0 -> 0
return 1 if (x & (1 << n) != 0) else 0
# Set Bit
def set_nth_bit(x, n):
return x | (1 << n)
# Clear Bit
def clear_nth_bit(x, n):
mask = ~(1 << n)
return x & mask
def clear_left_to_i(x, n):
# inclusive
# clear from most significant bit to ith
mask = (1 << n) - 1
return x & mask
#TODO: lookup and complete function
#def clear_i_to_0(x, n):
# Update Bit
def update_bit(x, n, v):
# clear nth bit
x &= ~(1 << n)
# set nth to v
return x | (v << n)
# calculates the number of 1s in a binary number
def hamming_weight(x):
count = 0
while x:
x &= (x - 1)
count += 1
return count
if __name__ == '__main__':
tricks()
test_cases = [
(0, 4, 1),
]
#for x, n, v in test_cases:
| true |
a49839096b6331714fc25f9f60024ad2295d1af1 | nnquangw/aivietnam.ai-week2 | /pie_estimate.py | 609 | 4.125 | 4 | import math
import random
def pi():
"""
Estimating PI's value from N points, a rectangle and a circle
:param N: number of random points
:return: a float approximates to PI
"""
N = 100000
Nt = 0 #number of random points inside the circle
for _ in range(N):
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
Nt = Nt + (x*x + y*y <= 1.0)*1
return 4.0*Nt/N
def e():
"""
Estimating e's value
:return: a float approximates to e
"""
n = 1000
e = 0
for i in range(n):
e = e + 1/math.factorial(i)
return e
| true |
b21cf4a05a09976fdeb5204424d9f58aa83785e5 | loganthomas/python-practice | /prep/fizzbuzz.py | 1,973 | 4.25 | 4 | """
FizzBuzz
--------
Write a program that outputs the string representation of numbers from
1 to n. For multiples of 3, it should output "Fizz" instead of the
number and for the multiples of 5 it should output "Buzz". For numbers
which are a multiple of both 3 and 5 it should output "FizzBuzz".
Notes
-----
%timeit fizzbuzz.fizzbuzz_naive(1000)
227 µs ± 997 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit fizzbuzz.fizzbuzz_concat(1000)
238 µs ± 5.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit fizzbuzz.fizzbuzz_hash(1000)
376 µs ± 708 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
"""
from typing import List
def fizzbuzz_naive(n: int) -> List[str]:
out = []
for num in range(1, n + 1):
if num % 15 == 0:
out.append("FizzBuzz")
elif num % 3 == 0:
out.append("Fizz")
elif num % 5 == 0:
out.append("Buzz")
else:
out.append(str(num))
return out
def fizzbuzz_concat(n: int) -> List[str]:
out = []
for num in range(1, n + 1):
num_str = ""
if num % 3 == 0:
num_str += "Fizz"
if num % 5 == 0:
num_str += "Buzz"
if not num_str:
num_str += str(num)
out.append(num_str)
return out
def fizzbuzz_hash(n: int) -> List[str]:
"""
Useful for when conditions grows. For example, if 7 should be Jazz.
Rather than multiple if statements, use a hash table O(n*m) where
m is number of conditions so really still O(n).
"""
out = []
# conditions = {3: "Fizz", 5: "Buzz", 7: "Jazz"}
conditions = {3: "Fizz", 5: "Buzz"}
for num in range(1, n + 1):
num_str = ""
for cond_key, cond_val in conditions.items():
if num % cond_key == 0:
num_str += cond_val
if not num_str:
num_str += str(num)
out.append(num_str)
return out
| true |
190b6272017f62a133b0918c7176bc6dcdd0e82e | loganthomas/python-practice | /misc/rock_paper_scissors.py | 1,267 | 4.21875 | 4 | ##########################################################
# Make a two-player Rock-Paper-Scissors game.
# (Hint: Ask for player plays (using input), compare them,
# print out a message of congratulations to the winner, and ask if the
# players want to start a new game)
# Remember the rules:
# Rock beats scissors
# Scissors beats paper
# Paper beats rock
def to_numb(choice):
if choice == "rock":
choice_num = 1
elif choice == "paper":
choice_num = 2
elif choice == "scissors":
choice_num = 3
else:
choice_num = "not a valid choice"
return choice_num
def game(p1, p2):
if (p1 == "not a valid choice") or (p2 == "not a valid choice"):
print("Both players must enter a valid choice")
winner = "Incorrect information entered"
elif p1 - p2 == -1:
winner = "Player2"
elif p1 - p2 == 2:
winner = "Player2"
elif p1 - p2 == 1:
winner = "Player1"
elif p1 - p2 == -2:
winner = "Player1"
else:
winner = "Tie"
return winner
player_1_choice = input("Player 1 make your choice: ")
p1 = to_numb(player_1_choice)
player_2_choice = input("Player 2 make your choice: ")
p2 = to_numb(player_2_choice)
print("The winner is", game(p1, p2))
| true |
7a085e6f961de406845059715790f2f81df674fe | loganthomas/python-practice | /advent_of_code/year_2017/day1.py | 2,066 | 4.125 | 4 | """
Day 1:
Part 1:
The captcha requires you to review a sequence of digits (your puzzle input) and find the sum of all
digits that match the next digit in the list. The list is circular, so the digit after the last
digit is the first digit in the list.
For example:
1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third
digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
Part 2:
Now, instead of considering the next digit, it wants you to consider the digit halfway around the
circular list. That is, if your list contains 10 items, only include a digit in your sum if the
digit 10/2 = 5 steps forward matches it. Fortunately, your list has an even number of elements.
For example:
1212 produces 6: the list contains 4 items, and all four digits match the digit 2 items ahead.
1221 produces 0, because every comparison is between a 1 and a 2.
123425 produces 4, because both 2s match each other, but no other digit has a match.
123123 produces 12.
12131415 produces 4.
Puzzle:
day1_puzzle.txt
Answers:
Part 1: 1251
Part 2: 1244
"""
from pathlib import Path
# No kwargs on purpose (for pytest)
def load_data():
input_file_path = Path(__file__).parent.joinpath("data/day1_puzzle.txt")
with open(input_file_path, "r") as input_file:
data = input_file.readline().strip()
return data
# Part 1 Solution
def captcha1(data):
""" Assumes data is a str """
# Add first digit to end
data = data + data[0]
out = sum([int(a) for a, b in zip(data, data[1:]) if a == b])
return out
# Part 2 Solution
def captcha2(data):
""" Assumes data is a str """
half_point = len(data) // 2
first_half = data[:half_point]
last_half = data[half_point:]
comp_data = last_half + first_half
out = sum([int(a) for a, b in zip(data, comp_data) if a == b])
return out
| true |
0b8e2cd366095e60d257ca11c0bc06c89bc3df14 | loganthomas/python-practice | /misc/letter_counter.py | 1,122 | 4.21875 | 4 | """
Practice Problem:
Given a word and a letter, count the number of occurrences the given
letter has in the given word.
"""
def letter_counter(word, letter):
"""
Count number of times a give letter occurs in a given word.
Args:
word (str): Word provided in which to count letter
letter (str): Letter provided to count in word. Of length 1.
Returns:
count - int representing number of times a give letter occurs
within the given word
"""
if word.isnumeric():
raise TypeError(f"Given word: '{word}' is a number not a word")
if letter.isnumeric():
raise TypeError(f"Given letter: '{letter}' is a number not a string")
if len(letter) != 1:
raise ValueError(f"Given letter: '{letter}' must be one character long")
count = sum([1 for let in word if let == letter])
print(f"{letter} occurs {count} time(s) in {word}")
return count
if __name__ == "__main__":
user_word = input("Please enter a word: ")
user_letter = input("Please enter a letter: ")
count = letter_counter(user_word, user_letter)
| true |
dcf88b8a5666c2add93a30314053ff1eb4530f63 | cifpfbmoll/practica-6-python-David-Sastre | /Práctica_6/P6_E10.py | 1,420 | 4.125 | 4 | #Escribe un programa que te pida los nombres y notas de alumnos. /
#Si escribes una nota fuera del intervalo de 0 a 10, el programa entenderá que no quieres introducir más notas de este alumno./
#Si no escribes el nombre, el programa entenderá que no quieres introducir más alumnos./
#Nota: La lista en la que se guardan los nombres y notas tiene esta estructura /
#[[nombre1, nota1, nota2, etc], [nombre2, nota1, nota2, etc], [nom3, nota1, nota2, etc], etc]
#Dame un nombre: Héctor Quiroga
#Escribe una nota: 4
#Escribe otra nota: 8.5
#Escribe otra nota: 12
#Dame otro nombre: Inés Valls
#Escribe una nota: 7.5
#Escribe otra nota: 1
#Escribe otra nota: 2
#Escribe otra nota: -5
#Dame otro nombre:
#Las notas de los alumnos son:
#Héctor Quiroga: 4.0 - 8.5
#Inés Valls: 7.5 - 1.0 - 2.0
list1=[]
persona=[]
alumno=input("Dame un nombre: ")
while alumno != "":
persona.append(alumno)
nota=float(input("Escribe una nota: "))
while 0<=nota<=10:
persona.append(nota)
nota=float(input("Escribe otra nota: "))
list1.append(persona)
persona=[]
alumno=(input("Dame otro nombre: "))
print("Las notas de los alumnos son: ")
for i in range (len(list1)):
print(list1[i][0],":",end=" ")
#print(list1[i][1],end=" ")
for j in range (1,len(list1[i])):
print(list1[i][j],end="-")
print("")
| false |
e69da611aefc097fb3a1df50ddd6bd61ffd4bce4 | zwdnet/elephant | /currency/currency_converter_v5.py | 1,415 | 4.34375 | 4 | # -*- coding:utf-8 -*-
"""小象学院python教程
汇率兑换4.0版,识别币种,让程序不停运行,将兑换功能封装到函数里,使程序结构化"""
def convert_currency(im, er):
"""
:param im: 待兑换货币金额
:param er: 汇率
:return: 兑换的货币金额
"""
return im / er
def main():
# 带单位的货币输入
currency_str_value = input("请输入带单位的货币金额(退出程序输入Q):")
# rmb_value = eval(rmb_str_value)
usd_vs_rmb = 6.77
convert_currency2 = lambda x:x/exchange_rate
while currency_str_value != 'Q':
unit = currency_str_value[-3:]
if unit == "CNY":
# 输入为人民币
rmb_value = eval(currency_str_value[:-3])
exchange_rate = usd_vs_rmb
usd_value = convert_currency2(rmb_value)
print("可兑换美元为", usd_value)
elif unit == "USD":
# 输入为美元
usd_value = eval(currency_str_value[:-3])
exchange_rate = 1.0 / usd_vs_rmb
rmb_value = convert_currency2(usd_value)
print("可兑换人民币为", rmb_value)
else:
# 其它情况
print("输入错误")
currency_str_value = input("请输入带单位的货币金额(退出程序输入Q):")
print("程序已退出")
if __name__ == '__main__':
main() | false |
12017f29a1e87170dd443c8ce8d642613d957740 | chetan-mali/Python-Traning | /Regular Expression/Regex_3_Creditcard_number_validation.py | 957 | 4.15625 | 4 | #Regular Expression Credit card number verification
"""
A valid credit card from ABCD Bank has the following characteristics:
It must start with a '4', '5' or ' 6'.
It must contain exactly 16 digits
It must only consist of digits (0-9)
It may have digits in groups of 4, separated by one hyphen "-"
It must NOT use any other separator like ', ' , '_', etc
It must NOT have 4 or more consecutive repeated digits
"""
import re
#List of credit card numbers
C_numbers =["4123456789123456","5123-4567-8912-3456","61234-567-8912-3456","4123356789123456","5133-3367-8912-3456","5123 - 3567 - 8912 - 3456"]
#regular Expression for Email Validation
expr=re.compile("^[456][0-9]{3}[-]?[0-9]{4}[-]?[0-9]{4}[-]?([0-9]{4})$")
#
for number in C_numbers:
result = expr.findall(number)
if len(result)>0 and not re.search(r'(\d)\1{3}', re.sub('-', '', number)) :
print(number,"Valid Number")
else:
print(number,"Invalid Number")
| true |
82fb65a4c890b03e132aa7a9c76eea74d8bf6cd0 | rahulgupta271/DSC510-Spring2019 | /KAMMA_LENIN_DSC510/lkamma_wk3_asmnt.py | 2,943 | 4.375 | 4 | # File: lkamma_wk3_asmnt.py
# Course: DSC501-303 Introduction to Programming
# Assignment#: 3.1
# Author: Lenin Kamma
# Date: 03/29/2019
# Description: This program calculates the total installation cost of fiber optic cable with taxes
# discount is given if user purchases more than 100 feet of cable
# Usage: This program requires total length of the optic fiber as the input
import datetime
# Changes the color of the text to green
print("\033[1;32;48m")
print('Welcome to BellFI Optic Fiber - Best place to buy optic fiber ')
print("\033[1;30;48m")
# Takes Input from the user for company name and feet
input_company = input('Please Enter Your Company Name: \n')
while True:
try:
print("\033[1;30;48m")
no_of_feet = float(input('Enter total length of optic fiber you want to purchase (In Feet) : \n'))
break
except ValueError:
print("\033[1;31;48m")
print(''"Sorry! That was not a valid number. Please try again..."'')
# Calculates the discount value per foot that needs to be applied
if no_of_feet <= 100:
disc_val = 0
else:
if (no_of_feet > 100) and (no_of_feet <= 250):
disc_val = 0.07
else:
if (no_of_feet > 250) and (no_of_feet <= 500):
disc_val = 0.17
else:
disc_val = 0.37
# Calculates the cost, sales tax and total cost rounded to nearest dollar
cal_cost = round(no_of_feet * 0.87, 2) # Actual cost of the cable
total_disc = round(no_of_feet * disc_val, 2) # Total Discount
cost_after_disc = round(cal_cost - total_disc, 2) # Cost after discount
cal_tax = round(cost_after_disc * 0.07, 2) # Tax calculated
final_cost = round(cost_after_disc + cal_tax, 2) # Final cost (includes tax)
print("\033[1;33;48m")
print("Actual Cost of the Cable : " + '%.2f' % cal_cost + "$")
if no_of_feet > 100:
print("Total Discount applied : " + "-"+'%.2f' % total_disc + "$")
print("Sub Total : " + '%.2f' % cost_after_disc + "$")
print("Total Cost of Your Purchase(plus 7% tax): " + '%.2f' % final_cost+"$")
inp_enter = input('Enter Y for Your Receipt : \n')
# Print receipt with company name, total cost and time
if inp_enter in ('y', 'Y'):
print("\033[1;32;48m")
print(" BellFI Optic Fiber \n\t\t RECEIPT\n\t")
print("\033[1;33;48m")
print("\t Buyer : " + input_company)
print("Total Optic Fiber Purchased:", + no_of_feet, "ft")
print("\t Sub Total : " + "$" + '%.2f' % cost_after_disc)
print("\tSales tax(7%): " + "$" + '%.2f' % cal_tax)
print("\t Total Cost : " + "$" + '%.2f' % final_cost)
print("\033[1;32;48m")
print("\nThank you for shopping BellFI!!")
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"), "\n")
else:
print("Thank you. Bye")
| true |
e213a3b6971e411b2d94343963be0f934fd59c9d | rahulgupta271/DSC510-Spring2019 | /ERICKSON_HOLLY_DSC510/Assignment_2.1.py | 2,265 | 4.34375 | 4 | """
File: Assignment_2.1.py
Author: Holly Erickson
Date: 2019-03-23
Course: DSC 510-T303 Intro to Programming
Assignment: 2.1
Desc: This program display a welcome message. Then retrieves a company name &
the number of feet of fiber optic cable to be installed from the user.
It calculate the installation cost and prints a receipt for the user.
Usage: Prompts user for input, performs calculations and outputs a receipt for fiber optic cable installed.
"""
import datetime
from decimal import localcontext, Decimal, ROUND_HALF_UP
# Global variables
install_rate = 0.87
tax_rate = 0.06
def round_half_up(number):
"""
This takes a number and rounds it to two decimal places.
I did it this way instead of using round() to avoid rounding down at .xx5
"""
with localcontext() as ctx:
ctx.rounding = ROUND_HALF_UP
two_places = Decimal("0.01")
return Decimal(str(number)).quantize(two_places)
print("\nWelcome to 'Always Online', the fiber optic cable store! ")
print("Our premium performance fiber optic cable costs $0.87 per foot including installation. \n")
# Retrieve the company name from the user.
company = input("Please enter your company name: \n")
# Retrieve the number of feet of fiber optic cable to be installed from the user. Ensures valid numeric input.
while True:
try:
feet = input("Please enter the number of feet of fiber optic cable you would like installed: \n")
feet = float(feet)
break
except ValueError:
print("Error: Not a valid number.")
# Calculate the installation cost and sales tax.
calculated_cost = (feet * install_rate)
tax = (calculated_cost * tax_rate)
calculated_cost = round_half_up(calculated_cost)
tax = round_half_up(tax)
# Print a receipt for the user including company name, number of feet to be installed, calculated cost, & total cost.
print("\nReceipt from Always Online")
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"), "\n")
print("Company name:", company)
print("Number of feet to be installed:", feet, "feet")
print("Calculated cost: $%s" % calculated_cost)
print("Sales tax: $%s" % tax)
print("Total cost: $%s" % round_half_up(calculated_cost+tax))
print("\nThank you for shopping!")
| true |
ae43a770aa72d98e07d9f3db8aa526709dbaadfa | alokkjnu/StringAndText | /6 SearchingReplacingCaseInsensitive.py | 627 | 4.53125 | 5 | # Searching and replacing Case-Insensitive Text
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
t1 = re.findall('python',text, flags=re.IGNORECASE)
print(t1)
t2 = re.sub('python','snake',text, flags=re.IGNORECASE)
print(t2)
def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
t3 = re.sub('python',matchcase('snake'),text,flags=re.IGNORECASE)
print(t3) | true |
73833c450e8c011dc43947dcb0520002d4e7314f | jaap17/004_JaapAnjaria | /LAB1/numpy/scalingmatrices.py | 749 | 4.21875 | 4 | import numpy as np
okmatrix = np.array([[1,2],[3,4]])
result = okmatrix*2 + 1
print(result)
# Add two sum compatible matrices
result1 = okmatrix + okmatrix
print(result1)
# Subtract two sum compatible matrices. This is called the difference vector
result2 = okmatrix - okmatrix
print(result2)
result = okmatrix * okmatrix # Multiply each element by itself
print(result)
matrix3x2 = np.array([[1, 2], [3, 4], [5, 6]]) # Define a 3x2 matrix
print('Original matrix 3 x 2')
print(matrix3x2)
print('Transposed matrix 2 x 3') # Transpose of a matrix
print(matrix3x2.T)
nparray = np.array([[1, 2, 3, 4]]) # Define a 1 x 4 matrix. Note the 2 level of square brackets
print('Original array')
print(nparray)
print('Transposed array')
print(nparray.T) | true |
ee20b32bd13a7bcfd1c281bba74460a0b9dbb302 | om1chael/week3-python-Deloitte | /Python-Lessons/if statments homework .py | 1,118 | 4.4375 | 4 | #######list of movies with d
movies = {"Spiderman": {'release Date': 2002, "rating":"PG"},
"shrek": {'release Date': 2001, "rating":"PG-13"},
"mission impossible": {'release Date': 1996,"rating":"PG-13"},
}
####### print the list of movies ###
print("movie list",movies.keys())
#### ask the user for input ###
movie=input("what movie do you want see from the list \n")
### make sure that the movie is within the list ###
while(movie not in movies.keys()):
print("Try again, movie does not exist")
movie = input("what movie do you want see from the list \n")
### another validatted input ###
valid=True
while valid:
age = input("give me your age:- ")
if(age.isdigit()):
age = int(age)
valid=False
else:
print("try again mate")
## the if section ##
statment= f"you can watch {movie}. Rated:{movies[movie]['rating']}. have a fun time"
if movies[movie]["rating"] == "PG" and int(age)> 10:
print(statment)
elif movies[movie]["rating"] == "PG-13" and int(age) > 13:
print(statment)
else:
print("try again mate, you are too young")
| true |
b3437016d253cf0b7b14744eb87a61ca87832369 | but764/new-python | /задание2.py | 680 | 4.21875 | 4 |
#Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте.
# Для заполнения списка элементов необходимо использовать функцию input().
my_list = list(input('ввидете числа без пробелов '))
for i in range(1, len(my_list), 2):
my_list[i - 1], my_list[i] = my_list[i], my_list[i - 1]
print(my_list) | false |
e1c478fd41212d7d8807dc51c623f1407d59b718 | ramsandhya/Python | /ex11-rawinput.py | 838 | 4.21875 | 4 | # print "How old are you?",
# age = 9
# print "How tall are you?",
# height = 10
# print "How muxh do you weigh?",
# weight = 11
#
# print "So you are %d old, %d tall and %d heavy" % (age, height, weight)
# prints input in line 11, put the name, says line 12 with name, prints line 13
# name = raw_input("What is your name?")
# print "Hello %r" % name
# print '6\'2"'
# Whatever we put in the prompt we get the outpit based on the %s and %d. if we put %r it will give th eresult in single quotes.
# name = raw_input("What is your name?")
# age = raw_input("How old are you?")
# print "Welcome %s , you are %rjane years old" % (name, age)
# The value we enter is getting converted to the integer so 40 will work but 6'5" will not
x = int(raw_input())
print x
# In order for 6'5" to work we need to take int off
x = raw_input()
print x
| true |
2dcb30fe40d2cb3278d6360833ca2c8b3cd89ef9 | Semihcansertbas/CS_PF_Python_Unit4 | /tryme4.py | 461 | 4.28125 | 4 | def is_power(x,y):
if (x == y):
return True
if (y == 0) or (y == 1): #Exception Handling
return False
# Recursive
return ((x%y)==0) and (is_power(x/y,y)) #Includes is_divisible function
print("is_power(10, 2) returns: ", is_power(10, 2))
print("is_power(27, 3) returns: ", is_power(27, 3))
print("is_power(1, 1) returns: ", is_power(1, 1))
print("is_power(10, 1) returns: ", is_power(10, 1))
print("is_power(3, 3) returns: ", is_power(3, 3))
| false |
060d8a18b506cf54ceeb8cd90bc9d30dcf57823e | SPOORTIA/Python-Tutorial | /program 3 - contd variables and strings.py | 1,284 | 4.4375 | 4 | # concatination of strings
message_1 = 'hello'
message_2 = 'hi'
message = message_1 + ' ' + message_2 + 'monkey'
print(message)
# f - formating
message = f'{message_1} {message_2}'
print(message)
message = f'{message_1} {message_2.upper()}'
print(message)
# dir - displays all the fuctions / attributes that are avaliable
print(dir(message))
# help fuction for string
print(help(str))
print(help(str.lower))
# integers and numbers
num = 3
print(type(num)) # prints the data type of num
mum = 3.12
print(type(num))
print(3+2)
print(3-2)
print(3*2)
print(3/2)
print(3//2)# drops decimal
print(3**2) # exponent
print(3%2) # modules
print(3+2*1)
print(3+(2+1))# order of operations
# incrementation
num = 2
num = num + 1
print(num)
num = 4
num += 2
num *= 10
num -= 2
print(num)
# build in numeric funtiions
num = -3
print(abs(-3))
num = 3.97
print(round(num))
print(round(num,1))
# numeric comparisons
num_1 = 3
num_2 = 4
print(num_1==num_2)
print(num_1!=num_2)
print(num_1>num_2)
print(num_1>=num_2)
print(num_1<num_2)
print(num_1<=num_2)
# type casting
num_1 = '5'
num_2 = '2'
print(num_1+num_2)
num_1 = int(num_1)
num_2 = int(num_2)
print(num_1+num_2)
num_1 = 5
num_2 = 2
print(num_1+num_2)
num_1 = str(num_1)
num_2 = str(num_2)
print(num_1+num_2)
| true |
789ff1c81d403bb60f9895131fc8ce8cc18ffd49 | saurabh02/Bajaj_cc | /src/median_unique.py | 2,321 | 4.125 | 4 | #!/usr/bin/env python
import sys
import numpy as np
def running_median(file_object, file):
'''
Counts the number of unique words per line in a file, and calculates their running median
Arguments:
file_object: name of file object created for the input file containing the tweets
Returns:
None
'''
count_tweets = 0 # Keep track of number of tweets
median = 0.0 # Current median
for line in file_object: # Going through each line in the file. This method avoids storing the entire file into memory
count_tweets += 1
unique_words = {} # Initialising a new dictionary that will store each unique word as a key
lst = line.split() # Splits the line into a list of words
for word in lst: # Going through each word in tweet, if it exists do nothing, else initialise it
if word not in unique_words:
unique_words[word] = 1
median = ((median*(count_tweets-1)) + len(unique_words))/count_tweets # Formula for calculating current median that scales well with input size
file.write(str(median) + '\n') # Writing the median of a growing list of medians to the output file
if __name__ == '__main__':
try:
input_file_path = sys.argv[1]
output_file_path = sys.argv[2]
except:
print "Error: please check file names or path"
tweets = open(input_file_path, 'r') # File object that points to the input file containing tweets, and opened in reading mode
ft2 = open(output_file_path, 'w') # File object that points to the output file containing medians, and opened in writing mode
running_median(tweets, ft2)
tweets.close() # Close the file object
ft2.close() # Close the file object
| true |
e19b7b76d79b4fc66ffc2f089dda41ba433f561e | itsanjan/generic-python | /programs/P07_PrimeNumber.py | 558 | 4.3125 | 4 | # This program checks whether the entered number is prime or not
def checkPrime(number):
isPrime = False
i = 0
if (number == 1 or number == 2):
print("Number is a prime")
for i in range(2, int(number / 2) + 1):
if number % i == 0:
print("Number is not a prime")
isPrime = False
break
else:
isPrime = True
if(isPrime):
print("Number is a prime")
if __name__ == '__main__':
input_number = int(input('Enter the number '))
checkPrime(input_number)
| true |
d9f243bc7e8c5623924700012385492527c16056 | jeancre11/PYTHON-2020 | /clase python con IDLE/listas_metodo pop.py | 471 | 4.3125 | 4 | """uso de datos y metodos"""
#lista1
#append y pop son METODOS.
lista1=[10, 20, 30]
print(lista1)
#lista2
lista2=[5,2,3,100]
print(lista2)
#concatenar listas
print('SE TIENE COMO CONCATENACIÓN')
print(lista1+lista2)
#sacar un elemento de la ultima posicion de la lista1, defoult ()
val=lista1.pop()
print('despues del metodo pop a lista1=', lista1)
#print(lista2)
valo=lista2.pop(2)
print('queda despues de pop en lista2=',lista2,'valor quitado:', valo)
#objeto.metodo
| false |
de03dc8a5351810f75de7d9e657a50c9aca23e6d | BenjaminJ12/Group-dance-thing | /main.py | 1,332 | 4.125 | 4 | #19/8/20
#Hello Github
#Initialise arrays
nameArray = []
ticketArray = []
#collect data
groupName = input('What is the name of your group? ')
groupNumber = float(input('How many peple are in your group? Enter a number between 4 and 10 '))
#input validation
while groupNumber <4 or groupNumber >10 or not groupNumber.is_integer():
print('Enter a number between 4 and 10 ')
groupNumber = float(input('How many peple are in your group? Enter a number between 4 and 10 '))
#make sure number of people is whole
groupNumber = int(groupNumber)
#loops the number of people in group
for counter in range(groupNumber):
name = input('Enter pupil name ')
photo = input('Do you want a group photo? Enter yes or no ' )
#more input validation
while photo != 'yes' and photo !='Yes' and photo !='no' and photo != 'No':
print('Please enter yes or no ')
photo = input('Do you want a group photo? Enter yes or no ' )
#Calculates ticket price
if photo == 'no' or photo =='No':
ticketPrice = 3.0
elif photo =='yes'or photo =='Yes':
ticketPrice = 4.99
#appends arrays
nameArray.append(name)
ticketArray.append(ticketPrice)
#Prints outputs
print('Group name:', groupName)
print('Number in group: ', groupNumber)
for counter in range(groupNumber):
print(nameArray[counter], ticketArray[counter])
| true |
27bfe898dceeb51223d113597243b67b7d38882e | pyzhaoxd/jsj | /python_base/数据结构.py | 635 | 4.4375 | 4 | #Python 的列表数据类型包含更多的方法。这里是所有的列表对象方法:
#list.append(x)
#把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]
x = [1,2,3,4]
print(len(x))
x.append(5)
print(x)
#list.extend(L)
#将一个给定列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L
l = [9,10]
x.extend(l)
print(x)
# list.insert(i, x)
# 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引,例如 a.insert(0, x)
# 会插入到整个列表之前,而 a.insert(len(a), x) 相当于 a.append(x)。
x.insert(0,13)
print(x)
| false |
9946e2ee2bc5c1d3f3c68ea901e4987b391042e6 | cholzkorn/coding-challenges | /is-trimorphic/is_trimorphic.py | 426 | 4.375 | 4 | # Function to check if a number is trimorphic
# A trimorphic number is a number whose cube ends in itself
# Input 4: TRUE - (4^3 is 64, which ends in 4)
# Input 13: FALSE - (13^3 is 2197, which ends in 97)
import re
def is_trimorphic(x):
xc = x ** 3
xs = str(x)
xcs = str(xc)
pattern = re.escape(xs) + r"$"
match = re.search(pattern, xcs)
if match:
return True
else:
return False
| true |
25d10b1e1e2e6bf1917ff4c5db8767e8a6159bc7 | stephen-weber/Project_Euler | /Python/Problem0019_Counting_Sundays.py | 2,456 | 4.15625 | 4 | """
Counting Sundays
Problem 19
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
Answer:
171
Completed on Thu, 24 Jan 2013, 03:27
"""
dayOftheWeek=[]
tomorrowsDate=[]
todaysDate=[]
leapYear=[]
count=0
todaysDate.append((1,1,1900))
tomorrowsDate.append((1,2,1900))
dayOftheWeek.append(0)
leapYear.append(False)
def testSun(unit):
global count
if dayOftheWeek[unit]==6 :
a,b,c =todaysDate[unit]
if b==1:
if c>1900:
count+=1
return
a=0
b=0
c=0
year=1900
unit=0
while c<2001:
testSun(unit)
x =dayOftheWeek[unit]
x=(x+1)%7
dayOftheWeek.append(x)
a,b,c=tomorrowsDate[unit]
todaysDate.append((a,b,c))
b=b+1
if (a==1):
if b>31:
b=1
a=2
elif (a==2):
if leapYear[unit]:
if b>29:
b=1
a=3
else:
if b>28:
b=1
a=3
elif (a==3):
if b>31:
b=1
a=4
elif (a==4):
if b>30:
b=1
a=5
elif (a==5):
if b>31:
b=1
a=6
elif (a==6):
if b>30:
b=1
a=7
elif (a==7):
if b>31:
b=1
a=8
elif (a==8):
if b>31:
b=1
a=9
elif (a==9):
if b>30:
b=1
a=10
elif (a==10):
if b>31:
b=1
a=11
elif (a==11):
if b>30:
b=1
a=12
elif (a==12):
if b>31:
b=1
a=1
c=c+1
unit+=1
if (c%100==0):
if c%400==0:
leapYear.append(True)
else:
leapYear.append(False)
elif (c%4==0):
leapYear.append(True)
else:
leapYear.append(False)
tomorrowsDate.append((a,b,c))
print count
| true |
501bcb3355aa3b73020e0d3ad3fa4f0adcf0a011 | imagine-maven/Programs | /arrayInPython.py | 1,436 | 4.40625 | 4 | # no built in support for arrays , lists can be used
# import numpy to work with arrays
cars = ['bmw', 'ford', 'ferrari', 'mini']
# access items
print(cars[0])
print(cars[2])
# modify items just like lists
cars[0] = 'toyota'
print(cars[0])
# length of an array
x = len(cars)
print(x)
# looping through array elements
for x in cars:
print(x)
# adding array element to the end of array
cars.append("hyundai")
print(cars)
# removing array elements
cars.pop(1) # removes element at index 1
print(cars)
cars.pop() # removes last element
print(cars)
# adding elements to array
cars.append("ford")
cars.append('hyundai')
print(cars)
# removing elements using remove() method
# remove() only remove first occurence of specified value
cars.remove('hyundai')
print(cars)
# more array methods
# same as list methods, refer to list methods
cars.clear() # empties array
print(cars)
# extend method
fruits = ['apple', 'banana', 'cherry','volvo']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
fruits.insert(1,'jaguar')
print(fruits)
fruits.reverse()
print(fruits)
x = fruits.index('banana')
print(x)
x = fruits.count('volvo')
print(x)
# sort methods
fruits.sort()
print(fruits)
fruits.sort(reverse=True)
print(fruits)
# sort the list by the length of values and reversed
def myFunc(e):
return len(e)
fruits.sort(reverse=True, key= myFunc)
print(fruits)
fruits.sort(key = myFunc)
print(fruits)
| true |
9302d5a73d65cb6b75db6de6a690e6011f50e15c | vaishnavi-gupta-au16/Simple-Python-Programs | /calculator.py | 540 | 4.21875 | 4 | while True:
num1=int(input("Enter 1st number "))
num2=int(input("Enter 2nd number "))
choice = input("Enter your choices +, -, *, / or type ''q'' to quit: ")
if choice == "+":
calc = num1 + num2
print(calc)
elif choice == "-":
calc = num1 - num2
print(calc)
elif choice == "*":
calc = num1 * num2
print(calc)
elif choice == "/":
calc = num1 / num2
print(calc)
elif choice == "q":
break
else:
print("wrong input")
| false |
0c11cfccb306a801e3e46103231129f174795b4e | vaishnavi-gupta-au16/Simple-Python-Programs | /Lists/store_variable.py | 472 | 4.3125 | 4 | # Take 10 integer inputs from user and store them in a list and print them on screen using function.
num = []
def store_variable():
n = int(input("enter the 10 integer inputs"))
for i in range(0,n):
a = int(input())
num.append(a)
print(num)
store_variable()
## other solution ##
# i = 1
# lst = []
# print("enter the digits you want to store")
# while i <= 10:
# num = int(input())
# lst.append(num)
# i = i+1
# print(lst)
| true |
706eac28ddb856c2b9bcf2a18323aa1ec752d828 | htrahddis-hub/DSA-Together-HacktoberFest | /trees/BinaryTrees/Easy/tree_implementation.py | 1,266 | 4.15625 | 4 |
# Implementing Tree Data Structure
class TreeNode :
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def get_level(self):
level = 0
p = self.parent
while p:
level += 1
p = p.parent
return level
def print_tree(self):
spaces = ' ' * self.get_level() * 3
prefix = spaces + "|__" if self.parent else ""
print(prefix+self.data)
if self.children :
for child in self.children:
child.print_tree()
def add_child(self,child):
child.parent = self
self.children.append(child)
def build_tree():
root = TreeNode("A")
B = TreeNode("B")
B.add_child(TreeNode("E"))
B.add_child(TreeNode("F"))
B.add_child(TreeNode("F"))
C = TreeNode("C")
C.add_child(TreeNode("H"))
C.add_child(TreeNode("I"))
C.add_child(TreeNode("J"))
D = TreeNode("D")
D.add_child(TreeNode("K"))
D.add_child(TreeNode("L"))
D.add_child(TreeNode("M"))
root.add_child(B)
root.add_child(C)
root.add_child(D)
root.print_tree()
if __name__ == '__main__' :
build_tree()
| false |
f20b29a9cdeb9aa91e23565f1f0dcb9b7914d021 | AlexeyZavar/informatics_solutions | /13 раздел(V2)/Задача G.py | 667 | 4.125 | 4 | #
# Напишите функцию CaseChange (c), меняющую регистр символа, то есть переводящую заглавные буквы в строчные, а строчные - в заглавные, остальные символы не меняющие. В решении нельзя использовать циклы. В решении нельзя использовать константы с неочевидным значением.
#
a = input()
def CaseChange(c):
c = str(c)
if c.isupper() == True:
return c.lower()
else:
return c.capitalize()
return c
print(CaseChange(a))
| false |
827040c9fa87434546df9f8365c41ece8cdd527d | Kuldeep28/Satrt_py | /zipinffuntion.py | 922 | 4.21875 | 4 | string="kuldeepop"
tup=[1,2,5,7,8,8,9,89,90]
print(list(zip(string,tup)))# in zip function the length of the zip list is depending on the value of the shortest listt
zipped=list(zip(string,tup))
for entity,num in zipped:# that cool we are using tupple assingnment to iterate over it as we are confirmed that there
# would be nly 2 entities in 1 entity of the given list
print(entity,num)
#we can use zip for and loop to traverse through three itewration at the sAme time that a great utility
def triple_triversal(ty1,ty2,ty3):
for wr1,wr2,wr3 in zip(ty1,ty2,ty3):
print(wr1,wr2,wr3)#here we are traversing the continous structure with same loop and i need it
st="kuldeepparasha"
st1="tanyaparashar"
st3="anitaparashar"
# enumerate is the functoin use if you wwant to traverse the structure with index and and the values at the same time
triple_triversal(st,st1,st3) | true |
7ae81ec8b202b1423b004d8fd492eb1fd8486972 | Kuldeep28/Satrt_py | /lists_dic_funtion.py | 869 | 4.34375 | 4 | #in this we are using the lists function used for geeting the key value from a dict
# thed item finctin will return the tupple of key value pairs
d={1:23,3.23:24,34:23}
print(list(d))
print(d.items())#give iterator dictitems
#Combining dict with zip yields a concise way to create a dictionary:
#>>> d = dict(zip('abc', range(3)))
#>>> print d
#{'a': 0, 'c': 2, 'b': 1}
#The dictionary method update also takes a list of tuples and adds them, as key-value pairs,
#to an existing dictionary
str1="kuldeep"
str2="parashar"
di=dict(zip(str1,str2))# this finction is actully mapping the tu[ples we get as ziped funtion as a key value pair
# so keep moving man please you are getting great at python bass code3 kar code
print(di)
for key,values in di.items():# use the iterator we get and find the key vlue pairr and do something went to do
print(key,"is",values) | true |
4f4316a8d2c72f21c28ff259d557c43b6bb75ec7 | hiaQ/learnPython | /test31.py | 616 | 4.15625 | 4 | #!/user/bin/env python
#coding:utf-8
str = input('please input:')
if str == '':
print('Please input!')
elif str == 'M':
print('It is Monday')
elif str == 'W':
print('It is Wednesday')
elif str == 'F':
print('It is Friday')
elif str == 'T':
print('Please input the second letter:')
letter = input('Please input:')
if letter == 'u':
print('It is Tuesday')
elif letter == 'h':
print('It is Thursday')
elif str == 'S':
print('Please input the second letter:')
letter = input('Please input:')
if letter == 'u':
print('It is Sunday')
elif letter == 'a':
print('It is Satday')
else:
print('data Error') | false |
c402b2784049210bd33472b0f01c7acb0336012b | Qwatha/Test | /2nd_exercise.py | 570 | 4.375 | 4 | """ Написать метод/функцию, который/которая на вход принимает число (float),
а на выходе получает число, округленное до пятерок."""
def func(float_number):
"""Функция принимает вещественное число и округляет его"""
if type(float_number) != float:
return "Введите число с плавающей точкой"
return float_number - float_number % 5
# Время 5 минут
print(func(27.23)) | false |
5936e36e171622063c5506f36aba4adc3ac4c8fc | gonzaloamadio/pacman | /app/board.py | 1,056 | 4.125 | 4 | """
The Board just has a width, a height and some walls.
The Board can only tell if a move is valid or invalid
"""
import logging
LOG = logging.getLogger(__name__)
class Board:
def __init__(self, x, y, walls):
self.x = x
self.y = y
self.walls = walls
LOG.debug("The board is %s by %s and the walls are %s", self.x, self.y,
self.walls)
def height(self):
return self.y
def width(self):
return self.x
def is_valid_move(self, x, y):
"""
Check if you can move to the x, y location
Moving to a wall is not allowed
Moving out of the board is not allowed
"""
is_in = x >= 0 and x < self.x and y >= 0 and y < self.y
LOG.debug("is_in for values (%s,%s) is: %s", x, y, is_in)
is_wall = (x, y) in self.walls
LOG.debug("is_wall for values (%s,%s) is: %s", x, y, is_wall)
is_valid = is_in and not is_wall
LOG.debug("is_valid for values (%s,%s) is: %s", x, y, is_valid)
return is_valid
| true |
571c1afec2aeeb3db64381176c485929236af584 | hazemshokry/CrackingTheCodingInterview | /CheckPermutation.py | 619 | 4.46875 | 4 | # Given two strings, write a method to decide if one is a permutation of the other.
# Example, Dog is considered a permutation of God.
def checkPermutation (string1, string2):
"""
:param string1: string #1 to check if it is considered as a permutation for string #2.
:param string2: string #2 to check if it is considered as a permutation for string #1.
:return: True if one string is a permutation of the other, False otherwise.
"""
if sorted(string1.lower()) == sorted(string2.lower()):
return True
return False
if __name__ == '__main__':
print(checkPermutation("dOg","God")) | true |
9a2417bca1c1da163dab3766ce8db79e94666f04 | hazemshokry/CrackingTheCodingInterview | /String Compression.py | 827 | 4.3125 | 4 | # Implement a method to perform basic string compression using the counts of repeated characters.
# For example: the string aabcccccaaa would be a2b1c5a3.
# Note: if the new string is larger than the older one, return the original.
def stringCompression(string):
"""
:param string:
:return: return a new string after compression
"""
if len(string) == 0:
return string
count = 0
finalString = ""
curr = string[0]
for c in string:
if curr == c:
count += 1
elif curr != c:
finalString += curr + str(count)
count = 1
curr = c
finalString += curr + str(count)
if len(finalString) > len(string):
return string
return finalString
if __name__ == '__main__':
print(stringCompression("aabcccccaaa"))
| true |
b2cfe6d7b3c8fd4cbfc67b82dab661cc2ad02762 | cdw2003/CodingDojoProjects | /Python/Algorithms/MultiplesSumAverage.py | 2,034 | 4.25 | 4 | #Multiples
def MultiplesOdd(): #first define a function that does not take any parameters.
for i in range (1,1001): #run a for loop that goes from 1 to 1,001 so that 1,000 is included.
if i % 2 == 1: #use an if statement to select only the odd values.
print i #print the i values that meet the condition of being odd values.
#
MultiplesOdd() #run the function to print the values.
def Multiples5(): #first define a function that does not take any parameters.
for i in range (5, 1000001): #run a for loop that goes from 1 to 1 million and 1.
if i % 5 == 0: #use an if statement to test whether the value is divisible by 5.
print i #if the value meets the condition of being divisible by 5, print the value.
Multiples5() #run the function to print the values.
#Sum List
a = [1, 2, 5, 10, 255, 3] #first define the variable a to establish the array.
def Sum(array): #then define a function Sum that takes an array as its parameter.
sum = 0 #establish a variable for sum so that sum can be calculated as we run through the array.
for i in range (0,len(array)-1): #create a for loop to iterate through the values of the array.
sum += a[i] #update the sum by adding each value of the array to the sum.
print sum #print the final value of sum.
Sum(a) #run the function to print the final sum value.
#Average List
a = [1, 2, 5, 10, 255, 3] #first define the variable a to establish the array.
def Avg(array): #then define a function Avg that takes an array as its parameter.
sum = 0 #establish a variable for sum so that the sum can be caluclated as we run through the array.
for i in range (0,len(array)-1): #create a for loop to iterate through the values of the array.
sum += a[i] #update the sum by adding each value of the array to the sum.
print sum/len(array) #print the value of the sum divided by the length of the array to get the average.
Avg(a) #run the function to print the average value.
| true |
88d65ac648be2bce67af9de17929160d6ee6c8d0 | antoniosalinasolivares/numericalMethods | /src/newtonRaphson.py | 1,589 | 4.21875 | 4 |
import math
import numpy as np
import matplotlib.pyplot as plt
class NewtonRaphson:
function = None
derivative = None
initial_point = None
def __init__(self, function, derivative, initial_point):
self.function = function
self.derivative = derivative
self.initial_point = initial_point
def isInside(self,error):
return abs(self.function(self.initial_point)) < error
def solve(self, error, steps=False):
for i in range(100):
if steps:
print("f(%f) = %f" % (self.initial_point, self.function(self.initial_point)))
self.initial_point = self.initial_point - (self.function(self.initial_point)/self.derivative(self.initial_point))
if self.isInside(error):
print("Bingo! f(%f) = %f" % (self.initial_point, self.function(self.initial_point)))
return self.initial_point
print('demasiadas iteraciones, busca un valor inicial mas conveniente')
# How to use it
#first we define an object of the class NewtonRhapson with receives the main function, its derivative and an initial point
nr = NewtonRaphson(lambda x: x**4 + x -3, lambda x: 4*(x**3) +1, 3)
#in this case we use lambdas to make it a one liner, but the function could be defined normally if it's preferred
#we can solve the equation by giving it a relative an absolute error (comparing it to the real result)
nr.solve(0.050)
#if we wanted to see each iteration of this process, we jus need to add a True to the arguments of the solve method
# nr.solve(0.050, True) | true |
f41b90f5484a6da32054b361f3448a5455182023 | rashmee/Python-Projects | /nonRepeatingCharacter.py | 278 | 4.1875 | 4 | # coding=utf-8
#Find the first non repeating character
def first_non_repeating_char(str):
for character in str:
if str.count(character) > 1:
continue
else:
return character
return -1
print first_non_repeating_char("oohay")
print first_non_repeating_char("abccba")
| true |
0263d7361cb9697d8b9a4e97033a4129ec504493 | rashmee/Python-Projects | /guessNumber.py | 1,475 | 4.28125 | 4 | # coding=utf-8
# The Goal: Similar to the first project, this project also uses the random module in
# Python. The program will first randomly generate a number unknown to the user.
# The user needs to guess what that number is. In other words, the user needs to be
# able to input information. If the user’s guess is wrong, the program should return
# some sort of indication as to how wrong (e.g. The number is too high or too low).
# If the user guesses correctly, a positive indication should appear. You’ll need
# functions to check if the user input is an actual number, to see the difference
# between the inputted number and the randomly generated numbers, and to then compare
# the numbers.
from random import randint
guessesTaken = 0
print("Hi! What is your name?")
myName = input()
_randNum_ = randint(1, 10)
print('Hi, ' + myName + ', I am ready with my number. Your turn!')
while guessesTaken<5:
print("Guess?")
theGuess = input()
theGuess = int(theGuess)
guessesTaken = guessesTaken+1
if theGuess < _randNum_:
print('Your guess is too low!')
elif theGuess > _randNum_:
print('Your guess it too high!')
else:
break
if theGuess == _randNum_:
guessesTaken = str(guessesTaken)
print('Awesome! ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if theGuess != _randNum_:
_randNum_ = str(_randNum_)
print('Nope! The number I was thinking of was ' + _randNum_)
| true |
b2c48680f43eed2bf16540a3fdab28d0347911ad | hakankaraahmet/python-projects | /password reminder.py | 216 | 4.15625 | 4 | name = "Freddie"
user_name = input("Please enter you user name: ").title()
if user_name == name:
print("Hello Freddie! The password is: Mercury")
else:
print("Hello {}! See you later.".format(user_name))
| true |
3d8b1f1ebb7f166cb3327dc656dfab6ec3373110 | grapefruit623/leetcode | /easy/144_binaryTreePreorder.py | 1,710 | 4.1875 | 4 | # -*- coding:utf-8 -*-
#! /usr/bin/python3
import unittest
from typing import Optional, List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
'''
AC
'''
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack=[]
ans=[]
temp = TreeNode(-1)
if root == None:
return ans
stack.append(root)
while stack != []:
temp = stack.pop()
ans.append(temp.val)
if temp.right != None:
stack.append(temp.right)
if temp.left != None:
stack.append(temp.left)
return ans
class Unittest(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_case1(self):
# root=[1,None,2,3]
root=TreeNode(1)
root.left=None
root.right=TreeNode(2)
root.right.left=TreeNode(3)
expected=[1,2,3]
self.assertEqual(expected, self.sol.preorderTraversal(root))
def test_case2(self):
root=None
expected=[]
self.assertEqual(expected, self.sol.preorderTraversal(root))
def test_case3(self):
# root=[1]
root=TreeNode(1)
expected=[1]
self.assertEqual(expected, self.sol.preorderTraversal(root))
def test_case4(self):
# root=[3,1,2]
root=TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(2)
expected=[3,1,2]
self.assertEqual(expected, self.sol.preorderTraversal(root))
if __name__ == "__main__":
unittest.main()
| true |
a186fb1e703f2276161e2e2923ee19fc576abea2 | EricRovell/project-euler | /deprecated/062/python/062.brute.py | 1,321 | 4.34375 | 4 | """
This is not optimised solution!
Even though the problem includes work with permutations,
it is not necessary to permute each and every cube to solve
the problem. This approach would take too much time and resources.
To explain the approch, let's take two arrays with the same elements
but in different order: [1, 2, 3] and [3, 2, 1]. By checking the
permutations of each list can be concluded that sets of permutations
are the same.
Using the uniqueness of the set of permutations, we can using the
following algorithm:
- Generate a cube
- Transform a cube to the sorted string representation (or list)
- Include sorted string into list
- Check if the list contains the given string as much times as the
problem asks
- If not -> increment a number to generate next cube.
- Repeat
The approach works but not really good one: it takes space for each
permutation to store and checking the number of occurences is expensive.
"""
def cubic_permutations(permutations):
number = 0
cubes = []
while True:
cube = sorted(list(str(number ** 3)))
cubes.append(cube)
if (cubes.count(cube) == permutations):
return cubes.index(cube) ** 3
number += 1
# assertions
#print(cubic_permutations(3))
#print(cubic_permutations(5))
| true |
1b9b7d0fbc3a640a68ea39be98bdb0706dfd1076 | sebaslherrera/holbertonschool-machine_learning | /math/0x00-linear_algebra/2-size_me_please.py | 335 | 4.1875 | 4 | #!/usr/bin/env python3
"""Module shape of a matrix """
def matrix_shape(matrix):
""" Return the shape of a matrix
returns a tuple with each index having the
number of corresponding elements """
ans = []
while (isinstance(matrix, list)):
ans.append(len(matrix))
matrix = matrix[0]
return ans
| true |
4848a19e3e05d125d617075f3db15d8553c0ed64 | wahome24/100-Days-of-Code---The-Complete-Python-Pro-Bootcamp | /Project_1.py | 580 | 4.5 | 4 | #1. Create a greeting for your program.
print('Welcome to band name generator!')
print()
#2. Ask the user for the city that they grew up in.
city = input('Please enter the name of the city you grew up in:\n').capitalize()
#3. Ask the user for the name of a pet
pet = input('What is the name of your pet?\n').capitalize()
#4. Combine the name of their city and pet and show them their band name.
print(f'The name of your band is {city} {pet}')
#5. Make sure the input cursor shows on a new line, see the example at: For that I have included the \n at the end of each line.
| true |
ac7772c77ec2880f32dda146ec3c4cbf2f1190e5 | LBolser/CIT228 | /Chapter5/hello_admin.py | 1,080 | 4.25 | 4 | print("<<<<< Exercise 5-8 >>>>>")
usernames = ["Admin","Beth","Charlie","Daisy","Ed"]
for name in usernames:
if name == "Admin":
print(f"Hello, how are you today, {name}?")
else:
print(f"Thank you for logging in, {name}.")
print("\n<<<<< Exercise 5-9 >>>>>")
usernames = []
if usernames:
for name in usernames:
if name == "Admin":
print(f"Hello, how are you today, {name}?")
else:
print(f"Thank you for logging in, {name}.")
else:
print("We need to get some users!")
print("\n<<<<< Exercise 5-10 >>>>>")
current_users = ["Admin","Beth","Charlie","Daisy","Ed"]
new_users = ["Admin", "Bernard", "Cecil", "Daisy", "Eloise"]
lower_current_users=[]
for user in current_users:
lower_current_users.append(user.lower())
lower_new_users=[]
for user in new_users:
lower_new_users.append(user.lower())
for user in lower_new_users:
if user in lower_current_users:
print(f"Please select a different name, \"{user.title()}\" is already taken.")
else:
print(f"Welcome, {user.title()}!") | false |
ba7e353c7f5b7255ba84b02c93dd8f5542eba464 | jackG97/PythonUdemyCourse | /Tutorials/venv/Data_Types_Variables_Strings.py | 457 | 4.15625 | 4 | character_name = "Tom"
character_age = "50"
print("There once was a man named " +character_name + ", ")
print("he was " + character_age + " years old. ")
character_name = "Mike"
print("he really liked the name "+character_name + ", ")
print("but didn't like being " +character_age + ". ")
phrase = "Giraffe Academy"
print(phrase.upper().isupper())
print(len(phrase))
print(phrase[0])
print(phrase.index("G"))
print(phrase.replace("Giraffe", "Elephant"))
| false |
245ea942db80ba1efb6c86c8ca08245ec3a1f182 | sethsdo/Python_Algorithms | /making_dictionaries.py | 497 | 4.125 | 4 | #Assignment: Making Dictionaries
#Create a function that takes in two lists and creates a single dictionary where the first list contains keys and the second values.
# Assume the lists will be of equal length.
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar", "wild"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
def make_dict(arr1, arr2):
new_dict = dict(zip(arr1, arr2))
return new_dict
make_dict(name, favorite_animal)
| true |
0277b0bcba538af98eb469a542ddc1c432eb0bc5 | sethsdo/Python_Algorithms | /List_Type.py | 814 | 4.1875 | 4 | #takes a list and prints a message for each element in the list, based on that element's data type
l = ['magical unicorns',19,'hello',98.98,'world']
j = [2,3,1,7,4,12,]
d = ['magical unicorns','hello','world']
def typeList(arr):
newArr = []
numSum = 0
for i in arr:
if type(i) == str:
newArr.append(i)
elif type(i) == float or int:
numSum+=i
if numSum > 0 and newArr != []:
print "The list you entered is of mixed type"
print "String: " + " ".join(newArr)
print "Sum: " + str(numSum)
elif numSum > 0:
print "The list you entered is of integer type"
print "Sum: " + str(numSum)
elif newArr != []:
print "The list you entered is of string type"
print "String: "+ " ".join(newArr)
typeList(l)
| true |
707c2624437f23743a6cec1b8a3164dd9a8db602 | Jainam2848/Usask-CMPT141-Assignments | /Assignment 1/a1q4.py | 539 | 4.125 | 4 | # NAME :- SHAH JAINAM DINESHKUMAR
# NSID :- AYQ754
# STUDENT NUMBER :- 11321534
# INSTRUCTOR'S NAME :- Nisha Puthiyedth
# COURSE :- CMPT 141
weight = float(input("Enter your weight in kg :"))
height = float(input("Eter your height in meters :"))
def bmi(weight, height):
""" This function will calculate the body's bmi
This function will take weight and height as parameters
and will return the value of bmi with respect to input taken
"""
b = weight / (height)**2
return b
print("Your BMI is : ",bmi(weight, height), "kg/m^2")
| false |
f762d44cd9757e1c63fa0ed1a399cc9f18fcfe9b | paulizio/pythonexercises | /collatz.py | 338 | 4.375 | 4 | #Type in a number,and this program will call the Collatz function until the number is 1
def collatz(number):
while number!=1:
if number%2==0:
number=number//2
print(number)
else:
number=3*number+1
print(number)
num=int(input('Insert number: '))
collatz(num)
| true |
353db06c182e9f8655c0c0d9ed0c4bc4f51ca8d2 | applebyn/obds_training | /python/PythonexerciseDNAstrand.py | 2,321 | 4.375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 14:12:15 2021
Find the complementary DNA strand
@author: andreas
"""
#find the complementary DNA strand
def complementarynucleotide(nucleotide):
#input is nucleotide A, T, C or G
#output is nucleotide A, T, C or G
output = None
#can get rid of this print(nucleotide)
if nucleotide == 'A':
output ='T'
elif nucleotide == 'T':
output = 'A'
elif nucleotide == 'G':
output = 'C'
elif nucleotide == 'C':
output = 'G'
#if the nucleotide is undetermined, the screen prints N
else:
output = "N"
# this print is not needed for now print(output)
return output
nucleotide= 'ATGHCCT'
complementarynucleotide(nucleotide)
# this is expecting an individual nucleotide, not a sequence
# to do a sequence
sequence = 'ATGCCT'
print(sequence)
def complementaryDNAstrand(strand):
#input is a strand of nucleotides A, T, C or G
#output is the complementary strand of nucleotides A, T, C or G
#output = None
# print the input strand
# take out the input print(strand)
# create a complementary strand
complementarystrand = ""
# use a "for" loop to recycle the earlier function
for n in strand:
# make a new variable for the complementary nucleotide
x = complementarynucleotide(n)
# if I take out this print(x)
complementarystrand = complementarystrand + x
print(complementarystrand)
#put the return indented to the left of the return()
#to allow the function to run through multiple loops
return (complementarystrand)
complementaryDNAstrand(sequence)
# if I want to put this output somewhere
complementary_strand = complementaryDNAstrand(sequence)
print(complementary_strand)
# write a script to return the reverse complement of a user supplied sequence
complementary_strand = complementaryDNAstrand(sequence)
# this will be a string variable
# how do you reverse a string on python? this is the key question
#google says
#txt = "hello"[::-1]
#print(txt)
#reverse_strand = complementary_strand[::-1]
#print(reverse_strand)
# do it as a new function
def reversestring (string):
return string[::-1]
print(reversestring ('abcde'))
print(reversestring (complementary_strand))
| true |
780a0db7d4ceb064a5514af1ac49a11514db67f0 | MichelGutardo/algorithms | /data_structure/queue_collection_deque.py | 956 | 4.34375 | 4 | #!/bin/python3
#collection_deque implementation using collection.deque class
#Use append() to add and popleft() elements in FiFo order
# Deque if preferred over list because append is quicker [ O(1) ], but
# pop operations as compared to list [ O(n) ]
from collections import deque
collection_deque = deque()
# append() to push element in the collection_deque
collection_deque.append("M")
collection_deque.append("i")
collection_deque.append("c")
collection_deque.append("h")
collection_deque.append("e")
collection_deque.append("l")
print("Initial collection_deque")
print(collection_deque)
# Removing elements
print("\nPop element from collection_deque:")
print(collection_deque.popleft())
print(collection_deque.popleft())
print(collection_deque.popleft())
print(collection_deque.popleft())
print(collection_deque.popleft())
print(collection_deque.popleft())
print ("\ncollection_deque after removing elements:")
print(collection_deque)
| true |
5f0bf6b6bd534c8901eb1f2fb3ff245b12e7b78f | vaishalicooner/practice_stacks_queues | /balance_parens_stack.py | 441 | 4.15625 | 4 | # Balance Parens with a Stack
def are_parens_balanced(symbols):
"""Are parentheses balanced in expression?"""
# make a stack
parens = Stack()
for char in symbols:
if char == "(":
parens.push(char) # push onto stack
elif char == ")":
if parens.is_empty():
return False
else:
parens.pop() # pop from stack
return parens.is_empty()
are_parens_balanced("((3+4)-(1+2))/(1+1)")
| true |
1aa46e19da8ae4ef5185d75bf2b97ad0d66ab061 | miguelex/Universidad-Python | /Fundamentos/operadores-logicos.py | 405 | 4.15625 | 4 | #a = int(input("Introduce un valor: "))
a =3
valorMinimo = 0
valorMaximo = 5
dentroRango = a >= valorMinimo and a <= valorMaximo
#print(dentroRango)
if(dentroRango):
print("Dentro del rango")
else:
print("Fuera del Rango")
vacaciones = False
diaDescanso = True
if(vacaciones or diaDescanso):
print("Puedes ir al parque")
else:
print("Tienes deberes que hacer")
print(not(vacaciones)) | false |
6935144e5631ab795771cad595e9f74cd42289c1 | miguelex/Universidad-Python | /Fundamentos/tuplas.py | 545 | 4.3125 | 4 | #Una tupla mantiene el orden oeri no se puede modificar
frutas = ("Naranja", "Platano", "Guayaba")
print(frutas)
#largo de la tupl
print(len(frutas))
#accediendo a un elemento
print(frutas[0])
#navegacion inversa
print(frutas[-1])
#rango
print(frutas[0:2]) #Excluyebdo indice 2
#modificar tupla
frutasLista = list(frutas)
frutasLista[1] = "Banana"
frutas = tuple(frutasLista)
print(frutas)
#iterar una tupla
for fruta in frutas:
print(fruta, end =" ")
# no podemso agregar ni eliminear elementos de uan tupla
del frutas
print(frutas) | false |
21687309adf8bb75f56e15267b33f3c63c29c165 | munkhbat57/nucamp_python | /1-Fundamentals/battlegame.py | 2,415 | 4.125 | 4 | game_on = True
while game_on:
wizard = "Wizard"
elf = "Elf"
human = "Human"
orc = "Orc"
wizard_hp = 70
elf_hp = 100
human_hp = 150
orc_hp = 200
wizard_damage = 150
elf_damage = 100
human_damage = 20
orc_damage = 120
dragon_hp = 300
dragon_damage = 50
while True:
print("1) Wizard")
print("2) Elf")
print("3) Human")
print("4) Orc")
print("5) Exit")
character = input("Choose your character: ").lower()
if character == '1' or character == "wizard":
character = wizard
my_hp = wizard_hp
my_damage = wizard_damage
break
elif character == '2' or character == "elf":
character = elf
my_hp = elf_hp
my_damage = elf_damage
break
elif character == '3' or character == "human":
character = human
my_hp = human_hp
my_damage = human_damage
break
elif character == '4' or character == "orc":
character = orc
my_hp = orc_hp
my_damage = orc_damage
break
elif character == '5' or character == "exit":
game_on = False
break
else:
print("Unknown character")
while game_on:
print(
f"Your chosen character is {character}, your hp is {my_hp}, your damage is {my_damage}")
dragon_hp -= my_damage
print(f"The {character} damaged the Dragon!\n")
if dragon_hp <= 0:
print("The Dragon has lost the battle\n")
decision = input("Do you want to play again? Y/n ").lower()
if decision == 'y':
game_on = True
elif decision == 'n':
game_on = False
break
my_hp -= dragon_damage
print(f"{character} has been damaged and it's hp is {my_hp}\n")
if my_hp <= 0:
print(f"{character} has lost the battle\n")
while True:
decision = input("Do you want to play again? Y/n ").lower()
if decision == 'y':
game_on = True
break
elif decision == 'n':
game_on = False
break
else:
continue
break
| false |
86138310509f15c39891d2886711d8d609734d5c | anmolrishi/ProgrammingHub | /bogosort.py | 602 | 4.1875 | 4 | # Bogosort: A very effective and efficient sorting algorithm :^)
import random
def isSorted(listOfNums):
for i in range(len(listOfNums) - 1):
if listOfNums[i] > listOfNums[i + 1]:
return False
return True
def main:
print("Input a list of numbers (seperated by [enter]s) and terminate input by entering a non-number value")
listOfNumbers = []
while True:
num = input("? ")
try:
listOfNumbers.append(float(num))
except:
break;
while not isSorted(listOfNumbers):
listOfNumbers = random.shuffle(listOfNumbers)
if __name__ == "__main__":
main()
| true |
67b2bcd448c3f7a3935f2f3ffc9c05b306f9895e | kakashi-hatake/wumpus | /wumpus_prebow.py | 2,491 | 4.125 | 4 | from random import choice
def create_tunnel(cfrom, cto):
"""create a tunnel between from and to"""
caves[cfrom].append(cto)
caves[cto].append(cfrom)
def visit_cave(number):
"""mark a cave as used"""
visited_caves.append(number)
unvisited_caves.remove(number)
def choose_cave(cave_list):
"""pick a cave provided it has less than three tunnels"""
number=choice(cave_list)
while len(caves[number]) >=3:
number = choice(cave_list)
return number
def print_caves():
"""print cave structure"""
for number in cave_numbers:
print number, ":", caves[number]
print '----------------'
def setup_caves(cave_numbers):
"""create the list of caves"""
caves = []
for cave in cave_numbers:
caves.append([])
return caves
def link_caves():
"""make two way tunnels between caves"""
while unvisited_caves !=[]:
this_cave = choose_cave(visited_caves)
next_cave = choose_cave(unvisited_caves)
create_tunnel(this_cave, next_cave)
visit_cave(next_cave)
def finish_caves():
"""link the rest of the caves with one way tunnels"""
for cave in cave_numbers:
while len(caves[cave]) < 3:
passage_to = choose_cave(cave_numbers)
caves[cave].append(passage_to)
def print_location(player_location):
"""tell player were they are"""
print "you are in cave", player_location
print "from here you can see caves:"
print caves[player_location]
if wumpus_location in caves[player_location]:
print "I smell a wumpus!"
def get_next_location():
"""get player's next location"""
print "which cave next"
player_input = raw_input("> ")
if(not player_input.isdigit() or
int(player_input) not in caves[player_location]):
print "the tunnels do no lead there"
return None
else:
return int(player_input)
cave_numbers = range(0,20)
unvisited_caves = range(0, 20)
visited_caves = []
caves = setup_caves(cave_numbers)
visit_cave(0)
##print_caves()
link_caves()
##print_caves()
finish_caves()
wumpus_location = choice(cave_numbers)
wumpus_friend_location = choice(cave_numbers)
player_location = choice(cave_numbers)
while (player_location == wumpus_location or
player_location == wumpus_friend_location):
player_location = choice(cave_numbers)
while True:
print_location(player_location)
new_location = get_next_location()
if new_location is not None:
player_location = new_location
if player_location == wumpus_location:
print "Aargh! you got eaten by the Wumpus"
break
| true |
a08f42e3bf4d1bad0300bef19434df11be473c2f | Jyothi-narayana/DSA | /MI1.py | 638 | 4.1875 | 4 | from sets import Set
class WordList:
"""Stores a list of words"""
def __init__(self):
"""Initializes a set to store the list of words"""
self.words = Set()
def addWord(self, word):
"""Add a word to the word list"""
self.words.add(word)
def addWords(self, words):
for w in words:
self.addWord(w)
def hasWord(self, word):
"""Check if a word exists in a word list"""
if (word in self.words):
return True
else:
return False
wl = WordList()
wl.addWords(['hello', 'heard', 'heaven', 'hear', 'heed', 'heap', 'help', 'hipster'])
print 'hello exists: ', wl.hasWord('hello')
print 'hell exists: ', wl.hasWord('hell')
| true |
ae935303ed1f963925c756fdb70b964600442f5e | ttafsir/100-days-of-code | /code/day1/day1_datetime.py | 1,341 | 4.25 | 4 | from datetime import date, time, timedelta, datetime
april_fools_2021 = date(year=2021, month=4, day=1)
noon = time(hour=12, minute=0, second=0)
midnite = time(hour=0, minute=0, second=0)
print(f"april fool's day is: {april_fools_2021}")
print(f"noon == {noon}")
print(f"midnight == {midnite}")
# working with dates
todays_date = date.today()
todays_date_w_time = datetime.today()
print(f"today: {todays_date}")
print(f"today w/ time: {todays_date_w_time}")
now = datetime.now()
print(f'now: {now}')
current_time = time(now.hour, now.minute, now.second)
print(f'current time: {current_time}')
datetime.combine(todays_date, current_time)
# working with datetime and strings
date_from_str = date.fromisoformat("2021-04-12")
print(date_from_str)
date_string = "04-12-2021 12:45:55"
date_fmt = "%m-%d-%Y %H:%M:%S"
dt = datetime.strptime(date_string, date_fmt)
print(dt)
# timedelta
days_since_new_year = todays_date - date.fromisoformat("2021-01-01")
print(f"days since new year 2021: {days_since_new_year}")
# the following would fail because you cannot do arithmetic
# with 'datetime.date' and 'datetime.datetime' objects
# date.fromisoformat("2021-12-31") - todays_date
# todays_date - now
# Arithmetic with datetime
yesterday = timedelta(days=-1)
print(f"yesterday is {yesterday} away")
print(f"yesterday was: {now + yesterday}")
| false |
ba37bec74aae29348f52ae94d4bafc4ccf6a912b | jusnlifa/shiyanlou-code | /while.py | 202 | 4.1875 | 4 | # coding=utf-8
myList = ['English','Chinese','Japane','German','France']
# while len(myList):
# print('pop element out:',myList.pop())
for language in myList:
print('current element is :',language) | false |
fa73596b37501bb2804ea41e75e46bed8461a723 | momentum-cohort-2019-02/w2d2-palindrome-yyapuncich | /palindrome.py | 1,628 | 4.4375 | 4 | # ask user for sentence or name and let them know if it's a palindrome
# ask user for input string
phrase_entered = input("Enter a phrase and let's check if it's a palindrome: ")
#remove all special characters and spaces from phrase
def remove_extra_spaces(phrase_entered):
"""This function removes spaces and special characters from phrase"""
letters = "abcdefghijklmnopqrstuvwxyz"
letters += letters.upper()
phrase_clean = ""
for char in phrase_entered:
if char in letters:
phrase_clean += char
return phrase_clean
phrase_new = remove_extra_spaces(phrase_entered).lower()
# function that reverses original string and returns that reverse
def reverse_phrase(phrase_new):
"""This function reverses the phrase entered and returns that reversed phrase"""
return phrase_new[::-1]
# defines phrase backwards using the reverse_phrase function
phrase_backwards = reverse_phrase(phrase_new)
# print(phrase_backwards) <----this was testing if it worked
# compare string to reverse of string, make function to do it?
# print response that confirms palindrome or not "is a palindrome" or "is not a palindrome"
def palindrome(phrase_new, phrase_backwards):
"""This function let's you know if you've entered a palindrome or not"""
if phrase_backwards == phrase_new:
# palindrome = True
print("This here is a palindrome: ", phrase_new, phrase_backwards)
else:
# palindrome = False
print("This here is not a palindrome: ", phrase_new, phrase_backwards)
palindrome(phrase_new, phrase_backwards)
# palindrome = True
# def palindrome():
| true |
11fe4ab12798b0c761227d0b183d90e0f7bcec89 | miroswd/python-impacta | /manipulandoArquivos.py | 724 | 4.15625 | 4 | # Read
# modo leitura ja esta embutido, nao precisa carregar modulo
# o arquivo deve permanecer no mesmo diretorio do arquivo py
def readFile(file):
arquivo = open(file,'r') # funcao open('nome','modo de manipulacao (r > read, w > write, a > apend, incluir depois do conteudo do arquivo, r+ > read e write)')
for linha in arquivo:
print(linha)
arquivo.close()
# no windows tem q passar o b, rb, wb, ab, r+b, pois o windows difere arquivos txt de binario
def saveFile(file, newText):
arquivo = open(file,'w')
arquivo.write(newText)
arquivo.close()
# Quando usar arquivos externos, sempre fechar o processo
# para evitar um bloqueio de acesso
saveFile('bomDia.txt', 'Hello World!')
readFile('bomDia.txt')
| false |
52f8962a2909bcb3d0117cbf2ee2d99a5fb713f5 | miroswd/python-impacta | /orientacaoAObjeto.py | 1,312 | 4.3125 | 4 | # Classe
# interpretar como uma receita
# atributos => ingredientes
# metodos => modo de fazer
# classe Pessoa
# atributos => nome, idade e sexo
# metodos => andar, comer e dormir
# Criando um Objeto
# p = Pessoa() # Declara variavel referenciando a classe Pessoa
# p.nome = 'Miro'
# p.idade = 20
# p.sexo = 'M'
# ---Objetos
# variavel que armazena um valor do tipo de uma classe
# ---Heranca
# herda atributos e metodos de outra classe
# criando um objeto professor
# Professor
# lecionar()
# herdou as caracteristicas do objeto Pessoa
# com uma nova funcionalidade
# pessoa e o pai da classe professor
# --- Polimorfismo
# significa 'muitas formas'
# Professor
# lecionar()
# dormir()
# Aluno
# lecionar()
# dormir()
# o dormir invocado, sera do professor ou do aluno, pois dormem de forma diferente
# object => objeto que sera pai da classe, se nao herdar usa o object
class Pessoa(object):
nome = None
# entre parenteses e passado o pai da classe, nao os parametros
# pass # informa q a classe/funcao esta vazia
# importar esse modulo no arquivo pessoas.py
##Criando um metodo(self) => identifica a propria classe
# todo primeiro parametro do metodo deve ser o self
def salvar(self,x):
self.nome = x
print("Salvando %s" %self.nome)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.