blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
473b2d32e7aca4f9b4f5850ce767331190f1ab47
pcmason/Automate-the-Boring-Stuff-in-Python
/Chapter 7 - Pattern Matching with Regular Expressions/dateDetection.py
2,067
4.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun May 2 17:27:33 2021 @author: paulmason program that detects valid dates in the format of DD/MM/YYYY """ #first import the regex module import re #create the date regex dateRegex = re.compile(r'(\d\d)/(\d\d)/(\d\d\d\d)') #search for a regex object mo = dateRegex.search('31/06/2304') #create an example for a correct leap year leapYear = dateRegex.search('29/02/2400') #create an incorrect example unrealDay = dateRegex.search('29/02/2015') #print the found regex date #print(mo.group()) #create a list for each date dates = [mo, leapYear, unrealDay] #create function to check if the date is valid def validDate(d, m, y): #if there are more than 31 days or less than 1 days this is not valid if d < 1 or d > 31: return False #if there are more than 12 months or less than 1 month than this is not valid if m < 1 or m > 12: return False #year is between 1000 to 2999 if y < 1000 or y > 2999: return False #April June September and November have only 30 days if (m == 4 or 6 or 9 or 11) and (d > 30): return False #February has 28 days except during leap years if m == 2 and y % 4 == 0 and (y % 400 == 0 or y % 100 != 0): #a leap year if d > 29: return False elif m == 2 and (y % 4 != 0 or y % 100 == 0): #not a leap year if d > 28: return False #if made it this far return true return True #call validDate on day, month and year #assign the groups to variable they represent by looping through dates for date in dates: day = int(date.group(1)) month = int(date.group(2)) year = int(date.group(3)) #debug printout, useful to see each group #print(day) #print(month) #print(year) #call validDate in the print statement below to determine if the date is valid (results: F, T, F) print('The date\'s ' + date.group() + ' validity is: ' + str(validDate(day, month, year)))
true
27c529bd1c70f36cf550bf53b2333c05681c6b50
sparkle6596/python-base
/pythonProject/function/calculator using function.py
519
4.15625
4
num1=float(input("enter number1")) num2=float(input("enter number2")) choice=(input("enter your choice")) def add(num1,num2): sum=num1+num2 print(sum) def sub(num1,num2): sub=num1-num2 print(sub) def mul(num1,num2): mul=num1*num2 print(mul) def division(num1,num2): division=num1/num2 print(division) if(choice=='+'): add(num1,num2) elif(choice=='-'): sub(num1,num2) elif(choice=='*'): mul(num1,num2) elif(choice=='/'): division(num1,num2) else: print("invalid")
false
065bb60114d3f78139202df70c4e4ca23ddde974
saikatsengupta89/PracPy
/BreakContinuePass.py
667
4.125
4
#to showcase break statement x= int(input("How many candies you want? ")) available_candies=5 i=1 while (i<=x): print ("Candy") i=i+1 if (i>available_candies): print("There were only 5 candies available") break print("Bye") #print all values from 1 to 100 but skip those are divisible by 3 #to showcase continue statement for i in range(1,101): if (i%3==0): continue; print (str(i)+" ", end="") print() #print all values from 1 to 100 but not the odd numbers #to showcase pass statement for i in range(1,100): if (i%2==0): print (str(i)+" ", end="") else: pass print()
true
e4af094f69a9d508f26145e5d56913c88d8e86ad
saikatsengupta89/PracPy
/class_inherit_constructor.py
1,420
4.46875
4
# IF YOU CREATE OBJECT OF SUB CLASS IT EILL FIRST TRY TO FIND INIT OF SUB CLASS # IF IT IS NOT FOUND THEN IT WILL CALL INIT OF SUPER CLASS # class A: def __init__(self): print ("This is from constructor A") def feature1(self): print ("Feature1A is working fine") def feature2(self): print ("Feature2 is working fine") class B: def __init__(self): print ("This is from constructor B") def feature1(self): print ("Feature1B is working fine") def feature3(self): print ("Feature3 is working fine") def feature4(self): print ("Feature4 is working fine") class C (A,B): def __init__(self): super().__init__() #calling the init of super class print ("This is from constructor C") #calling method of super class from subclass def feature(self): super().feature2() # by default the below statement will create an instance for class B and will call the constructor of class A # if there is no constructor defined for class B b= B() #below instance creation will call the __init__ of super class A and not B. This is due to MRO (Method Resolution Order) #whenever you have multiple class inheritance, the child class will always look up to that parent class which comes left #it will always start from left to right. c=C() c.feature1() c.feature()
true
90374fa7c243c334e5e8728a8a380f3d84ca1c99
saikatsengupta89/PracPy
/HCK_Calender.py
725
4.34375
4
import calendar def which_day(day_str): month, day, year= day_str.split(" ") if (int(year) < 2000 or int(year) > 3000): print("INVALID") else: weekday= calendar.weekday(int(year), int(month), int(day)) if(weekday==0): print("Monday") elif (weekday==1): print("Tuesday") elif (weekday==2): print("Wednesday") elif (weekday==3): print("Thursday") elif (weekday==4): print("Friday") elif (weekday==5): print("Saturday") else: print("Sunday") if __name__=="__main__": inp=input("Enter day in format MM DD YYYY :") which_day(inp)
false
da1e1cf498dea793b77f216f80969d1dffbe4631
handes2019/Python
/hm_08_综合案例_猜拳游戏.py
649
4.28125
4
""" 1、出拳 玩家:手动输入 电脑:1、固定:剪刀;2、随机 2、判断输赢 2.1 玩家获胜 2.2 平局 2.3 电脑获胜 """ # 1.出拳 import random # 玩家 player = int(input('请出拳: 0 -- 拳头; 1 -- 剪刀; 2 -- 布; ')) # 电脑 computer = random.randint(0, 2) print(computer) # 2. 判断输赢 # 玩家获胜 if ((player == 0) and (computer == 1)) or ((player == 1) and (computer == 2)) or ((player == 2) and (computer == 0)): print('玩家获胜,23333') # 平局 elif player == computer: print('平局,别走,再来一局') # 电脑获胜 else: print('电脑获胜')
false
8119dc127f1f9b1a05bb1890769527bb08f40d46
m-tranter/cathedral
/python/Y8/hangman.py
1,442
4.125
4
# hangman.py - simple hangman game from random import * def main(): WORDS = ['acorn', 'apple', 'apricot', 'grape', 'grapefruit', 'kiwi', 'lemon', 'mango', 'melon', 'orange', 'peach', 'pear', 'pineapple', 'raspberry', 'satsuma'] # pick a word randomly word = choice(WORDS) guessed, lWord = '', len(word) print("*** Hangman ***") print("\nThe word is {} letters long.".format(lWord)) print("_ " * lWord) for i in range(5): letter = input("\nGuess a letter: ").lower() if len(letter) == 1: if letter in word: temp = "\nYes, the word contains " guessed += letter else: temp = "\nNo, it doesn't contain " output = ' '.join(x if x in guessed else '_' for x in word) print("{0} '{1}'.\n{2}".format(temp, letter, output)) else: print("Just one letter for now please!") print("\nThat's all your letter guesses used up.") if input("\nNow guess the word: ") == word: print("\nWell done, you got it.") else: print("\nSorry, wrong. It was: \"{}\".".format(word)) if __name__ == "__main__": main()
true
28572191a4f31cf43fd927dca3e721ce4aff03d6
kevmo/pyalgo
/guttag/031.py
618
4.21875
4
# INSTRUCTIONS # input: integer # output: root and power such that 0 < pwr < 6 and # root**pwr = integer from sys import argv user_number = int(argv[1]) def find_root_and_power(num): """ Input: num Returns a root, power such that power is 2 and 5, inclusive, and root**power = num. """ root = 0 for pwr in range(2, 6): while root**pwr < num: root += 1 if root**pwr == num: return root, pwr else: root = 0 print "There is no root, power pair for {}.".format(num) return None print find_root_and_power(user_number)
true
4c5e94f7469efc1849249ab4c47050a2ff62bbf3
moayadalhaj/data-structures-and-algorithms401
/challenges/stack-queue-pseudo/stack_queue_pseudo/stack_queue_pseudo.py
2,378
4.40625
4
class Node: def __init__(self, value): self.value = value self.next = None class Stack: """ create a stack class that containes three methods push: to add a new node at the top of stack pop: to delete the top node in the stack peek: to return the value of top node if it exist """ def __init__(self): self.top = None def push(self, value): """ push: to add a new node at the top of stack """ node = Node(value) node.next = self.top self.top = node def pop(self): """ pop: to delete the top node in the stack """ if self.top == None: raise Exception("This stack is empty") temp=self.top self.top=self.top.next temp.next=None return temp.value def peek(self): """ peek: to return the value of top node if it exist """ try: return self.top.value except: return "This stack is empty" class PseudoQueue: """ PseudoQueue class that implement a standard queue interface which containes two methods enqueue: which inserts value into the PseudoQueue, using a first-in, first-out approach. dequeue: which extracts a value from the PseudoQueue, using a first-in, first-out approach. """ def __init__(self): self.front = Stack() self.rear = Stack() def enqueue(self, value): """ enqueue: which inserts value into the PseudoQueue, using a first-in, first-out approach. """ node = Node(value) if not self.rear.top: self.front.top = node self.rear.top = node else: temp = self.rear.top self.rear.push(value) self.rear.top.next = None temp.next = self.rear.top def dequeue(self): """ dequeue: which extracts a value from the PseudoQueue, using a first-in, first-out approach. """ try: temp = self.front.pop() return temp except: return 'This queue is empty' if __name__ == '__main__': a = PseudoQueue() a.enqueue(5) a.enqueue(6) a.enqueue(7) print(a.dequeue()) print(a.dequeue()) print(a.dequeue()) print(a.dequeue())
true
74e25d370002de7de1af58c8d519a445974211db
miklashevichaleksandr/lesson2
/age.py
413
4.125
4
user_age = input('Введите ваш возраст: ') user_age = int(user_age) if user_age <= 6: print ('Вам нужно учиться в детском саду') elif 6 < user_age <= 17: print('Вам нужно учиться в школе') elif 17 < user_age <= 23: print('Вам нужно учиться в ВУЗе') elif user_age > 23: print('Вам нужно работать')
false
022ac59fc09a1e47b58038fc2b2c081da84ec48a
maniiii2/PSP-LAB-PYTHON-
/python/condition_demo.py
367
4.1875
4
#Conditional statements #using if statement find the largest among two numbers x=int(input("enter first number")) print("x=",x) print(type(x)) y=int(input("enter second number")) print("y=",y) print(type(y)) if x>y: print("x is greater than y") elif x==y: print("x is equal to y") else: print("y is greater than x") z=x+y print("Z",z)
true
ec9d5a106d1b21e409890b52b34f0c233f17c2e5
thtay/Algorithms_and_DataStructure
/CrackingCodingInterview_Python/Arrays_and_Strings/stringComp.py
1,251
4.1875
4
''' String compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaa would be a2b1c5a3. If the "compressed" string would not become smaller than the orignal string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). ''' ''' let's iterate through the word: two pointer appraoch would work here aaabbbcccaakk ^^ if if i and f are the same increment only f and count another aaabbbcccaakk ^ ^ i f same as above aaabbbcccaakk ^ ^ i f not the same. so append i and the counter and move i to f and increment f by 1 ''' def stringComp(word): ans = "" forward = 1 i = 0 counter = 1 while forward < len(word): if word[i] == word[forward]: counter += 1 forward += 1 else: ans += word[i] ans += str(counter) i = forward forward += 1 counter = 1 if forward + 1 > len(word): ans += word[i] ans += str(counter) if len(ans) >= len(word): return word return ans ''' Test Cases ''' print(stringComp('aaabbbcccaakk')) print(stringComp('aabbbcccaakkc')) print(stringComp('abcnfjdk')) print(stringComp('aabbbcccaakkc')) print(stringComp('aabbbcccaaaakkcb'))
true
d74ddb75db7228a67bdab656e47e54523277ac5d
kagomesakura/palindrome
/pal.py
291
4.21875
4
def check_palindrome(string): half_len = len(string) // 2 #loop through half the string for i in range(half_len): if string[i] != string[len(string)-1-i]: return False return True user_input = input('what is your word? ') print(check_palindrome(user_input))
true
0a60c23622abd6a9c4a6348054f54b08484719ef
chudichen/algorithm
/linked_list/reverse_list.py
859
4.125
4
# -*- coding: utf-8 -*- """ 反转链表 解题思路将使用虚拟before指针,将head的值依次传递给before,最终形成反转链表。 https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/2378/ """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverse_list(self, head: ListNode) -> ListNode: before = None while head: temp = head.next head.next = before before = head head = temp return before # 测试方法 if __name__ == '__main__': headNode = ListNode(1) add = headNode for i in range(2, 6): add.next = ListNode(i) add = add.next solution = Solution() solution.reverse_list(headNode)
false
23a92b7be84aea5b82f891cc5eb99f807c3f0e49
dhilanb/snakifywork
/Unit 1 and 2 Quiz/Problem5.py
280
4.125
4
A= int(input("How many feet does a nail go up during the day? ")) B= int(input("How many feet does the snail fall at night? ")) H= int(input("How high would you like the snail to go up? ")) days= H/(A-B) print("It will take the snail "+str(days)+" days to go up "+str(H)+" feet.")
true
fe732b17a297b599562ad04b0f19832c1e2fdeaf
carlita98/MapReduce-Programming
/1.Distributed greed/P1_mapper.py
569
4.1875
4
#!/usr/bin/python # Filtering parttern: It evaluates each line separately and decides, # based on whether or not it contains a given word if it should stay or go. # In particular this is the Distributed Grep example. # Mapper: print a line only if it contains a given word import sys import re searchedWord = sys.argv[1] for line in sys.stdin: line = re.sub( r'^\W+|\W+$', '', line ) words = re.split(r'\s' , line) words = [item.lower() for item in words] if searchedWord.lower() in words: print( "" + '\t' + line )
true
0b070f64a2cb7dfa6e30f39dd56909c8161f7b85
ajaymonga20/Projects2016-2017
/question2.py
1,698
4.53125
5
# AJAY MONGA -- QUESTION 2 -- COM SCI TEST -- FEBRUARY 14, 2017 # imports # Nothing to Import # Functions def caught_speeding(speed, birthday): if (speed <= 60) and (birthday == False): # Returns 0 if the speed is less than 60 return 0 elif (speed >= 61) and (speed <= 80) and (birthday == False): # If the speed is in the range of 61-80 and it is not their birthday, it returns a 1 return 1 elif (speed > 81) and (birthday == False): # If the speed is any integer larger than 81 and not their birthday, then it returns 2 return 2 elif (birthday == True) and (speed <= 65): # If it is their birthday and their seed is 65 or lower then it returns 0 return 0 elif (birthday == True) and (speed >= 66) and (speed <= 85): # If it is their birthday and they are between 66-85, then it returns 1 return 1 elif (birthday == True) and (speed >= 86): # If it is their birthday, but are going any faster than 86 then it returns 2 return 2 def input_string(birthday): # This small function tells the system that if user answers "yes" to the promt, then to convert that to True or False for the caught_speeding function def input_string(birthday): if (birthday == "yes") return True elif (birthday == "no"): return False # Main Code speed = input("what is your speed? ") # This asks for the speed, it is input for integers birthday = raw_input("Is it your birthday? answer: yes or no ") # This asks for if it is your birthday or not, this is raw_input for strings input_string(birthday) # This calls the function to convert the "yes" or "no" to True or False print caught_speeding(speed, birthday) # This prints the result from the caught_speeding function
true
da0c154b6829240f2f583aac92f8d213b4802a78
Rufaidah/TestBootcampArkademy9
/PrintPattern.py
558
4.25
4
side = int(input("Masukkan sisi persegi : ")) def drawImage(side): # row for i in range(side): # column for j in range(side): if (i == (side - 1) / 2) or (j == (side - 1) / 2) \ or (i | j == 0) or (i == 0 and j == side - 1) \ or (i == side - 1 and j == 0) or (i == side - 1 and j == side - 1): print("*", end='') else: print("=", end='') print() if side % 2 == 0: print("Panjang sisi harus ganjil") else: drawImage(side)
false
f050bb18b1a8914af117e64b15d22d2e2b06a422
nsatterfield2019/Notes
/Week 8_Plotting.py
651
4.25
4
# PLOTTING (withmathploitlib) import matplotlib.pyplot as plt plt.figure(1) # creates a new window plt.plot([1, 2, 3, 4]) # if there is no x axis, it just gives index 0, 1, 2... plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.figure(2, facecolor ='limegreen') # opens up a new window/figure x = [x for x in range(10)] y = [y**2 for y in range(10)] # plot.plt takes kwarg (keyword arguments) plt.plot(x,y, color='violet', marker='o', markersize=10, linestyle="--", alpha=0.5) plt.xlabel('time (days)') plt.ylabel('excitement level (yays)', color = 'red') plt.title('Example Plot', color = 'blue', fontsize=30) plt.axis([1, 10, 10, 100]) plt.show()
true
da762ad4794c151ea8f9d3c9133d336b974da541
matt-ankerson/ads
/queues/supermarket_model_1.py
2,103
4.1875
4
from queue import Queue from customer import Customer import random as r # Author: Matt Ankerson # Date: 15 August 2015 # This script models queue behaviour at a supermarket. # The scenario is: 10 checkouts, a customer selects a checkout at random. class SuperMarket(object): def __init__(self): r.seed() self.n_customers = 0 self.done = False self.time_taken = 0 self.checkouts = [] for k in range(10): # build list of checkout queues q = Queue() self.checkouts.append(q) def add_customer(self): # randomly assign a new customer to a queue c = Customer(r.randint(1, 5)) self.checkouts[r.randint(0, 9)].enqueue(c) self.n_customers += 1 # increment n_customers def clock_a_minute(self): self.time_taken += 1 # add a customer every two minutes. if self.n_customers <= 1000 and self.time_taken % 2 == 0: self.add_customer() # decrement time required for the people at the head of each queue for checkout in self.checkouts: if not checkout.is_empty(): # decrement time left for the first customer checkout.first().checkout_time -= 1 if checkout.first().checkout_time <= 0: # if the customer has finished, pull them off the queue checkout.dequeue() # assess whether or not we have customers left to deal with self.done = self.queues_empty() def queues_empty(self): # check to ensure that we've still got customers to deal with empty = True if self.n_customers < 1000: empty = False else: for checkout in self.checkouts: if not checkout.is_empty(): empty = False return empty if __name__ == "__main__": print("Random Queue Assignment: ") soup = SuperMarket() while not soup.done: soup.clock_a_minute() print("Time taken: " + str(soup.time_taken))
true
e6eb97080ddf47dda39b56673e6d47b390fe705a
GiovanniSinosini/cycle_condictions
/area_peri.py
269
4.375
4
pi = 3.1415 # Calculator perimeter and area radius = float(input("Enter radius value (in centimeters): ")) area = pi * (radius **2) perimeter = 2 * pi * radius print("The area value is:{:.2f}".format(area)) print( "The perimeter value is:{:.2f}".format(perimeter))
true
1a4aa8ce1b0ea42467a39d3c2f422f2465037f9b
GiovanniSinosini/cycle_condictions
/pythagorean_theorem.py
504
4.46875
4
import math adjacent = float(input ("Enter the value of the side adjacent: ")) opposite = float(input("Enter the value of the side opposite: ")) #hypotenuse = math.sqrt((math.pow(adjacent, 2) + math.pow(opposite,2))) #print ("Hypotenuse has a value of: ", hypotenuse) #hypotenuse = ((adjacent ** 2) + (opposite ** 2)) **(1/2) #print("Hypotenuse has a value of: {:.2f} " .format(hypotenuse)) hypotenuse = math.hypot(adjacent, opposite) print("Hypotenuse has a value of: {:.2f}" .format(hypotenuse))
false
03347d591443192c119d3fb82f4f4712279ebb62
Parkduksung/study-python
/chapter/chapter1,2,3.py
1,300
4.28125
4
# chapter1,2,3,4,5 확인문제. #--------------chapter 1----------------- # 1-1번 print("Hello Python") #--------------chapter 2----------------- print("# 연습문제") print("\\\\\\\\") # \ 4개만 나옴. print("-" * 8) # - 8번 찍힘. print("abcde"[1]) # b print("abcde"[1:]) # bcde print("abcde"[1:2]) # b print("abcde"[:1]) # a print("abcde"[:4]) # a print(4**4) # 제곱연산자. 4의 4승임. print(4,"*",4,"=",4*4) # 16 print(2+2-2*2/2*2) # 0 str_input1 = input("숫자 입력>") num_input1 = float(str_input1) print() print(num_input1, "inch") print(num_input1 * 2.54, "cm") str_input1 = input("원의 반지름 입력>") num_input1 = float(str_input1) print() print("반지름", str_input1) print("둘레", 2*3.14*str_input1) print("넓이", 3.14 * str_input1**2) a = "abcd" b = "dcba" print(a,b) # swap tmp = a a = b b = tmp print(a,b) a = "1 2 3 4 5 6".split(" ") print(a) num1 = input("입력해봐 숫자 > ") last_num = int(num1) if last_num == 0 : print("o") else: print("x") # \ 를 써서 줄바꿈해준다. if int(num1) == 0 \ or num1 == 2 \ or num1 == 4 \ or num1 == 6 \ or num1 == 8 : print("0") else: print("x") if str(num1) in "02468" : print("o") else: print("x")
false
b844861db93e2d99d345d5b0e83ef01a88622fb2
mwharmon1/UnitTestStudentClass
/test/test_student.py
1,875
4.28125
4
""" Author: Michael Harmon Last Date Modified: 10/28/2019 Description: These unit tests will test the Student class constructors and functionality """ import unittest from class_definitions import student as s class MyTestCase(unittest.TestCase): def setUp(self): self.student = s.Student('Harmon', 'Michael', 'BIS') def tearDown(self): del self.student def test_object_created_required_attributes(self): student = s.Student('Harmon', 'Michael', 'BIS') assert student.last_name == 'Harmon' assert student.first_name == 'Michael' assert student.major == 'BIS' def test_object_created_all_attributes(self): student = s.Student('Harmon', 'Michael', 'BIS', 4.0) assert student.last_name == 'Harmon' assert student.first_name == 'Michael' assert student.major == 'BIS' assert student.gpa == 4.0 def test_student_str(self): self.assertEqual(str(self.student), "Harmon, Michael has major BIS with gpa: 0.0") def test_object_not_created_error_last_name(self): with self.assertRaises(ValueError): student = s.Student('100', 'Michael', 'BIS') def test_object_not_created_error_first_name(self): with self.assertRaises(ValueError): student = s.Student('Harmon', '200', 'BIS') def test_object_not_created_error_major(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', '12345') def test_object_not_created_error_gpa(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', 'BIS', 'Bad GPA') def test_object_not_created_error_gpa_not_in_range(self): with self.assertRaises(ValueError): student = s.Student('Harmon', 'Michael', 'BIS', 5.0) if __name__ == '__main__': unittest.main()
true
93193ffd4d3a9d84cda21227724b8d7214285958
Jovan-Popovic/django_developers_lab
/predavanje-01/oo.py
1,059
4.125
4
from copy import deepcopy class Animal(): number_of_animals = 0 def __init__(self, latin_name, birth_age, weight, location): self.latin_name = latin_name self.birth_age = birth_age self.weight = weight self.__location = location Animal.number_of_animals += 1 def say_hello(self): print(f'Hello, I am {self.latin_name} {self.birth_age} {self.weight}') def __repr__(self): return f'{self.latin_name}' def say_your_age(self, now_year): print('Hello, I am', now_year - self.birth_age, 'years old') animal_1 = Animal('Lorem ipsum', 2019, 5, 5) # # animal_1.say_hello() # print(animal_1) # animal_1.say_your_age(2020) # del animal_1 animal_2 = deepcopy(animal_1) animal_2.latin_name = "Ipsim Lorem" print(animal_1) print(animal_2) # print(animal_2._Animal__location) print(dir(animal_2)) print(hasattr(animal_2,'_Animal__location')) class Dog(Animal): def say_hello(self): print("Av av av av") rex = Dog('Canus',2019,5,200) print(rex)
false
010d035dd41d553525cb4580569679b03412378e
durgareddy577/python
/python_programmes/string3.py
740
4.28125
4
name="durga reddy"; name1="DURGA REDDY"; sentence="1abc2abc3abc4abc5"; sentence1="this is durga reddy from banglore"; print(len(name)); #to find the length of the string print(name.upper()); #to covert lower case latter to uppercase latter print(name1.lower()) #TO CONVERT UPPER CASE LATTER TO LOWERCASE LATTERS print(sentence.replace("abc","xyz")); #to replace all occuaratons strings with anothe string print(sentence.replace("abc","xyz",1)); print(sentence.replace("abc","xyz",2)); print(sentence1[8:13]); print(sentence1[8:13:1]); print(sentence1[8:13:3]); print(name[-1]); print(name[1]); print(name[:]); print(name[2:]); print(name[:4]); print(name[:-1]); print(name[::2]); print(name[::-1]); print(name[0:-1])
false
08e693a2fbd53015bf7834908ee32ce141e8db99
SaneStreet/challenge-100
/challenge105/challenge105.py
896
4.1875
4
""" To use the python script in Command Prompt: Write 'python your_file_name.py' Example: 'python challenge101.py' """ # imports the 'month_name' functionality from the calendar module from calendar import month_name # function with int as parameter def MonthName(number): # variable holding the name of the month from 'number' monthName = month_name[number] # if number is less than 1 if(number < 1): # prompt the user with a message print("Number is below 1. Must be between 1 - 12.") # else if number is more than 12 elif(number > 12): # prompt the user with a message print("Number is above 12. Must be between 1 - 12.") # if everything above is False else: # print the name of the month print(monthName) # function calls with arguments (must be a number between 1 - 12) MonthName(1) MonthName(4) MonthName(12)
true
2a53348c85e88768fd75baa03fa1b7232a4906d7
yjthay/Leetcode
/63.py
1,835
4.375
4
''' 63. Unique Paths II Medium 862 120 Favorite Share 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). Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in the grid. Note: m and n will be at most 100. ''' import copy class Solution(object): def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ paths = copy.deepcopy(obstacleGrid) rows = len(obstacleGrid) cols = len(obstacleGrid[0]) for row in range(rows): for col in range(cols): if obstacleGrid[row][col] == 1: paths[row][col] = 0 else: if row == 0 and col == 0: paths[row][col] = 1 elif row == 0: paths[row][col] = paths[row][col - 1] elif col == 0: paths[row][col] = paths[row - 1][col] else: paths[row][col] = paths[row - 1][col] + paths[row][col - 1] # if obstacleGrid[row-1][col]==1: # paths[row][col] = paths[row][col-1] # elif obstacleGrid[row][col-1]==1: # paths[row][col] = paths[row-1][col] # else: # paths[row][col] = paths[row-1][col]+paths[row][col-1] # print(paths) return paths[rows - 1][cols - 1]
true
5bed340e0c8961445a0a0f3b577f1d386be6639d
gabrielrnascimento/calculadora
/calculadora_v1.py
1,267
4.3125
4
# Calculadora em Python print("\n******************* Python Calculator *******************") def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x / y print ('\nSelecione o número da opção desejada:') print ('1 - Soma') print ('2 - Subtração') print ('3 - Multiplicação') print ('4 - Divisão') escolha = int(input('\nDigite sua opção (1/2/3/4):' )) if escolha == 1: num1 = int(input('\nDigite o primeiro número : ')) num2 = int(input('\nDigite o segundo número : ')) print() print(num1,'+', num2, '=',add(num1,num2)) elif escolha == 2: num1 = int(input('\nDigite o primeiro número : ')) num2 = int(input('\nDigite o segundo número : ')) print() print(num1,'-', num2, '=',subtract(num1,num2)) elif escolha == 3: num1 = int(input('\nDigite o primeiro número : ')) num2 = int(input('\nDigite o segundo número : ')) print() print(num1,'*', num2, '=',multiply(num1,num2)) elif escolha == 4: num1 = int(input('\nDigite o primeiro número : ')) num2 = int(input('\nDigite o segundo número : ')) try: print(num1,'/',num2,'=',divide(num1,num2)) except ZeroDivisionError: print('\nVocê não pode dividir um número por 0') else: print('\nOpção inválida!')
false
169c8d5734e4b1e190cc3af9e7c1c47f9e00111a
alimulyukov/Course_Work_2021
/ConVolCylStep4.py
1,218
4.1875
4
import math print("\n\tThe volume of a Cylinder is:") print("\n\t\t\tV = \u03C0 \u00D7 radius\u00B2 \u00D7 height") print("\n\tThis program will take as input the radius and height") print("\tand print the volume.") file = open("data.txt","a") #w,r,a name = input("\n\tWhat is your name: ") radius = 1 height = 1 while (radius != 0 or height != 0): try: radius = input("\n\tInput radius (cm): ") radius = int(radius) height = input("\n\tInput height (cm): ") height = int(height) except: print("\n\t\tNumeric Type Required") height = -1 radius = -1 if (radius >= 0 and height >= 0): volume = math.pi * radius * radius * height volume = round(volume,2) print("\n\t\tHi "+name+"!") print("\n\t\tGive a cylinder with:") print("\t\tRadius = "+str(radius)) print("\t\tHeight = "+str(height)) print("\t\tThe volume is: "+str(volume)+"\n") file.write(str(volume)+"\n") else: print("\n\t\tYou have entered an invalid value") print("END PROGRAM") file.close() ''' 1) User a try except structure to account for String inputs try: <try code block> <try code block> <try code block> except: <except code block> 2) Write information to file to be accessed later. '''
true
a82fa240bd47e700230e5798dfdb882f29888208
eldadpuzach/MyPythonProjects
/Functions/Display Calendar.py
303
4.46875
4
# Python program to display calendar of given month of the year # import module import calendar yy = 2018 mm = 10 # To ask month and year from the user # yy = int(input("Enter year: ")) # mm = int(input("Enter month: ")) # display the calendar for i in range(1, 13): print(calendar.month(yy, i))
true
73a3a32ed53c506ee8c65ed16230c58dc15e9848
coretx09/pythons21
/10.list_method.py
2,133
4.71875
5
""" les List sont des variables modifiables, dans laquelle on peut mettre plusieurs autres variables et effectuer les operations suivantes: """ numeros = [7, 9, 3, 2, 8] # une liste print(f"la liste: {numeros}") print(f"{numeros[0]} le premier element de la liste") # affiche l'element se trouvant a l'index i numeros.append(20) # ajoute print(f"{numeros} On ajoute 20") numeros.insert(0, 10) # ajoute un element en precisant son index .insert(index, object) print(f"{numeros} On ajoute 10 en 1ere position") numeros.remove(7) # supprime un element par sa valeur print(f"{numeros} On a supprime 7") del numeros[2] # supprime un element par son index print(f"{numeros} on a supprime l'element se trouvant a l'index 2") print(numeros.pop(2)) # enleve et renvoie l'element se trouvant a l'index i .pop(i), ou le dernier element si .pop() print(f"{numeros} on a enleve l'element se trouvant a l'index 2") print(f"l'index de 8: {numeros.index(8)}") # donne l'index de l'element,renvoie error si l'element n'est pas ds la list print(f"8 se trouve dans les numeros : {8 in numeros}") # renvoie True or False print( f"il y'a combien de 5 dans la liste numeros : {numeros.count(5)}") # renvoie le nombre d'occurence d'une valeur numeros.sort() # classifie par ordre croissant et decroissant .sort(reverse=True) print(numeros) numeros.reverse() print(f"{numeros} ") # m'est en position inverse numeros2 = numeros.copy() # copie print(f"numeros2: {numeros2} copie de numeros") numeros.append(30) print(f"{numeros}") numeros.clear() # supprime tous elements print(f"{numeros} on a supprime tous les elements de la liste") # exemple nombres = [2, 2, 4, 6, 4, 1, 6] uniques = [] for i in nombres: if i not in uniques: uniques.append(i) print(uniques) # .extend et .append chiffres_1 = [6, 4, 7, 2] chiffres_2 = [6, 4, 7, 2] chiffres_manquand = [5, 3] chiffres_1.append(chiffres_manquand) #.append ajoute la liste dans la liste print(f"{chiffres_1} ajout de [5, 3] avec .append)") chiffres_2.extend(chiffres_manquand) #.extend ettend la liste print(f"{chiffres_2} ajout de [5 et 3] avec .extend")
false
874eb33018e94ed35c455f77dec7e86842d4351a
lilliansun/cssi_2018_intro
/python/python-testing/fizzbuzz.py
570
4.34375
4
"""my implementation of fizzbuzz""" def fizz_buzz(num): """Prints different words for certain natural numbers This function prints out fizz when a number is divisible by 3, buzz when divisible by 5, and fizzbuzz when divisible by both. Args: num: (int) The number to convert based on fizzbuzz rules. """ if ((num%3 == 0) and (num%5 == 0)): print("fizzbuzz") elif num%3 == 0: print("fizz") elif num%5 == 0: print("buzz") else: print(num) for this in range(1, 100): fizz_buzz(this)
true
582b693640f4e32601b7b1a7f34049218cbba291
sreehari333/pdf-no-3
/to check male or female.py
379
4.40625
4
gender = input("Please enter your Gender : ") if (gender == "M" or gender == "m" or gender == "Male" or gender == "male"): print("The gender in Male") elif (gender == "F" or gender == "f" or gender == "FeMale" or gender == "Female" or gender == "feMale" or gender == "female"): print("The gender is Female") else: print("Please provide an appropriate format")
true
6d78a8beb5805d430f4470b07415f09a6d713753
naresh3736-eng/python-interview-problems
/trees/binaryTree_is_fullBinaryTree.py
2,056
4.1875
4
class Node: def __init__(self, key): self.key = key self.leftchild = None self.rightchild = None # using recursion def isFullBT_recursion(root): if root is None: return None if root.leftchild is None and root.rightchild is None: return True if root.leftchild is not None and root.rightchild is not None: return isFullBT_recursion(root.leftchild) and isFullBT_recursion(root.rightchild) return False root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40); root.left.left = Node(50); root.right.left = Node(60); root.right.right = Node(70); root.left.left.left = Node(80); root.left.left.right = Node(90); root.left.right.left = Node(80); root.left.right.right = Node(90); root.right.left.left = Node(80); root.right.left.right = Node(90); root.right.right.left = Node(80); root.right.right.right = Node(90); if isFullBT_recursion(root): print "The Binary tree is full" else: print "Binary tree is not full" # using iterative approach def isFullBT_iterative(root): if root is None: return None queue = [] queue.append(root) while len(queue) >=1: node = queue[0] queue.pop(0) if node.leftchild is None and node.rightchild is None: continue if node.leftchild is not None or node.rightchild is not None: return False queue.append(node.leftchild) queue.append(node.rightchild) return True root = Node(10) root.left = Node(20) root.right = Node(30) root.left.right = Node(40); root.left.left = Node(50); root.right.left = Node(60); root.right.right = Node(70); root.left.left.left = Node(80); root.left.left.right = Node(90); root.left.right.left = Node(80); root.left.right.right = Node(90); root.right.left.left = Node(80); root.right.left.right = Node(90); root.right.right.left = Node(80); root.right.right.right = Node(90); if isFullBT_iterative(root): print "The Binary tree is full" else: print "Binary tree is not full"
true
62ebadffa4205282a3fb81a7ddd679bf8da0dc94
snekhasri/spring.py
/spring.py
832
4.34375
4
import turtle as t #importing the module as "t" t.bgcolor("green") def spiral_shape(p,c): #creating a function with parameters "p" and "c" if p > 0: #if the p is less than 0, t.forward(p) #moving the turtle forward at p units t.right(c) #setting the turtle right at an angle of c spiral_shape(p-5,c) #calling the function with the arguments as given t.shape('classic') #setting the shape of the turtle as "classic" t.reset() #resetting the turtle t.pen(speed=25) #setting the speed of the pen to 25 length = 400 #declaring a variable "length" to 400 turn_by = 121 #declaring a varibale "turn_by" to 121 t.penup() #the drawing is not ready t.setpos(-length/2, length/2) #setting the position as given t.pendown() #starting to draw spiral_shape(length, turn_by) #calling the function with the given arguments
true
c5a328137b59adfa9e23b295e695a2d53026e7e6
Naveen8282/python-code
/palyndrome.py
230
4.15625
4
def IsPalyndrome(input1): txt = input1[::-1] if txt == input1: return "yes" else: return "no" str1=str(input("enter the string: ")) print ("is the string %s Palyndrome? %s" % (str1,IsPalyndrome(str1)))
true
5b8b60e383c8ad3b9597a0774b7c55706fcc0497
acbahr/Python-Practice-Projects
/magic_8_ball_gui.py
1,524
4.3125
4
# 1. Simulate a magic 8-ball. # 2. Allow the user to enter their question. # 3. Display an in progress message(i.e. "thinking"). # 4. Create 20 responses, and show a random response. # 5. Allow the user to ask another question or quit. # Bonus: # - Add a gui. # - It must have box for users to enter the question. # - It must have at least 4 buttons: # - ask # - clear (the text box) # - play again # - quit (this must close the window) # Basic text in TKinter is called a label import random import tkinter as tk """ def magic_8ball(): root = tk.Tk() # constructor class in TKinter. Creates a blank window active = True responses = ['Yes', 'No', 'Maybe', 'Try Again', "It's Possible", 'It is in the stars', 'Ask me another time', 'I am not sure', 'Ask your mother', 'Ask your father', 'Only if you Live Bearded'] while active: label1 = tk.Label(text='What would you like to ask?') label1.pack() entry = tk.Entry(width=75) entry.pack() question = entry.get() if question != 'n' or question != 'N': thinking = tk.Label(text='thinking....') thinking.pack() return random.choice(responses) else: print('thinking...') print(random.choice(responses)) try_again = input('Would you like to try again? y/n: ') if try_again.lower() == 'n': active = False root.mainloop() # mainloop keeps running the window until closed by user magic_8ball() """
true
bcedd8033fc9cbef7b282c0433f010472d32f10c
longy1/python-elib
/python_cookbook/04_Iterator_and_Generator/02_proxy_iterator.py
611
4.53125
5
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ implement __iter__() to return iterator object """ # 可迭代对象只需实现__next__(), 此例借助了list的实现 class Node: def __init__(self, value): self._value = value self._children = [] def add_child(self, node): self._children.append(node) def __repr__(self): return f'Node({self._value})' def __iter__(self): return iter([self] + self._children) if __name__ == '__main__': root = Node(1) root.add_child(Node(2)) root.add_child(Node(3)) for i in root: print(i)
false
37c3e583c372fc2adbec60ca23e524fa9d4de0fc
dfrog3/pythonClass
/python/week 1/three_sort_david.py
1,772
4.1875
4
print("Hello, I will sort three integers for you.\nPlease enter the first integer now") firstNumber = int(input()) print("Thank you.\nPlease enter the second integer.") secondNumber = int(input()) print("Thank you.\n please eneter the last integer.") thirdNumber = int(input()) #fills starting variables if firstNumber < secondNumber and firstNumber < thirdNumber: smallestNumber = firstNumber elif firstNumber < secondNumber and firstNumber > thirdNumber: middleNumber = firstNumber elif firstNumber > secondNumber and firstNumber < thirdNumber: middleNumber = firstNumber elif firstNumber > secondNumber and firstNumber > thirdNumber: largestNumber = firstNumber else: print("error in first sort block") #first number sorting code block if secondNumber < firstNumber and secondNumber < thirdNumber: smallestNumber = secondNumber elif secondNumber < firstNumber and secondNumber > thirdNumber: middleNumber = secondNumber elif secondNumber > firstNumber and secondNumber < thirdNumber: middleNumber = secondNumber elif secondNumber > firstNumber and secondNumber > thirdNumber: largestNumber = secondNumber else: print("error in second sort block") #second number sorting code block if thirdNumber < secondNumber and thirdNumber < firstNumber: smallestNumber = thirdNumber elif thirdNumber < secondNumber and thirdNumber > firstNumber: middleNumber = thirdNumber elif thirdNumber > secondNumber and thirdNumber < firstNumber: middleNumber = thirdNumber elif thirdNumber > secondNumber and thirdNumber > firstNumber: largestNumber = thirdNumber else: print("error in third sort block") #third number sorting code block print("The results are in.\n", smallestNumber , middleNumber , largestNumber)
true
1e04b2e77b982dbea75275781f2ed4937dbdca86
k-unker/codewars_katas
/where_is_my_parent.py
1,351
4.21875
4
#!/usr/bin/env python3 ''' Mothers arranged dance party for children in school. On that party there are only mothers and their children. All are having great fun on dancing floor when suddenly all lights went out.Its dark night and no one can see eachother.But you were flying nearby and you can see in the dark and have ability to teleport people anywhere you want. Legend: -Uppercase letters stands for mothers,lowercase stand for their children. I.E "A" mothers children are "aaaa". -Function input:String contain only letters,Uppercase letters are unique. Task: Place all people in alphabetical order where Mothers are followed by their children.I.E "aAbaBb" => "AaaBbb". ''' def find_children(dancing_brigade): myarr = [] dancing_brigade = sorted(dancing_brigade) for i in range(len(dancing_brigade)): if dancing_brigade[i].lower() in dancing_brigade or dancing_brigade[i].upper() in dancing_brigade: myarr.append(dancing_brigade[i]) mysmall = dancing_brigade[i].lower() mylarge = dancing_brigade[i].upper() mycounter = dancing_brigade.count(mysmall) - dancing_brigade.count(mylarge) a = 0 while a <= mycounter: myarr.append(dancing_brigade[i].lower()) a += 1 return ''.join(myarr)[:len(dancing_brigade)]
true
0fd5a273d72beb9bf7cbc4c663f13410a4aeb881
prkapadnis/Python
/Programs/eighth.py
440
4.21875
4
""" Reverse a number """ number = int(input("Enter the number:")) reverse = 0 if number < 0: number = number * (-1) while number != 0: remainder = number % 10 reverse = reverse * 10 + remainder number = number // 10 print(-reverse) else : while number != 0: remainder = number % 10 reverse = reverse * 10 + remainder number = number // 10 print(-reverse) print(2**31)
true
b3ed3b8ea862043d0d89d77bc1fceb90325acabe
prkapadnis/Python
/Set.py
620
4.1875
4
myset = set() print(type(myset)) myset = {1,2,3,4,5} print(myset) #built in function myset.add(2)# This does not made any change because set don't allow the duplicate values print(myset) myset.remove(2) print("After removing 2:", myset) # print("Using pop() function: ",myset.pop()) print(myset) second_set = {3,4,5,6} unioun_set = myset.union(second_set) print("The Union of set is:",unioun_set) print("The Intersection of set is:", myset.intersection(second_set)) print("The Difference of set is:", myset.difference(second_set)) print("The Symmetric Difference of set is:", myset.symmetric_difference(second_set))
true
c553606397136f91a2ad94d3c48c0f5d0f999a5b
prkapadnis/Python
/OOP/Class_var.py
1,797
4.25
4
""" Difference between class variable and Instance variable Instance Variable: -The Instance variable is unique for each instance -If we changed the class variable for specific instance then it will create a new instance variable for that instance Class Variable: The class variable is shared among all instance of class - cannot be changed by instance - It is also known as static variable Note : 1].__dict__ : It will return a dictionary that contains the attribute of instance """ class Student: branch = "Computer Engineering" pratik = Student() ajit = Student() #For Pratik instance pratik.name = "Pratik" # This name is a instance variable of pratik pratik.rollNum = 69 #For Ajit intance ajit.name = "Ajit" # This name is instance variable of Ajit ajit.rollNum = 50 print(f"The Name {pratik.name} and Roll number {pratik.rollNum} and branch is {pratik.branch}") print(f"The Name {ajit.name} and Roll number {ajit.rollNum} and branch is {ajit.branch}") print("All the instance variable of Pratik:",pratik.__dict__) print("All the instance variable of ajit:",ajit.__dict__) # If we have to change the branch for specific instance ajit.branch = "Civil Enginnering" print("After changing the branch") print(f"The Name {pratik.name} and Roll number {pratik.rollNum} and branch is {pratik.branch}") print(f"The Name {ajit.name} and Roll number {ajit.rollNum} and branch is {ajit.branch}") #If we change the branch of specific instance then it creates a new instance variable # for that instance and it does not affect the class variable print("After chaging the class variable for specific instance:",ajit.__dict__) #And We can access it by clas name print("The class variable is:",Student.branch)
true
4c55155e0f66164f9f1512cb51c007b23234a1be
prkapadnis/Python
/Data Structure/Linked List/SinglyLinkedList.py
2,746
4.15625
4
class Node: def __init__(self, data): # defination of Node self.data = data self.next_node = None class LinkedList: def __init__(self): self.head = None self.size = 0 def reverse(self): privious = None current = self.head next = None while current!= None: next = current.next_node current.next_node = privious privious = current current = next self.head = privious print("The linked list is reversed!!") def get_size(self): return self.size def display(self): current = self.head print("The Data: ",end="") while current: print(current.data, end=" ") current = current.next_node #Insertion Operation def insert_at_first(self, data): new_node = Node(data) self.size+=1 if self.head is None: self.head = new_node else: new_node.next_node = self.head self.head = new_node def insert_at_middle(self, data, position): new_node = Node(data) self.size += 1 current = self.head for i in range(1, position-1): current = current.next_node new_node.next_node = current.next_node current.next_node = new_node def insert_at_last(self, data): new_node = Node(data) self.size += 1 current = self.head while current.next_node: current = current.next_node current.next_node = new_node #deleting Operations the nodes def delete_first(self): delete_node = self.head self.head = self.head.next_node del delete_node print("The first node Deleted!!") def delete_middle(self, position): delete_node = self.head.next_node temp_node = self.head for i in range(1, position-1): delete_node = delete_node.next_node temp_node = temp_node.next_node temp_node.next_node = delete_node.next_node del delete_node print(f"{position}th node deleted!!") def delete_last(self): current = self.head.next_node last_second_node = self.head while current.next_node: current = current.next_node last_second_node = last_second_node.next_node last_second_node.next_node = None del current list = LinkedList() list.insert_at_first(10) list.insert_at_last(20) list.insert_at_last(30) list.insert_at_middle(25, 3) list.display() print() print("The size is:",list.get_size()) list.delete_first() list.delete_last() list.delete_middle(2) list.reverse() list.display()
true
48db87ee9b1285a6b269caba3b64b40f9ea89035
prkapadnis/Python
/File/second.py
896
4.40625
4
""" write() function: - The Write function writes the specified text into the file. - Where the specified text is inserted is depends on the file mode and stram position. - if 'a' is a file mode then it well be inserted at the stream position and default is end of the file. - if 'w' is a file mode then it will override the file and insert it at the begining. """ with open("Python/File/my_data2.txt", mode="w", encoding="utf-8") as myFile: myFile.write("Some Random Text \nand more random text \nand more and more and more random text") with open("Python/File/my_data2.txt", encoding="utf-8") as myFile: print(myFile.read()) print() with open("Python/File/my_data2.txt", mode="w", encoding="utf-8") as myFile: myFile.write("Name: pratik Rajendra Kapadnis") with open("Python/File/my_data2.txt", encoding="utf-8") as myFile: print(myFile.read())
true
7ca93f1f2fdf8f757c2206e747681e600453d93b
prkapadnis/Python
/Iterables/Iterable.py
1,178
4.34375
4
""" Iterable : Iterable are objects that are capable of returning their member one at a time means in short anything we can liip over is an iterable. Iterator : Iterable are objects which are representing the stream of data that is iterable. iterator creates something iterator pool which allows us to loop over an item in iterable using thetwo methods that is __iter__() and __next__(). __iter__(): The __iter__() method returns the iterator of an iterable. __next__():The __next__() method returns the next element of an iterator Key points: - The difference between Iterable and Iterator is that the __next__() method is only accessible to the Iterator. The Iterable only have __iter__() method. - Iterator also have __iter__() method because iterators are also iterables but not vice versa. """ sample = [1, 2, 3] it = iter(sample) print(next(it)) print(next(it)) print(next(it)) # If overshoot the limit the number of times we call the next() method. then an exception # is occur which is called StopIteration Exception. # print(next(it))
true
2a06954878ad58139831283b2ec6ec0a6cb9ec74
marciniakdaw/Python-Udemy
/BMI calculator.py
519
4.25
4
height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) BMI_score=round(weight/height**2) if BMI_score<19: print(f"Your BMI is {BMI_score}, you are underweight.") elif BMI_score<25: print(f"Your BMI is {BMI_score}, you have a normal weight.") elif BMI_score<30: print(f"Your BMI is {BMI_score}, you are slightly overweight.") elif BMI_score<35: print(f"Your BMI is {BMI_score}, you are obese.") else: print(f"Your BMI is {BMI_score}, you are clinically obese.")
true
4b3f73baf3fbd69d6bf149be403396cea9222ab5
j-tanner/Python.Assignments
/Assignment_8.4.py
240
4.1875
4
filename = input("Enter file name: ") filehandle = open(filename) wordlist = list() for line in filehandle: for words in line.split(): if words not in wordlist: wordlist.append(words) wordlist.sort() print(wordlist)
true
ab72ffcb3709b58a3f84c1d70833507f67fbd8da
courses-learning/python-crash-course
/4-1_pizzas.py
225
4.3125
4
# Make a list of 3x types of pizza and use a for loop to print pizzas = ['peperoni', 'hawian', 'meat feast'] for pizza in pizzas: print(f"I like {pizza} pizza.") print('I like pizza takeaway nearly as much as Indian!!!')
true
fc2476fdf4eef757a32e62cbebc4e225b63fe132
courses-learning/python-crash-course
/5-6_stage_of_life.py
469
4.15625
4
def life_stage(age): if age < 2: return "a baby" elif age >= 2 and age < 4: return "a toddler" elif age >= 4 and age < 13: return "a kid" elif age >= 13 and age < 20: return "a teenager" elif age >= 20 and age < 65: return "an adult" elif age >= 65: return "an elder" else: return "not entering a valid age" age = int(input("What is your age? ")) print(f"You are {life_stage(age)}")
false
9704184ee7eda4aa6fcfd13a73861f640ad65780
HanxianshengGame/PythonPrimer
/二.bookStudy/5_1_内置类型陷阱.py
1,054
4.125
4
# !/usr/bin/env Python2 # -*- coding: utf-8 -*- # @Author : 得灵 # @FILE : 5_1内置类型陷阱.py # @Time : 2021/1/6 18:49 # @Software : PyCharm # @Introduce: This is # [1] 赋值创建引用,而不是复制 L = [1,2, 3] M = ['X', L, 'Y'] print(M) L[1] = 0 print(M) # 若非需要共享引用,请采纳分片和 copy/ copy.deepcopy L = [1,2, 3] M = ['X', L[:], 'Y'] print(M) L[1] = 0 print(M) # [2] 重复会增加层次深度 L = [4, 5, 6] X = L * 4 Y = [L] * 4 print(X) print(Y) # 生成的是 4 个 L 的引用 [[],[],[],[]] L[0] = 0 print(X) # 不变 print(Y) # 联动修改 L = [4, 5, 6] Y = [list(L)] * 4 # 实质是先拷贝了 L 一份,再生成4份相同的引用 L[1] = 0 print(Y) Y[0][1] = 99 print(Y) # [3] 注意(避免, 自己引用自己)循环数据结构 L = ['grail'] L.append(L) # 避免 print(L) # [4] 不可变类型不可以在原位置修改 T = (1,2,3) # T[1] = 3 # Error T = T[:1] + (3,3) print(T)
false
af60ab371883f6f5e0590b7039684f5c8037b4a7
HanxianshengGame/PythonPrimer
/一.videoStudy/8_元组.py
1,226
4.3125
4
# !/usr/bin/env Python3 # -*- coding: utf-8 -*- # @Author : 得灵 # @FILE : 8_元组.py # @Time : 2020/12/12 20:46 # @Software : PyCharm # @Introduce: This is 元组 # 元组: # 1. 不可变的序列,在创建之后不能做任何的修改 # 2. 用()创建元组类型,数据项用逗号来分割 # 3. 可以是任何的类型 # 4. 当元组中只有一个元素时,要加上逗号,不然解释器会当作整形来处理 # 5. 同样支持切片操作 first_tuple = () # 空元组 first_tuple = ("python",) # 单个元素的元组 print(id(first_tuple)) first_tuple = ("abcd", 89, 9.33, "peter", [11, 22, 33]) print(id(first_tuple)) # 由于元组并不支持修改,所以重新赋值元组则重新开辟新地址 first_tuple[first_tuple.index([11, 22, 33])][0] = 1 # 列表可生成 print(first_tuple) # 遍历打印元组 for item in first_tuple: print(item, end=" ") print(first_tuple[2:4]) print(first_tuple[::-1]) # -1 表示从右往左遍历, 1 代表步长 print(first_tuple[::-2]) # 反转元组,每隔2个取一个 print(first_tuple[-2:-1:]) # 取倒数第二个开始到最后一个的元组 # 子元素计数 second_tuple = [11, 11] print(second_tuple.count(11))
false
9bfc0342386bc8efdc7be6ac1f7988ae91ee022c
sacktock/practicals
/adspractical17extra.py
2,981
4.34375
4
#adspractical17extra.py #algorithms and data structures practical week 17 #matthew johnson 22 february 2013, last revised 15 february 2018 ##################################################### """an extra question that has nothing to do with the algorithms from the lectures, but gives some practice on thinking about graph algorithms""" #define an example tree using adjacency lists V = "ABCDEFGHIJKLM" E = {'A': 'BCD', 'C': 'AGH', 'B': 'AEF', 'E': 'BIJK', 'D': 'A', 'G': 'C', 'F': 'BL', 'I': 'E', 'H': 'C', 'K': 'EM', 'J': 'E', 'M': 'K', 'L': 'F'} T = (V, E) """ in a tree, there is a unique path between each pair of vertices; the diameter of a tree is the longest such path (the diameter of the example tree above is 6); write a function that takes a tree and returns its diameter the function should be recursive; first, what is the diameter of a tree on 1 vertex? what if the tree has more vertices and you remove one of them and split the tree into many smaller trees; what do you need to know about the smaller trees to find the diameter of the larger tree? """ def tree_diameter(T): """given a tree as a pair, the vertex set and adjacency lists, return the diameter of the tree""" V, E = T #complete the function here #uncomplete root = '' for v in V: if len(E[v]) == 2: root = v break lDiameter = 1 + tree_diameter(rT) rDiameter = 1 + tree_diameter(lT) return max(max(rDiameter,lDiameter),) ################################################### #the following function might prove useful def print_lists(G): """takes a graph with adjacency list representation and prints the lists""" V, E = G for vertex in V: n = "" for neighbour in E[vertex]: n += neighbour + ", " print (vertex[0] + ": " + n[:-2]) ################################################### #tests V1 = "A" E1 = {'A': ''} T1 = (V1, E1) V2 = "AB" E2 = {'A': 'B', 'B': 'A'} T2 = (V2, E2) V3 = "ABC" E3 = {'A': 'B', 'C': 'B', 'B': 'AC'} T3 = (V3, E3) V4 = "ABCD" E4 = {'A': 'B', 'C': 'BD', 'B': 'AC', 'D': 'C'} T4 = (V4, E4) E4a = {'A': 'B', 'C': 'B', 'B': 'ACD', 'D': 'B'} T4a = (V4, E4a) V5 = "ABCDEFGHIJKLMNOPQR" E5 = {'A': 'B', 'C': 'BD', 'B': 'AC', 'E': 'DF', 'D': 'CE', 'G': 'FH', 'F': 'EG', 'I': 'HJ', 'H': 'GI', 'K': 'JL', 'J': 'IK', 'M': 'LN', 'L': 'KM', 'O': 'NP', 'N': 'MO', 'Q': 'PR', 'P': 'OQ', 'R': 'Q'} T5 = (V5, E5) E5a = {'A': 'B', 'C': 'BD', 'B': 'ACG', 'E': 'DF', 'D': 'CE', 'G': 'BH', 'F': 'E', 'I': 'HJ', 'H': 'GI', 'K': 'JL', 'J': 'IK', 'M': 'LN', 'L': 'KM', 'O': 'NP', 'N': 'MO', 'Q': 'PR', 'P': 'OQ', 'R': 'Q'} T5a = (V5, E5a) def test(): assert tree_diameter(T) == 6 assert tree_diameter(T1) == 0 assert tree_diameter(T2) == 1 assert tree_diameter(T3) == 2 assert tree_diameter(T4) == 3 assert tree_diameter(T4a) == 2 assert tree_diameter(T5) == 17 assert tree_diameter(T5a) == 16 print ("all tests passed")
true
65264cc2e04a26029120617c562595610d3062eb
4RCAN3/PyAlgo
/pyalgo/maths/prime.py
413
4.21875
4
''' module for checking whether a given number is prime or not ''' def prime(n: int): ''' Checking if the number has any factors in the range [2, sqrt(n)] else it is prime ''' if (n == 2): return True result = True for i in range (2, int(n ** 0.5)): if (n % i == 0): result = False break return result ''' PyAlgo Devansh Singh, 2021 '''
true
102598ec16c86c089841565cdb47a942b795735a
4RCAN3/PyAlgo
/pyalgo/maths/power.py
928
4.375
4
''' module for calculating x to the power y (x ** y) efficiently ''' def big_power(x: int, y: int, MOD = None): ''' For calculating powers where x and y are large numbers ''' result = 1 if MOD is None: while (y > 0): if (y & 1): result *= x x *= x y >>= 1 else: while (y > 0): if (y & 1): result *= x x *= x y >>= 1 result %= MOD return result def mod_power(x: int, y:int, MOD: int): ''' For calculating powers where modular arithmetic is used ''' result = 1 x = x % MOD if (x == 0): return 0 while (y > 0): if (y & 1 == 1): result = ((result % MOD) * (x % MOD)) % MOD y = y >> 1 x = ((x % MOD) * (x % MOD)) % MOD return result ''' PyAlgo Devansh Singh, 2021 '''
false
29c43a96ac935c7f9da7b2bfbc227507d74fd02c
4RCAN3/PyAlgo
/pyalgo/graph/bfs.py
977
4.21875
4
''' module for implementation of breadth first search ''' def bfs(graph: list, start: int): """ Here 'graph' represents the adjacency list of the graph, and 'start' represents the node from which to start """ visited, queue = set(), [start] while (queue): vertex = queue.pop(0) if (vertex not in visited): visited.add(vertex) queue.extend(graph[vertex] - visited) return visited def bfs_paths(graph: list, start: int, goal: int): """ Returns all possible paths between a start vertex and a goal vertex, where the first path is the shortest path """ queue = [(start, [start])] while (queue): (vertex, path) = queue.pop(0) for next in (graph[vertex] - set(path)): if (next == goal): yield path + [next] else: queue.append((next, path + [next])) return queue ''' PyAlgo Devansh Singh, 2021 '''
true
800dc205db1402fb2c155c6d4ac5af0de549988d
niranjan2822/List
/Key Lists Summations.py
1,147
4.21875
4
# Key Lists Summations # Sometimes, while working with Python Dictionaries, we can have problem in which we need to perform the replace of # key with values with sum of all keys in values ''' Input : {‘gfg’: [4, 6, 8], ‘is’: [9, 8, 2], ‘best’: [10, 3, 2]} output : {‘gfg’: 18, ‘is’: 19, ‘best’: 15} ''' # Method #1 : Using sum() + loop # This is one of the ways in which this task can be performed. In this, we perform the summation using sum, and # iteration to each key is done in brute way using loop. # Python3 code to demonstrate working of # Key Values Summations # Using sum() + loop # initializing dictionary test_dict = {'gfg': [4, 6, 8], 'is': [9, 8, 2], 'best': [10, 3, 2]} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # Key Values Summations # Using sum() + loop for key, value in test_dict.items(): test_dict[key] = sum(value) # printing result print("The summation keys are : " + str(test_dict)) # output : The original dictionary is : {'gfg': [4, 6, 8], 'is': [9, 8, 2], 'best': [10, 3, 2]} # The summation keys are : {'gfg': 18, 'is': 19, 'best': 15}
true
382a8915e11e58f68d73b4451e9efaa294ff1ffb
niranjan2822/List
/Iterating two lists at once.py
1,777
4.65625
5
# Iterating two lists at once # Sometimes, while working with Python list, we can have a problem in which we have to iterate over two list elements. # Iterating one after another is an option, but it’s more cumbersome and a one-two liner is always recommended over # that ''' Input 1 : [4, 5, 3, 6, 2] Input 2 : [7, 9, 10, 0] The paired list contents are : 4 5 3 6 2 7 9 10 0 ''' # Method #1 : Using loop + “+” operator # Python3 code to demonstrate working of # Iterating two lists at once # using loop + "+" operator # initializing lists test_list1 = [4, 5, 3, 6, 2] test_list2 = [7, 9, 10, 0] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Iterating two lists at once # using loop + "+" operator # printing result print("The paired list contents are : ") for ele in test_list1 + test_list2: print(ele, end=" ") # output : Output : # The original list 1 is : [4, 5, 3, 6, 2] # The original list 2 is : [7, 9, 10, 0] # The paired list contents are : # 4 5 3 6 2 7 9 10 0 # Method #2 : Using chain() # This is the method similar to above one, but it’s slightly more memory efficient as the chain() is used to # perform the task and creates an iterator internally. # Python3 code to demonstrate working of # Iterating two lists at once # using chain() from itertools import chain # initializing lists test_list1 = [4, 5, 3, 6, 2] test_list2 = [7, 9, 10, 0] # printing original lists print("The original list 1 is : " + str(test_list1)) print("The original list 2 is : " + str(test_list2)) # Iterating two lists at once # using chain() # printing result print("The paired list contents are : ") for ele in chain(test_list1, test_list2): print(ele, end=" ")
true
4ffa4b3471cedec80b47c6408b8bf1318c28dc40
siddbose97/maze
/DFS/maze.py
1,240
4.15625
4
#logic inspired by Christian Hill 2017 #create a cell class to instantiate cells within the grid which will house the maze #every cell will have walls and a coordinate pair class cell: # create pairs of walls wallPairs = {"N":"S", "S":"N", "E":"W", "W":"E"} def __init__(self, x, y): #give a wall coordinates xy and then give it walls (all bool true) self.xCoord = x self.yCoord = y self.walls = {"N": True, "S": True, "E": True, "W": True} def checkWalls(self): #check if all walls are still present for key in self.walls: if self.walls[key] == True: continue else: return False return True def removeWall(self, neighbor, wall): #if removing one wall for a cell, remove corresponding wall in other cell if self.walls[wall] == False: neighborWall = cell.wallPairs[wall] neighbor.walls[neighborWall] = False #use corresponding wall to remove accordingly class maze: #initialize a maze as cells in rows and columns based on input values #initialize by taking input row and column and then using 0,0 as a starting cell pass
true
8b589bdd3f9299888080234f814c617e111817c1
Purushotamprasai/Python
/Rehaman/001_Basic_understanding/001_basic_syntax.py
1,023
4.125
4
#!/usr/bin/python # the above line is shabang line ( path of python interpreter) #single line comment ( by using hash character '#' ''' We can comment multiple lines at a time by using triple quotes ''' # the below code understand for statement concept ''' 1---> single statemnt ''' # a line which is having single executable instruction print " this is single statement example " ''' 2----> multiple statement ''' # a single line which is having more than one executable instruction print "hello " ; print "hai" ; print "bye" ''' 3 ---> multiline statement ''' # a single instruction which may contine more than one line print "hello \ hai \ bye " ''' 4---> compound statement / indentation statement in othe preogramming language syntax block_name { st1 --- --- } in python syntax: block_name : st1 st2 st3 st4 ''' if(__name__ == "__main__"): print " i am in if block" print " i am very happy for learning python" print "hai i am error statement"
true
efe69eec4380f3041992e4b82eb1252f32876859
Purushotamprasai/Python
/Rohith_Batch/Operator/Logical Operator/001_understand.py
908
4.3125
4
# this file is understand for logical operators ''' Logical AND ---> and --------------------- Defination : ----------- if 1st input is false case then output is 1st input value other wise 2nd input value is the output Logical OR---> or --------------------- Defination : ----------- if 1st input is false case then output is 2st input value other wise 1st input value is the output Logicakl not ---> not --------------------- Defination : ----------- if 1st input is false case then output is True boolean data other wise False boolean data as on output ''' def main(): a = input("enter boolean data") # True b = input("enter boolean daata") # False print a ," logical and", b," is ", a and b print a , "logical or ",b, " is ", a or b print " logical not ", b ,"is " , not b if(__name__ =="__main__"): main()
true
ad53e27408916456b808dea9bdc0662692a5fd24
Purushotamprasai/Python
/Z.R/files/002_write.py
355
4.125
4
file_obj = open("readfile.txt","w") ''' file opened as write mode if the file is not existed 1st create then open it" file is existed then removes previous data and open as fresh file if the is open as write mode we cant use read methodes ''' data =input("enter some data") file_obj.write(data) d =file_obj.read() file_obj.close()
true
72a0cc33029ff768a219bfe8517ed7793abfe467
Purushotamprasai/Python
/Rohith_Batch/Operator/Relational/Bitwise_Even or Odd.py
299
4.34375
4
''' Program : Find the Given number is Even or Odd using bitwise operator Programmer : Rohit ''' def main(): a = input('Enter a value: ') if a&1==0: print "Number is Even" else: print "Number is Odd" if (__name__=="__main__"): main()
true
6644874636bb8a22a6fb4cbb5519c82567e41561
Purushotamprasai/Python
/Tarun/003_tuple_datatype.py
605
4.25
4
# list data type var_l = ( 1, 2,4.5 ,"str") # hetro genious datatype print var_l # we are printing list of var_1 elements print len(var_l) # no of elements in a list print max(var_l) # maximum list element print min(var_l) # minimum list element print tuple("python")#('p','y','t','h','o','n') # tuple indexing # positive / forwaord print var_l[0] # 1 print var_l[1] # 2 # negatice / reverse print var_l[-1] # "str" print var_l[2] # 4.5 # tuple slicing print var_l[1 : 3] # (2,4.5) print var_l[:] # (1,2,4.5,"str") # tuple dicing print var_l[0 : :2] # (1,4.5)
false
e1194fa52edbd9f140b0d048833b2fd13e6517ff
Purushotamprasai/Python
/hussain_mani/python_introduction/003_Python Basic Built-in function/Built_in_function_info.py
1,541
4.21875
4
# python Basic Built -in Function ''' Function :- --------------- -----> Function is a set of instructions for doing any one task -----> there are two types 1. User Defined Function :- --------------------------- The programmer can define function def ----> user defined function 2. Built-in function :- --------------------------- ----> the functions are already available in python interpreter ---> Basic Built Function --------------------------- ---> Input function ---> Output function ---> type and id ---> Data type convertions function ---> Number system conversion function ''' #Input function :- #---------------- ----> Are used for to read the data from keyword by user/ client / programmer In python we have two input functions 1. raw_input() 2. input() # Output function:- -------------------- ----> To display the data on monitor we can use print keyword ----> print keyword we can use in 2 ways 1. print "statement" 2. print("function") #type ----- ----> type is a function which is return type of data type(obj) # id ----> to know the memory location od any variable / object id(obj) # data type conversion function:- -------------------------------- ---> we can convert one datatype element to targeted datatype int () float() complex() bool() str() list() tuple() set() dict() ---> we can use with in raw_input
true
041eb90a66c152abb9e581e4b2361686ec58b5bc
Purushotamprasai/Python
/Sai_Krishna/001_Python_Basic_Syntax/001_instruction.py
935
4.34375
4
# this is single line comment ''' This is multiple line comment ''' # what is the use of the comment ''' As a programmer we know what we are writing the script By using comment we can you can give brief explanation for any statment ''' # statement # single statement #------> A single line which is having single executable instruction ''' >>> print "hello" hello >>> print "hai" hai >>> a =100 >>> ''' # Multiple statement #----> A single line which may have more than one executable instruction ''' >>> print "hello" ;print "hai" ;print "bye" hello hai bye >>> ''' #multiline statement #------> A single statement it may continue more than one line ''' >>> print ''' #hai #hello #bye ''' hai hello bye >>> a =1+2+4+\ 5+6+7+\ 8+9 >>> a 42 ''' if(10 <20): print "hai" print "hello" print"bye"
false
a57998b659eb1ad0d09749a74eb54a6a7db0e58c
TomiMustapha/Shleep
/week.py
623
4.15625
4
## Week class ## ## Each week is a list of fixed size 7 of positive ints ## Represents a week in which we log hours of sleep ## We can then combine weeks into a matrix to be represented graphically import numpy as np class Week(): def __init__(self): self.nodes = np.array([]) def insert_node(self, node): if (not type(node) == int): raise TypeError("Not an int.") elif (self.nodes.size >= 7): raise ValueError("Week has exceeded 7") else: self.nodes = np.append(self.nodes, node)
true
97487f7c395f37af614556864394127eeeb006b7
parker57/210CT
/week4/adv2_qs.py
1,754
4.25
4
## Adapt the Quick Sort algorithm to find the mth smallest element out of a list of n integers, where m is ## read from the standard input. ## For example, when m = 5, your version of Quick Sort will output the 5th smallest element out of your ## input list. import random def quickselect(array, m): def sort(array, left, right, index): if left == right: return array[left] #Found/ base case. #If return array is only one long, will leave stack pivot = left #Primitive pivot selection/ not ideal. wall = pivot for i in range(left+1, right+1): if array[i] < array[left]: wall += 1 array[wall], array[i] = array[i], array[wall] array[wall], array[left] = array[left], array[wall] if index>wall: #If index is greater than wall, sort larger return sort(array, wall+1, right, index) elif index<wall: #If index is less than wall, sort smaller return sort(array, left, wall-1, index) else: #If index is equal to wall, mth smallest found. return array[wall] if len(array) < 1: return if m not in range(0, len(array)): raise IndexError('Index searched is out of range, remember index uses zero-based numbering') return sort(array, 0, len(array) - 1, m) if __name__ == '__main__': array_size = int(input('How many integers should the list be? ')) m = int(input('Finding the Mth smallest, what is m? ')) test_list = [random.randint(0,99) for i in range(array_size)] print('List: ',test_list) print(m,'th element is: ',quickselect(test_list,m)) print('Sorted list: ',sorted(test_list))
true
521e916bcc367920ddb63aedcd90e84e38ac7f42
Anshul-GH/jupyter-notebooks
/UdemyPythonDS/DS_BinarySearchTree/Node.py
2,982
4.46875
4
# Defining the class Node class Node(object): # Construction for class Node def __init__(self, data): self.data = data # defining both the child nodes as NULL for the head node self.leftChild = None self.rightChild = None # Defining the insert function. # 'data' contains the new value to be inserted within the tree. # 'self' designates the node which is calling this function def insert(self, data): # If the new data value is less than calling node's data the new value has to go to left branch of the tree if data < self.data: if not self.leftChild: # if there are no nodes on the left self.leftChild = Node(data) # assign the new node as the left child else: # if there are nodes on the left self.leftChild.insert(data) # call the insert function again with the immediate left child node # If the new data value is greater than calling node's data the new value has to go to right branch of the tree else: if not self.rightChild: # if there are no nodes on the right self.rightChild = Node(data) # assign the new node as the right child else: # if there are nodes on the right self.rightChild.insert(data) # call the insert function again with the immediate right child node # Defining the remove function # Parameters: self, data and parent node def remove(self, data, parentNode): if data < self.data: if self.leftChild is not None: self.leftChild.remove(data, self) elif data > self.data: if self.rightChild is not None: self.rightChild.remove(data, self) else: if self.leftChild is not None and self.rightChild is not None: self.data = self.rightChild.getMin() self.rightChild.remove(self.data, self) elif parentNode.leftChild == self: if self.leftChild is not None: tempNode = self.leftChild else: tempNode = self.rightChild parentNode.leftChild = tempNode elif parentNode.rightChild == self: if self.leftChild is not None: tempNode = self.leftChild else: tempNode = self.rightChild parentNode.rightChild = tempNode def getMin(self): if self.leftChild is None: return self.data else: self.leftChild.getMin() def getMax(self): if self.rightChild is None: return self.data else: self.rightChild.getMax() def traverseInOrder(self): if self.leftChild is not None: self.leftChild.traverseInOrder() print(self.data) if self.rightChild is not None: self.rightChild.traverseInOrder()
true
99467384dfdee08e2f5794af6db8e964807ccc95
JFarina5/Python
/password_tester.py
1,107
4.25
4
""" This program takes a given user password and adds 'points' to that password, then calculates the total amount of 'points'. The program will take the total amount of points and then inform the user if they have a strong password or a weak password. """ import re def password_test(): value = 0 user_pass = input("Please enter a password for testing: ") if re.search('[a-z]', user_pass): value = value + 1 if re.search('[A-Z]', user_pass): value = value + 1 if re.search('[0-9]', user_pass): value = value + 1 if re.search('[!@#$%^&*()~_+":?<>.,;-=]', user_pass): value = value + 1 if len(user_pass) < 10: print("Your password should contain more than 10 characters\n") password_score(value) def password_score(value): if value == 4: print("Strong Password") if value == 3: print("Medium Password") if value == 2: print("Weak Password") if value == 1: print("Very Weak Password, consider changing your password now.") return 0 if __name__ == '__main__': password_test()
true
8f8505622fbd3ab77638a28c71d98133d5980fa7
JFarina5/Python
/palindrome_tester.py
623
4.4375
4
""" The purpose of this program is to test a string of text and determine if that word is a palindrome. """ # Palindrome method, which disregards spaces in the user's input and reverses that string # in order to test the input to see if it is a palindrome. def palindrome(): string = input("Please insert a palindrome: ").lower() if ' ' in string: string = string.replace(' ', '') elif str(string) == str(string)[::-1]: print("The following string is a palindrome.\n") else: print("The following string is not a palindrome.\n") if __name__ == '__main__': palindrome()
true
18b0a035d045cfdb818ecabd0c29fad2a166fa70
ImLeosky/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/square.py
2,164
4.28125
4
#!/usr/bin/python3 """ the class Square that inherits from Rectangle """ from models.rectangle import Rectangle class Square(Rectangle): """ Class Square inherits from Rectangle """ def __init__(self, size, x=0, y=0, id=None): """ Class constructor """ width = size height = size super().__init__(width, height, x, y, id) self.size = self.width def __str__(self): """ he overloading __str__ method should return """ str1 = "[{}] ({}) ".format(Square.__name__, self.id) str2 = "{}/{} - {}".format(self.x, self.y, self.size) return(str1 + str2) @property def size(self): """ the getter """ return(self.width) @size.setter def size(self, value): """ The setter should assign (in this order) the width and the height - with the same value """ self.width = value self.height = value def update(self, *args, **kwargs): """ *args is the list of arguments - no-keyworded arguments **kwargs can be thought of as a double pointer to a dictionary: key/value (keyworded arguments) **kwargs must be skipped if *args exists and is not empty """ if len(args) > 0: self.id = args[0] if len(args) > 1: self.size = args[1] if len(args) > 2: self.x = args[2] if len(args) > 3: self.y = args[3] if args is None or len(args) == 0: for key, value in kwargs.items(): if key == "id": self.id = value if key == "size": self.size = value if key == "x": self.x = value if key == "y": self.y = value def to_dictionary(self): """ that returns the dictionary representation of a Rectangle: """ dicts = { "x": self.x, "y": self.y, "id": self.id, "size": self.size} return(dicts)
true
830e2ac7c2d5a8e558877538c644ff87a2747f3b
alammahbub/py_begin_oct
/5. list.py
1,402
4.53125
5
# list in python start with square brackets # list can hold any kind of data friends = ["asib","rony","sajia"] print(friends) # accessing list item with there index print(friends[2]+" has index 2") # accessing list from back or, as negative index print(friends[-1]+" has index -1") # Asigning new item in list by using index friends[2] = "Borhan" print(friends[0:2]) # list function lucky_number = [4,8,9,32,23] friends = ["Asib","Rony","Sajia","Borhan","Rakib"] print(friends) # extend function combine one list with another friends.extend(lucky_number) print(friends) # append add new item at the end friends.append("Maksud") print(friends) # insert can insert data item into any choosen location friends.insert(4,"Sumon") print(friends) # remove delete data item as there index friends.remove(4) print(friends) # pop remove a single item from back or index -1 friends.pop() print(friends) # index of an item can be accessed by index function print(friends.index(9)) friends.append("Borhan") print(friends.count("Borhan")) # sort function will sort data in ascending order if there is only same type of data lucky_number.sort() print(lucky_number) # Reverse function rearrenge data item as index 0 = index -1 lucky_number.reverse() print(lucky_number) #copy function of a list return all data to a new list friends2 = friends.copy() print(friends2)
true
2a6f7cbc33008d2a22ba3974e0e90201caab553a
marko-despotovic-bgd/python
/EndavaExercises/1_3_stringoperations.py
381
4.34375
4
# 1. Strings and Numbers # 1.3. Write a console program that asks for a string and outputs string length # as well as first and last three characters. print('Please enter some string: ') string = (input()) print('Length: {}\nFirst 3 chars: {}\nLast 3 chars: {}'.format(len(string), string[:3], string[-3::1]))
true
e21afb700a8297f49dc193bd9f7d5c72b5c95c07
4Empyre/Bootcamp-Python
/35python_bike/bike.py
780
4.21875
4
class Bike(object): def __init__ (self, price, max_speed): self.price = price self.max_speed = max_speed self.miles = 0 def displayInfo(self): print "Price:",self.price,"Max Speed:",self.max_speed,"Miles:", self.miles def ride(self): self.miles += 10 print "Riding" return self def reverse(self): if self.miles >= 5: # Prevents miles from going negative. self.miles -= 5 print "Reversing" return self bike1 = Bike("$200", "25mph") bike2 = Bike("$250", "27mph") bike3 = Bike("$350", "29mph") bike1.ride().ride().ride().reverse().displayInfo() bike2.ride().ride().reverse().reverse().displayInfo() bike3.reverse().reverse().reverse().displayInfo()
true
c2b4a96ee434e18f2be2f2758478331919d65582
brucekaushik/basicblog
/apps/hello-world/valid-month.py
1,189
4.4375
4
# ----------- # User Instructions # # Modify the valid_month() function to verify # whether the data a user enters is a valid # month. If the passed in parameter 'month' # is not a valid month, return None. # If 'month' is a valid month, then return # the name of the month with the first letter # capitalized. # months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] # build dictionary month_abbrs = dict((m[:3].lower(), m) for m in months) def valid_month(month): if month: cap_month = month.capitalize(); if cap_month in months: return cap_month def valid_month_short(month): if month: short_month = month[:3].lower() # get first 3 letters of input return month_abbrs.get(short_month) # check if short_month exists in the dictionary print valid_month("january") print valid_month("jan") print valid_month_short("january") print valid_month_short("jan") print valid_month_short("janasfasfaf") print valid_month_short("jjjj")
true
84b2266797647b9933d5ca848251e60e19222bcf
cameronww7/Python-Workspace
/Python-Tutorials/Python-Object-Inheritance.py
1,303
4.21875
4
from __future__ import print_function import math # Python Object Inheritance print("Python Object Inheritance") class Shape(object): def __init__(self): self.color = "Red" self.sides = 0 def calcArea(self): return 0 class Quadrilateral(Shape): def __init__(self, w, l, c): self.sides = 4 self.width = w self.length = l self.color = c def calcArea(self): return self.width * self.length class Square(Quadrilateral): def __init__(self, w, c): super(Square, self).__init__(w, w, c) class Circle(Shape): def __init__(self, r, c): super(Circle, self).__init__() self.radius = r self.color = c def calcArea(self): return math.pi * (self.radius ** 2) class Triangle(Shape): def __init__(self, s1, s2, s3, c): Shape.__init__(self) self.s1 = s1 self.s2 = s2 self.s3 = s3 self.color = c def printArea(s): print(s.calcArea()) sq1 = Square(5, "Blue") sq2 = Square(9, "Green") circle1 = Circle(10, "Orange") t1 = Triangle(2, 3, 4, "Purple") print("Square Sizes:", sq1.width, "x", sq1.sides, sq1.color, ",", sq2.width, "x", sq2.sides, sq2.color) print("Circle:", circle1.radius, circle1.color) printArea(sq1)
false
6dad3d3891bda5551a6e6a3f03a442236cf2a9ae
cameronww7/Python-Workspace
/Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/113-Py-ZippingAndUnzippingFiles.py
2,175
4.1875
4
from __future__ import print_function import zipfile import shutil import os """ Prompt 113-Py-ZippingAndUnzippingFiles """ print("113-Py-ZippingAndUnzippingFiles") """ Unzipping and Zipping Files As you are probably aware, files can be compressed to a zip format. Often people use special programs on their computer to unzip these files, luckily for us, Python can do the same task with just a few simple lines of code. """ print("\n113-Py-ZippingAndUnzippingFiles") print("- - - - - - - - - - ") # Create Files to Compress # slashes may need to change for MacOS or Linux f = open("new_file.txt", 'w+') f.write("Here is some text") f.close() # slashes may need to change for MacOS or Linux f = open("new_file2.txt", 'w+') f.write("Here is some text") f.close() """ Zipping Files The zipfile library is built in to Python, we can use it to compress folders or files. To compress all files in a folder, just use the os.walk() method to iterate this process for all the files in a directory. """ comp_file = zipfile.ZipFile('comp_file.zip', 'w') comp_file.write("new_file.txt", compress_type=zipfile.ZIP_DEFLATED) comp_file.write('new_file2.txt', compress_type=zipfile.ZIP_DEFLATED) comp_file.close() """ Extracting from Zip Files We can easily extract files with either the extractall() method to get all the files, or just using the extract() method to only grab individual files. """ zip_obj = zipfile.ZipFile('comp_file.zip', 'r') print(zip_obj.extractall("extracted_content")) """ Using shutil library Often you don't want to extract or archive individual files from a .zip, but instead archive everything at once. The shutil library that is built in to python has easy to use commands for this: """ print(os.getcwd()) """ directory_to_zip = "" # Creating a zip archive output_filename = 'example' # Just fill in the output_filename and the directory to zip # Note this won't run as is because the variable are undefined shutil.make_archive(output_filename, 'zip', directory_to_zip) # Extracting a zip archive # Notice how the parameter/argument order is slightly different here shutil.unpack_archive(output_filename, directory_to_zip, 'zip') """
true
ec0cbb2d72776eedda8618778e642c7944080959
cameronww7/Python-Workspace
/Python-Bootcomp-Zero_To_Hero/Sec-14-Py-Adv_Modules/106-Py-Date_Time.py
1,964
4.40625
4
from __future__ import print_function import datetime """ Prompt 106-Py-Date_Time """ print("106-Py-Date_Time") """ datetime module Python has the datetime module to help deal with timestamps in your code. Time values are represented with the time class. Times have attributes for hour, minute, second, and microsecond. They can also include time zone information. The arguments to initialize a time instance are optional, but the default of 0 is unlikely to be what you want. time Let's take a look at how we can extract time information from the datetime module. We can create a timestamp by specifying datetime.time(hour,minute,second,microsecond) """ print("\ndatetime.time(4, 20, 1)") print("- - - - - - - - - - ") t = datetime.time(4, 20, 1) # Let's show the different components print(t) print('hour :', t.hour) print('minute:', t.minute) print('second:', t.second) print('microsecond:', t.microsecond) print('tzinfo:', t.tzinfo) print('Earliest :', datetime.time.min) print('Latest :', datetime.time.max) print('Resolution:', datetime.time.resolution) """ Dates datetime (as you might suspect) also allows us to work with date timestamps. Calendar date values are represented with the date class. Instances have attributes for year, month, and day. It is easy to create a date representing today’s date using the today() class method. """ print("\ndatetime.date.today()") print("- - - - - - - - - - ") today = datetime.date.today() print(today) print('ctime:', today.ctime()) print('tuple:', today.timetuple()) print('ordinal:', today.toordinal()) print('Year :', today.year) print('Month:', today.month) print('Day :', today.day) print('Earliest :', datetime.date.min) print('Latest :', datetime.date.max) print('Resolution:', datetime.date.resolution) print("\ndatetime.date(2015, 3, 11)") print("- - - - - - - - - - ") d1 = datetime.date(2015, 3, 11) print('d1:', d1) d2 = d1.replace(year=1990) print('d2:', d2)
true
47226b0ba22174336343d4f6fe2648d053ec8612
cameronww7/Python-Workspace
/Python-Bootcomp-Zero_To_Hero/Sec-8-Py-OOP/66-OOP-Challenge.py
2,257
4.3125
4
from __future__ import print_function import math """ Prompt 66-OOP-Challenge """ print("66-OOP-Challenge") """ Object Oriented Programming Challenge For this challenge, create a bank account class that has two attributes: owner balance and two methods: deposit withdraw As an added requirement, withdrawals may not exceed the available balance. Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn. """ print("\n66-OOP-Challenge\n") print("- - - - - - - - - - ") class Account: def __init__(self, xName, xBalance): self.name = xName self.curBalance = xBalance def owner(self): print("The Account Holder Name is : {}".format(self.name)) return self.name def balance(self): print("Your Current Balance is : {}".format(self.curBalance)) return self.curBalance def deposit(self, xDepositAmount): print("Processing Deposit of {}".format(xDepositAmount)) self.curBalance = self.curBalance + xDepositAmount print("Deposit Accepted, Your new Balance is : {}".format(self.curBalance)) return True def withdraw(self, xWithdrawAmount): print("Processing Withdraw of {}".format(xWithdrawAmount)) if xWithdrawAmount > self.curBalance: print("Error : Do not have enough Balance") return False else: self.curBalance = self.curBalance - xWithdrawAmount print("Withdraw Accepted, Your new Balance is : {}".format(self.curBalance)) return True # 1. Instantiate the class acct1 = Account('Jose', 100) # 2. Print the object print("\n# 2. Print the object") print(acct1) # 3. Show the account owner attribute print("\n# 3. Show the account owner attribute") print(acct1.owner()) # 4. Show the account balance attribute print("\n# 4. Show the account balance attribute") print(acct1.balance()) # 5. Make a deposit print("\n# 5. Make a deposit") print(acct1.deposit(50)) # 6. Make a withdrawal print("\n# 6. Make a withdrawal") print(acct1.withdraw(75)) # 7. Make a withdrawal that exceeds the available balance print("\n# 7. Make a withdrawal that exceeds the available balance") print(acct1.withdraw(500))
true
6e8687c78e8198d41807ef3bd1652efcf16bffe9
romanitalian/romanitalian.github.io
/sections/python/spiral_matrix/VH7Isb3mRqUaaHCc_spiral-matrix-in-python.py
1,751
4.28125
4
#!/usr/bin/env python3 # http://runnable.com/VH7Isb3mRqUaaHCc/spiral-matrix-in-python def change_direction(dx, dy): # not allowed!3 if abs(dx+dy) != 1: raise ValueError if dy == 0: return dy, dx if dx == 0: return -dy, dx def print_spiral(N=5, M=6): if N < 0 or M < 0: return None dx, dy = 1, 0 # direction x, y = 0, 0 # coordinate start = 0 # initial value for the matrix max_digits = len(str(N*M-1)) # for pretty printing left_bound, right_bound = 0, N-1 upper_bound, bottom_bound = 1, M-1 # zero filled 2d array matrix = [[0 for i in range(N)] for j in range(M)] for not_use in range(N*M): matrix[y][x] = start if (dx > 0 and x >= right_bound): dx, dy = change_direction(dx, dy) right_bound -= 1 if (dx < 0 and x <= left_bound): dx, dy = change_direction(dx, dy) left_bound += 1 if (dy > 0 and y >= bottom_bound): dx, dy = change_direction(dx, dy) bottom_bound -= 1 if (dy < 0 and y <= upper_bound): dx, dy = change_direction(dx, dy) upper_bound += 1 x += dx y += dy start += 1 print('\n'.join([' '.join(['{:0{pad}d}'.format(val, pad=max_digits) for val in row]) for row in matrix])) if __name__ == '__main__': print_spiral() # def spiral(X, Y): # x = y = 0 # dx = 0 # dy = -1 # for i in range(max(X, Y)**2): # if (-X/2 < x <= X/2) and (-Y/2 < y <= Y/2): # print (x, y) # # DO STUFF... # if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y): # dx, dy = -dy, dx # x, y = x+dx, y+dy
true
dff98da96027c42420440cdae33e55c3dcab539b
kelvinadams/PythonTheHardWay
/ex11.py
386
4.40625
4
# Python the Hard Way - Exercise 11 # prompts user for their age, height, and weight print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') height = input() print("What is your weight?", end=' ') weight = input() # prints out the input in a new format print( f"Alrighty, so you're {age} years old, {height} tall, and weigh {weight}.")
true
3932cf29243c102f8534f103365e4b8401934a96
arelia/django-girls-blog
/intro/python_intro_part_one.py
550
4.1875
4
print("Hello, Django Girls!") myInfo = {'firstName': 'Arelia', 'lastName': 'Jones'} print("My name is " + myInfo['firstName'] + " " + myInfo['lastName'] + ".") a = 4 b = 6 if a == 4: print(" is greater than ") elif b == 2: print(" is less than ") else: print("I don't know the answer") def hi(): print('Hi there!') print('How are you?') hi() def hi(name): if name == "Arelia": print("Hi Arelia!") elif name == "Jones": print("Hi Jones!") else: print("Hi anonymous!") hi("Ola") def hi(name): print("Hi " + name + "!") hi("Rachel")
false
b7fc72d816e4fbf3dad343eb6f7f2cf47847a7e7
SujeethJinesh/Computational-Physics-Python
/Jinesh_HW1/Prob1.py
414
4.1875
4
import math def ball_drop(): height = float(input("please input the height of the tower: ")) #This is how many meters tall the tower is gravity = 9.81 #This is the acceleration (m/s^2) due to gravity near earth's surface time = math.sqrt((2.0*height)/gravity) #derived from h = 1/2 gt^2 to solve for time print("It will take the ball ", time, " seconds to fall to earth.") #Final output statement.
true
f6146b7e9826f07bc27579b30a5b48abbc35be7a
SujeethJinesh/Computational-Physics-Python
/Jinesh_HW1/Prob2.py
870
4.21875
4
import math def travel_time(): distance_from_planet = float(input("Enter distance from planet in light years: ")) #gets user input for light year distance speed_of_craft = float(input("please enter speed as a fraction of c: ")) #gets speed of craft in terms of c from user stationary_observer_time_years = distance_from_planet/speed_of_craft #calculates time according to stationary observer moving_observer_time_years = stationary_observer_time_years*math.sqrt(1 - pow(speed_of_craft, 2.0)) #Time dilation equation solved for observer's time print("It will take ", stationary_observer_time_years, " years according to the stationary observer's reference frame.") #output for stationary observer print("It will take ", moving_observer_time_years, " years according to the travelling observer's reference frame.") #output for moving observer
true
a037cc7c52fa60741d40e9ac8f715b9e3bd7cc02
carolinemascarin/LPTHW
/ex5.py
714
4.21875
4
#Exercise 5 myname = 'Caroline Mascarin' myage = 27 myheight = 175 myeyes = 'Black' myteeth = 'White' myhair = 'Brown' print "Lets talk about %s." % myname print "She is %d centimeters tall" %myheight print "She's got %s eyes and %s hair" % (myeyes, myhair) print "if I add %d and %d I get %d" % (myage, myheight, myage + myheight) print "my name is %s" % myname print "my name is %r" % myname print "my age is %o" % myage """ 4. Try to write some variables that convert the inches and pounds to centimeters and kilos. Do not just type in the measurements. Work out the math in Python. """ #converting km to pounds x = 20 #kg y = 2.2 # pounds print x * y #converting cm to inch x = 175 #cm y = 2.54 #inch print x / y
true
99af0848e395225fbdfa555324a93e1f03ede662
nlscng/ubiquitous-octo-robot
/p100/problem-196/MostOftenSubtreeSumBST.py
1,563
4.125
4
# This problem was asked by Apple. # # Given the root of a binary tree, find the most frequent subtree sum. The subtree sum of a node is the sum of all values under a node, including the node itself. # # For example, given the following tree: # # 5 # / \ # 2 -5 # Return 2 as it occurs twice: once as the left leaf, and once as the sum of 2 + 5 - 5. """ Another variation of BST traversal that should benefit from bubbling things back up to root. """ from common.treenode.MyBST import IntNode from collections import defaultdict def most_frequent_sum_bst(root: IntNode) -> int: # This should be O(n) in time and space, n being the number of nodes in the tree, since we visit # each node one time before passing back up. assert root counts: defaultdict = defaultdict(int) # a dictionary of sum:count key-value pairs def traverse(node: IntNode) -> int: left_sum = traverse(node.left) if node.left is not None else 0 right_sum = traverse(node.right) if node.right is not None else 0 my_sum = node.val + left_sum + right_sum counts[my_sum] += 1 return my_sum traverse(root) return max([v for (k, v) in counts.items()]) c = IntNode(-5) b = IntNode(2) a = IntNode(5, b, c) # assert most_frequent_sum_bst(a) == 2 # -3 # -2 -1 # 4 1 2 2 # 4 1 2 2, 3, 3, 3 g = IntNode(2) f = IntNode(2) e = IntNode(1) d = IntNode(4) c = IntNode(-1, f, g) b = IntNode(-2, d, e) a = IntNode(-3, b, c) assert most_frequent_sum_bst(a) == 3, "Actual: {}".format(most_frequent_sum_bst(a))
true
43dc120d758dd3a1d5c60582ce1df81c0a6a8459
nlscng/ubiquitous-octo-robot
/p100/problem-188/PythonFunctionalDebug.py
782
4.15625
4
# This problem was asked by Google. # # What will this code print out? # # def make_functions(): # flist = [] # # for i in [1, 2, 3]: # def print_i(): # print(i) # flist.append(print_i) # # return flist # # functions = make_functions() # for f in functions: # f() # How can we make it print out what we apparently want? ##Google # Very interesting problem, worthy of the google sticker, although in the end it's so simple def make_functions(): flist = [] for i in [1, 2, 3]: def print_i(statement): # Remember none of the func body is executed in declaration print(statement) flist.append((print_i, i)) return flist functions = make_functions() for f, a in functions: f(a)
true
62ebf7681cc0f040b0ccb64d4c2218a1d2c5c7ad
nlscng/ubiquitous-octo-robot
/p000/problem-98/WordSearchPuzzle.py
2,521
4.21875
4
# This problem was asked by Coursera. # # Given a 2D board of characters and a word, find if the word exists in the grid. # # The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those # horizontally or vertically neighboring. The same letter cell may not be used more than once. # # For example, given the following board: # # [ # ['A','B','C','E'], # ['S','F','C','S'], # ['A','D','E','E'] # ] # exists(board, "ABCCED") returns true, exists(board, 'SEE') returns true, exists(board, "ABCB") returns false. def snake_word_search(board: list, word: str) -> bool: # This is dfs looking for the first character match in given word, if found, we dfs explore and find following # matches. # Assume width of the board is n, height of the board is m, and size of target word is s, then this solution is # O(n*m) in time and O(s) in space if not board or not word: return False def find_neighbor_locs(bd: list, row: int, col: int) -> list: res = [] width, height = len(bd[0]), len(bd) if row > 0: res.append((row - 1, col)) if col > 0: res.append((row, col - 1)) if row < height - 1: res.append((row + 1, col)) if col < width - 1: res.append((row, col + 1)) return res def explore_and_mark(bd: list, target: str, row: int, col: int, visited: set) -> bool: if len(target) == 0: return True neighbor_locs = find_neighbor_locs(bd, row, col) for neighbor_r, neighbor_c in neighbor_locs: if (neighbor_r, neighbor_c) not in visited and bd[neighbor_r][neighbor_c] == target[0]: visited.add((neighbor_r, neighbor_c)) if explore_and_mark(bd, target[1:], neighbor_r, neighbor_c, visited): return True return False for r in range(len(board)): for c in range(len(board[0])): if board[r][c] == word[0]: visited = {(r, c)} found = explore_and_mark(board, word[1:], r, c, visited) if found: return True return False test_board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'] ] assert not snake_word_search([], 'some') assert not snake_word_search(test_board, '') assert snake_word_search(test_board, 'ABCCED') assert snake_word_search(test_board, 'SEE') assert not snake_word_search(test_board, 'ABCB')
true
70bf93d87d438fffa829d69fb3b1eb615a5322a0
nlscng/ubiquitous-octo-robot
/p000/problem-88/DivisionWithoutOperator.py
546
4.21875
4
# This question was asked by ContextLogic. # # Implement division of two positive integers without using the division, multiplication, or modulus operators. # Return the quotient as an integer, ignoring the remainder. def raw_division(n: int, m: int) -> int: if n < m: return raw_division(m, n) quot, cur_sum = 0, 0 while cur_sum <= n: quot += 1 cur_sum += m return quot - 1 assert raw_division(1, 1) == 1 assert raw_division(2, 1) == 2 assert raw_division(10, 3) == 3 assert raw_division(11, 7) == 1
true
5a75a95a3a659a9a970c94aebfc13950730718a1
nlscng/ubiquitous-octo-robot
/p000/problem-6/XorLinkedList.py
1,961
4.1875
4
# An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev # fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR # linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at # index. # # If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and # dereference_pointer functions that converts between nodes and memory addresses. ##Google def get_pointer(object): return 1234 def dereference_pointer(address): return 4321 class XorLinkedListNode: # I guess this xor linked list rely on the special fact # that A xor B = C => A xor C = B, B xor C = A def __init__(self, value: int, prev_add): self.value = value self.ptr = prev_add ^ 0 def set_pointer(self, new_ptr): self.ptr = new_ptr class XorLinkedList: def __init__(self): self.head = None self.tail = None def add(self, value): if self.head is None: self.head = XorLinkedListNode(value, 0) else: node = self.head prev_add = 0 while node.ptr is not None: cur_add = get_pointer(node) node = dereference_pointer(prev_add ^ node.ptr) prev_add = cur_add new_node = XorLinkedListNode(value, get_pointer(node)) node.set_ptr(prev_add ^ get_pointer(new_node)) def get(self, index): if index <= 0: return None node = self.head prev_add = 0 while node.ptr is not None and index > 0: cur_add = get_pointer(node) node = dereference_pointer(prev_add ^ cur_add) prev_add = cur_add index -= 1 return node.value # hmm, how do I test this with the fake get_pointer and dereference ...
true
ede2ca2fec4c1156fb877811d1f5274749299ea2
nlscng/ubiquitous-octo-robot
/p000/problem-58/SearchInRotatedSortedArray.py
1,415
4.15625
4
# Good morning! Here's your coding interview problem for today. # # This problem was asked by Amazon. # # An sorted array of integers was rotated an unknown number of times. # # Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't # exist in the array, return null. # # For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array). # # You can assume all the integers in the array are unique. ''' left ... mid ... right b: > left or < mid => left, else go right b: > left and < mid go left, go right so both scenario relies on the value of left to decide which half to go ''' def rotated_binary_search(nums: list, k: int) -> int: # GG: this is a very interesting binary search exercise if not nums: return None if len(nums) < 2 and nums[0] != k: return None left = 0 right = len(nums) while left < right: mid = (left + right) // 2 if nums[mid] == k: return mid if k >= nums[left]: right = mid else: left = mid return None assert rotated_binary_search([], 3) is None assert rotated_binary_search([1], 3) is None assert rotated_binary_search([1], 1) == 0 assert rotated_binary_search([1, 3], 3) == 1 assert rotated_binary_search([12, 18, 25, 2, 8, 10], 8) == 4
true
c6d5c270f8a215c1b8d8060d15e4073d6339a8bb
nlscng/ubiquitous-octo-robot
/p000/problem-68/AttackingBishop.py
1,467
4.28125
4
# Good morning! Here's your coding interview problem for today. # # This problem was asked by Google. # # On our special chessboard, two bishops attack each other if they share the same diagonal. This includes bishops # that have another bishop located between them, i.e. bishops can attack through pieces. # # You are given N bishops, represented as (row, column) tuples on a M by M chessboard. Write a function to count the # number of pairs of bishops that attack each other. The ordering of the pair doesn't matter: (1, 2) is considered # the same as (2, 1). # # For example, given M = 5 and the list of bishops: # # (0, 0) # (1, 2) # (2, 2) # (4, 0) # The board would look like this: # # [b 0 0 0 0] # [0 0 b 0 0] # [0 0 b 0 0] # [0 0 0 0 0] # [b 0 0 0 0] # You should return 2, since bishops 1 and 3 attack each other, as well as bishops 3 and 4. def find_attacking_bishops(board_width: int, bishop_locs: list): count = 0 for i in range(len(bishop_locs)): for j in range(i+1, len(bishop_locs)): if abs(bishop_locs[i][0] - bishop_locs[j][0]) == abs(bishop_locs[i][1] - bishop_locs[j][1]): count += 1 return count assert find_attacking_bishops(5, [(0, 0), (1, 2), (2, 2)]) == 1, \ "actual: {}".format(find_attacking_bishops(5, [(0, 0), (1, 2), (2, 2)])) assert find_attacking_bishops(5, [(0,0), (1,2), (2,2), (4,0)]) == 2, \ "actual: {}".format(find_attacking_bishops(5, [(0,0), (1,2), (2,2), (4,0)]))
true
5b4735c804aafaa74f3a0461bc53fb5befbc6093
chandrikakurla/implementing-queue-with-array-space-efficient-way-in-python-
/qu_implement queue using array.py
2,962
4.1875
4
#class to implement queue class Queue: def __init__(self,size): self.queue=[None] *size self.front=-1 self.rear=-1 self.size=size #function to check empty stack def isEmpty(self): if self.front==-1 and self.rear==-1: return True else: return False #function to check full stack def isFull(self): #if next of rare is front then stack is full if ((self.rear+1)%(self.size))==self.front: print("queue is full") return True else: return False #function to insert element into queue in rear side def Enqueue(self,data): if self.isFull(): return elif (self.isEmpty()): self.front=0 self.rear=0 self.queue[0]=data else: #increment rear #use of array in circular fashion to effeciently use space in array self.rear=(self.rear+1)%(self.size) self.queue[self.rear]=data #function to remove element from front def Dequeue(self): if (self.isEmpty()): print("queue is empty") return #if queue contains single element after removing make queue empty elif self.front==self.rear: temp=self.queue[self.front] self.front=-1 self.rear=-1 return temp else: temp=self.queue[self.front] #update front of queue self.front=(self.front+1)%(self.size) return temp #function to return front element of queue def Front(self): if self.isEmpty(): print("Queue is empty") else: print("Front item is", self.queue[self.front]) #function to return last element of queue def Rear(self): if self.isEmpty(): return else: print("rear item is",self.queue[self.rear]) #function to print elements of queue in inserted order def print_queue(self): if self.isEmpty(): print("queue is empty") return if self.front==0 and self.rear==0: print(self.queue[0]) return current=self.front print("front element is"+str(self.queue[current])) while(True): print(self.queue[current]) current=(current+1)%(self.size) if(current==self.rear): print(self.queue[current]) break if __name__=="__main__": que=Queue(10) que.Enqueue(1) que.Enqueue(2) que.Enqueue(3) que.Enqueue(4) que.Enqueue(5) que.print_queue() print("dequed element is"+str(que.Dequeue())) print("dequed element is"+str(que.Dequeue())) que.print_queue() que.Front() que.Rear()
true
041e238b857fa33960c8f51c95e21d5fd2e4cf0d
lindajaracuaro/My-Chemical-Polymorphism
/My chemical polymorphism.py
782
4.28125
4
# Chemical polymorphism! In this program you'll have fun using chemistry and polymorphism. Add elements and create molecules. class Atom: def __init__(self, label): self.label = label def __add__(self, other): # Return as a chemical composition return self.label + other.label def __repr__(self): return self.label class Molecule: def __init__(self, atoms): if type(atoms) is list: self.atoms = atoms def __repr__(self): # Return as a list of molecules return self.atoms sodium = Atom("Na") chlorine = Atom("Cl") # Salt chemical composition using label AND using Polymorphism salt_pol = sodium + chlorine print(salt_pol) # Salt Molecule as a list salt = Molecule([sodium, chlorine]) print(salt.atoms)
true
6b0f193dc597b8d5f02db807376a3a7f4f39bcdd
rowens794/intro-to-cs
/ps1/ps1.py
599
4.125
4
portion_down_payment = .25 r = .04 annual_salary = float(input('what is your annual salary? ')) portion_saved = float(input('what portion of your salary will you save? ')) total_cost = float(input('how much does your dream house cost? ')) current_savings = 0 months = 0 print('pre loop') print(current_savings) print(total_cost * portion_down_payment) while current_savings < total_cost * portion_down_payment: months = months + 1 current_savings = current_savings + current_savings * \ r / 12 + annual_salary / 12 * portion_saved print('in loop') print(current_savings)
true
f18337a4c73ad850e323599b21a91263b75ce1d9
JKH2124/jnh-diner-project-py
/diner_project.py
2,157
4.40625
4
# J & K's Diner dinnerMenu = ['STEAK', '15', 'CHICKEN', '12', 'PORK', '11', 'SALAD', '12'] sidesMenu = ['FRIES', 'RICE', 'VEGGIES', 'SOUP', '1'] dinnerSelect = input("Please select an entree: ").upper() if dinnerSelect == dinnerMenu[0]: print("Excellent choice! The price for that entree is {}".format(dinnerMenu[1])) input("And how would you like your steak?") dinner_main = [dinnerMenu[0], dinnerMenu[1]] elif dinnerSelect == dinnerMenu[2]: print("Wonderful! The price for that entree is {}".format(dinnerMenu[3])) dinner_main = [dinnerMenu[2], dinnerMenu[3]] elif dinnerSelect == dinnerMenu[4]: print("Tasty! The price for that entree is {}".format(dinnerMenu[5])) dinner_main = [dinnerMenu[4], dinnerMenu[5]] elif dinnerSelect == dinnerMenu[6]: print("One of our most popular! The price for that entree is {}".format(dinnerMenu[7])) dinner_main = [dinnerMenu[6], dinnerMenu[7]] else: print("Please make a valid selection") sidesSelect = input("You also have your choice of two sides to go with your meal. What is the first side you would like? ").upper() if sidesSelect == sidesMenu[0] or sidesSelect == sidesMenu[1] or sidesSelect == sidesMenu[2] or sidesSelect == sidesMenu[3]: print("Ok.") first_side_price = sidesMenu[4] else: print("We currently do not offer that on our menu.") sidesSelect = input("And what would you like for your second side?").upper() if sidesSelect == sidesMenu[0]: print("Very good! The price for those sides is {}".format(sidesMenu[4])) side_price = sidesMenu[4] elif sidesSelect == sidesMenu[1]: print("Super! The price for those sides is {}".format(sidesMenu[4])) side_price = sidesMenu[4] elif sidesSelect == sidesMenu[2]: print("Nice! The price for those sides is {}".format(sidesMenu[4])) side_price = sidesMenu[4] elif sidesSelect == sidesMenu[3]: print("Sounds good! The price for those sides is {}".format(sidesMenu[4])) side_price = sidesMenu[4] else: print("We currently do not offer that on our menu.") dinnerTotal = int(dinner_main[1]) + int(side_price) + int(first_side_price) print("The total cost for your dinner comes to {}".format(dinnerTotal))
true
9cf2dec2e90b8164e3470892b68f38fe9bef4dd7
EliksonBT/estcmp060-
/fibonacci-spiral-fractal.py
1,970
4.46875
4
# Programa em python para plotar a espiral # fractal de fibonacci import turtle import math def fiboPlot(n): a = 0 b = 1 square_a = a square_b = b # Setando a cor da caneta para azul x.pencolor("blue") # Desenhando o primeiro quadrado x.forward(b * factor) x.left(90) x.forward(b * factor) x.left(90) x.forward(b * factor) x.left(90) x.forward(b * factor) # Prosseguindo com a série Fibonacci temp = square_b square_b = square_b + square_a square_a = temp # Desenhando o resto dos quadrados for i in range(1, n): x.backward(square_a * factor) x.right(90) x.forward(square_b * factor) x.left(90) x.forward(square_b * factor) x.left(90) x.forward(square_b * factor) # Prosseguindo com a série Fibonacci temp = square_b square_b = square_b + square_a square_a = temp # Trazendo a caneta para o ponto inicial do gráfico espiral x.penup() x.setposition(factor, 0) x.seth(0) x.pendown() # Setando a cor da caneta para vermelho x.pencolor("red") # Fibonacci Spiral Plot x.left(90) for i in range(n): print(b) fdwd = math.pi * b * factor / 2 fdwd /= 90 for j in range(90): x.forward(fdwd) x.left(1) temp = a a = b b = temp + b # Here 'factor' signifies the multiplicative # factor which expands or shrinks the scale # of the plot by a certain factor. factor = 1 # Taking Input for the number of # Iterations our Algorithm will run n = int(input('Enter the number of iterations (must be > 1): ')) # Plotting the Fibonacci Spiral Fractal # and printing the corresponding Fibonacci Number if n > 0: print("Fibonacci series for", n, "elements :") x = turtle.Turtle() x.speed(100) fiboPlot(n) turtle.done() else: print("Number of iterations must be > 0")
false
e645165c06b68fadc275ab51ed701a00887f5688
Gaurav-Pande/DataStructures
/leetcode/graphs/add_search_trie.py
1,636
4.15625
4
# link: https://leetcode.com/problems/add-and-search-word-data-structure-design/ class TrieNode(object): def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word=False class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: None """ current = self.root for letter in word: current = current.children[letter] current.is_word=True def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ current = self.root self.result = False self.dfs(current, word) return self.result def dfs(self,current, word): if not word: if current.is_word: self.result = True return else: if word[0] == '.': for children in current.children.values(): self.dfs(children, word[1:]) else: current = current.children.get(word[0]) if not current: return self.dfs(current,word[1:]) # Your WordDictionary object will be instantiated and called as such: # obj = WordDictionary() # obj.addWord(word) # param_2 = obj.search(word)
true