blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4844eb4416c99f709e8d8d7d4219bee020c7adb6
nbpillai/npillai
/Odd or Even.py
205
4.3125
4
print("We will tell you if this number is odd or even.") number = eval(input("Enter a number! ")) if number%2==0: print("This is an even number!") else: print ("This number is an odd number!")
true
ee4bb01eb029819b15ee23c478edab0aada9608b
ari-jorgensen/asjorgensen
/SimpleSubstitution.py
1,140
4.15625
4
# File: SimpleSubstitution.py # Author: Ariana Jorgensen # This program handles the encryption and decryption # of a file using a simple substitution cipher. # I created this algorithm myself, only borrowing the # randomized alphabet from the Wikipedia example # of substitution ciphers # NOTE: For simplicity, all characters are converted to lowercase # Regular alphabet & randomized substitution # alphabet to be used for encyrption/decryption alpha = 'abcdefghijklmnopqrstuvwxyz' subAlpha = 'vjzbgnfeplitmxdwkqucryahso' def simpleSubEncrypt(line): subLine = '' subWord = '' for word in line: for char in word: try: char = char.lower() ind = alpha.index(char) newChar = subAlpha[ind] subWord += newChar except ValueError: subWord = char subLine += subWord subWord = '' return subLine def simpleSubDecrypt(line): normalLine = '' normalWord = '' for word in line: for char in word: try: char = char.lower() ind = subAlpha.index(char) newChar = alpha[ind] normalWord += newChar except ValueError: normalWord += char normalLine += normalWord normalWord = '' return normalLine
true
f09176c324c14916ee1741dd82077dd667c86353
cbarillas/Python-Biology
/lab01/countAT-bugsSoln.py
903
4.3125
4
#!/usr/bin/env python3 # Name: Carlos Barillas (cbarilla) # Group Members: none class DNAString(str): """ DNAString class returns a string object in upper case letters Keyword arguments: sequence -- DNA sequence user enters """ def __new__(self,sequence): """Returns a copy of sequence in upper case letters""" return str.__new__(self,sequence.upper()) def length(self): """Returns length of sequence""" return len(self) def getAT(self): """Returns the AT content of the sequence""" num_A = self.count("A") num_T = self.count("T") return ((num_A + num_T)/self.length()) """ Builds a new DNAString object based on what the user inputs Prints the AT content of the sequence """ DNA = input("Enter a DNA sequence: ") coolString = DNAString(DNA) print ("AT content = {:0.3f}".format(coolString.getAT()))
true
92db81dc42cd42006e58a7acb64347ef443b4afc
mattin89/Autobiographical_number_generator
/Autobiographic_Numbers_MDL.py
1,542
4.15625
4
''' By Mario De Lorenzo, md3466@drexel.edu This script will generate any autobiographic number with N digits. The is_autobiographical() function will check if numbers are indeed autobiographic numbers and, if so, it will store them inside a list. The main for loop will check for sum of digits and if the number of 1s is 0, 1 or 2. After inserting the N digits, the script will tell you how long it should take. You can decide which for loop condition to keep based on your purpose. ''' import collections from tqdm import tqdm user = input("N digits: ") b_list = [] def is_autobiographical(num): lst = list(map(int, list(num))) counts = collections.Counter(lst) return all(lst[i] == counts.get(i, 0) for i in range(len(lst))) def check_ones(num): #The numbers of 1s can only be 0,1, or 2 check = str(num) if num > 10: if int(check[1]) >= 3: return True else: return False else: return False #for i in tqdm(range(10**(int(user)-1), 10**(int(user)))): #Only N digits numbers for i in tqdm(range(10**(int(user)))): #All numbers up to N digits sum_of_digits = sum(int(digit) for digit in str(i)) if sum_of_digits == len(str(i)): #Only checks the numbers that the sum of each digits is equal to the length if is_autobiographical(str(i)): b_list.append(i) if check_ones(i) and i > 10: temp = str(i) temp1 = int(temp[0]) i = (temp1+1) * (10 ** (len(temp)-1)) print() print(b_list)
true
801c588912b99c98b0076b70dbbd8d7b2184c23e
garetroy/schoolcode
/CIS210-Beginner-Python/Week 2/counts.py
1,410
4.4375
4
""" Count the number of occurrences of each major code in a file. Authors: Garett Roberts Credits: #FIXME Input is a file in which major codes (e.g., "CIS", "UNDL", "GEOG") appear one to a line. Output is a sequence of lines containing major code and count, one per major. """ import argparse def count_codes(majors_file): """ Adds majors to a list. Counts the amount of times a major is in a list and then prints the major and the count in the list. If it is already a previously gone through major, it skips it and goes to the next. """ majors = [ ] gone_through = [ ] for line in majors_file: majors.append(line.strip()) majors = sorted(majors) count = 0 for major in majors: count = majors.count(major) if major in gone_through: continue gone_through.append(major) print(major, count) def main( ): """ Interaction if run from the command line. Usage: python3 counts.py majors_code_file.txt """ parser = argparse.ArgumentParser(description="Count major codes") parser.add_argument('majors', type=argparse.FileType('r'), help="A text file containing major codes, one major code per line.") args = parser.parse_args() # gets arguments from command line majors_file = args.majors count_codes(majors_file) if __name__ == "__main__": main( )
true
2e18fd51ae66bc12003e51accf363523f227a76e
agzsoftsi/holbertonschool-higher_level_programming
/0x06-python-classes/5-square.py
1,007
4.46875
4
#!/usr/bin/python3 """Define a method to print a square with #""" class Square: """Class Square is created""" def __init__(self, size=0): """Initializes with a size""" self.size = size @property def size(self): """method to return size value""" return self.__size @size.setter def size(self, value): """method to set a size value""" if type(value) != int: raise TypeError('size must be an integer') if value < 0: raise ValueError('size must be >= 0') """Verify that size is not negative or 0""" self.__size = value def area(self): """Return the area of the square""" return self.__size**2 def my_print(self): """Prints square with # in stdout.""" if self.__size == 0: print() else: for num in range(0, self.__size): print('#' * self.__size) """loop to print the square"""
true
15c852d2d567f3334eb8c3dea00bf41cc1fa38e8
Zantosko/digitalcrafts-03-2021
/week_1/day5/fibonacci_sequence.py
755
4.34375
4
# Fibonacci Sequence sequence_up_to = int(input("Enter number > ")) # Inital values of the Fibacci Sequence num1, num2 = 0, 1 # Sets intial count at 0 count = 0 if sequence_up_to <= 0: print("Error endter positive numbers or greater than 0") elif sequence_up_to == 1: print(f"fib sequence for {sequence_up_to}") print(sequence_up_to) else: # Iterates continously until counter is greater than the number that the user inputs while count < sequence_up_to: print(num1) # Holds sum of initial values added_nums = num1 + num2 # Reassign second value to first value num1 = num2 # Reassign first value to second value num2 = added_nums # Increment counter count += 1
true
e6e3fb65e165ec1b9e9f584539499c22d545d2f2
nelsonje/nltk-hadoop
/word_freq_map.py
628
4.21875
4
#!/usr/bin/env python from __future__ import print_function import sys def map_word_frequency(input=sys.stdin, output=sys.stdout): """ (file_name) (file_contents) --> (word file_name) (1) maps file contents to words for use in a word count reducer. For each word in the document, a new key-value pair is emitted with a value of 1. """ template = '{} {}\t{}' for line in input: file_name, words = line.strip().split('\t') for word in words.strip().split(): print(template.format(word, file_name, 1), file=output) if __name__ == '__main__': map_word_frequency()
true
b8eb07e732f80f4303e5020aecb26f7711e93d1d
PederBG/sorting_algorithms
/InsertionSort.py
510
4.25
4
""" Sorting the list by iterating upwards and moving each element back in the list until it's sorted with respect on the elements that comes before. RUNTIME: Best: Ω(n), Average: Θ(n^2), Worst: O(n^2) """ def InsertionSort(A): for i in range(1, len(A)): key = A[i] j = i - 1 while j > -1 and A[j] > key: A[j + 1] = A[j] j = j - 1 A[j + 1] = key # --------------------------------------- """ l = [4, 3, 2, 6, 1] InsertionSort(l) print(l) """
true
708c3f290a705b46dc828a704a3d4e2a431fee51
zadadam/algorithms-python
/sort/bubble.py
1,066
4.125
4
import unittest def bubble_sort(list): """Sort list using Bubble Sort algorithm Arguments: list {integer} -- Unsorted list Returns: list {integer} -- Sorted list """ swap=True test ="It is a bad code"; while swap: swap = False for n in range(len(list) - 1 ): if list[n] > list[n+1]: current = list[n] list[n] = list[n + 1] list[n + 1] = current swap = True return list class TestBubbleSort(unittest.TestCase): def test_sort(self): self.assertListEqual(bubble_sort([1, 1]), [1, 1]) self.assertListEqual(bubble_sort([1, 2]), [1, 2]) self.assertListEqual(bubble_sort([1, 2]), [1, 2]) self.assertListEqual(bubble_sort([2, 1]), [1, 2]) self.assertListEqual(bubble_sort([6, 3, 9, 1, 43]), [1, 3, 6, 9, 43]) self.assertListEqual(bubble_sort([14, 46, 43, 27, 57, 41, 45, 21, 70]), [14, 21, 27, 41, 43, 45, 46, 57, 70]) if __name__ == '__main__': unittest.main()
true
109ec4c8b4316cc46479ab9cfe93f2fe7a9f817d
vishul/Python-Basics
/openfile.py
500
4.53125
5
# this program opens a file and prints its content on terminal. #files name is entered as a command line argument to the program. #this line is needed so we can use command line arguments in our program. from sys import argv #the first command line argument i.e program call is saved in name and the #second CLA is stored in filename this is the name of the file to be opened name,filename=argv txt=open(filename) #everything inside the file is printed on the terminal. print txt.read() txt.close()
true
2e3924cd0819ea47b3d5081e4d24647a31ea19fa
bsextion/CodingPractice_Py
/MS/Fast Slow Pointer/rearrange_linkedlist.py
1,332
4.15625
4
class Node: def __init__(self, value, next=None): self.value = value self.next = next def print_list(self): temp = self while temp is not None: print(str(temp.value) + " ", end='') temp = temp.next print() def reorder(head): middle = find_middle(head) reversed_middle = reverse_middle(middle) ptr_head = head head = head.next while(head): pass #while reverse_middle #temp to hold the next values: ptr_head.next #ptr.head = middle #ptr.head.next = temp #reverse_middle = reverse_middle.next #have a pointer pointing to the middle of the list #reverse the second half of the linked list using recursion #start from the begininng, place after node, move the node to the next # TODO: Write your code here return def reverse_middle(head): if head is None or head.next is None: return head p = reverse_middle(head.next) head.next.next = head head.next = None return p def find_middle(head): slow_pointer = head fast_pointer = head while fast_pointer: slow_pointer = slow_pointer.next fast_pointer = fast_pointer.next.next return slow_pointer head = Node(2) head.next = Node(4) head.next.next = Node(6) head.next.next.next = Node(8) head.next.next.next.next = Node(10) head.next.next.next.next.next = Node(12) reorder(head)
true
4c5761f987c88512f2b4f0a3240f71ae39f10101
bsextion/CodingPractice_Py
/Google/L1/challenge.py
1,215
4.34375
4
# Due to the nature of the space station's outer paneling, all of its solar panels must be squares. # Fortunately, you have one very large and flat area of solar material, a pair of industrial-strength scissors, # and enough MegaCorp Solar Tape(TM) to piece together any excess panel material into more squares. # For example, if you had a total area of 12 square yards of solar material, you would be able to make one # 3x3 square panel (with a total area of 9). That would leave 3 square yards, so you can turn those into # three 1x1 square solar panels. # Write a function solution(area) that takes as its input a single unit of measure representing the total # area of solar panels you have (between 1 and 1000000 inclusive) and returns a list of the areas of the # largest squares you could make out of those panels, starting with the largest squares first. # So, following the example above, solution(12) would return [9, 1, 1, 1]. # highest square root that doesn't go over, remaining would then find the highest def solution(area): arr = [] while area > 0: sqrtRound = int(area ** 0.5) sqrtRound *= sqrtRound arr.append(sqrtRound) area -= sqrtRound return arr
true
a32fa47fe2f8e571a862e53e89d76ab67efebc21
Lalesh-code/PythonLearn
/Oops_Encapsulation.py
1,484
4.4375
4
# Encapsulation: this restrict the access to methods and variables. This can prevent the data from being get modified accidently or by security point of view. This is achived by using the private methods and variables. # Private methods denoted by "__" sign. # Public methods can be accessed from anywhere but Private methods is accessed only in their classes & methods. class MyClass(): __a=100 # valiable a is defined here as private denoted as '__' def display(self): print(self.__a) # passed here the same __a variable private one. obj=MyClass() obj.display() # O/p = 100 # print(MyClass.__a) # __a private variable outsie of class cannot be accesed. AttributeError: type object 'MyClass' has no attribute '__a' class MyClass(): def __display1(self): # Private Method print("This is first display method") def display2(self): # Public Method print("This is second display method") self.__display1() obje=MyClass() obje.display2() # only public method is accessed here. display1 private method cannot be. # We can access private variables outside of class indiretly using methods: class MyClass(): __empid=101 # Private variable def getempid(self,eid): self.__empid = eid # method to get the getempid. def dispempid(self): print(self.__empid) # method to get the dispempid. obj=MyClass() obj.getempid(105) # 105 obj.dispempid() # 101
true
b9104f7316d95eaa733bbbd4926726472855046e
emma-rose22/practice_problems
/HR_arrays1.py
247
4.125
4
'''You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.''' import numpy as np nums = input().split() nums = [int(i) for i in nums] nums = np.array(nums) nums.shape = (3, 3) print(nums)
true
4239aaee9e02cf22c29b61d6e60efabf702abcb5
asiapiorko/Introduction-to-Computer-Science-and-Programming-Using-Python
/Unit 1 Exercise 1.py
1,616
4.1875
4
""" In this problem you'll be given a chance to practice writing some for loops. 1. Convert the following code into code that uses a for loop. prints 2 prints 4 prints 6 prints 8 prints 10 prints Goodbye! """ # First soultion for count in range(2,11,2): print(count) print("Goodbye!") # First solution improved newlist = print([count for count in range(2,11,2)]) print("Goodbye!") # Second soultion for count in range(10): if count != 0 and count % 2 == 0: print(count) print("Goodbye!") # Second solution - improvement newlist = [count for count in range(10) if count != 0 and count % 2 == 0 ] print(newlist) print("Goodbye!") """ 2. Convert the following code into code that uses a for loop. prints Hello! prints 10 prints 8 prints 6 prints 4 prints 2 """ # First solution print("Hello!") for count in range(10,0,-2): print(count) # First solution improvement print("Hello!") newlist = [count for count in range(10,0,-2)] print(newlist) """ 3. Write a for loop that sums the values 1 through end, inclusive. end is a variable that we define for you. So, for example, if we define end to be 6, your code should print out the result: 21 which is 1 + 2 + 3 + 4 + 5 + 6. """ # First solution def sum_values(): number = int(input("Define a number: ")) end = 0 for number in range(number+1): end += number return end # Another solution def sum_values(end): total = end for next in range(end): total += next return total
true
84fce63f043d3b48c019739dce5d9a58df6c0198
arcstarusa/prime
/StartOutPy4/CH7 Lists and Tuples/drop_lowest_score/main.py
678
4.21875
4
# This program gets a series of test scores and # calculates the average of the scores with the # lowest score dropped. 7-12 def main(): # Get the test scores from the user. scores = get_scores() # Get the total of the test scores. total = get_total(scores) # Get the lowest test scores. lowest = min(scores) # Subtract the lowest score from the total. total -= lowest # Calculate the average. Note that we divide # by 1 less that the number of scores because # the lowest score was dropped. average = total / (len(scores) -1) # Display the average. print('The average, with the lowest score dropped', 'is:', average)
true
18c597902f1fa9e14de3506f2cce0d357af647b0
arcstarusa/prime
/StartOutPy4/CH12 Recursion/fibonacci.py
457
4.125
4
# This program uses recursion to print numbers from the Fibonacci series. def main(): print('The first 10 numberss in the ') print('Fibonacci series are:') for number in range(1,11): print(fib(number)) # The fib function returns returns the nth number # in the Fibonacci series. def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n -1) + fib(n -2) # Call the main function. main()
true
1684ed5ced8288e821c464db286a72f0c1098b0a
arcstarusa/prime
/StartOutPy4/CH8 Strings/validate_password.py
420
4.15625
4
# This program gets a password from the user and validates it. 8-7 import login1 def main(): # Get a password from the user. password = input('Enter your password: ') # Validate the password. while not login1.valid_password(password): print('That password is not valid.') password = input('Enter your password: ') print('That is valid password.') # Call the main function. main()
true
46cba8a43cb65ece9a372e4c99c46b987d88dbd7
LesterAGarciaA97/OnlineCourses
/08. Coursera/01. Python for everybody/Module 1/Week 06/Code/4.6Functions.py
1,004
4.4375
4
#4.6 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and #time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use #the function to do the computation. The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). #You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input unless you want to - you #can assume the user types numbers properly. Do not name your variable sum or use the sum() function. def computepay(h,r): if h > 40: p = 1.5 * r * (h - 40) + (40 *r) else: p = h * r return p hrs = input("Enter Hours:") hr = float(hrs) rphrs = input("Enter rate per hour:") rphr = float(rphrs) p = computepay(hr,rphr) print("Pay",p)
true
6cb09e7a8ff19cabb2a5b2218c1fbf3b994ffa5e
Kilatsat/deckr
/webapp/engine/card_set.py
2,455
4.125
4
""" This module contains the CardSet class. """ from engine.card import Card def create_card_from_dict(card_def): """ This is a simple function that will make a card from a dictionary of attributes. """ card = Card() for attribute in card_def: setattr(card, attribute, card_def[attribute]) return card class CardSet(object): """ A card set is simply a set of cards. This could be anything from 52 playing cards to every magic card created. These can be loaded from a configuration file or defined via python. """ def __init__(self): self.cards = {} def load_from_list(self, card_list): """ This function takes in a list of dicts and uses that to create the card set. If any card definition in the list does not have a name, it will be considered an invalid card definition and will not be included in the card set. This will add to anything that is currently in the card set. A card added to the card set will overwrite any card already in the card set with the same name. """ for card_def in card_list: card_name = card_def.get('name', None) if card_name is not None: self.cards[card_name] = card_def def all_cards(self): """ Return a list of all the cards for this card set. """ return self.cards.values() def create(self, card_name, number=1): """ Create an instance of the card with card_name. If number == 1 then this will return a single instance. Otherwise this returns a list of cards each of which is a copy of the card_name. If there is no card with card_name in the card set, then an error will be thrown. """ card_name = self.cards.get(card_name, None) if card_name is None: raise ValueError("Unable to get card {0}".format(card_name)) if number == 1: return create_card_from_dict(card_name) elif number > 1: return [create_card_from_dict(card_name) for _ in range(number)] else: return [] def create_set(self): """ Create a single instance of every card in this set. This will return a list which contains a Card object for every card in this set. """ return [create_card_from_dict(self.cards[x]) for x in self.cards]
true
9f0a9465e1d2f2328088cc53093a61101005a17c
CaseyTM/day1Python
/tuples.py
1,320
4.34375
4
# arrays (lists) are mutable (changeable) but what if you do not want them to be so, enter a tuple, a constant array (list) a_tuple = (1,3,8) print a_tuple; # can loop through them and treat them the same as a list in most cases for number in a_tuple: print number; teams = ('falcons', 'hawks', 'atl_united', 'silverbacks'); for team in teams: if team == 'hawks': print 'Go Hawks!'; else: print "It's basketball season"; team_a = 'falcons'; print team_a == 'falcons'; # comparison operators have same syntax as JS team_b = 'braves'; condition_1 = team_a == 'falcons'; condition_2 = team_b == 'braves'; if condition_1 and condition_2: print 'Hooray'; # python's version of indexOf is "in" print 'hawks' in teams if team == 'hawks': print 'go hawks'; elif team == 'falcons': print 'sad superbowl'; if 'hawks' in teams: print 'go hawks'; if 'falcons in teams': print 'go falcons'; # message = input("please enter your name"); height = raw_input("in inches, how tall are you?\n"); if(int(height) >= 42): print "you are tall enough to go on the batman rollercoaster"; else: print "maybe try the kiddie coaster"; current = 1; # while (current < 10): # print current; # current += 1; answer = "play" while answer != "quit": answer = raw_input("say quit to stop the game\n");
true
864b676fbc74522541658bec2bc88d3af97b4598
csojinb/6.001_psets
/ps1.3.py
1,208
4.3125
4
import math STARTING_BALANCE = float(raw_input('Please give the starting balance: ')) INTEREST_RATE = float(raw_input('Please give the annual interest' 'rate (decimal): ')) MONTHLY_INTEREST_RATE = INTEREST_RATE/12 balance = STARTING_BALANCE monthly_payment_lower_bound = STARTING_BALANCE/12 monthly_payment_upper_bound = (STARTING_BALANCE * (1 + MONTHLY_INTEREST_RATE)**12)/12 while (monthly_payment_upper_bound - monthly_payment_lower_bound) > 0.01 \ or balance > 0: monthly_payment = (monthly_payment_lower_bound + monthly_payment_upper_bound)/2 balance = STARTING_BALANCE for month in range(1,13): interest = balance * MONTHLY_INTEREST_RATE balance += interest - round(monthly_payment,2) balance = round(balance,2) if balance < 0: break if balance > 0: monthly_payment_lower_bound = monthly_payment else: monthly_payment_upper_bound = monthly_payment print 'Monthly payment to pay off debt in 1 year:', round(monthly_payment,2) print 'Number of months needed: ', month print 'Balance: ', balance
true
ccb1ec3d8b7974b3ad05c38924c2856d2c5f01db
edenuis/Python
/Sorting Algorithms/mergeSortWithO(n)ExtraSpace.py
1,080
4.15625
4
#Merge sort from math import ceil def merge(numbers_1, numbers_2): ptr_1 = 0 ptr_2 = 0 numbers = [] while ptr_1 < len(numbers_1) and ptr_2 < len(numbers_2): if numbers_1[ptr_1] <= numbers_2[ptr_2]: numbers.append(numbers_1[ptr_1]) ptr_1 += 1 else: numbers.append(numbers_2[ptr_2]) ptr_2 += 1 if ptr_1 < len(numbers_1): return numbers + numbers_1[ptr_1:] elif ptr_2 < len(numbers_2): return numbers + numbers_2[ptr_2:] return numbers def mergeSort(numbers): if len(numbers) <= 1: return numbers size = ceil(len(numbers)/2) numbers_1 = mergeSort(numbers[:size]) numbers_2 = mergeSort(numbers[size:]) numbers = merge(numbers_1, numbers_2) return numbers if __name__ == "__main__": assert mergeSort([1,2,3,4,5]) == [1,2,3,4,5] assert mergeSort([5,4,3,2,1]) == [1,2,3,4,5] assert mergeSort([5,2,3,4,4,2,1]) == [1,2,2,3,4,4,5] assert mergeSort([]) == [] assert mergeSort([-1,23,0,123,5,6,4,-12]) == [-12,-1,0,4,5,6,23,123]
true
64fe2ed64c6fe5c801e88f8c1e266538f7d51d40
brodieberger/Control-Statements
/(H) Selection statement that breaks loops.py
345
4.25
4
x = input("Enter string: ") #prompts the user to enter a string y = input("Enter letter to break: ") #Letter that will break the loop for letter in x: if letter == y: break print ('Current Letter:', letter) #prints the string letter by letter until it reaches the letter that breaks the loop. input ("Press Enter to Exit")
true
ed767807eae30530f1d4e121217585aff3bcea75
austBrink/Tutoring
/python/Maria/makedb.py
2,370
4.34375
4
import sqlite3 def main(): # Connect to the database. conn = sqlite3.connect('cities.db') # Get a database cursor. cur = conn.cursor() # Add the Cities table. add_cities_table(cur) # Add rows to the Cities table. add_cities(cur) # Commit the changes. conn.commit() # Display the cities. display_cities(cur) # Close the connection. conn.close() # The add_cities_table adds the Cities table to the database. def add_cities_table(cur): # If the table already exists, drop it. cur.execute('DROP TABLE IF EXISTS Cities') # Create the table. cur.execute('''CREATE TABLE Cities (CityID INTEGER PRIMARY KEY NOT NULL, CityName TEXT, Population REAL)''') # The add_cities function adds 20 rows to the Cities table. def add_cities(cur): cities_pop = [(1,'Tokyo',38001000), (2,'Delhi',25703168), (3,'Shanghai',23740778), (4,'Sao Paulo',21066245), (5,'Mumbai',21042538), (6,'Mexico City',20998543), (7,'Beijing',20383994), (8,'Osaka',20237645), (9,'Cairo',18771769), (10,'New York',18593220), (11,'Dhaka',17598228), (12,'Karachi',16617644), (13,'Buenos Aires',15180176), (14,'Kolkata',14864919), (15,'Istanbul',14163989), (16,'Chongqing',13331579), (17,'Lagos',13122829), (18,'Manila',12946263), (19,'Rio de Janeiro',12902306), (20,'Guangzhou',12458130)] for row in cities_pop: cur.execute('''INSERT INTO Cities (CityID, CityName, Population) VALUES (?, ?, ?)''', (row[0], row[1], row[2])) # The display_cities function displays the contents of # the Cities table. def display_cities(cur): print('Contents of cities.db/Cities table:') cur.execute('SELECT * FROM Cities') results = cur.fetchall() for row in results: print(f'{row[0]:<3}{row[1]:20}{row[2]:,.0f}') # Execute the main function. if __name__ == '__main__': main()
true
bf639aca06615e7a8d84d9322024c17873504c00
austBrink/Tutoring
/python/Sanmi/averageRainfall.py
1,362
4.5
4
# Write a program that uses ( nested loops ) to collect data and calculate the average rainfall over a period of two years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. # review loops NUMBER_OF_YEARS = 2 NUMBER_OF_MONTHS_IN_YEAR = 12 # array / list months = ["Jan","Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # containers or a structure totalRainFall = [] # run a loop for two years.. for i in range(0, NUMBER_OF_YEARS): print(f'DATA FOR YEAR {i + 1}') for j in range(0, NUMBER_OF_MONTHS_IN_YEAR): print(f'Enter the inches of rainfall for {months[j]}') tempRainfallAmount = float(input()) totalRainFall.insert(len(totalRainFall),tempRainfallAmount) totalMonths = NUMBER_OF_YEARS * NUMBER_OF_MONTHS_IN_YEAR print(f'TOTAL NUMBER OF MONTHS: {totalMonths}') rainfallTotal = 0 for n in range(0,len(totalRainFall)): rainfallTotal = rainfallTotal + totalRainFall[n] print(f'THE TOTAL RAINFALL WAS {rainfallTotal}') print(f'THE AVERAGE RAINFALL PER MONTH IS {rainfallTotal / totalMonths}')
true
c25780c144bbff40242092fbbe961a3b5e72c8e4
roshan1966/ParsingTextandHTML
/count_tags.py
862
4.125
4
# Ask the user for file name filename = input("Enter the name of a HTML File: ") def analyze_file(filename): try: with open (filename, "r", encoding="utf8") as txt_file: file_contents = txt_file.read() except FileNotFoundError: print ("Sorry, the file named '" + filename + "' was not found") else: tags = [] openings = file_contents.split('<') for opening in openings: if len(opening) > 1: if opening[0] != '/': opening = opening.split('>')[0] opening = opening.split(' ')[0] tags.append('<' + opening + '>') print ("Number of tags: " + str(len(tags))) for i in range(len(tags)): print (str(i+1) + ". " + str(tags[i])) analyze_file(filename)
true
374c16f971fc2238848a91d94d43293c592e6f03
udaybhaskar8/git-project
/functions/ex4.py
322
4.125
4
import math # Calculate the square root of 16 and stores it in the variable a a =math.sqrt(16) # Calculate 3 to the power of 5 and stores it in the variable b b = 3**5 b=math.pow(3, 5) # Calculate area of circle with radius = 3.0 by making use of the math.pi constant and store it in the variable c c = math.pi * (3**2)
true
9affcfc38a322081ef4afeb658aa97ec03f871ab
mckennec2014/cti110
/P3HW1_ColorMix_ChristianMcKenney.py
975
4.28125
4
# CTI-110 # P3HW1 - Color Mixer # Christian McKenney # 3/17/2020 #Step-1 Enter the first primary color #Step-2 Check if it's valid #Step-3 Enter the second primary color #Step-4 Check if it's valid #Step-5 Check for combinations of colors and display that color # Get user input color1 = input('Enter the first primary color: ') if color1 == "red" or color1 == "blue" or color1 == "yellow": color2 = input('Enter the second primary color: ') if color2 == "red" or color2 == "blue" or color2 == "yellow": if color1 == "red" and color2 == "blue": print('These colors make purple') if color1 == "red" and color2 == "yellow": print('These colors make orange') if color1 == "blue" and color2 == "yellow": print('These colors make green') else: print('Invalid input') else: print('Invalid input')
true
7008005de70aadea1bebd51d8a068272c7f7b6af
mckennec2014/cti110
/P5HW2_MathQuiz _ChristianMcKenney.py
2,012
4.375
4
# This program calculates addition and subtraction with random numbers # 4/30/2020 # CTI-110 P5HW2 - Math Quiz # Christian McKenney #Step-1 Define the main and initialize the loop variable #Step-2 Ask the user to enter a number from the menu #Step-3 If the user enters the number 1, add the random numbers and # display the addition problem #Step-4 If the user enters the number 2, subtract the random numbers and # display the subtraction problem #Step-5 If the user enters 3, terminate the program import random def main(): # The loop variable i = 0 while i != 1: print('\nMAIN MENU\n') print('--------------------') print('1) Add Random Numbers') print('2) Subtract Random Numbers') print('3) Exit\n') # Ask the user to pick which option choice = int(input('Which would you like to do? ')) if choice == 1: addRandom() elif choice == 2: subRandom() elif choice == 3: # The program will terminate print('The program will terminate') i = 1 else: print('Not a valid option') def addRandom(): randomnum1 = random.randrange(1,300) randomnum2 = random.randrange(1,300) answer = randomnum1 + randomnum2 print(' '+str(randomnum1)+'\n+ '+str(randomnum2)) guess = int(input('\nWhat is the answer? ')) if guess == answer: print('Congratulations! you got it correct!') elif guess != answer: print(answer) def subRandom(): randomnum1 = random.randrange(1,300) randomnum2 = random.randrange(1,300) answer = randomnum1 - randomnum2 print(' '+str(randomnum1)+'\n- '+str(randomnum2)) guess = int(input('\nWhat is the answer? ')) if guess == answer: print('Congratulations! you got it correct!') elif guess != answer: print(answer) main()
true
7e3ff4cbf422f91773d66991a05720718ec42bd7
cs112/cs112.github.io
/recitation/rec8.py
1,585
4.1875
4
""" IMPORTANT: Before you start this problem, make sure you fully understand the wordSearch solution given in the course note. Now solve this problem: wordSearchWithIntegerWildCards Here we will modify wordSearch so that we can include positive integers in the board, like so (see board[1][1]): board = [ [ 'p', 'i', 'g' ], [ 's', 2, 'c' ], ] When matching a word, a positive integer on the board matches exactly that many letters in the word. So the board above contains the word "cow" starting from [1,2] heading left, since the 2 matches "ow". It also contains the word "cows" for the same reason. But it does not contain the word "co", since the 2 must match exactly 2 letters. To make this work, of the three functions in our wordSearch solution, the outer two do not have to change, but the innermost one does. Rewrite the innermost function here so that it works as described. Your function should return True if the word is in the wordSearch and False otherwise. """ def wordSearch(board, word): return 42 # place your solution here! def testWordSearch(): print("Testing wordSearch()...", end="") board = [ [ 'p', 'i', 'g' ], [ 's', 2, 'c' ] ] assert(wordSearch(board, "cow") == True) assert(wordSearch(board, "cows") == True) assert(wordSearch(board, "coat") == False) assert(wordSearch(board, "pig") == True) assert(wordSearch(board, "z") == False) assert(wordSearch(board, "zz") == True) print("Passed!") # testWordSearch() # uncomment this line to test!
true
63d2eda6cbc8cbfc8c992828adb506ffd7f5a075
cs112/cs112.github.io
/challenges/challenge_1.py
759
4.15625
4
################################################################################ # Challenge 1: largestDigit # Find the largest digit in an integer ################################################################################ def largestDigit(n): n = abs(n) answer = 0 check =0 while n >0: check = n%10 n //= 10 if check > answer: answer = check return answer def testLargestDigit(): print("Testing largestDigit()...", end="") assert(largestDigit(1) == 1) assert(largestDigit(9233) == 9) assert(largestDigit(187932) == 9) assert(largestDigit(0) == 0) assert(largestDigit(10) == 1) assert(largestDigit(-1) == 1) assert(largestDigit(-236351) == 6) print("Passed!")
true
ac1c189338811d43945c5e96f729085aaffe26d8
Halal-Appnotrix/Problem-Solving
/hackerrank/Problem-Solving/Algorithm/Implementation/Grading_Students.py
783
4.125
4
# # The function is expected to return an INTEGER_ARRAY. # The function accepts INTEGER_ARRAY grades as parameter. # def gradingStudents(grades): grades_array = [] for grade in grades: the_next_multiple_of_5 = (((grade // 5)+1)*5) if grade < 38: grades_array.append(grade) elif (the_next_multiple_of_5 - grade) < 3: grades_array.append(the_next_multiple_of_5) else: grades_array.append(grade) return grades_array if __name__ == '__main__': grades_count = int(input().strip()) grades = [] for _ in range(grades_count): grades_item = int(input().strip()) grades.append(grades_item) result = gradingStudents(grades) print('\n'.join(map(str, result)))
true
b57b87613722928d3011f9bba5325e962765a403
matsalyshenkopavel/codewars_solutions
/Stop_gninnipS_My_sdroW!.py
833
4.125
4
"""Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (like the name of this kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.""" def spin_words(sentence): sentence_list = sentence.split() sentence_list = [x[::-1] if len(x) >= 5 else x for x in sentence_list] return " ".join(sentence_list) # spinWords("Hey fellow warriors") => "Hey wollef sroirraw" # spinWords("This is a test") => "This is a test" # spinWords("This is another test") => "This is rehtona test" print(spin_words("Hey fellow warriors")) #"Hey wollef sroirraw" print(spin_words("This is a test")) #"This is a test" print(spin_words("This is another test")) #"This is rehtona test"
true
e9183dc00682ac9e38bc8f01fd49f4b5f3c9fa37
Isha09/mit-intro-to-cs-python
/edx/week1/prob1.py
552
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 6 14:52:43 2017 @author: esha Prog: Assume s is a string of lower case characters. Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'. For example, if s = 'azcbobobegghakl', your program should print: Number of vowels: 5 """ s = str(input("Enter any string:")) count = 0 for ch in s: if(ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u'): count += 1 print('Number of vowels:',count)
true
90fd58a60095a888058eb7788255886b6870056a
david778/python
/Point.py
1,233
4.4375
4
import math class Point(object): """Represents a point in two-dimensional geometric coordinates""" def __init__(self, x=0.0, y=0.0): """Initialize the position of a new point. The x and y coordinates can be specified. If they are not, the point defaults to the origin.""" self.move(x, y) def move(self, x, y): """Move the point to a new location in two-dimensional space.""" self.x = x self.y = y def reset(self): """Reset the point back to the geometric origin: 0, 0 """ self.move(0.0, 0.0) def calculate_distance(self, other_point): """Calculate the distance from this point to a second point passed as a parameter. This function uses the pythagorean theorem to calculate the distance between the two points. The distance is returned as float.""" return math.sqrt((self.x - other_point.x) ** 2 + (self.y - other_point.y) ** 2) # Creating instance objects point_a = Point(2, -2) point_b = Point(2, 2) point_x = Point(0, 0) point_y = Point(7, 1) # distance entry a and b distance_a = point_a.calculate_distance(point_b) distance_b = point_x.calculate_distance(point_y) print(distance_a) print(distance_b)
true
47c580cf46d2c83ebf1ca05601c7f4c05ea4d913
nitred/nr-common
/examples/mproc_example/mproc_async.py
1,442
4.15625
4
"""Simple example to use an async multiprocessing function.""" from common_python.mproc import mproc_async, mproc_func # STEP - 1 # Define a function that is supposed to simulate a computationally intensive function. # Add the `mproc_func` decorator to it in order to make it mproc compatible. @mproc_func def get_square(x): """Return square of a number after sleeping for a random time.""" import random import time time.sleep(random.random()) return x**2 # STEP - 2 # Create a list of list of argument for the `get_square` function. # The length of the outer list determines the number of times the function is going to be called asynchronously. # In this example, the length is 20. The final `iterof_iterof_args` will look like [[0], [1], [2] ...] iterof_iterof_args = [[i] for i in range(20)] # STEP -3 # Call the function 20 times using multiprocessing. # We limit the number of processes to be 4 and at any time there will be a max of 4 results. # The output is a generator of results. results_gen = mproc_async(get_square, iterof_iterof_args=iterof_iterof_args, n_processes=4, queue_size=4) # STEP - 4 # Print the results. # Each result looks like a tuple of (original_index, function_output) for async_index, result in enumerate(results_gen): call_index, func_output = result print(async_index, call_index, func_output)
true
d6fb8c780bc46b577df3beb95265bf6addd4d2e1
ronBP95/insertion_sort
/app.py
690
4.21875
4
def insertion_sort(arr): operations = 0 for i in range(len(arr)): num_we_are_on = arr[i] j = i - 1 # do a check to see that we don't go out of range while j >= 0 and arr[j] > num_we_are_on: operations += 1 # this check will be good, because we won't check arr[-1] # how can i scoot arr[j] up a place in our list arr[j+1] = arr[j] j -= 1 # where am i j += 1 arr[j] = num_we_are_on # ordered array return arr, operations test_arr = [3, 4, 5, 8, 2, 1, 4] ordered_array, operations = insertion_sort(test_arr) print(ordered_array, operations)
true
7314f15c59cd41a095c2d6c9e12e824ff23f9dad
davidalanb/PA_home
/Py/dicts.py
1,188
4.4375
4
# make an empty dict # use curly braces to distinguish from standard list words = {} # add an item to words words[ 'python' ] = "A scary snake" # print the whole thing print( words ) # print one item by key print( words[ 'python' ] ) # define another dict words2 = { 'dictionary': 'a heavy book', \ 'class': 'a group of students' } # add all keys/items in words2 to words words.update( words2 ) # add another key/item words.update( { 'object': 'something'} ) #change a definition words.update( { 'class': 'an echelon of society'} ) print( words ) # iterate with keys, 2 ways: #for key in words.keys(): for key in words: print( key, end='; ' ) print() # iterate with values for value in words.values(): print( value, end='; ' ) print() # iterate with keys and values for key, value in words.items(): print( key, ':', value, end='; ' ) print() try: print( words[ 'key' ] ) except Exception as e: print( type(e) ) key = 'nasef' # ask for permission if key in words: print( words[ key ] ) else: print( 'key', key, 'not found' ) # ask for forgiveness try: print( words[ key ] ) except KeyError: print( 'key',key,'not found' )
true
f8f481911c4d3d8b79082899528af93978e92957
amitjpatil23/simplePythonProgram
/Atharva_35.py
620
4.25
4
# Simple program in python for checking for armstrong number # Python program to check if the number is an Armstrong number or not y='y' while y == 'y': # while loop # take input from the user x = int(input("Enter a number: ")) sum = 0 temp = x while temp > 0: #loop for checking armstrong number digit = temp % 10 sum += digit ** 3 temp //= 10 if x == sum: print(x,"is an Armstrong number") else: print(x,"is not an Armstrong number") y=input("WNamt to continue?(y/n)") #Condition for multiple run
true
0c8893cdaadd507fb071816a92dd52f2c8955d65
amitjpatil23/simplePythonProgram
/palindrome_and_armstrong_check.py
630
4.21875
4
def palindrome(inp): if inp==inp[::-1]: #reverse the string and check print("Yes, {} is palindrome ".format(inp)) else: print("No, {} is not palindrome ".format(inp)) def armstrong(number): num=number length=len(str(num)) total=0 while num>0: temp=num%10 total=total+(temp**length) #powering each digit with length of number and adding num=num//10 if total==number: print("{} is Armstrong number".format(number) ) else: print("{} is not an Armstrong number".format(number) ) palindrome('qwerewq') armstrong(407)
true
a26e88d420464e4c075984303274738ce61db468
SongYippee/leetcode
/LinkedList/86 分片链表.py
1,529
4.15625
4
# -*- coding: utf-8 -*- # @Time : 1/14/20 10:17 PM # @Author : Yippee Song # @Software: PyCharm ''' Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. Example: Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5 ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ first = None firstTmp = None second = None secondTmp = None tmp = head while tmp: nextNode = tmp.next if tmp.val < x: if not first: first = tmp firstTmp = first else: firstTmp.next = tmp firstTmp = firstTmp.next tmp.next = None else: if not second: second = tmp secondTmp = tmp else: secondTmp.next = tmp secondTmp = secondTmp.next tmp.next = None tmp = nextNode if firstTmp: firstTmp.next = second return first else: return second
true
04a19b417325d45e3b776f200eed3d80042a2159
uran001/Small_Projects
/Hot_Potato_Game/hot_potato_classic.py
1,236
4.125
4
# Note the import of the Queue class from queue import ArrayQueue def hot_potato(name_list, num): """ Hot potato simulator. While simulating, the name of the players eliminated should also be printed (Note: you can print more information to see the game unfolding, for instance the list of players to whom the hot potato is passed at each step...) :param name_list: a list containing the name of the players, e.g. ["John", "James", "Alice"] :param num: the counting constant (i.e., the length of each round of the game) :return: the winner (that is, the last player standing after everybody else is eliminated) """ print("Game is started with players") r = 1 n = 0 while 1: if len(name_list) == 1: return name_list[0] print ("Round {0}".format(r)) print(name_list) for x in range(len(name_list)): n += 1 if n % num == 0: print(name_list[x]) name_list.remove(name_list[x]) r += 1 if __name__ == '__main__': name_list = ["Marco", "John", "Hoang", "Minji", "Hyunsuk", "Jiwoo"] winner = hot_potato(name_list, 5) print("...and the winner is: {0}".format(winner))
true
474cc9eb3ba257339e9b726479cfa10f03c14e29
rbarrette1/Data-Structures
/LinkedList/LinkedList.py
2,055
4.21875
4
from Node import * # import Node class head = "null" # first node of the linked list class LinkedList(): def __init__(self): self.head = None # set to None for the time being # insert after a specific index def insert_after_index(self, index, new_node): node = self.head # get the first node for i in range(index): # loop through by accessing the next node node = node.next # move to the next node if(i == index-1): # if at the desired index new_node.next = node.next # set the next node of the new node to the node currently in its' place node.next = new_node # set the next node of the node currently in its' place with the new node # remove from a particular index def remove_after_index(self, index): print("Removing after index: " + str(index)) node = self.head if(index == 0): # if removing the first node self.head = node.next # set head to the next node for i in range(index): node_before = node # save previous node and current node to connect both node = node.next if(i == index-1): # when at the desired index print("Connecting nodes: " + str(node_before.value) + " and " + str(node.next.value)) # connect the next node of the previous node with the next node of the current to delete the current node node_before.next = node.next # travel to a specific index def traverse_to_node(self, index): print("Traversing to: " + str(index)) node = self.head # get the first node for i in range(index): # stop at index node = node.next # move to the next node # travel to the end of the linked list def traverse_through_linkedlist(self): print("Traversing...") node = self.head # get the first node while node is not None: # while the next node exists print(node.value) node = node.next # move to the next node
true
642410d99d761e9565cd2829893d08bf901e7c7b
Johnscar44/code
/python/notes/elif.py
331
4.125
4
secret_num = "2" guess = input("guess the number 1 - 3: ") if guess.isdigit() == False: print("answer can only be a digit") elif guess == "1": print("Too Low") elif guess == "2": print("You guessed it!") elif guess == "3": print("Too high") else: print("Guess not in rage 1 - 3") print("please try again")
true
a2b2da73552e61cc2a3fbae380186374984d0b0f
Johnscar44/code
/compsci/moon.py
1,207
4.1875
4
phase = "Full" distance = 228000 date = 28 eclipse = True # - Super Moon: the full moon occurs when the moon is at its closest approach to earth (less than 230,000km away). # - Blue Moon: the second full moon in a calendar month. In other words, any full moon on the 29th, 30th, or 31st of a month. # - Blood Moon: a lunar eclipse during a full moon. if phase == "Full" and distance < 230000 and date >= 29 and eclipse == True: print("Super Blue Blood Moon") elif phase == "Full" and date <= 28 and distance < 230000 and eclipse == True: print("Super Blood Moon") elif phase == "Full" and date >= 29 and eclipse == True: print("Blue Blood Moon") elif phase == "Full" and distance < 230000 and date >= 29 and eclipse == False: print("Super Blue Moon") elif phase == "Full" and distance < 230000 and date <= 29 and eclipse == False: print("Super Moon") elif phase == "Full" and distance > 230000 and date <= 29 and eclipse == False: print("Full Moon") elif phase == "Full" and distance > 230000 and date <= 29 and eclipse == True: print("Blood Moon") elif phase == "Full" and distance > 230000 and date >= 29 and eclipse == False: print("Blue Moon") else: print("Moon")
true
6d2ddc65b018e810f4e4e6dc4424cc6025853faa
Johnscar44/code
/compsci/newloop.py
562
4.375
4
mystery_int_1 = 3 mystery_int_2 = 4 mystery_int_3 = 5 #Above are three values. Run a while loop until all three #values are less than or equal to 0. Every time you change #the value of the three variables, print out their new values #all on the same line, separated by single spaces. For #example, if their values were 3, 4, and 5 respectively, your #code would print: #2 3 4 #1 2 3 #0 1 2 #-1 0 1 #-2 -1 0 while mystery_int_1 > 0 and mystery_int_2 > 0 and mystery_int_3 > 0: mystery_int_1 -= 1 print(mystery_int_1 , mystery_int_2 , mystery_int_3)
true
570a915a233eee00cc23b34d7ce3cf2c78940d75
Johnscar44/code
/compsci/forloop.py
957
4.71875
5
#In the designated areas below, write the three for loops #that are described. Do not change the print statements that #are currently there. print("First loop:") for i in range(1 , 11): print(i) #Write a loop here that prints the numbers from 1 to 10, #inclusive (meaning that it prints both 1 and 10, and all #the numbers in between). Print each number on a separate #line. for i in range(-5 , 6): print("Second loop:") #Write a loop here that prints the numbers from -5 to 5, #inclusive. Print each number on a separate line. for i in range(1 , 21): if i % 2 == 0: print("Third loop:" , i) #Write a loop here that prints the even numbers only from 1 #to 20, inclusive. Print each number on a separate line. # #Hint: There are two ways to do this. You can use the syntax #for the range() function shown in the multiple-choice #problem above, or you can use a conditional with a modulus #operator to determine whether or not to print.
true
691d922adfbb58996dabc180a1073ef06afa000a
choprahetarth/AlgorithmsHackerRank01
/Python Hackerrank/oops3.py
827
4.25
4
# Credits - https://www.youtube.com/watch?v=JeznW_7DlB0&ab_channel=TechWithTim # class instantiate class dog: def __init__(self,name,age): self.referal = name self.age = age # getter methods are used to print # the data present def get_name(self): return self.referal def get_age(self): return self.age # these setter functions are # added to modify the existing # data, that is stored there def set_age(self,age): self.age=age def set_name(self,name): self.referal = name d1 = dog("Snoop", 46) d2 = dog("Dre", 48) # print existing data print(d1.get_age()) print(d1.get_name()) # modify data using getter methods d1.set_age(52) d1.set_name("Eminem") # print the modified data print(d1.get_age()) print(d1.get_name())
true
5960a9e747851838f2823ab0b3b5027275d12b97
choprahetarth/AlgorithmsHackerRank01
/Old Practice/linkedList.py
1,093
4.46875
4
# A simple python implementation of linked lists # Node Class class Node: # add an init function to start itself def __init__(self,data): self.data = data self.next = None # initialize the linked list with null pointer # Linked List Class class linkedList: # add an init function to initialize the head def __init__(self): self.head = None # initialize the head of the LL # function that traverses the linked list def traverse(headValue): while(headValue!=None): print(headValue.data) headValue=headValue.next # main function if __name__ == '__main__': # pehle initialize the linked list linked_List = linkedList() # then assign the first node to the head value linked_List.head = Node(1) # then make two more nodes second = Node(2) third = Node(3) # then link the head's next value with the second node linked_List.head.next = second # then link the next of the second node with the third second.next = third # function to traverse a linked list traverse(linked_List.head)
true
b499e6ecc7e711bf74441b89fec4fcc49712b4a3
Mohini-2002/Python-lab
/Method(center,capitalize,count,encode,decode)/main.py
702
4.28125
4
#Capitalize (capital the first of a string and its type print) ST1 = input("Enter a string :") ST1 = ST1.capitalize() print("After capitalize use : ", ST1, type(ST1)) #Center (fill the free space of a string and and its type print) ST2 = input("ENter a string :") ST2 = ST2.center(20, "#") print("After center use :", ST2, type(ST2)) #Count (Count the st occurs in string and its type print) ST3 = input("Enter a string :") ST3 = ST3.count('O', 1, 10) print(ST3, type(ST3)) #Encode ST4 = input("Enter a string : ") ST4 = ST4.encode("utf-8") print(ST4, type(ST4)) #Decode ST5 = input("Enter a string :") ST5 = ST5.decode(encoding="UTF-8", erros='strict') print(ST5, type(ST5))
true
718d8989750b21513fff2c0eea78016432b90a4d
asimihsan/challenges
/epi/ch12/dictionary_word_hash.py
2,509
4.15625
4
#!/usr/bin/env python # EPI Q12.1: design a hash function that is suitable for words in a # dictionary. # # Let's assume all words are lower-case. Note that all the ASCII # character codes are adjacent, and yet we want a function that # uniformly distributes over the space of a 32 bit signed integer. # # We can't simply use a cryptographic hash function because these are # unacceptably slow. We could use CRC32, and it might be decent, but # what is more intuitive? import operator import string class DictionaryWord(object): __slots__ = ('value', 'primes') primes = {'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 'g': 17, 'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37, 'm': 41, 'n': 43, 'o': 47, 'p': 53, 'q': 59, 'r': 61, 's': 67, 't': 71, 'u': 73, 'v': 79, 'w': 83, 'x': 89, 'y': 97, 'z': 101} def __init__(self, value): self.value = value def __hash__(self): """A hash function must be consistent with equals (any two objects which are equal must have the same hash code). A hash function should ideally uniformly distribute its output as a signed integer; Python chops off the sign bit and does the modulus into the dictionary for us. """ # With Douglas Adams on our side this takes longer than a # minute. Ouch! #return 42 # I know summing the chars is bad, but how bad? 19s! #return sum(ord(x) for x in self.value) # How about assigning a prime number per letter, then returning # the product? Takes 3.5s. #return reduce(operator.mul, (self.primes[x] for x in self.value)) # What about the product of chars? 3.4s! Better than primes! #return reduce(operator.mul, (ord(x) for x in self.value)) # How about a Java hashCode approach? Sum chars but mult # by Mersenne prime each time. 3.0s! # Likely better because more peturbation on single char # changes. result = 17 for x in self.value: result = 31 * result + ord(x) return result # With the system default it takes 2.2s #return hash(self.value) if __name__ == "__main__": lookup = set() with open("/usr/share/dict/words") as f_in: lines = (line.strip() for line in f_in if all(elem in string.ascii_lowercase for elem in line.strip())) for line in lines: lookup.add(DictionaryWord(line))
true
70e759634d967837b0faed377ced9807c4a604f8
xct/aoc2019
/day1.py
920
4.125
4
#!/usr/bin/env python3 ''' https://adventofcode.com/2019/day/1 Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. ''' data = [] with open('data/day1.txt','r') as f: data = f.readlines() # Part 1 (Fuel for the base mass) sum1 = 0 for mass in data: mass = int(mass) fuel = mass//3 - 2 sum1 += fuel print(f'Sum = {sum1}') # That's the right answer! You are one gold star closer to rescuing Santa. # Part 2 (Fuel for the fuel) def get_fuel(mass): fuel_sum = 0 remaining_mass = mass while True: fuel = remaining_mass//3 - 2 if fuel <= 0: break fuel_sum += fuel remaining_mass = fuel return fuel_sum sum2 = 0 for mass in data: mass = int(mass) fuel = get_fuel(mass) sum2 += fuel print(f'Sum = {sum2}')
true
3f26a0de9a124b493c1dc5734a2f9e9d30ef6114
vaishalibhayani/Python_example
/Python_Datatypes/sequence_types/dictionary/dictionary1.py
516
4.28125
4
emp={ 'course_name':'python', 'course_duration':'3 Months', 'course_sir':'brijesh' } print(emp) print(type(emp)) emp1={1:"vaishali",2:"dhaval",3:"sunil"} print(emp1) print(type(emp1)) #access value using key print("first name inside of the dictionary:" +emp1[2]) #access value using key print("first name inside the dictionary:" +emp1[3]) ## fetch or show only keys of dictionary print(emp1.keys()) # fetch or show only Value of dictionary print(emp1.values())
true
52c255ca2ffcc9b42da2427997bcfa6b539127d2
NaveenSingh4u/python-learning
/basic/python-oops/python-other-concept/generator-ex4.py
1,121
4.21875
4
# Generators are useful in # 1. To implement countdown # 2. To generate first n number # 3. To generate fibonacci series import random import time def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b for n in fib(): if n > 1000: break print(n) names = ['sunny', 'bunny', 'chinmayee', 'vinny'] subjects = ['Python', 'Java', 'Blockchain'] def people_list(num): results = [] for i in range(num): person = { 'id': i, 'name': random.choice(names), 'subject': random.choice(subjects) } results.append(person) return results def generate_people_list(num): for i in range(num): person = { 'id': i, 'name': random.choice(names), 'subject': random.choice(subjects) } yield person # See the performance difference between both approach. t1 = time.clock() people = people_list(10000) t2 = time.clock() print('Time taken : ', t2 - t1) t1 = time.clock() people = generate_people_list(10000) t2 = time.clock() print('Time taken : ', t2 - t1)
true
bbb15cfc351270d4c09f884ac0e9debb4804aae5
NaveenSingh4u/python-learning
/basic/python-oops/book.py
920
4.125
4
class Book: def __init__(self, pages): self.pages = pages def __str__(self): return 'The number of pages: ' + str(self.pages) def __add__(self, other): total = self.pages + other.pages b = Book(total) return b def __sub__(self, other): total = self.pages - other.pages b = Book(total) return b def __mul__(self, other): total = self.pages * other.pages b = Book(total) return b b1 = Book(100) b2 = Book(200) b3 = Book(700) print('Add') print(b1 + b2) print(b1 + b3) print('Sub') print(b1 - b2) print('Mul') print(b1 * b2) # Note : 1.whenever we are calling + operator then __add__() method will be called. # 2. Whenever we're printing Book object reference then __str__() method will be called. print("Printing multiple add ..") print(b1 + b2 + b3) print(" add with multiple") print(b1 * b2 + b2 * b3)
true
c1a3ee82f1c10cc499283df4e4e95f00df71dc1b
Dhanshree-Sonar/Interview-Practice
/Guessing_game.py
808
4.3125
4
##Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, ##then tell them whether they guessed too low, too high, or exactly right. # Used random module to generate random number import random def guessing_game(): while True: num = 0 while num not in range(1,10): num = input('Enter number between 1 to 9:') game_num = random.randint(1,9) print 'Your Number: ' + str(num) print 'Generated Number: ' + str(game_num) if num == game_num: return 'Congrats!! You guessed it right...' elif abs(num - game_num) <= 2: return 'You were so close!' elif abs(num - game_num) >= 3: return 'You were not close!' result = guessing_game() print result
true
226843bbc68bab71fbe2cfb3416925baa898a273
simplex06/clarusway-aws-devops
/ozkan-aws-devops/python/coding-challenges/cc-003-find-the-largest-number/largest_number.py
270
4.25
4
# The largest Number of a list with 5 elements. lst = list() for i in range(5): lst.append(int(input("Enter a number: "))) largest_number = lst[0] for j in lst: if j > largest_number: largest_number = j print("The largest number: ", largest_number)
true
b86d5d0f2b570cfad3678ce341c44af297399e32
N-eeraj/perfect_plan_b
/armstrong.py
343
4.15625
4
import read num = str(read.Read(int, 'a number')) sum = 0 #variable to add sum of numbers for digit in num: sum += int(digit) ** len(num) #calculating sum of number raised to length of number if sum == int(num): print(num, 'is an amstrong number') #printing true case else : print(num, 'is not an amstrong number') #printing false case
true
4b20faae3875ba3a2164f691a4a32e61ca944a27
harishassan85/python-assignment-
/assignment3/question2.py
226
4.21875
4
# Write a program to check if there is any numeric value in list using for loop mylist = ['1', 'Sheraz', '2', 'Arain', '3', '4'] for item in mylist: mynewlist = [s for s in mylist if s.isdigit()] print(mynewlist)
true
07669066a5ce7a1561da978fc173c710f3ec7e3a
neonblueflame/upitdc-python
/homeworks/day2_business.py
1,836
4.21875
4
""" Programming in Business. Mark, a businessman, would like to purchase commodities necessary for his own sari-sari store. He would like to determine what commodity is the cheapest one for each type of products. You will help Mark by creating a program that processes a list of 5 strings. The format will be the name of the commodity plus its price (<name>-<price>). Author: Sheena Dale Mariano Date created: 20190830 """ commodities = [ "Sensodyne-100, Close Up-150, Colgate-135", "Safeguard-80, Protex-50, Kojic-135", "Surf-280, Ariel-350, Tide-635", "Clover-60, Piatos-20, Chippy-35", "Jelly bean-60, Hany-20, Starr-35" ] def get_price(commodity): return int(commodity.split("-")[1]) def get_cheapest(commodities): cheapest = commodities[1] cheapest_price = get_price(commodities[1]) for item in commodities: price = get_price(item) if price <= cheapest_price: cheapest_price = price cheapest = item return cheapest, cheapest_price def get_cheapest_commodities(commodities): commodity_arr = [] for commodity in commodities: commodity_arr.append(commodity) items_arr = [] for commodity in commodity_arr: items_arr.append(commodity.split(", ")) total_price = 0 cheapest_commodities = [] for items in items_arr: cheapest_item, cheapest_price = get_cheapest(items) total_price += int(cheapest_price) cheapest_commodities.append(cheapest_item) return total_price, cheapest_commodities ############################################################ for commodity in commodities: print(commodity) print() total, cheapest = get_cheapest_commodities(commodities) print(f"Cheapest: { ', '.join(cheapest) }") print(f"Total: { total }")
true
cdc3ed9862e362dc21b899ef3b059a6a9889d6ee
RobSullivan/cookbook-recipes
/iterating_in_reverse.py
938
4.53125
5
# -*- coding: utf-8 -*- """ This is a quote from the book: Reversed iteration only works if the object in question has a size that can be determined or if the object implements a __reversed__() special method. If neither of these can be satisfied, you’ll have to convert the object into a list first. Be aware that turning an iterable into a list could consume a lot of memory if it’s large. Defining a reversed iterator makes the code much more efficient, as it’s no longer necessary to pull the data into a list and iterate in reverse on the list. """ class Countdown: def __init__(self, start): self.start = start #Forward iterator def __iter__(self): n = self.start while n > 0: yield n n -= 1 #Reverse iterator def __reversed__(self): n = 1 while n <= self.start: yield n n += 1 if __name__ == '__main__': c = Countdown(5) for n in reversed(c): print(n)
true
b4ff9851641f8baea2c54f7dd16f206db16827de
isachard/console_text
/web.py
1,633
4.34375
4
"""Make a program that takes a user inputed website and turn it into console text. Like if they were to take a blog post what would show up is the text on the post Differents Links examples: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world https://www.stereogum.com/2025831/frou-frou-reuniting-for-2019-tour/tour-dates/ https://medium.freecodecamp.org/dynamic-class-definition-in-python-3e6f7d20a381 """ from scrapy import simple_get from bs4 import BeautifulSoup # Summary of the script: # Basically, takes the url from the user # checks if the url is valid (OK 200 response) # then with the help of beautifulsoup library transform the url to a pretify html ready to extract specific content # Because depending on the class, id and naming the content of the post may vary # I provide a couple of examples and a simple method that checks commoms naming for the post content # After finding the correct the specific tag the library will extract only the text wiht the '.text' call if __name__ == '__main__': def check_content_div(html): if html.find(class_= "post_body"): return html.find(class_= "post_body").text if html.find(class_= "section-content"): return html.find(class_= "section-content").text if html.find(class_= "article-content clearfix"): return html.find(class_= "article-content clearfix").text url = input("Hello user enter your BlogPost: ") raw_html = simple_get(url) html = BeautifulSoup(raw_html, 'html.parser') content = check_content_div(html) print("\n" + content + "\n")
true
d89df8cc1bffb63dd1f867650b54c55e141602ed
yuch7/CSC384-Artificial-Intelligence
/display_nonogram.py
2,535
4.125
4
from tkinter import Tk, Canvas def create_board_canvas(board): """ Create a Tkinter Canvas for displaying a Nogogram solution. Return an instance of Tk filled as a grid. board: list of lists of {0, 1} """ canvas = Tk() LARGER_SIZE = 600 # dynamically set the size of each square based on cols and rows n_columns = len(board[0]) n_rows = len(board) divide = max(n_columns, n_rows) max_size = LARGER_SIZE / divide canvas_width = max_size * n_columns canvas_height = max_size * n_rows # create the intiial canvas with rows and columns grid canvas.canvas = Canvas( canvas, width=canvas_width, height=canvas_height, borderwidth=0, highlightthickness=0) canvas.title("Nonogram Display") canvas.canvas.pack(side="top", fill="both", expand="true") canvas.rows = len(board) canvas.columns = len(board[0]) canvas.cell_width = max_size canvas.cell_height = max_size canvas.rect = {} canvas.oval = {} insert_canvas_grid(canvas, board) return canvas def insert_canvas_grid(canvas, board): """ Insert black and white squares onto a canvas depending on the values inside of the board. A value of 1 corresponds to a black square, while a value of 0 corresponds to a white squre. canvas: Tk object board: list of lists of {0, 1} """ # generate the visual board by iterating over board for column in range(len(board[0])): for row in range(len(board)): x1 = column * canvas.cell_width y1 = row * canvas.cell_height x2 = x1 + canvas.cell_width y2 = y1 + canvas.cell_height # set the tile to black if it's a solution tile if board[row][column] == 1: canvas.rect[row, column] = canvas.canvas.create_rectangle( x1, y1, x2, y2, fill="black") else: canvas.rect[row, column] = canvas.canvas.create_rectangle( x1, y1, x2, y2, fill="white") def display_board(board): """ Takes in a final nonogram board, and creates the visual representation of the board using NonogramDisplay. A value of one inside of our nonogram representation means that the associated tile is colored. board: a list of lists (each list is a row) example: >>> display_board([[0, 1, 0], [1, 1, 0], [1, 0, 0]]) """ app = create_board_canvas(board) app.mainloop()
true
9d7c458469e1303571f12dfa15fa71133c5d2355
suterm0/Assignment9
/Assignment10.py
1,439
4.34375
4
# Michael Suter # Assignment 9 & 10 - checking to see if a string is the same reversable # 3/31/20 def choice(): answer = int(input("1 to check for a palindrome, 2 to exit!>")) while answer != 1 and 2: choice() if answer == 1: punc_string = input("enter your string>") return punc_string else: if answer == 2: exit() def punctuation_check(punc_string): string = '' if not punc_string.isalpha(): for char in punc_string: if char.isalpha(): string += char print(string) return string else: string = punc_string return string def palindrome_check(string): string = string.lower() length = int(len(string)) # gets the number of characters in the string if length == 0 or length == 1: return print("This is a palindrome,", True) elif string[0] != string[-1]: # if first [0] and last letter [`]are not the same then its not a palindrome return print("This is not a palindrome,", False) else: return palindrome_check(string[1:-1]) # You need to get the input from the user in a loop so it can happen multiple times print("Type your word to see if it is a palindrome") punctuations = ''' !/?@#$;,()-[]{}<>./%^:'"&*_~ ''' # Your punctuation check returns a value i = choice() value = punctuation_check(i) result = palindrome_check(value) print(result)
true
3c3bbefb54ddf8e30798a9115ba4de97aca0d396
chng3/Python_work
/第四章练习题/4-12.py
719
4.46875
4
#4-10 my_foods = ['pizza', 'falafel', 'carrot cake', 'chocolate'] print("The first three items in the list are:") print(my_foods[:3]) print("Three items from the middle of the list are:") print(my_foods[1:3]) print("The last items in the list are:") print(my_foods[-3:]) #4-11 你的披萨和我的披萨 pizzas = ['tomato', 'banana', 'apple'] friend_pizzas = pizzas[:] pizzas.append('hotdog') friend_pizzas.append('pineapple') print("My favorite pizzas are:") for pizza in pizzas[:]: print(pizza) print("My friend's favorite pizzas are:") for friend_pizza in friend_pizzas[:]: print(friend_pizza) #4-12 foods = ['pizza', 'falafel', 'carrot cake', 'ice cream'] for food in foods[:]: print(food)
true
86e74e6b83be3976ba48f90728a50334811df18a
cycho04/python-automation
/game-inventory.py
1,879
4.3125
4
# You are creating a fantasy video game. # The data structure to model the player’s inventory will be a dictionary where the keys are string values # describing the item in the inventory and the value is an integer value detailing how many of that item the player has. # For example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} # means the player has 1 rope, 6 torches, 42 gold coins, and so on. # Write a function named displayInventory() that would take any possible “inventory” and display it like the following: # Inventory: # 12 arrow # 42 gold coin # 1 rope # 6 torch # 1 dagger # Total number of items: 62 #then.. # Imagine that a vanquished dragon’s loot is represented as a list of strings like this: # dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] # Write a function named addToInventory(inventory, addedItems), where the inventory parameter # is a dictionary representing the player’s inventory (like in the previous project) # and the addedItems parameter is a list like dragonLoot. The addToInventory() function # should return a dictionary that represents the updated inventory. # Note that the addedItems list can contain multiples of the same item. stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def displayInventory(inventory): print('Inventory: ') item_count = 0 for k, v in inventory.items(): item_count += int(v) print(v, k) print('Total number of items:', item_count) def addToInventory(inventory, addedItems): for i in addedItems: if i in inventory: inventory[i] += 1 else: inventory[i] = 1 return inventory modified = addToInventory(stuff, dragonLoot) displayInventory(modified)
true
70a3ee1c969065898bdb77d2aa0b8004a0364fbf
rajmohanram/PyLearn
/003_Conditional_Loop/06_for_loop_dict.py
582
4.5
4
# let's look at an examples of for loop # - using a dictionary # define an interfaces dictionary - items: interface names interface = {'name': 'GigabitEthernet0/2', 'mode': 'trunk', 'vlan': [10, 20, 30], 'portfast_enabled': False} # let's check the items() method for dictionary interface_items = interface.items() print("Dictionary items:", interface_items) print("\t---> items() method produce Tuples in a list") # loop through items in the list print("\n---> Iterating through dictionary...") for key, value in interface.items(): print("key:", key, " - value:", value)
true
0cd762b867fbd84b8319eeb89b10c0fcb73675ef
rajmohanram/PyLearn
/004-Functions/01_function_intro.py
758
4.46875
4
""" Functions: - Allows reuse of code - To create modular program - DRY - Don't Repeat Yourselves """ # def: keyword to define a function # hello_func(): name of the function - Prints a string when called # () - used to get the parameters: No parameters / arguments used in this function def hello_func(): print("Hello World!, Welcome to Python function") # hello_func_return(): name of the function - Returns a string when called def hello_func_return(): welcome = "Hello World! Welcome to PYTHON FUNCTION" return welcome # main program if __name__ == "__main__": # call the function by its name hello_func() # get a value returned from a function & print it greeting = hello_func_return() print(greeting)
true
d8d9a875d2a71f214c7041c2df0b0fcf298e4c8b
jda5/scratch-neural-network
/activation.py
2,158
4.21875
4
import numpy as np class ReLU: def __init__(self): self.next = None self.prev = None def forward(self, inputs): """ Implements Rectified Linear Unit (ReLU) function - all input values less than zero are replaced with zero. Finally it sets two new attributes: (1) the inputs being passed to the activation function - so that this can be referenced later during backpropagation; (2) the output of the layer - so that this can be passed on to the following layer. :param inputs: the values being passed to the activation function from the associated layer """ output = np.maximum(0, inputs) setattr(self, 'output', output) setattr(self, 'inputs', inputs) def backward(self, dvalues): """ The derivative of the ReLU function with respect to its inputs are zero if the input is less than zero. Since we are modifying the dvalues variable inplace, it's best to make a copy of them. :param dvalues: The derivatives received from the proceeding layer :return: """ dinputs = dvalues.copy() dinputs[self.inputs < 0] = 0 setattr(self, 'dinputs', dinputs) class Softmax: def forward(self, inputs): """ First the function exponentiates each value. However, it subtracts the largest of the inputs (row-wise) before doing the exponentiation to avoid the NaN trap. This creates un-normalized probabilities. Then we normalize these probabilities by dividing by the sum of the rows. Finally the output and input values are saves so that they can be referenced during backpropagation. :param inputs: the values being passed to the activation function from the associated layer """ exp_values = np.exp(inputs - np.max(inputs, axis=1, keepdims=True)) output = exp_values / np.sum(exp_values, axis=1, keepdims=True) setattr(self, 'output', output) setattr(self, 'inputs', inputs) # No need for a backwards function as this will be handled by the combined Softmax and Categorical Cross Entropy class
true
594edacffdac059e2f6b34a514d402659b9ed4a1
leon-lei/learning-materials
/binary-search/recursive_binary_search.py
929
4.1875
4
# Returns index of x in arr if present, else -1 def binarySearch(arr, left, right, x): # Check base case if right >= left: mid = int(left + (right - left)/2) # If element is present at the middle itself if arr[mid] == x: return mid # If element is smaller than mid, then it can only # be present in left subarray elif arr[mid] > x: return binarySearch(arr, left, mid-1, x) # Else the element can only be present in right subarray else: return binarySearch(arr, mid+1, right, x) else: # Element is not present in the array return -1 ### Test arr = [2, 3, 4, 10, 40, 55, 90, 122, 199] x = 55 # Function call result = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print('Element is present at index {}'.format(result)) else: print('Element is not present in array') print('Done')
true
1421aac5bb5d2864179392ec3580146803b0dc22
signalwolf/Algorithm
/Chapter2 Linked_list/Insert a node in sorted linked list.py
1,244
4.28125
4
# https://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/ # insert by position class LinkedListNode(object): def __init__(self, val): self.val = val self.next = None def create_linked_list(arr): dummy_node = LinkedListNode(0) prev = dummy_node for val in arr: curr = LinkedListNode(val) prev.next = curr prev = curr return dummy_node.next def printLinked_list (head): res = [] while head != None: res.append (head.val) head = head.next print res def insert(head, val): dummy_node = LinkedListNode(0) dummy_node.next = head prev, curr= dummy_node, head # print curr.val, prev.val while curr and curr.val < val: curr= curr.next prev = prev.next prev.next = LinkedListNode(val) if curr: prev.next.next = curr return dummy_node.next head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 100)) head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 0)) head = create_linked_list([1,3,4,7,8,10]) printLinked_list(insert(head, 5)) # Output: # [1, 3, 4, 7, 8, 10, 100] # [0, 1, 3, 4, 7, 8, 10] # [1, 3, 4, 5, 7, 8, 10]
true
cc2ca652d4ef4f7b5b6f4198f1e92a6f3a85ad63
YSreylin/HTML
/1101901079/list/Elist10.py
289
4.21875
4
#write a Python program to find the list of words that are longer than n from a given list of words a = [] b = int(input("Enter range for list:")) for i in range(b): c = input("Enter the string:") a.append(c) for j in a: d = max(a, key=len) print("\n",d,"is the longest one")
true
97d96de1162239c5e135bc9ce921625b5c88a080
YSreylin/HTML
/1101901079/Array/array.py
242
4.40625
4
#write python program to create an array of 5 integers and display the array items. #access individual element through indexes. import array a=array.array('i',[]) for i in range(5): c=int(input("Enter array:")) a.append(c) print(a)
true
7d6b9fc6ddd4a6cc4145d1568965666b48b030ed
YSreylin/HTML
/1101901079/0012/04.py
204
4.125
4
#this program is used to swap of two variable a = input('Enter your X variable:') b = input('Enter your Y variable:') c=b d=a print("Thus") print("The value of X is:",c) print("The value of Y is:",d)
true
1a1d300c97c45ce4e321530f3a30d296fe165bf2
YSreylin/HTML
/1101901079/0012/Estring6.py
394
4.25
4
'''write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. if the string lenth of the given string is less then 3, leave it unchanged''' a = input("Enter the word:") x = a[-3:] if len(a)>3: if x=='ing': print(a+"ly") else: print(a+"ing") else: print(a)
true
4373addc9af220054ff54a7d6abb1073bf7a602d
TaviusC/cti110
/P3HW2_MealTipTax_Cousar.py
1,327
4.25
4
# CTI-110 # P3HW2 - MealTipTax # Tavius Cousar # 2/27/2019 # # Enter the price of the meal # Display tip choices # Enter the tip choice # Calculate the total price of meal (price of meal * tip + price) # Calculate the sales tax (charge * 0.07) # Calculate the total (charge + sales tax) # if tip == '0.15', '0.18', or '0.2' # Display tip # Display tax # Display total # else: # Display Error # Enter the price of meal price = float(input('Enter the price of the meal: ')) # Enter tip choices print('You have three choices for tip percentages:') print('15% - type: 0.15') print('18% - type: 0.18') print('20% - type: 0.2') tip = float(input('Enter tip: ')) # Calculations charge = price * tip + price tax = float(0.07) sales_tax = charge * tax total = charge + sales_tax # Display the tip, sales tax, and total if tip == float('0.15'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) elif tip == float('0.18'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) elif tip == float('0.2'): print('Tip: ', tip) print('Sales Tax: ', format(sales_tax, '.2f')) print('Total: ', format(total, '.2f')) else: print('Error')
true
09e2ea08b77fa1a4e33180cac2ed46e872f281fb
ImayaDismas/python-programs
/variables_dict.py
455
4.3125
4
#!/usr/bin/python3 def main(): d = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} for k in sorted(d.keys()): #sorted sorts the alphabetically print(k, d[k]) #using a different definition of the dictionaries a = dict( one=1, two = 2, three = 3, four = 4, five = 'five' )#usually are mutable a['seven'] = 7#one can add this for k in sorted(a.keys()): #sorted sorts the alphabetically print(k, a[k]) if __name__ == "__main__": main()
true
278144e8d19ad06065719defc62f8b4c2e29c786
Mansalu/python-class
/003-While/main.py
1,093
4.34375
4
# While Loops -- FizzBuzz """ Count from 1 to 100, printing the current count. However, if the count is a multiple of 3, print "Fizz" instead of the count. If the count is a multiple of 5 print "Buzz" instead. Finally, if the count is a multiple of both print "FizzBuzz" instead. Example 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz """ #Intro print("This is a FizzBuzz game.") #Defining Count and Limit for Fizz Buzz. Count = 0 Limit = 100 # Running while loop of count from 0 to 100 in increments of 1. while (Count < Limit): Count += 1 # If Count is divisible by 5 and 3 then the program prints Fizz Buzz. if (Count % 5 == 0 and Count % 3 == 0 ): print ("Fizz Buzz") # Else if the previous condition is not satisfied, # then check if count is divisible by 5 then print Buzz if it is. elif (Count % 5 == 0): print ("Buzz") elif (Count % 3 == 0): print("Fizz") # If none of these conditions are satisfied then the count is printed. else: print (Count) print ("END OF FIZZ BUZZ") # END
true
d741d285f023ad8223a5c095775a8d0b225f4b4a
cabhishek/python-kata
/loops.py
1,045
4.3125
4
def loop(array): print('Basic') for number in array: print(number) print('Basic + Loop index') for i, number in enumerate(array): print(i, number) print('Start from index 1') for i in range(1, len(array)): print(array[i]) print('Choose index and start position') for i, number in enumerate(array[1:], start=1): print(i, number) print('Basic while loop') i = 0 while i < len(array): print(i, array[i]) i +=1 print('Simulate \'while\' with \'for\'') for i in range(len(array)): print(i, array[i]) print('Basic backward loop') for number in array[::-1]: print(number) print('Backward loop with index') for i in range(len(array)-1, -1,-1): print(array[i]) print('Loops with flexible step number') for number in array[::2]: print(number) print('Iterate Curr and next element') for (curr, next) in zip(array, array[1:]): print(curr, next) loop([1,2,3,4,5,6,7,8,9,10])
true
a1d66f9acca5ecd0062f9842e07a5158b109587b
cabhishek/python-kata
/word_break.py
1,280
4.28125
4
""" Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because "leetcode" can be segmented as "leet code". """ def word_break_2(word, dict): for i in range(len(word)): first = word[:i] second = word[i:] if first in dict and second in dict: return True return False print(word_break_2("leetcode", ["leet", "code"])) dict = ["leet", "code", "is", "great", "mark", "for"] string = "leetcodeismark" # More general case. def word_break(string, dict): words = [] def find_words(string): for i in range(len(string)+1): prefix = string[:i] if prefix in dict: words.append(prefix) find_words(string[i:]) find_words(string) return " ".join(words) print(word_break(string, dict)) # without closure def word_break_3(string, dict): if string in dict: return [string] for i in range(len(string)+1): prefix = string[:i] if prefix in dict: return [prefix] + word_break_3(string[i:], dict) return [] print(" ".join(word_break_3(string, dict)))
true
ec077fa4521bd2584b13d15fe3b3866dd4ff4fde
rtyner/python-crash-course
/ch5/conditional_tests.py
337
4.34375
4
car = 'mercedes' if car == 'audi': print("This car is made by VW") else: print("This car isn't made by VW") if car != 'audi': print("This car isn't made by VW") car = ['mercedes', 'volkswagen'] if car == 'volkswagen' and 'audi': print("These cars are made by VW") else: print("Not all of these cars are made by VW")
true
0c04919a425328f8a1dfcf7e612a6d8f1780e61d
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/matthew_denko/lesson03/slicing_lab.py
1,731
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 28 15:08:38 2019 @author: matt.denko """ """Write some functions that take a sequence as an argument, and return a copy of that sequence: with the first and last items exchanged. with every other item removed. with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. with the elements reversed (just with slicing). with the last third, then first third, then the middle third in the new order.""" # with the first and last items exchanged sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def exchange_first_last(seq): f = seq[0] l = seq[-1] seq[0]= l seq[-1] = f return print(seq) exchange_first_last(sequence) # with every other item removed. def every_other_removed(seq): f = seq[0] l = seq[-1] seq = [] seq.append(l) seq.append(f) return print(seq) every_other_removed(sequence) # with the first 4 and the last 4 items removed, and then every other item in the remaining sequence. sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def keep_the_middle(seq): del seq[0:4] del seq[-4:] return print(seq) keep_the_middle(sequence) # with the elements reversed (just with slicing). sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def elements_reversed(seq): seq[::-1] return print(sequence) elements_reversed(sequence) # with the last third, then first third, then the middle third in the new order sequence = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] def thirds_switched(seq): first = seq[-5:] second = seq[0:5] third = seq[5:10] seq = [] seq = first + second + third return print(seq) thirds_switched(sequence)
true
51cf6b8c764ffef5e24eede476fff19f76d66df4
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/jraising/lesson02/series.py
2,261
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 17 17:09:09 2019 @author: jraising """ def fibo(n): fib = [0,1] for i in range(n-1): fib.append(fib[i] + fib[i+1]) return (fib[n]) ans = fibo(5) print (ans) def lucas(n): luc = [2,1] for i in range(n-1): luc.append(luc[i] + luc[i+1]) print(luc) return (luc[n]) luca = lucas(6) print(luca) """ This function has one required parameter and two optional parameters. The required parameter will determine which element in the series to print. The two optional parameters will have default values of 0 and 1 and will determine the first two values for the series to be produced. Calling this function with no optional parameters will produce numbers from the fibo series (because 0 and 1 are the defaults). Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers. Other values for the optional parameters will produce other series. Note: While you could check the input arguments, and then call one of the functions you wrote, the idea of this exercise is to make a general function, rather than one specialized. So you should re-implement the code in this function. """ def sumseries(n, first = 0, second = 1): series =[first, second] for i in range(n): series.append(series[i] + series[i+1]) return series[n] result = sumseries(6,2,1) print(result) if __name__ == "__main__": # run some tests assert fibo(0) == 0 assert fibo(1) == 1 assert fibo(2) == 1 assert fibo(3) == 2 assert fibo(4) == 3 assert fibo(5) == 5 assert fibo(6) == 8 assert fibo(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 # test that sumseries matches fibo assert sumseries(5) == fibo(5) assert sumseries(7, 0, 1) == fibo(7) # test if sumseries matched lucas assert sumseries(5, 2, 1) == lucas(5) # test if sumseries works for arbitrary initial values assert sumseries(0, 3, 2) == 3 assert sumseries(1, 3, 2) == 2 assert sumseries(2, 3, 2) == 5 assert sumseries(3, 3, 2) == 7 assert sumseries(4, 3, 2) == 12 assert sumseries(5, 3, 2) == 19 print("tests passed")
true
e1f1be756bda5a8452dd18deec0c7e936c17f673
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/jammy_chong/lesson03/list_lab.py
1,919
4.3125
4
def create_list(): global fruit_list fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] #Seris 1 create_list() print(fruit_list) new_fruit = input("Add another fruit to the end of the list: ") fruit_list.append(new_fruit) print(fruit_list) user_number = input(f"Choose a number from 1 to {len(fruit_list)} to display fruit: ") print(f"The fruit you chose is {fruit_list[int(user_number)-1]}") second_fruit = input("Add another fruit to the beginning of the list: ") fruit_list = [second_fruit] + fruit_list print(fruit_list) third_fruit = input("Add another fruit to the beginning of the list: ") fruit_list.insert(0, third_fruit) print(fruit_list) print("The fruits that start with P are: " ) for fruit in fruit_list: if fruit[0] == "P": print(fruit) #Series 2 create_list() fruit_list.pop() print(fruit_list) #Bonus fruit_list = fruit_list * 2 print(fruit_list) #confirm_delete = 1 while True: delete_fruit = input("Type the fruit you want to delete :") if delete_fruit in fruit_list: for x in range(fruit_list.count(delete_fruit)): fruit_list.remove(delete_fruit) break #confirm_delete = 0 print(fruit_list) #Series 3 create_list() print(fruit_list) fruits_to_delete = [] for fruit in fruit_list: like = input(f"Do you like {fruit}?: ") while like not in("yes","no"): like = input("Please enter yes or no: ") if like == "no": fruits_to_delete.append(fruit) for fruit in fruits_to_delete: fruit_list.remove(fruit) if len(fruit_list) > 1: print(f"You like these fruits: {fruit_list}.") elif len(fruit_list) == 1: print(f"You like this fruit: {fruit_list[0]}.") else: print("You don't like any fruit from the list.") #Series 4 create_list() new_list = [] for item in fruit_list: new_list.append(item[::-1]) fruit_list.pop() print(f"Original list: {fruit_list}. New List: {new_list}.")
true
45e749325dc2d163416366a6a3046a83d97bbd76
UWPCE-PythonCert-ClassRepos/Python210_Fall2019
/students/matthew_denko/lesson02/fizz_buzz.py
603
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 21 20:51:19 2019 @author: matt.denko """ """Write a program that prints the numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number. For the multiples of five print “Buzz” instead of the number. For numbers which are multiples of both three and five print “FizzBuzz” instead.""" for i in range (1,101): if ((i % 3) + (i % 5)) < 1: print("FizzBuzz") elif i % 3 == 0: print("Fizz") elif i % 5 == 0: print("Buzz") else: print(i)
true
000a7bafb0c973ba1869c322e84efb75ee41e6f1
mohamedamine456/AI_BOOTCAMP
/Week01/Module00/ex01/exec.py
249
4.125
4
import sys result = "" for i, arg in enumerate(reversed(sys.argv[1:])): if i > 0: result += " " result += "".join(char.lower() if char.isupper() else char.upper() if char.islower() else char for char in reversed(arg)) print(result)
true
dffcce747fb2c794585df237849517bd8b637d9f
data-pirate/Algorithms-in-Python
/Arrays/Two_sum_problem.py
1,690
4.21875
4
# TWO SUM PROBLEM: # In this problem we need to find the terms in array which result in target sum # for example taking array = [1,5,5,15,6,3,5] # and we are told to find if array consists of a pair whose sum is 8 # There can be 3 possible solutions to this problem #solution 1: brute force # this might not be the best choice to get the job done but will be easy to implement # time complexity: O(n^2) def two_sum_brute_force(arr, target): for i in range(len(arr)): for j in range(i+1, len(arr)): if arr[i] + arr[j] == target: print(arr[i], arr[j]) return True return False arr = [9,3,1,4,5,1] target = 13 print(two_sum_brute_force(arr, target)) # prints 9 4 True # solution 2: Hash table # Time Complexity: O(n) # Space Complexity: O(n) def two_sum_hash_table(A, target): ht = dict() for i in range(len(A)): if A[i] in ht: print(ht[A[i]], A[i]) return True else: ht[target - A[i]] = A[i] return False A = [-2, 1, 2, 4, 7, 11] target = 13 print(two_sum_hash_table(A,target)) # solution 3: Using to indices # Here, we have two indices that we keep track of, # one at the front and one at the back. We move either # the left or right indices based on whether the sum of the elements # at these indices is either greater than or less than the target element. # Time Complexity: O(n) # Space Complexity: O(1) def two_sum(A, target): i = 0 j = len(A) - 1 while i < j: if A[i] + A[j] == target: print(A[i], A[j]) return True elif A[i] + A[j] < target: i += 1 else: j -= 1 return False A = [-2, 1, 2, 4, 7, 11] target = 13 print(two_sum(A,target))
true
aa990f7844b6d49bc9eb2c019150edbc65b32833
oskar404/code-drill
/py/fibonacci.py
790
4.53125
5
#!/usr/bin/env python # Write a function that computes the list of the first 100 Fibonacci numbers. # By definition, the first two numbers in the Fibonacci sequence are 0 and 1, # and each subsequent number is the sum of the previous two. As an example, # here are the first 10 Fibonnaci numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34. import sys def fibonacci(size): buf = [0, 1] if size <= 2: return buf[:size] size -= 2 while size >= 0: buf.append(buf[-1]+buf[-2]) size -= 1 return buf def main(): assert len(sys.argv) == 2, "Missing number argument or too many arguments" size = int(sys.argv[1]) assert size >= 0, "Number argument must be positive" print("{}".format(fibonacci(size))) if __name__ == '__main__': main()
true
959cd3062b855c030b92cfe0f2edbbe141018508
kctompkins/my_netops_repo
/python/userinput.py
220
4.125
4
inputvalid = False while inputvalid == False: name = input("Hey Person, what's your name? ") if all(x.isalpha() or x.isspace() for x in name): inputvalid = True else: inputvalid = False print(name)
true
3759abcbab3aff89acc59fe4228f0146ee2eaa56
HSabbir/Design-pattern-class
/bidding/gui.py
1,717
4.1875
4
import tkinter as tk from tkinter import ttk from tkinter import * from bidding import biddingraw # this is the function called when the button is clicked def btnClickFunction(): print('clicked') # this is the function called when the button is clicked def btnClickFunction(): print('clicked') # this is the function called when the button is clicked def btnClickFunction(): print('clicked') root = Tk() # This is the section of code which creates the main window root.geometry('880x570') root.configure(background='#F0F8FF') root.title('bidding') # This is the section of code which creates the a label Label(root, text='this is a label', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=300, y=77) # This is the section of code which creates a button Button(root, text='Bidder 1', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=179, y=289) # This is the section of code which creates the a label Label(root, text='bid value', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=188, y=239) # This is the section of code which creates a button Button(root, text='Bidder 2', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=362, y=297) # This is the section of code which creates a button Button(root, text='Bidder 3 ', bg='#F0F8FF', font=('arial', 12, 'normal'), command=btnClickFunction).place(x=571, y=299) # This is the section of code which creates the a label Label(root, text='bid val 2', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=371, y=246) # This is the section of code which creates the a label Label(root, text='bid val 3', bg='#F0F8FF', font=('arial', 12, 'normal')).place(x=577, y=249) root.mainloop()
true
cd79e3b1ce72569bb62b994695e4483798346a0c
Luke-Beausoleil/ICS3U-Unit3-08-Python-is_it_a_leap_year
/is_it_a_leap_year.py
926
4.28125
4
#!/usr/bin/env python3 # Created by: Luke Beausoleil # Created on: May 2021 # This program determines whether inputted year is a leap year def main(): # this function determines if the year is a leap year # input year_as_string = input("Enter the year: ") # process & output try: year = int(year_as_string) if year > 0: if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("\nIt is not a leap year.") else: print("\nIt is a leap year.") else: print("\nIt is a leap year.") else: print("\nIt is not a leap a year.") else: print("\nInvalid Input.") except (Exception): print("\nInvalid Input.") finally: print("\nDone.") if __name__ == "__main__": main()
true
322be9bbf093725a12f82482cd5b9d0ffdf98dcc
bgschiller/thinkcomplexity
/Count.py
1,966
4.15625
4
def count_maker(digitgen, first_is_zero=True): '''Given an iterator which yields the str(digits) of a number system and counts using it. first_is_zero reflects the truth of the statement "this number system begins at zero" It should only be turned off for something like a label system.''' def counter(n): i = 0 for val in count(digitgen, first_is_zero): yield val if i > n: break i += 1 return counter def count(digitgen, first_is_zero=True): '''Takes an iterator which yields the digits of a number system and counts using it. If first_is_zero is True, digitgen begins counting with a zero, so when we roll over to a new place, the first value in the new place should be the element following zero. compare the two test cases for a better understanding.''' def subcount(digitgen, places): if places == 1: for d in digitgen(): yield d else: for d in digitgen(): for ld in subcount(digitgen, places - 1): yield d + ld for d in digitgen(): yield d places = 2 while True: first = first_is_zero for d in digitgen(): if first: first = False continue for ld in subcount(digitgen, places - 1): yield d + ld places += 1 if __name__ == "__main__": import string def labelelements(): for char in string.ascii_lowercase: yield char for char in string.ascii_uppercase: yield char def base2(): for d in range(2): yield str(d) label_counter = count_maker(labelelements, first_is_zero=False) for label in label_counter(200): print label base2_counter = count_maker(base2, first_is_zero=True) for b2 in base2_counter(200): print b2
true
a8f2158fe199c282b8bdc33f257f393eb70e6685
iamaro80/arabcoders
/Mad Libs Generator/06_word_transformer.py
737
4.21875
4
# Write code for the function word_transformer, which takes in a string word as input. # If word is equal to "NOUN", return a random noun, if word is equal to "VERB", # return a random verb, else return the first character of word. from random import randint def random_verb(): random_num = randint(0, 1) if random_num == 0: return "run" else: return "kayak" def random_noun(): random_num = randint(0,1) if random_num == 0: return "sofa" else: return "llama" def word_transformer(word): # your code here if word == 'NOUN': return random_noun() if word == 'VERB': return random_verb() else: return word[0] print word_transformer('verb')
true
7c017d73da7b2e702aecf6fa81114580389afe09
Numa52/CIS2348
/Homework1/3.18.py
862
4.25
4
#Ryan Nguyen PSID: 180527 #getting wall dimensions from user wall_height = int(input("Enter wall height (feet):\n")) wall_width = int(input("Enter wall width (feet):\n")) wall_area = wall_width * wall_height print("Wall area:", wall_area, "square feet") #calculating gallons of paint needed #1 gallon of paint covers 350 square feet paint_needed = wall_area / 350 print("Paint needed:", '{:.2f}'.format(paint_needed), "gallons") #rounding paint_needed to nearest whole to get # of cans needed cans = round(paint_needed) print("Cans needed:", cans, "can(s)\n") #asking user for color selection color = input("Choose a color to paint the wall:\n") if (color == 'red'): cost = cans * 35 elif (color == 'blue'): cost = cans * 25 elif (color == 'green'): cost = cans * 23 #printing the final cost print("Cost of purchasing", color, "paint: $" + str(cost))
true
f5540eb90b304d519809c8c010add05fc11e491f
sindhumudireddy16/Python
/Lab 2/Source/sortalpha.py
296
4.375
4
#User input! t=input("Enter the words separated by commas: ") #splitting words separated by commas which are automatically stored as a list. w=t.split(",") #sorting the list. w1=sorted(w) #iterating through sorted list and printing output. for k in w1[:-1]: print(k+",",end='') print(w1[-1])
true
263387b1a516c9558c26c0d6fd2df142ff9edcc6
muondu/caculator
/try.py
528
4.40625
4
import re def caculate(): #Asks user to input operators = input( """ Please type in the math operation you will like to complete + for addition - for subtraction * for multiplication / for division """ ) #checks if the opertators match with input if not re.match("^[+,-,*,/]*$", operators): print ("Error! Only characters above are allowed!") caculate() # checks empty space elif operators == "" : print('please select one of the above operators') caculate() caculate()
true
1edd3809d431ece230d5d70d15425bd2fa62e43a
jabhij/DAT208x_Python_DataScience
/FUNCTIONS-PACKAGES/LAB3/L1.py
445
4.3125
4
""" Instructions -- Import the math package. Now you can access the constant pi with math.pi. Calculate the circumference of the circle and store it in C. Calculate the area of the circle and store it in A. ------------------ """ # Definition of radius r = 0.43 # Import the math package import math # Calculate C C = 2*math.pi*r # Calculate A A = math.pi*(r**2) # Build printout print("Circumference: " + str(C)) print("Area: " + str(A))
true
c82f373f42c0124c42d3ec8dd89184a0897998a1
jabhij/DAT208x_Python_DataScience
/NUMPY/LAB1/L2.py
614
4.5
4
""" Instructions -- Create a Numpy array from height. Name this new array np_height. Print np_height. Multiply np_height with 0.0254 to convert all height measurements from inches to meters. Store the new values in a new array, np_height_m. Print out np_height_m and check if the output makes sense. """ # height is available as a regular list # Import numpy import numpy as np # Create a Numpy array from height: np_height np_height = np.array(height) # Print out np_height print (np_height) # Convert np_height to m: np_height_m np_height_m = (0.0254 * np_height) # Print np_height_m print (np_height_m)
true