blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
3ec6fd0dcd97904b08c95fe17cac67b03a75a61f
luthraG/ds-algo-war
/general-practice/11_09_2019/p11.py
648
4.15625
4
''' 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? ''' from timeit import default_timer as timer power = int(input('Enter the power that needs to be raised to base 2 :: ')) start = timer() sum_of_digits = 0 number = 2 << (power - 1) number = str(number) length = len(number) i = 0 while i < length: sum_of_digits += int(number[i]) i += 1 # while number != 0: # sum_of_digits += (number % 10) # number //= 10 end = timer() print('Sum of digits of 2 raised to power {} is {}'.format(power, sum_of_digits)) print('Time taken is {}'.format(end - start))
true
33f5c2d803562730098d3b4393d5843d9d2f9d4a
luthraG/ds-algo-war
/general-practice/14_09_2019/p18.py
1,586
4.34375
4
''' https://leetcode.com/problems/unique-email-addresses/ Every email consists of a local name and a domain name, separated by the @ sign. For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name. Besides lowercase letters, these emails may contain '.'s or '+'s. If you add periods ('.') between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.) If you add a plus ('+') in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.) It is possible to use both of these rules at the same time. Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails? ''' import re def unique_emails_count(emails): unique_emails = [] for email in emails: email_split = email.split('@') email = re.sub(r'\.', '', email_split[0]) email = email + '@' + email_split[1] email = re.sub(r'\+(.*?)(?=@)', '', email) unique_emails.append(email) return len(set(unique_emails)) emails = str(input('Enter list of emails : ')).split(',') emails = list(map(str, emails)) print('Total unique emails count is {}'.format(unique_emails_count(emails)))
true
2016817647c32c5e148437225c826b39f2ce8ee4
luthraG/ds-algo-war
/general-practice/10_09_2019/p3.py
2,228
4.125
4
class Node: def __init__(self, data = None): self.data = data self.next = None class LinkedList: def __init__(self): self.start_node = Node() def add_to_start(self, data): node = Node(data) node.next = self.start_node.next self.start_node.next = node def add_to_end(self, data): node = Node(data) n = self.start_node while n.next is not None: n = n.next n.next = node def remove_from_begining(self): node = self.start_node.next if node is None: print('List is empty. Nothing to delete') else: self.start_node.next = node.next node = None def remove_from_end(self): node = self.start_node if node.next is None: print('List is empty. Nothing to delete') else: while node.next.next is not None: node = node.next node.next = None def traverse_list(self): node = self.start_node while node is not None: if node.data is not None: print(node.data) node = node.next def count(self): c = 0 node = self.start_node while node is not None: if node.data is not None: c += 1 node = node.next return c if __name__ == '__main__': linkedList = LinkedList() number = int(input('Enter number of items to add in list :: ')) for i in range(number): data = int(input('Enter data :: ')) # If i is even then add to start, else add to end if i & 1 == 1: linkedList.add_to_end(data) else: linkedList.add_to_start(data) count = linkedList.count() print('Total items in the list :: {}'.format(count)) MAX_ALLOWED = 2 diff = count - MAX_ALLOWED if diff > 0: print('Going to remove {} items from end'.format(diff)) for i in range(diff): linkedList.remove_from_end() print('List items are') linkedList.traverse_list() print('Total items in the list :: {}'.format(linkedList.count()))
true
b3aaf2652c1cfda99a9c3b3c8e1d7d47b358abb4
luthraG/ds-algo-war
/general-practice/18_09_2019/p12.py
1,035
4.15625
4
''' Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. Note: All given inputs are in lowercase letters a-z. ''' def longest_common_prefix(str1, str2): length1 = len(str1) length2 = len(str2) if length1 == 0 or length2 == 0: return '' else: i = 0 while i < length1 and i < length2: if str1[i] != str2[i]: break i += 1 return str1[0:i] if i > 0 else '' def longest_common_prefix_solution(items): length = len(items) common_prefix = items[0] if length > 0 else '' i = 1 while i < length: common_prefix = longest_common_prefix(common_prefix, items[i]) i += 1 return common_prefix
true
6d53601a7fc6a0c2fb2e35f5685770bd5e771798
stollcode/GameDev
/game_dev_oop_ex1.py
2,829
4.34375
4
""" Game_dev_oop_ex1 Attributes: Each class below, has at least one attribute defined. They hold data for each object created from the class. The self keyword: The first parameter of each method created in a Python program must be "self". Self specifies the current instance of the class. Python Directions: Create a Python module on your Z:\GameDev folder named oop_ex1.py. Add the following code to the module. Do not forget to test!!! *** Teacher Class *** 1. Define a class named Teacher containing the following attributes: a. Attributes: i. name ii. gender iii. date_of_birth iv. phone_number b. Set all attributes to default as empty strings (also called null strings). Write the code below the triple quotes below. """ # Your code goes here. """ *** Monkey Class **** 2. Define a class named Monkey containing the following attributes: a. Attributes: i. age ii. species iii. is_rain_forest b. Set the default age to zero, species to an empty string and is_rain_forest to False. Write the code below the triple quotes below. """ # Your code goes here """ *** Fish Class *** 3. Define a class named Fish with the following attributes: a. Attributes: i. is_fresh_water ii. weight iii. age iv. gender b. Set the following defaults for the attributes: is_fresh_water to False, weight to 0.0, age to 0 and gender to an empty string. c. Define a breathe() method that returns the following string: The fish breathes Do not forget to include self as the first parameter of the method. Example: def breathe(self): Write the code below the triple quotes below. """ # Your code goes here """ *** Enemy Class *** 4. Create a class named Enemy with the following attributes: a. Attributes: i. Name = "Goblin" ii. health = 100 Write the code below the triple quotes below. """ # Your code goes here """ *** Testing *** 5. For each class: a. Print a message describing the class being tested (ie. "Testing the Fish Class:") b. Create an object instance. c. Set all attribute values. (be creative, unless otherwise specified) d. Modify the attribute values. e. Print the attribute values using descriptive headings f. Call methods for the class where appropriate. g. Print any values returned by the methods, with descriptive headings. Write the tests below the triple quotes below. """ # Test the Teacher class here # Test the Monkey class here # Test the Fish class here (Don't forget to call the breathe() method) # Test the Enemy class below.
true
0f227ae102e644024608c93a33dac90b39f2dcb9
greenblues1190/Python-Algorithm
/LeetCode/14. 비트 조작/393-utf-8-validation.py
1,893
4.15625
4
# https://leetcode.com/problems/utf-8-validation/ # Given an integer array data representing the data, return whether it is a valid UTF-8 encoding. # A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: # For a 1-byte character, the first bit is a 0, followed by its Unicode code. # For an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, # followed by n - 1 bytes with the most significant 2 bits being 10. # This is how the UTF-8 encoding would work: # Char. number range | UTF-8 octet sequence # (hexadecimal) | (binary) # --------------------+--------------------------------------------- # 0000 0000-0000 007F | 0xxxxxxx # 0000 0080-0000 07FF | 110xxxxx 10xxxxxx # 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx # 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx # Note: The input is an array of integers. # Only the least significant 8 bits of each integer is used to store the data. # This means each integer represents only 1 byte of data. from typing import List class Solution: def validUtf8(self, data: List[int]) -> bool: def check(bytes: int, start: int) -> bool: for i in range(start + 1, start + bytes): if i >= len(data) or (data[i] >> 6) != 0b10: return False return True start = bytes = 0 while start < len(data): code = data[start] if code >> 3 == 0b11110: bytes = 4 elif code >> 4 == 0b1110: bytes = 3 elif code >> 5 == 0b110: bytes = 2 elif code >> 7 == 0b0: bytes = 1 else: return False if not check(bytes, start): return False start += bytes return True
true
02bd64d1871d08a5ef5354e4962074dc01363b8e
darrenthiores/PythonTutor
/Learning Python/level_guessing.py
2,170
4.125
4
# membuat app number guessing dengan level berbeda import random def low_level() : number = random.randint(1,10) chances = 3 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def med_level() : number = random.randint(1,25) chances = 5 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def high_level() : number = random.randint(1,50) chances = 8 while (chances > 0) : guess = int(input('Your guess : ')) if (guess == number) : print ('Congratss you win the game!!') break elif (guess > number) : print ('your guess is too high, go with a lower number') elif (guess < number) : print ('your guess is too low, go with a bigger number') if (chances <= 0) : print ('you lose the game!!') def pick_level() : print ('='*10,'Number Guessing Game','='*10) print ('[1] Low Level (1 - 10, 3 chances)') print ('[2] Medium Level (1 - 25, 5 chances)') print ('[3] High Level (1 - 50, 8 chances)') print ('[4] EXIT') menu = int(input('Pick level (index) : ')) if (menu == 1) : low_level() elif (menu == 2) : med_level() elif (menu == 3) : high_level() elif (menu == 4) : exit() else : print ('Which level did you picked?') if __name__ == "__main__": while (True) : pick_level()
true
9b39f95066e6bf5919683302f61adc5f40300a60
younism1/Checkio
/Password.py
1,673
4.15625
4
# Develop a password security check module. # The password will be considered strong enough if its length is greater than or equal to 10 symbols, it has at least # one digit, as well as containing one uppercase letter and one lowercase letter in it. # The password contains only ASCII latin letters or digits. # Input: A password as a string. # Output: Is the password safe or not as a boolean or any data type that can be converted and processed as a boolean. # In the results you will see the converted results. # checkio('A1213pokl') == False # checkio('bAse730onE') == True # checkio('asasasasasasasaas') == False # checkio('QWERTYqwerty') == False # checkio('123456123456') == False # checkio('QwErTy911poqqqq') == True def checkio(data: str) -> bool: upper = False lower = False digit = False if not len(data) >= 10: # print("Your password needs to be 10 characters long or more") return False for i in data: if i.isdigit(): digit = True if i.isupper(): upper = True if i.islower(): lower = True return upper and digit and lower if __name__ == '__main__': #self-checking and not necessary for auto-testing assert checkio('A1213pokl') == False, "1st example" assert checkio('bAse730onE4') == True, "2nd example" assert checkio('asasasasasasasaas') == False, "3rd example" assert checkio('QWERTYqwerty') == False, "4th example" assert checkio('123456123456') == False, "5th example" assert checkio('QwErTy911poqqqq') == True, "6th example" print("Passed all test lines ? Click 'Check' to review your tests and earn cool rewards!")
true
522385d08ccd855e401d141f9f4e8ccf1535f926
purwokang/learn-python-the-hard-way
/ex6.py
971
4.15625
4
# creating variable x that contains format character x = "There are %d types of people." % 10 # creating variable binary binary = "binary" # creating variable do_not do_not = "don't" # creating variable y, contains format character y = "Those who know %s and those who %s." % (binary, do_not) # printing content of variable x print(x) # printing content of variable y print(y) # printing the content of variable x print("I said: %r." % x) # printing the content of variable y print("I also said: '%s'." % y) # creating variable with boolean content hilarious = True # creating variable, contains format character joke_evaluation = "Isn't that joke so funny?! %r" # printing combination of two variables print(joke_evaluation % hilarious) # creating variable w with string content w = "This is the left side of..." # variable e, the content is string as well e = "a string with a right side." # printing both variable w and e, consist of strings print(w + e)
true
ea1e981b9a899e15fddce5b28d20ea97c05b5ccd
lovingstudy/Molecule-process
/point2Plane.py
1,296
4.15625
4
#--------------------------------------------------------------------------------------------------- # Name: point2Plane.py # Author: Yolanda # Instruction: To calculate the distance of a point to a plane, which is defined by 3 other points, # user should input the coordinates of 3 points in the plane into (x1,y1,z1)(x2,y2,z2)(x3,y3,z3), # also input the coordinates of the point out of the plane into (x0,y0,z0). This program will # print the distance. # Application: Measure the distance of a atom to a benzene ring. #--------------------------------------------------------------------------------------------------- import numpy as np from scipy import linalg # 3 points to define a plane. For example, 3 atoms in a benzene ring. x1, y1, z1 = 0.421, 9.340, 10.017 x2, y2, z2 = -0.042, 8.673, 8.866 x3, y3, z3 = 0.785, 8.316, 7.853 # Train the equation of the plane. Equation: Ax + By + Cz + 1 = 0 A = np.array([[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]]) b = np.array([[-1],[-1],[-1]]) pr = list(linalg.inv(A).dot(b).flat) + [1] # pr == [A, B, C, 1] # The point out of the plane. x0, y0, z0 = 2.691, 11.980, 9.187 # Calculte the distance of the point to the plane. d = np.abs(sum([p*x for p,x in zip(pr, [x0,y0,z0,1])])) / np.sqrt(sum([a**2 for a in pr[:3]])) print "Distance: ", d
true
3c1219e7c7c57db39fc61e7551c9e3e8808fadb7
league-python-student/level1-module2-ezgi-b
/_01_writing_classes/_b_intro_to_writing_classes.py
2,725
4.3125
4
""" Introduction to writing classes """ import unittest # TODO Create a class called student with the member variables and # methods used in the test class below to make all the tests pass class Student: def __init__(self, name, grade): self.name = name self.grade = grade self.homework_done = False def do_homework(self): self.homework_done = True def go_to_school(self, start = "7 am"): return self.name + " is leaving for school at " + start # ================== DO NOT MODIFY THE CODE BELOW ============================ class WriteClassesTests(unittest.TestCase): student_1 = Student(name='Zeeshan', grade=7) student_2 = Student(name='Amelia', grade=8) student_3 = Student(name='Penelope', grade=9) def test_student_objects_created(self): self.assertIsNotNone(WriteClassesTests.student_1, msg='student 1 not created!') self.assertIsNotNone(WriteClassesTests.student_2, msg='student 2 not created!') self.assertIsNotNone(WriteClassesTests.student_3, msg='student 3 not created!') def test_names(self): self.assertTrue(WriteClassesTests.student_1.name == 'Zeeshan') self.assertTrue(WriteClassesTests.student_2.name == 'Amelia') self.assertTrue(WriteClassesTests.student_3.name == 'Penelope') def test_grades(self): self.assertTrue(WriteClassesTests.student_1.grade == 7) self.assertTrue(WriteClassesTests.student_2.grade == 8) self.assertTrue(WriteClassesTests.student_3.grade == 9) def test_student_methods(self): self.assertEquals(False, WriteClassesTests.student_1.homework_done) self.assertEquals(False, WriteClassesTests.student_2.homework_done) self.assertEquals(False, WriteClassesTests.student_3.homework_done) WriteClassesTests.student_1.do_homework() WriteClassesTests.student_2.do_homework() WriteClassesTests.student_3.do_homework() self.assertEquals(True, WriteClassesTests.student_1.homework_done) self.assertEquals(True, WriteClassesTests.student_2.homework_done) self.assertEquals(True, WriteClassesTests.student_3.homework_done) def test_going_to_school(self): leave_str = WriteClassesTests.student_1.go_to_school(start='6 am') self.assertEqual('Zeeshan is leaving for school at 6 am', leave_str) leave_str = WriteClassesTests.student_2.go_to_school(start='6:30 am') self.assertEqual('Amelia is leaving for school at 6:30 am', leave_str) leave_str = WriteClassesTests.student_3.go_to_school() self.assertEqual('Penelope is leaving for school at 7 am', leave_str) if __name__ == '__main__': unittest.main()
true
e897af19e5fdf1f6ab3568b14ae124c5971a2a57
Prabhjyot2/workshop-python
/L2/P2.py
235
4.40625
4
#wapp to read radius of circle & find the area & circumference r = float(input("Enter the radius ")) pi = 3.14 area = pi * r** 2 print("area=%.2f" %area) cir = 2 * pi * r print("cir=%.4f" %cir) print("area=", area, "cir=", cir )
true
532793eb6901f35e2184ab5b510aea233c5a484b
Sher-Chowdhury/CentOS7-Python
/files/python_by_examples/loops/iterations/p02_generator.py
845
4.34375
4
# functions can return multiple values by using the: # return var1,var2....etc # syntax. # you can also do a similar thing using the 'yield' keyword. fruits = ['apple', 'oranges', 'banana', 'plum'] fruits_iterator = iter(fruits) # we now use the 'next' builtin function # https://docs.python.org/3.3/library/functions.html # a genarotor is simply a functions that contains one or more 'yield' lines. def fruits(): print("about to print apple") yield 'apple' print("about to print oranges") yield 'oranges' print("about to print banana") yield 'banana' print("about to print plum") yield 'plum' fruit = fruits() print(type(fruit)) print(next(fruit)) print(next(fruit)) print(next(fruit)) print(next(fruit)) # the yield command effectively pauses the function until the next 'next' command is executed.
true
f9886344b8c61878d322680525f4f4afe8220042
abbi163/MachineLearning_Classification
/KNN Algorithms/CustomerCategory/teleCust_plots.py
873
4.125
4
import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('E:\Pythoncode\Coursera\Classification_Algorithms\KNN Algorithms\CustomerCategory/teleCust1000t.csv') # print(df.head()) # value_counts() function is used to count different value separately in column custcat # eg. # 3 281 # 1 266 # 4 236 # 2 217 # count() function counts the number of value in column custcat, or sum of all value_counts(), here 1000 print(df['custcat'].value_counts()) # if sample is from 1 is to 100 , then bin size of 50 implies 50 range of histgram, from [0,2) to [98,100], Last bin include 100 # basically bins are number of class size. df.hist(column = 'income', bins = 50) plt.show() print(df.count()) plt.scatter(df.custcat, df.income, color = 'blue') plt.xlabel('custcat') plt.ylabel('income') plt.show()
true
491ffe454bdd5161ea332eb5114561b1a56b8e36
sacheenanand/pythondatastructures
/ReverseLinkedList.py
557
4.1875
4
__author__ = 'sanand' # To implement reverse Linked we need 3 nodes(curr, prev and next) we are changing only the pointers here. class node: def __init__(self, value, nextNode=None): self.value = value self.nextNode = nextNode class LinkedList: def __init__(self, head): self.head = head def reverse(self): current = head prev = None while True: next = current.nextNode current.nextNode = prev prev = current current = next return prev
true
04dce36f9f552216ea548da767dbf306fc2de8e9
mrvbrn/HB_challenges
/medium/code.py
1,162
4.1875
4
"""TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. """ class Codec: def __init__(self): self.url_to_code={} self.code_to_url={} def encode(self, longUrl: str) -> str: """Encodes a URL to a shortened URL. """ letters = string.ascii_letters+string.digits while longUrl not in self.url_to_code: code = "".join([random.choice(letters) for _ in range(6)]) if code not in self.code_to_url: self.url_to_code[longUrl]=code self.code_to_url[code]=longUrl return self.url_to_code[longUrl] def decode(self, shortUrl: str) -> str: """Decodes a shortened URL to its original URL. """ return self.code_to_url[shortUrl[-6:]]
true
289820dd78f4cf13538bde92149ae03d3e93784c
mrvbrn/HB_challenges
/hard/patternmatch.py
2,712
4.59375
5
"""Check if pattern matches. Given a "pattern string" starting with "a" and including only "a" and "b" characters, check to see if a provided string matches that pattern. For example, the pattern "aaba" matches the string "foofoogofoo" but not "foofoofoodog". Patterns can only contain a and b and must start with a: >>> pattern_match("b", "foo") Traceback (most recent call last): ... AssertionError: invalid pattern >>> pattern_match("A", "foo") Traceback (most recent call last): ... AssertionError: invalid pattern >>> pattern_match("abc", "foo") Traceback (most recent call last): ... AssertionError: invalid pattern The pattern can contain only a's: >>> pattern_match("a", "foo") True >>> pattern_match("aa", "foofoo") True >>> pattern_match("aa", "foobar") False It's possible for a to be zero-length (a='', b='hi'): >>> pattern_match("abbab", "hihihi") True Or b to be zero-length (a='foo', b=''): >>> pattern_match("aaba", "foofoofoo") True Or even for a and b both to be zero-length (a='', b=''): >>> pattern_match("abab", "") True But, more typically, both are non-zero length: >>> pattern_match("aa", "foodog") False >>> pattern_match("aaba" ,"foofoobarfoo") True >>> pattern_match("ababab", "foobarfoobarfoobar") True Tricky: (a='foo', b='foobar'): >>> pattern_match("aba" ,"foofoobarfoo") True """ def pattern_match(pattern, astring): """Can we make this pattern match this string?""" # Q&D sanity check on pattern assert (pattern.replace("a", "").replace("b", "") == "" and pattern.startswith("a")), "invalid pattern" count_a = pattern.count("a") count_b = pattern.count("b") first_b = pattern.find("b") for a_length in range(0, len(astring) // count_a + 1): if count_b: b_length = (len(astring) - (a_length*count_a)) / float(count_b) else: b_length = 0 if int(b_length) != b_length or b_length < 0: continue b_start = a_length * first_b if matches(pattern=pattern, a=astring[0:a_length], b=astring[b_start:b_start+int(b_length)], astring=astring): return True return False def matches(pattern, a, b, astring): test_string = "" for p in pattern: if p == "a": test_string += a else: test_string += b return test_string == astring if __name__ == '__main__': import doctest if doctest.testmod().failed == 0: print("\n*** ALL TESTS PASSED. WE'RE WELL-MATCHED!\n")
true
560459ddf49384a758c3bcfde15517ba99e44077
shaikharshiya/python_demo
/fizzbuzzD3.py
278
4.15625
4
number=int(input("Enter number")) for fizzbuzz in range(1,number+1): if fizzbuzz % 3==0 and fizzbuzz%5==0: print("Fizz-Buzz") elif fizzbuzz % 3==0: print("Fizz") elif fizzbuzz % 5==0: print("Buzz") else: print(fizzbuzz)
true
c21f73253780164661997fa29d873dec5a4803ce
A7xSV/Algorithms-and-DS
/Codes/Py Docs/Zip.py
424
4.4375
4
""" zip() This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. """ x = [1, 2, 3, 4] y = [5, 6, 7, 8] print x print y zipped = zip(x, y) print zipped # Unzip x2, y2 = zip(*zipped) print x2 print y2 print (x == list(x2)) and (y == list(y2))
true
a194787f8f7e817bf3b7166bcb3b9bce96e024ef
ataylor1184/cse231
/Proj01/Project01.py
1,221
4.46875
4
####################################################### # Computer Project #1 # # Unit Converter # prompt for distance in rods # converts rods to different units as floats # Outputs the distance in multiple units # calculates time spent walking that distance ######################################################## Rods = input("Input rods: ") Rods = float(Rods) print("You input " + str(Rods) + " rods.") print("Conversions") Furlongs = round(float(Rods / 40) ,3) # Converts Rods to Furlongs Meters = round(float(Rods * 5.0292) , 3) # Converts Rods to Meters Feet = round(float(Meters / .3048) ,3) # Converts Meters to Feet Miles = round(float(Meters / 1609.34) , 3) # Converts Meters to Miles SpeedInRods = float(3.1 *320)/60 # Converts MpH to Rods per minute Time = round(float(Rods / SpeedInRods) ,3) # Divides distance by speed print("Meters: " + str(Meters)) print("Feet: " + str(Feet)) print("Miles: " + str(Miles)) print("Furlongs: " + str(Furlongs)) print("Minutes to walk " + str(Rods) + " rods: " + str(Time)) #print("Minutes to walk " + str(Rods) + " Rods:" + )
true
7f3dc6666df5dbc8b2144dd22a4c175a299aa599
Princess-Katen/hello-Python
/13:10:2020_Rock_Paper_Scissors + Loop _v.4.py
1,696
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 21 13:18:18 2020 @author: tatyanamironova """ from random import randint player_wins = 0 computer_wins = 0 winning_score = 3 while player_wins < winning_score and computer_wins < winning_score: print (f'Player score: {player_wins} Computer score: {computer_wins}') print('Rock...') print('Paper...') print('Scissors...') player = input('(Player, make your move): ').lower() if player == 'quit' or player == 'q': break rand_num = randint(0,2) if rand_num == 0: computer = 'rock' elif rand_num == 1: computer = 'paper' else: computer = 'scissors' print(f'computer plays {computer}') if player == computer: print('Its a tie!') elif player == 'rock': if computer == 'scissors': print('Player wins') player_wins += 1 elif computer == 'paper': print('computer wins') computer_wins += 1 elif player == 'paper': if computer == 'scissors': print('computer wins') computer_wins += 1 elif computer == 'rock': print('Player wins') player_wins += 1 elif player == 'scissors': if computer == 'paper': print('Player wins') player_wins += 1 elif computer == 'rock': print('computer wins') computer_wins += 1 else: print('something went wrong') if player_wins > computer_wins: print('Congrats,you won!') elif player_wins == computer_wins: print('Its a tie') else: print('Unfortunately, the computer won')
true
556c8b35139d8948b0c218579785dd640b57acde
prateek-chawla/DailyCodingProblem
/Solutions/Problem_120.py
1,456
4.1875
4
''' Question --> This problem was asked by Microsoft. Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances. And in every even call of getInstance(), return the first instance and in every odd call of getInstance(), return the second instance. Approach --> Create two instances and a flag to keep track of calls to getInstance() Raise Exception on invalid instantiation ''' class Singleton: first_instance = None second_instance = None evenFlag = False def __init__(self): if Singleton.first_instance is not None and Singleton.second_instance is not None: raise Exception(" This is a Singleton Class ") else: if Singleton.first_instance is None: Singleton.first_instance = self else: Singleton.second_instance = self @staticmethod def getInstance(): if Singleton.first_instance is None or Singleton.second_instance is None: Singleton() else: if Singleton.evenFlag: Singleton.evenFlag = not Singleton.evenFlag return Singleton.first_instance else: Singleton.evenFlag = not Singleton.evenFlag return Singleton.second_instance obj1 = Singleton.getInstance() obj2 = Singleton.getInstance() obj3 = Singleton.getInstance() print(obj3) obj4 = Singleton.getInstance() print(obj4)
true
8e5c8f5ee8b8540d1c9d91dee38b44d67da57580
franky-codes/Py4E
/Ex6.1.py
433
4.375
4
#Example - use while loop to itterate thru string & print each character fruit = 'BANANA' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 #Exercise - use while loop to itterate thru string backwards fruit = 'BANANA' index = -1 # because len(fruit) - 1 is the last index in the string_x while index < len(fruit): letter = fruit[index] print(letter) index = index - 1
true
43716fe322cd9e307b98cefa32a1e35a1d387b87
omvikram/python-ds-algo
/dynamic-programming/longest_increasing_subsequence.py
2,346
4.28125
4
# Dynamic programming Python implementation of LIS problem # lis returns length of the longest increasing subsequence in arr of size n def maxLIS(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] > arr[j] and lis[i] < lis[j] + 1 : lis[i] = lis[j]+1 # Initialize maximum to 0 to get # the maximum of all LIS maximum = 0 # Pick maximum of all LIS values for i in range(n): maximum = max(maximum , lis[i]) return maximum # end of lis function # Driver program to test above function arr = [10, 22, 9, 33, 21, 50, 41, 60] arr1 = [16, 3, 5, 19, 10, 14, 12, 0, 15] arr2 = [10, 8, 6, 4, 2, 0] print ("LIS length of arr is ", maxLIS(arr)) print ("LIS length of arr1 is ", maxLIS(arr1)) print ("LIS length of arr2 is ", maxLIS(arr2)) ############################################################################################## # Given a list of N integers find the longest increasing subsequence in this list. # Example # If the list is [16, 3, 5, 19, 10, 14, 12, 0, 15] # one possible answer is the subsequence [3, 5, 10, 12, 15], another is [3, 5, 10, 14, 15]. # If the list has only one integer, for example: [14], the correct answer is [14]. # One more example: [10, 8, 6, 4, 2, 0], a possible correct answer is [8]. # Function to print the longest increasing subsequence def lisNumbers(arr): n = len(arr) # Declare the list (array) for LIS and # initialize LIS values for all indexes by 1 lis = [1]*n # Compute optimized LIS values in bottom up manner for i in range (1 , n): for j in range(0 , i): if arr[i] > arr[j] and lis[i] < lis[j] + 1 : lis[i] = lis[j]+1 # print(arr) # print(lis) myLISlist = [] # Print the LIS sequence from all LIS values for i in range(0, len(lis)): if(i == 0): myLISlist.append(arr[0]) elif(i > 0 and lis[i] == lis[i-1]): if(arr[i] > arr[i-1]): myLISlist.append(arr[i-1]) else: myLISlist.remove(arr[i-1]) myLISlist.append(arr[i]) elif(i > 0 and lis[i] > lis[i-1]): myLISlist.append(arr[i]) print myLISlist lisNumbers([10, 22, 9, 33, 21, 50, 41, 60]) lisNumbers([16, 3, 5, 19, 10, 14, 12, 0, 15]) lisNumbers([10, 8, 6, 4, 2, 0])
true
b4c01ca063d09ba24aff1bfe44c719043d24d1c3
omvikram/python-ds-algo
/dynamic-programming/pattern_search_typo.py
1,035
4.28125
4
# Input is read from the standard input. On the first line will be the word W. # On the second line will be the text to search. # The result is written to the standard output. It must consist of one integer - # the number of occurrences of W in the text including the typos as defined above. # SAMPLE INPUT # banana # there are three bananas on the tree and one banano on the ground # SAMPLE OUTPUT # 2 def findTyposCount(): txt = input("Please enter the searching text here:") pat = input("Please enter the searchable pattern here:") pat_len = len(pat) txt_arr = txt.split(" ") counter_list = [] for each in txt_arr: counter = 0 txt_len = len(each) if(txt_len >= pat_len): ## Call a function to check the max possible match between each text and pattern ## If matching count > 1 then we can consider it as typo (ideally matching count > pat_len/2) counter_list.append(each) print(counter_list) findTyposCount()
true
a3ca34db407b81382afc3e61e6abbc74eed86c3a
omvikram/python-ds-algo
/dynamic-programming/bit_count.py
568
4.3125
4
# Function to get no of bits in binary representation of positive integer def countBits(n): count = 0 # using right shift operator while (n): count += 1 n >>= 1 return count # Driver program i = 65 print(countBits(i)) ########################################################################## # Python3 program to find total bit in given number import math def countBitsByLog(number): # log function in base 2 take only integer part return int((math.log(number) / math.log(2)) + 1); # Driver Code num = 65; print(countBitsByLog(num));
true
5fff518a9ffe783632b8d28920772fbc7ab54467
omvikram/python-ds-algo
/data-strucutres/linked_list.py
1,483
4.4375
4
# Python program to create linked list and its main functionality # push, pop and print the linked list # Node class class Node: # Constructor to initialize # the node object def __init__(self, data): self.data = data self.next = None # LinkedList class class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Remove an item from the LinkedList def pop(self, key): temp = self.head # If head node itself holds the key to be deleted if(self.head.data == key): self.head = temp.next temp = None return # this loop is to just set the prev node while (temp is not None): if(temp.data == key): break else: prev = temp temp = temp.next #after the loop just change the next node if(temp == None): return prev.next = temp.next temp = None # Utility function to print it the linked LinkedList def printList(self): temp = self.head while(temp): print(temp.data) temp = temp.next # Driver program for testing llist = LinkedList() llist.push(20) llist.push(4) llist.push(15) llist.push(10) llist.printList() llist.pop(4) llist.printList()
true
8ac6c88830679c6fb29732e283ec1884d30fdaa8
omvikram/python-ds-algo
/data-strucutres/heap.py
742
4.125
4
import heapq ## heapify - This function converts a regular list to a heap. In the resulting heap the smallest element ## gets pushed to the index position 0. But rest of the data elements are not necessarily sorted. ## heappush – This function adds an element to the heap without altering the current heap. ## heappop - This function returns the smallest data element from the heap. ## heapreplace – This function replaces the smallest data element with a new value supplied in the function. H = [21,1,45,78,3,5] # Use heapify to rearrange the elements heapq.heapify(H) print(H) # Add element heapq.heappush(H,8) print(H) # Remove element from the heap heapq.heappop(H) print(H) # Replace an element heapq.heapreplace(H,6) print(H)
true
43486f405621613de5d973ecfa3dfed21356969f
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W11p2.py
1,257
4.75
5
# Give a string, remove all the punctuations in it and print only the words # in it. # Input format : # the input string with punctuations # Output format : # the output string without punctuations # Example # input # “Wow!!! It’s a beautiful morning” # output # Wow Its a beautiful morning # # Python Program for # # Creation of String # # Creating a String # # with single Quotes # String1 = 'Welcome to the Geeks World' # print("String with the use of Single Quotes: ") # print(String1) # # Creating a String # # with double Quotes # String1 = "I'm a Geek" # print("\nString with the use of Double Quotes: ") # print(String1) # # Creating a String # # with triple Quotes # String1 = '''I'm a Geek and I live in a world of "Geeks"''' # print("\nString with the use of Triple Quotes: ") # print(String1) # # Creating String with triple # # Quotes allows multiple lines # String1 = '''Geeks # For # Life''' # print("\nCreating a multiline String: ") # print(String1) string=input() punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' for x in string.lower(): if x in punctuations: string = string.replace(x, "") print(string,end="")
true
ddce169af5d2b344a2d3ce1e4e90a8c381f767af
Adil-Anzarul/VSC-codes-c-cpp-python
/python_language/W9p2.py
949
4.1875
4
# Panagrams # Given an English sentence, check whether it is a panagram or not. # A panagram is a sentence containing all 26 letters in the English alphabet. # Input Format # A single line of the input contains a stirng s. # Output Format # Print Yes or No # Example: # Input: # The quick brown fox jumps over a lazy dog # Output: # Yes # Input: # The world will be taken over by AI # Output: # No l = input().lower() s = 'abcdefghijklmnopqrstuvwxyz' for i in s: if i not in l: print('No',end='') break else: print('Yes',end='') # import string as st # s=list(input().upper()) # if list(st.ascii_uppercase) == sorted(list(set(sorted(s)[sorted(s).index('A'):]))): # print("Yes",end="") # else: # print('No',end="") # # import string library function # import string # # Storing the value in variable result # result = string.ascii_uppercase # # Printing the value # print(result) # print(type(result))
true
7e21b51ec88b79191088614971bbc325fff0fabf
AhhhHmmm/Programming-HTML-and-CSS-Generator
/exampleInput.py
266
4.15625
4
import turtle # This is a comment. turtle = Turtle() inputs = ["thing1", "thing2", "thing3"] for thing in inputs: print(thing) # comment!!! print(3 + 5) # little comment print('Hello world') # commmmmmmm 3 + 5 print("ahhhh") # ahhhh if x > 3: print(x ** 2)
true
df7282d45332baf2d25d9ca1794b55cd802aac6c
evab19/verklegt1
/Source/models/Airplane.py
1,156
4.25
4
class Airplane: '''Module Airplane class Module classes are used by the logic layer classes to create new instances of Airplane gets an instance of a Airplane information list Returns parameters if successful --------------------------------- ''' def __init__(self, name = "", model = "", producer = "", number_of_seats = "", plane_status = "A"): self.name = name self.model = model self.producer = producer self.number_of_seats = number_of_seats self.plane_status = plane_status def __str__(self): return "{}{:20}{}{:20}{}{:25}{}{:20}{}{:10}{}".format('| ', self.name, '| ', self.model, '| ', self.producer, '| ', str(self.number_of_seats), '| ', str(self.plane_status), '|') def get_name(self): return str(self.name) def get_model(self): return str(self.model) def get_producer(self): return str(self.producer) def get_number_of_seats(self): return str(self.number_of_seats) def get_plane_status(self): return str(self.plane_status)
true
905df9bcdb837b6e0692e1b2033aff9f72619a45
DrakeDwornik/Data2-2Q1
/quiz1/palindrome.py
280
4.25
4
def palindrome(value: str) -> bool: """ This function determines if a word or phrase is a palindrome :param value: A string :return: A boolean """ result = True value_rev = value[::-1] if value != value_rev: result = False return result
true
15250c4e99d8133175c5956444b1473f70f194bb
Steven98788/Ch.03_Input_Output
/3.1_Temperature.py
446
4.5
4
''' TEMPERATURE PROGRAM ------------------- Create a program that asks the user for a temperature in Fahrenheit, and then prints the temperature in Celsius. Test with the following: In: 32 Out: 0 In: 212 Out: 100 In: 52 Out: 11.1 In: 25 Out: -3.9 In: -40 Out: -40 ''' print("Welcome to my Fahrenheit to Celsius converter!") Fahrenheit=int(input("What is your Fahrenheit?")) Celsius=(Fahrenheit-32)*5/9 print("Your Celsius is",Celsius)
true
30cb2152ba61fdc70e20fde9f9b71daa05ffafa1
divyachandramouli/Data_structures_and_algorithms
/4_Searching_and_sorting/Bubble_sort/bubble_sort_v1.py
555
4.21875
4
# Implementation of bubble sort def bubble_sorter(arr): n=len(arr) i=0 for j in range(0,n): for i in range(0,n-j-1): #In the jth iteration, last j elements have bubbled up so leave them if (arr[i]>arr[i+1]): arr[i],arr[i+1]=arr[i+1],arr[i] return arr array1=[21,4,1,3,9,20,25,6,21,14] print(bubble_sorter(array1)) " Average and worst case time complexity: O(n*n)" " The above algorithm always runs O(n^2) time even if the array is sorted." "It can be optimized by stopping the algorithm if inner loop didn't cause any swap"
true
3f3205aea8dd64a69b9ed91f6aab600d63da9475
divyachandramouli/Data_structures_and_algorithms
/3_Queue/Queue_builtin.py
384
4.21875
4
# Queue using Python's built in functions # Append adds an element to the tail (newest element) :Enqueue # Popleft removes and returns the head (oldest element) : Dequeue from collections import deque queue=deque(["muffin","cake","pastry"]) print(queue.popleft()) # No operation called popright - you dequeue the head which is the oldest element queue.append("cookie") print(queue)
true
91a3b5ba76ba9b77775c981e048aec2cae7e8d9d
Fabulinux/Project-Cognizant
/Challenges/Brian-08302017.py
1,007
4.25
4
import sys def main(): # While loop to check if input is valid while(1): # Try/Except statement for raw_input return try: # Prompt to tell user to input value then break out of while val = int(raw_input("Please input a positive integer: ").strip()) break except: # Except invalid input error and prompts again print "Invalid input, try again." continue # Construction of the staircase for step in xrange(val): # Variable to reduce redundancy breakpoint = val-step-1 # Creates the spaces for the step for space in range(0, breakpoint): sys.stdout.write(' ') # Creates the actual steps using "#" for pound in range(breakpoint, val): sys.stdout.write('#') #Print new line for next step print "" # Basic main method call in python if running as a stand alone program if __name__ == "__main__": main()
true
78f333af2427a13909aa28b67c4be1675d3e81f7
AlexOKeeffe123/mastermind
/game/board.py
2,682
4.15625
4
import random from typing import Text #Chase class Board: def __init__(self, length): """The class constructor Args: self (Display): an instance of Display """ self._items = {} # this is an empty dictionary self._solutionLength = length def to_string(self): """Converts the board data to its string representation. Args: self (Board): an instance of Board. Returns: string: A representation of the current board. """ lines = "\n--------------\n" for name, values in self._items.items(): # "Player {name}: ----, ****" lines += f"Player {name}: {values[1]}, {values[2]}\n" lines += "--------------" return lines def apply(self, turn): """ Applies the given turn to the playing surface. Gets player's turn, name, and values Args: self (Board): an instance of Board. turn (Turn): The turn to apply. """ guesserName = turn.get_guesser_name() values = self._items[guesserName] values[1] = turn.get_guess() values[2] = self._create_hint(values[0], values[1]) def prepare(self, player): """Sets up the board with an entry for each player. Args: self (Board): an instance of Board. player (string): gets player's values """ name = player.get_name() code = str(random.randint(10 ** (self._solutionLength - 1), 10 ** self._solutionLength)) guess = hint = "" for char in range(self._solutionLength): guess += "-" hint += "*" self._items[name] = [code, guess, hint] def _create_hint(self, code, guess): """Generates a hint based on the given code and guess. Args: self (Board): An instance of Board. code (string): The code to compare with. guess (string): The guess that was made. Returns: string: A hint in the form [xxxx]""" hint = "" for index, letter in enumerate(guess): if code[index] == letter: hint += "x" elif letter in code: hint += "o" else: hint += "*" return hint def get_solution(self, name): """Gets solution Args: self (Board): An instance of Board. Return: name (String): gets player's name integer (Int): gets code""" return self._items[name][0]
true
b614122fb0117d4dd5afb5f148f5f803013a3397
LeedsCodeDojo/Rosalind
/AndyB_Python/fibonacci.py
1,355
4.25
4
def fibonacci(n, multiplier=1): """ Generate Fibonacci Sequence fib(n) = fib(n-1) + fib(n-2)*multiplier NB Uses recursion rather than Dynamic programming """ if n <= 2: return 1 return fibonacci(n-1, multiplier) + fibonacci(n-2, multiplier) * multiplier def fibonacciDynamic(n, multiplier=1): """ Generate Fibonacci Sequence NB Uses Dynamic programming """ def processGeneration(populationHistory,generationCount): generationSize = populationHistory[-1] + populationHistory[-2] * multiplier populationHistory.append(generationSize) return populationHistory[1:] initialPopulation = [0,1] return reduce(processGeneration, xrange(n-1), initialPopulation)[-1] def mortalFibonacci(n, lifespan): """ Generate Fibonacci Sequence with Lifespan NB Uses Dynamic programming so that sufficent generations are held in list Last element of returned list contains the final generation """ def processGeneration(populationHistory,generationCount): generationSize = populationHistory[-1] + populationHistory[-2] - populationHistory[0] populationHistory.append(generationSize) return populationHistory[1:] initialPopulation = ([0] * (lifespan-1)) + [1] return reduce(processGeneration, xrange(n), initialPopulation)[-1]
true
65a0a9921a54d50b0e262cccf64d980c2762f2f7
edwinjosegeorge/pythonprogram
/longestPalindrome.py
838
4.125
4
def longestPalindrome(text): '''Prints the longest Palendrome substring from text''' palstring = set() #ensures that similar pattern is stored only once longest = 0 for i in range(len(text)-1): for j in range(i+2,len(text)+1): pattern = text[i:j] #generates words of min lenght 2 (substring) if pattern == pattern[::-1]: #checks for palendrome palstring.add(pattern) #stores all palindrome if len(pattern) > longest: longest = len(pattern) if len(palstring) == 0: print("No palindrome substring found found") else: print("Longest palindrome string are ") for pattern in palstring: if len(pattern) == longest: print(pattern) longestPalindrome(input("Enter some text : "))
true
c3e4d19ad6b650bd400a75799c512bb8eecad4c9
ldswaby/CMEECourseWork
/Week3/Code/get_TreeHeight.py
2,274
4.5
4
#!/usr/bin/env python3 """Calculate tree heights using Python and writes to csv. Accepts Two optional arguments: file name, and output directory path.""" ## Variables ## __author__ = 'Luke Swaby (lds20@ic.ac.uk), ' \ 'Jinkai Sun (jingkai.sun20@imperial.ac.uk), ' \ 'Acacia Tang (t.tang20@imperial.ac.uk), ' \ 'Dengku Tang (dengkui.tang20@imperial.ac.uk)' __version__ = '0.0.1' ## Imports ## import sys import pandas as pd import numpy as np ## Functions ## def TreesHeight(degrees, dist): """This function calculates heights of trees given distance of each tree from its base and angle to its top, using the trigonometric formula height = distance * tan(radians) Arguments: - degrees: The angle of elevation of tree - dist: The distance from base of tree (e.g., meters) Output: - The heights of the tree, same units as "distance" """ radians = degrees * np.pi / 180 height = dist * np.tan(radians) print(height) return height def main(argv): """Writes tree height results to CSV file including the input file name in the output file name. """ if len(argv) < 2: print("WARNING: no arguments parsed. Default filename used: " "'trees.csv'.\n") filename = "trees.csv" outdir = "../Data/" elif len(argv) == 2: filename = argv[1] outdir = "../Data/" elif len(argv) == 3: filename = argv[1] outdir = argv[2] # Accept output directory path as second arg else: print("WARNING: too many arguments parsed.Default filename used: " "'trees.csv'.\n") filename = "trees.csv" outdir = "../Data/" filename_noExt = filename.split('/')[-1].split('.')[0] # Assumes no full # stops in filename save_name = "../Results/%s_treeheights_python.csv" % filename_noExt filepath = outdir + filename trees_data = pd.DataFrame(pd.read_csv(filepath)) trees_data["Height"] = TreesHeight(trees_data["Angle.degrees"], trees_data["Distance.m"]) # Save to csv trees_data.to_csv(save_name, sep=",", index=False) return 0 ## Main ## if __name__ == "__main__": status = main(sys.argv) sys.exit(status)
true
954c952dba2e72d6b70c9d345b96090b0a43b732
timmy61109/Introduction-to-Programming-Using-Python
/examples/TestSet.py
549
4.3125
4
from Set import Set set = Set() # Create an empty set set.add(45) set.add(13) set.add(43) set.add(43) set.add(1) set.add(2) print("Elements in set: " + str(set)) print("Number of elements in set: " + str(set.getSize())) print("Is 1 in set? " + str(set.contains(1))) print("Is 11 in set? " + str(set.contains(11))) set.remove(2) print("After deleting 2, the set is " + str(set)) print("The internal table for set is " + set.getTable()) set.clear() print("After deleting all elements") print("The internal table for set is " + set.getTable())
true
f20df9950890ea3b43729837524065283366aa60
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeFactorialTailRecursion.py
322
4.15625
4
# Return the factorial for a specified number def factorial(n): return factorialHelper(n, 1) # Call auxiliary function # Auxiliary tail-recursive function for factorial def factorialHelper(n, result): if n == 0: return result else: return factorialHelper(n - 1, n * result) # Recursive call
true
0ad23dca684097914370ac9f35a385b80ed74cc4
timmy61109/Introduction-to-Programming-Using-Python
/examples/ComputeLoan.py
687
4.21875
4
# Enter yearly interest rate annualInterestRate = eval(input( "Enter annual interest rate, e.g., 8.25: ")) monthlyInterestRate = annualInterestRate / 1200 # Enter number of years numberOfYears = eval(input( "Enter number of years as an integer, e.g., 5: ")) # Enter loan amount loanAmount = eval(input("Enter loan amount, e.g., 120000.95: ")) # Calculate payment monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12)) totalPayment = monthlyPayment * numberOfYears * 12 # Display results print("The monthly payment is", int(monthlyPayment * 100) / 100) print("The total payment is", int(totalPayment * 100) /100)
true
97a050e009a2c1e53a1842a6c7de60a6d6148b90
timmy61109/Introduction-to-Programming-Using-Python
/examples/QuickSort.py
1,267
4.21875
4
def quickSort(list): quickSortHelper(list, 0, len(list) - 1) def quickSortHelper(list, first, last): if last > first: pivotIndex = partition(list, first, last) quickSortHelper(list, first, pivotIndex - 1) quickSortHelper(list, pivotIndex + 1, last) # Partition list[first..last] def partition(list, first, last): pivot = list[first] # Choose the first element as the pivot low = first + 1 # Index for forward search high = last # Index for backward search while high > low: # Search forward from left while low <= high and list[low] <= pivot: low += 1 # Search backward from right while low <= high and list[high] > pivot: high -= 1 # Swap two elements in the list if high > low: list[high], list[low] = list[low], list[low] while high > first and list[high] >= pivot: high -= 1 # Swap pivot with list[high] if pivot > list[high]: list[first] = list[high] list[high] = pivot return high else: return first # A test function def main(): list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12] quickSort(list) for v in list: print(str(v) + " ", end = "") main()
true
324bb0fd6f126c77d953ba9dc1096f8bdb0d9a50
timmy61109/Introduction-to-Programming-Using-Python
/examples/SierpinskiTriangle.py
2,218
4.25
4
from tkinter import * # Import tkinter class SierpinskiTriangle: def __init__(self): window = Tk() # Create a window window.title("Sierpinski Triangle") # Set a title self.width = 200 self.height = 200 self.canvas = Canvas(window, width = self.width, height = self.height) self.canvas.pack() # Add a label, an entry, and a button to frame1 frame1 = Frame(window) # Create and add a frame to window frame1.pack() Label(frame1, text = "Enter an order: ").pack(side = LEFT) self.order = StringVar() entry = Entry(frame1, textvariable = self.order, justify = RIGHT).pack(side = LEFT) Button(frame1, text = "Display Sierpinski Triangle", command = self.display).pack(side = LEFT) window.mainloop() # Create an event loop def display(self): self.canvas.delete("line") p1 = [self.width / 2, 10] p2 = [10, self.height - 10] p3 = [self.width - 10, self.height - 10] self.displayTriangles(int(self.order.get()), p1, p2, p3) def displayTriangles(self, order, p1, p2, p3): if order == 0: # Base condition # Draw a triangle to connect three points self.drawLine(p1, p2) self.drawLine(p2, p3) self.drawLine(p3, p1) else: # Get the midpoint of each triangle's edge p12 = self.midpoint(p1, p2) p23 = self.midpoint(p2, p3) p31 = self.midpoint(p3, p1) # Recursively display three triangles self.displayTriangles(order - 1, p1, p12, p31) self.displayTriangles(order - 1, p12, p2, p23) self.displayTriangles(order - 1, p31, p23, p3) def drawLine(self, p1, p2): self.canvas.create_line( p1[0], p1[1], p2[0], p2[1], tags = "line") # Return the midpoint between two points def midpoint(self, p1, p2): p = 2 * [0] p[0] = (p1[0] + p2[0]) / 2 p[1] = (p1[1] + p2[1]) / 2 return p SierpinskiTriangle() # Create GUI
true
bf8d3d46a74e9da8fe560231ceb161cd57a3316d
timmy61109/Introduction-to-Programming-Using-Python
/examples/MergeSort.py
1,246
4.21875
4
def mergeSort(list): if len(list) > 1: # Merge sort the first half firstHalf = list[ : len(list) // 2] mergeSort(firstHalf) # Merge sort the second half secondHalf = list[len(list) // 2 : ] mergeSort(secondHalf) # Merge firstHalf with secondHalf into list merge(firstHalf, secondHalf, list) # Merge two sorted lists */ def merge(list1, list2, temp): current1 = 0 # Current index in list1 current2 = 0 # Current index in list2 current3 = 0 # Current index in temp while current1 < len(list1) and current2 < len(list2): if list1[current1] < list2[current2]: temp[current3] = list1[current1] current1 += 1 current3 += 1 else: temp[current3] = list2[current2] current2 += 1 current3 += 1 while current1 < len(list1): temp[current3] = list1[current1] current1 += 1 current3 += 1 while current2 < len(list2): temp[current3] = list2[current2] current2 += 1 current3 += 1 def main(): list = [2, 3, 2, 5, 6, 1, -2, 3, 14, 12] mergeSort(list) for v in list: print(str(v) + " ", end = "") main()
true
674a0def98a2f37c3dae8cf1ce070c767431b66a
timmy61109/Introduction-to-Programming-Using-Python
/examples/EfficientPrimeNumbers.py
1,451
4.15625
4
def main(): n = eval(input("Find all prime numbers <= n, enter n: ")) # A list to hold prime numbers list = [] NUMBER_PER_LINE = 10 # Display 10 per line count = 0 # Count the number of prime numbers number = 2 # A number to be tested for primeness squareRoot = 1 # Check whether number <= squareRoot print("The prime numbers are \n") # Repeatedly find prime numbers while number <= n: # Assume the number is prime isPrime = True # Is the current number prime? if squareRoot * squareRoot < number: squareRoot += 1 # Test whether number is prime k = 0 while k < len(list) and list[k] <= squareRoot: if number % list[k] == 0: # If true, not prime isPrime = False # Set isPrime to false break # Exit the for loop k += 1 # Print the prime number and increase the count if isPrime: count += 1 # Increase the count list.append(number) # Add a new prime to the list if count % NUMBER_PER_LINE == 0: # Print the number and advance to the new line print(number); else: print(str(number) + " ", end = "") # Check whether the next number is prime number += 1 print("\n" + str(count) + " prime(s) less than or equal to " + str(n)) main()
true
3eea73798a4ddc9043f2123d5ba6f919ca239929
timmy61109/Introduction-to-Programming-Using-Python
/examples/DataAnalysis.py
496
4.15625
4
NUMBER_OF_ELEMENTS = 5 # For simplicity, use 5 instead of 100 numbers = [] # Create an empty list sum = 0 for i in range(NUMBER_OF_ELEMENTS): value = eval(input("Enter a new number: ")) numbers.append(value) sum += value average = sum / NUMBER_OF_ELEMENTS count = 0 # The number of elements above average for i in range(NUMBER_OF_ELEMENTS): if numbers[i] > average: count += 1 print("Average is", average) print("Number of elements above the average is", count)
true
255e39ff64323b2afa0102ac92302511229317d6
timmy61109/Introduction-to-Programming-Using-Python
/examples/TwoChessBoard.py
1,263
4.15625
4
import turtle def main(): drawChessboard(-260, -20, -120, 120) # Draw first chess board drawChessboard(20, 260, -120, 120) # Draw second chess board turtle.hideturtle() turtle.done() # Draw one chess board def drawChessboard(startx, endx, starty, endy): # Draw chess board borders turtle.pensize(3) # Set pen thickness to 3 pixels turtle.penup() # Pull the pen up turtle.goto(startx, starty) turtle.pendown() # Pull the pen down turtle.color("red") for i in range(4): turtle.forward(240) # Draw a line turtle.left(90) # Turn left 90 degrees # Draw chess board inside drawMultipleRectangle(startx, endx, starty, endy) drawMultipleRectangle(startx + 30, endx, starty + 30, endy) # Draw multiple rectangles def drawMultipleRectangle(startx, endx, starty, endy): turtle.color("black") for j in range(starty, endy, 60): for i in range(startx, endx, 60): fillRectangle(i, j) # Draw a small rectangle def fillRectangle(i, j): turtle.penup() turtle.goto(i, j) turtle.pendown() turtle.begin_fill() for k in range(4): turtle.forward(30) # Draw a line turtle.left(90) # Turn left 90 degrees turtle.end_fill() main()
true
6bfb64ca94d7670bada63dfcd9229cba6baa3d25
wjr0102/Leetcode
/Easy/MinCostClimb.py
1,094
4.21875
4
#!/usr/local/bin # -*- coding: utf-8 -*- # @Author: Jingrou Wu # @Date: 2019-05-07 01:46:49 # @Last Modified by: Jingrou Wu # @Last Modified time: 2019-05-07 01:53:03 ''' On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed). Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1. Example 1: Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top. Example 2: Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3]. ''' import sys def minCostClimbingStairs(cost): """ :type cost: List[int] :rtype: int """ result = [sys.maxsize for i in range(len(cost))] result[0] = cost[0] result[1] = min(cost[0], cost[1]) for i in range(2, len(cost)): result[i] = min(result[i - 1], result[i - 2] + cost[i]) return result[len(cost) - 1]
true
f7a5fe592f5c42ffa1b5d8f6d63d11d588403556
ujjwalbaid0408/Python-Tutorial-with-Examples
/Ex22_StructuringElementForMorphological Transformations.py
697
4.15625
4
# Structuring element """ We manually created a structuring elements in the previous examples with help of Numpy. It is rectangular shape. But in some cases, you may need elliptical/ circular shaped kernels. So for this purpose, OpenCV has a function, cv2.getStructuringElement(). You just pass the shape and size of the kernel, you get the desired kernel. """ import cv2 import numpy as np # Rectangular Kernel rect = cv2.getStructuringElement(cv2.MORPH_RECT,(5,5)) # Elliptical Kernel ellipt = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) # Cross-shaped Kernel cross = cv2.getStructuringElement(cv2.MORPH_CROSS,(5,5)) print rect print ellipt print cross
true
da60d5b35c0c7be1a238dd303ce6ce1f07d9ae80
Max-Fu/MNISTPractice
/Digits_With_Neural_Network.py
1,035
4.21875
4
#!/usr/bin/python #Import data and functions from scikit-learn packets, import plotting function from matplotlib from sklearn.neural_network import MLPClassifier import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm #load the digits and asign it to digits digits = datasets.load_digits() #Use MLPClassifier (provided by sci-kit learn) to create a Neural Network with five layers (supervised learning) #lbfgs: stochastic gradient descent #hidden_layer_sizes: five hidden units and two hidden layer #alpha: regulation penalty clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5,2), random_state = 4) #load trainning data sets to two vectors X and y X,y = digits.data[:-10], digits.target[:-10] #Apply the neural network to the data set clf.fit(X,y) #print the prediction print('Prediction: ', clf.predict(digits.data[-2])) #print the picture of the digit plt.imshow(digits.images[-2], cmap=plt.cm.gray_r, interpolation = "nearest") #show the digit with matplotlib plt.show()
true
521f7092961eafb8ec49952366a9457e6549341f
HackerajOfficial/PythonExamples
/exercise1.py
348
4.3125
4
'''Given the following list of strings: names = ['alice', 'bertrand', 'charlene'] produce the following lists: (1) a list of all upper case names; (2) a list of capitalized (first letter upper case);''' names = ['alice', 'bertrand', 'charlene'] upNames =[x.upper() for x in names] print(upNames) cNames = [x.title() for x in names] print(cNames)
true
fd9c99441cba0d403b6b880db4444f95874eeb0c
micriver/leetcode-solutions
/1684.py
2,376
4.3125
4
""" You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed. Return the number of consistent strings in the array words. Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Output: 2 Explanation: Strings "aaab" and "baa" are consistent since they only contain characters 'a' and 'b'. Example 2: Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: All strings are consistent. Example 3: Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] Output: 4 Explanation: Strings "cc", "acd", "ac", and "d" are consistent. Constraints: 1 <= words.length <= 104 1 <= allowed.length <= 26 1 <= words[i].length <= 10 The characters in allowed are distinct. words[i] and allowed contain only lowercase English letters. Count the number of strings where the allowed characters are consistent if words[i][j] DOES NOT EQUAL ab[i] * n then do not increase the count to return """ allowed = "ab" words = ["ad", "bd", "aaab", "baa", "badab"] # Output: 2 def countConsistentStrings(allowed, words): # count = 0 # loop through words # for i in range(len(words)): # for j in range(len(words[i])): # print(words[i][j]) # for i in range(len(words)): # for j in range(len(words[i])): # # for x in range(len(allowed)): # x = 0 # while x in range(len(allowed)): # if words[i][j] == allowed[x]: # x += 1 # if j == len(words[i]) - 1: # count += 1 # else: # i += 1 # return count count = 0 allowed = set(allowed) for word in words: for letter in word: if letter not in allowed: count += 1 break # return the number of consistent strings return len(words) - count # couldn't figure out a solution so decided to go with: https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/971323/Python-3-solution-100-faster-than-any-other-codes # what is set(): https://www.geeksforgeeks.org/python-set-method/ # countConsistentStrings(allowed, words) print(countConsistentStrings(allowed, words))
true
aab785831638f7e29f6ca68343eff9c5cdc29c0e
micriver/leetcode-solutions
/1470_Shuffle_Array.py
983
4.375
4
""" Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] Example 3: Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] """ # What is happening? Using the given integer (n) as a separator creating two arrays, you must reshuffle the given array and return a new array with the paired indexes from typing import List # nums = [2, 5, 1, 3, 4, 7] # n = 3 # Output: [2,3,5,4,1,7] nums = [1, 2, 3, 4, 4, 3, 2, 1] n = 4 # Output: [1, 4, 2, 3, 3, 2, 4, 1] def shuffle(nums: List[int], n: int) -> List[int]: result = [] for i in range(n): result.append(nums[i]) result.append(nums[i + n]) return result print(shuffle(nums, n))
true
26b569a159c98d69b9bdadbb2c8e498bacc41edf
sumibhatta/iwbootcamp-2
/Data-Types/26.py
348
4.3125
4
#Write a Python program to insert a given string at the beginning #of all items in a list. #Sample list : [1,2,3,4], string : emp #Expected output : ['emp1', 'emp2', 'emp3', 'emp4'] def addString(lis, str): newList = [] for item in lis: newList.append(str+"{}".format(item)) return newList print(addString([1,2,3,4], 'emp'))
true
3151f1dd3c21b3603d8c616b643cdfb3f25d79a3
sumibhatta/iwbootcamp-2
/Data-Types/12.py
218
4.21875
4
#Write a Python script that takes input from the user and # displays that input back in upper and lower cases. string = "Hello Friends" upper = string.upper() lower = string.lower() print(string) print(upper) print(lower)
true
aa5cdbd2c62421ab8a68d3112e4703ff70504bff
KenFin/sarcasm
/sarcasm.py
1,715
4.25
4
while True: mainSentence = input("Enter your sentence here: ").lower() # making everything lowercase letters = "" isCapital = 0 # Re-initializing variables to reset the sarcastic creator for letter in mainSentence: if letter == " ": # If there's a space in the sentence, add it back into the final sentence letters += " " elif isCapital == 0: # If it's not a space run it through the magic sentence converter compare = """1234567890-=[]\;',./`""" # List of all the special characters in a special order compare2 = """!@#$%^&*()_+{}|:"<>?~""" # List of all the shifted special characters in the same order count = 0 # Counting to retain which space the special character is in if letter in compare: for i in compare: count += 1 # Keeping track of what space the special character is in if letter == i: letter = compare2[count-1] # Changes the letter break elif letter in compare2: # Checks to see if the special character is a shifted one for i in compare2: count += 1 # Keeps track of the space if letter == i: letter = compare[count-1] # Changes the letter break letters += letter.capitalize() # Adds the letter and if it isn't a special character it capitalizes it isCapital += 1 # Allows it to alternate between capitalizing and not elif isCapital == 1: # If the last letter was changed just add this letter normally letters += letter # Adds letter to the sentence isCapital -= 1 # Allows next letter to be changed print(f"Here is your sarcastic sentence: {letters}") input("Press enter to continue.")
true
f44e6b5789ee7c3d75a1891cb4df186016ff8d1a
tgm1314-sschwarz/csv
/csv_uebung.py
2,240
4.34375
4
import csv class CSVTest: """ Class that can be used to read, append and write csv files. """ @staticmethod def open_file(name, like): """ Method for opening a csv file """ return open(name, like) @staticmethod def get_dialect(file): """ Method that sniffs out the dialect of a give csv file :param file: file you want to know the dialect off """ d = csv.Sniffer().sniff(file.read(1024)) file.seek(0) return d @staticmethod def reg_dialect(name, delimiter): """ Method that can be used to register a new dialect for yourself :param name: the name of the dialect you want to register :param delimiter: the delimiter you want to set for the dialect """ csv.register_dialect(name, delimiter=delimiter) @staticmethod def read_file(file, dialect): """ Method that can be used to read a csv file :param file: the file you want to read :param dialect: the dialect that is used in the file """ return csv.reader(file, dialect) @staticmethod def append_files(reader1, reader2): """ Method that can be used to append two csv files together so it can be put into a third one :param reader1: input from the first file :param reader2: input from the second file """ out = [] for row in reader1: out.append(row) for row in reader2: out.append(row) return out @staticmethod def write_file(file, dialect, output): """ Method that can be used for writing a new csv file :param file: name of the file you want to write :param dialect: the dialect the file you want to write has :param output: what the file you want to write contains """ writer = csv.writer(file, dialect=dialect) for i in output: writer.writerow(i) @staticmethod def close_file(file): """ Method that is used for closing the csv files once you are finished :param file: the file you want to close """ file.close()
true
c1249eca315f652960a09c2b903c93121c8a19c4
saiso12/ds_algo
/study/OOP/Employee.py
452
4.21875
4
''' There are two ways to assign values to properties of a class. Assign values when defining the class. Assign values in the main code. ''' class Employee: #defining initializer def __init__(self, ID=None, salary=None, department=None): self.ID = ID self.salary = salary self.department = department def tax(self): return self.salary * 0.2 def salaryPerDay(self): return self.salary / 30
true
60f24bde8f1acd6637010627b439584eb8d08f32
mosesobeng/Lab_Python_04
/Lab04_2_3.py
1,048
4.3125
4
print 'Question 2' ##2a. They will use the dictionary Data Structure cause they will need a key and value ## where stock is the key and price is the value shopStock ={'Apples ' : '7.3' , 'Bananas ' : '5.5' , 'Bread ' : '1.0' , 'Carrots ':'10.0','Champagne ':'20.90','Strawberries':'32.6'} print 'The Initial Items in the store' for i in shopStock: print i +' '+ shopStock[i] print'' ##Changing the value of straberries shopStock['Strawberries']='63.43' ##Adding another item to dictionary shopStock['Chicken ']='6.5' print 'The Final Items in the store' for i in shopStock: print i +' '+ shopStock[i] print'' print'' print'' print 'Question 3' ##3a. The list should be used ## ##3b. print 'The List for advertisement' in_stock = shopStock.keys() ##3c. always_in_stock=() ##convertion from list to tuple always_in_stock+=tuple(in_stock) ##3d. print '' print 'Come to shoprite! We always sell:' for i in always_in_stock : print i
true
863c76edceb3d1e98acd52d7b45b114153532a1f
PreetiChandrakar/Letsupgrade_Assignment
/Day1.py
634
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[4]: num=int(input("Enter Number to check prime or not:")) m=0 i=0 flag=0 m=int(num/2) for i in range(2,m+1): if(num%i==0) : print("Number is not prime") flag=1 break if(flag==0) : print("Number is prime") # In[3]: num=int(input("Enter Number to get Factotial:")) i=0 fact = 1 for i in range(2,num+1) : fact = fact * i print("Factorial of",num, "is:",fact) # In[8]: num=int(input("Enter Number till you need to find sum from 1 to:")) i=1 sum =0 while(i<=num): sum = sum + i i=i+1 print(sum) # In[ ]:
true
ba934740e3a009ec713f7c3630b71ec56d9bb699
killo21/poker-starting-hand
/cards.py
2,285
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 25 17:30:27 2020 @author: dshlyapnikov """ import random class Card: def __init__(self, suit, val): """Create card of suit suit [str] and value val [int] 1-13 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King suit can be "clubs", "diamonds", "hearts", "spades".""" assert type(suit) is str assert suit == "clubs" or suit == "diamonds" or suit == "hearts" or suit == "spades" assert type(val) is int assert val > 0 and val < 14 self.suit = suit self.val = val def getSuit(self): """A card's suit. Can be "clubs", "diamonds", "hearts", "spades".""" return self.suit def getVal(self): """A card's value. [int] 1-13. 1 - Ace, 2 - 2, 3 - 3,..., 11 - Jack, 12 - Queen, 13 - King""" return self.val def getShortHand(self): """Short hand [str] notation to represent a card. The first character is the chard's value 1-13, J, Q, K, or A. The second char is the card's suit C - clubs, D - diamonds, H - hearts, S - spades.""" result = "" if self.val == 1: result = "A" elif self.val == 11: result = "J" elif self.val == 12: result = "Q" elif self.val == 13: result = "K" else: result = str(self.val) result = result + self.suit[0].capitalize() return result class Deck: def __init__(self): """Creates a shuffled deck of 52 [card] objects.""" self.cardCount = 52 suits = ["clubs", "diamonds", "hearts", "spades"] self.cards = [] for suit in suits: for val in range(1, 14): c = Card(suit, val) self.cards.append(c) random.shuffle(self.cards) def getCount(self): """The [int] number of cards in the deck. Between 0-52 inclusive.""" return self.cardCount def draw(self): """The first [card] in the deck. Removed from the deck without replacement.""" card = self.cards[0] self.cards = self.cards[1:] self.cardCount -= 1 return card
true
141b6d72a3890b96f51838d1b4806763f0c60684
sivaneshl/python_ps
/tuple.py
801
4.25
4
t = ('Norway', 4.953, 4) # similar to list, but use ( ) print(t[1]) # access the elements of a tuple using [] print(len(t)) # length of a tuple for item in t: # items in a tuple can be accessed using a for print(item) print(t + (747, 'Bench')) # can be concatenated using + operator print(t) # immutable print(t * 3) # can be used with multiply operator # nested tuples a = ((120, 567), (747, 950), (474, 748), (747,738)) # nested tuples print(a[3]) print(a[3][1]) # single element tuple h = (849) print(h, type(h)) # this is treated as a int as a math exp h = (858,) # single element tuple with trailing comma print(h, type(h)) e = () # empty tuple print(e, type(e)) # parenthesis of literal tuples may be omitted p = 1, 1, 3, 5, 6, 9 print(p, type(p))
true
a29a778e801e3ca3e9a5904fafca8310de0b0b43
sivaneshl/python_ps
/range.py
541
4.28125
4
# range is a collection # arithmetic progression of integers print(range(5)) # supply the stop value for i in range(5): print(i) range(5, 10) # starting value 5; stop value 10 print(list(range(5, 10))) # wrapping this call to the list print(list(range(0, 10, 2))) # 2 is the step argument # enumerate - to count t = [6, 44, 532, 2232, 534536, 36443643] for i in enumerate(t): # enumerate returns a tuple print(i) # tuple unpacking of enumerate for i, v in enumerate(t): print("i={} v={}".format(i,v))
true
003112e87a05bb6da91942b2c5b3db98d082193a
joshua-hampton/my-isc-work
/python_work/functions.py
370
4.1875
4
#!/usr/bin/python def double_it(number): return 2*number def calc_hypo(a,b): if (type(a)==float or type(a)==int) and (type(b)==float or type(b)==int): hypo=((a**2)+(b**2))**0.5 else: print 'Error, wrong value type' hypo=False return hypo if __name__ == '__main__': print double_it(3) print double_it(3.5) print calc_hypo(3,4) print calc_hypo('2',3)
true
d2822cfa674d1c3701c46e6fd305bf665f26ace4
nkpydev/Algorithms
/Sorting Algorithms/Selection Sort/selection_sort.py
1,030
4.34375
4
#-------------------------------------------------------------------------# #! Python3 # Author : NK # Desc : Insertion Sort Implementation # Info : Find largest value and move it to the last position. #-------------------------------------------------------------------------# def sort_selection(user_input): l = len(user_input) for i in range(l-1,0,-1): max = 0 for j in range(1,i+1): if user_input[j]>user_input[max]: max = j user_input[max],user_input[i] = user_input[i],user_input[max] return user_input if __name__ == '__main__': final_sorted = [] get_user_input = [int(x) for x in input('\nEnter numbers to be sorted [seperated by ","]:').split(',')] #int(x) is import as we are looking forward to integers and not string value print('\nUser Input before Sorting:\t',get_user_input) final_sorted = sort_selection(get_user_input) print('\nUser Input after Bubble Sort:\t',get_user_input)
true
4cb75a34e0f6806c8990bc06079272effbc2451c
patrickdeyoreo/holbertonschool-interview
/0x19-making_change/0-making_change.py
1,161
4.15625
4
#!/usr/bin/python3 """ Given a list of coin denominations, determine the fewest number of coins needed to make a given amount. """ def makeChange(coins, total): """ Determine the fewest number of coins needed to make a given amount. Arguments: coins: list of coin denominations total: total amount to make Return: If the amount cannot be produced by the given denominations, return -1. Otherwise return the fewest number of coins needed to make the amount. """ if total > 0: checked = [True] checked.extend(False for _ in range(total)) n_coins = 0 queue = [0] while queue: n_coins += 1 level = [] for value in queue: for coin in coins: if value + coin == total: return n_coins if value + coin >= total: continue if not checked[value + coin]: checked[value + coin] = True level.append(value + coin) queue = level return -1 return 0
true
31d07fd3332e0b6ca050f4ee3df184451287d710
gauborg/code_snippets_python
/14_power_of_two.py
1,220
4.625
5
''' Description: The aim of this code is to identify if a given numer is a power of 2. The program requires user input. The method keeps bisecting the number by 2 until no further division by 2 is possible. ''' def check_power_of_two(a, val): # first check if a is odd or equal to zero or an integer if (a <= 0): print("Number is zero!") return None elif (a%2 != 0): print("Odd number! Cannot be a power of 2!") return None else: residual = a count = 0 while((residual != 0)): if (residual%2 == 1): return None # go on dividing by 2 every time half = residual/2 residual -= half count += 1 # stop when the final residual reaches 1 if (residual == 1): break return count # user input for number number = int(input("Enter a number = ")) # call function to check if the number is power of 2. power = check_power_of_two(number, 0) if (power != None): print("The number is a power of 2, power =", power) elif(power == None): print("The number is not a power of 2.")
true
f65d53c042bebae591090aebbf16b3b155e0eee2
gauborg/code_snippets_python
/7_random_num_generation.py
1,416
4.5
4
''' This is an example for showing different types of random number generation for quick reference. ''' # code snippet for different random options import os import random # generates a floating point number between 0 and 1 random1 = random.random() print(f"\nRandom floating value value between using random.random() = {random1}\n") # generates a floating number between a given range random2 = random.uniform(1, 5) print(f"Random floating vlaue between 1 and 5 using random.uniform() = {random2}\n") # generates a number using Gaussian distribution random3 = random.gauss(10, 2) print(f"Gaussian distribution with mean 10 and std deviation 2 using random.gauss() = {random3}\n") # generates a random integer between a range random4 = random.randrange(100) print(f"Random integer value between using random.randrange() = {random4}\n") # generates a random integer between a range with inclusion random5 = random.randrange(0, 100, 11) print(f"Random integer value with spacing 11 between using random.randrange() = {random5}\n") # choosing an element from a list at random random6 = random.choice(['win', 'lose', 'draw']) print(f"Random element chosen from the list using random.choice() = {random6}") print("If sequence is empty, it will raise IndexError.\n") # shuffling a list some_numbers = [1.003, 2.2, 5.22, 7.342, 21.5, 76.3, 433, 566, 7567, 65463] random.shuffle(some_numbers) print(some_numbers)
true
2c17e2b6ed89bebf30bbf9a2f25bb8f0793c0019
jkamby/portfolio
/docs/trivia/modulesAndClients/realcalc.py
1,358
4.15625
4
import sys import stdio def add(x, y): """ Returns the addition of two floats """ return float(x) + float(y) def sub(x, y): """ Returns the subtraction of two floats """ return float(x) - float(y) def mul(x, y): """ Returns the multiplication of two floats """ return float(x) * float(y) def div(x, y): """ Returns the division of two floats """ if(float(y) == 0): stdio.writeln("The divisor must not be zero.") return else: return float(x) / float(y) def mod(x, y): """ Returns the modulo of two ints """ if(int(y) == 0): stdio.writeln("The mudulo operand may not be zero.") return else: return int(x) % int(y) def exp(x, y): """ Returns the result of one float raised to the power of the other """ return float(x) ** float(y) def main(): a = sys.argv[1] b = sys.argv[2] stdio.writeln("Addition: " + str(add(a, b))) stdio.writeln("Subtraction: " + str(sub(a, b))) stdio.writeln("Multiplication: " + str(mul(a, b))) stdio.writeln("Division: " + str(div(a, b))) stdio.writeln("Modulo: " + str(mod(a, b))) stdio.writeln("Exponentiation: " + str(exp(a, b))) if __name__ == '__main__': main()
true
a743debf018b5322b6a681783aa0a009fbfd3b61
karingram0s/karanproject-solutions
/fibonacci.py
722
4.34375
4
#####---- checks if input is numerical. loop will break when an integer is entered def checkInput(myinput) : while (myinput.isnumeric() == False) : print('Invalid input, must be a number greater than 0') myinput = input('Enter number: ') return int(myinput) #####---- main print('This will print the Fibonacci sequence up to the desired number.') intinput = checkInput(input('Enter number: ')) while (intinput < 1) : print('Number is 0, please try again') intinput = checkInput(input('Enter number: ')) a = 0 b = 1 temp = 0 for i in range(intinput) : print('{0} '.format(a+b), end='', flush=True) if (i < 1) : continue else : temp = a + b a = b b = temp print('')
true
b97a94399afac9b9f793d680ffb01892f041ff25
arononeill/Python
/Variable_Practice/Dictionary_Methods.py
1,290
4.3125
4
import operator # Decalring a Dictionary Variable dictExample = { "student0" : "Bob", "student1" : "Lewis", "student2" : "Paddy", "student3" : "Steve", "student4" : "Pete" } print "\n\nDictionary method get() Returns the value of the searched key\n" find = dictExample.get("student0") print find print "\n\nDictionary method items() returns view of dictionary's (key, value) pair\n" view = dictExample.items() print "\n", view print "\n\nDictionary method keys() Returns View Object of All Keys\n" keys = dictExample.keys() print "\n", keys print "\n\nDictionary method popitem() Returns the dictionary contents\nminus the top key and value as they have been popped off the stack\n" dictExample.popitem() print dictExample print "\n\nDictionary method pop() removes and returns element having given key, student4\n\n" dictExample.pop("student4") print dictExample print "\n\nDictionary method max() returns largest key\n" print "max is ", max(dictExample) print "\nDictionary method min() returns smallest key\n" print "min is ", min(dictExample) print "\nDictionary method sorted() returns sorted keys in ascending order\n" print (sorted(dictExample)) print "\nDictionary method sorted() returns sorted keys in descending order\n" print (sorted(dictExample, reverse=True))
true
e54903690eceffc1bd7b49faa2db0f79d111f974
TheManyHatsClub/EveBot
/src/helpers/fileHelpers.py
711
4.125
4
# Take a file and read it into an array splitting on a given delimiter def parse_file_as_array(file, delimiter=None): # Open the file and get all lines that are not comments or blank with open(file, 'r') as fileHandler: read_data = [(line) for line in fileHandler.readlines() if is_blank_or_comment(line) == False] # If no delimiter is given, split on newlines, else we need to split on the delimiter if delimiter is None: file_array = read_data else: file_array = "".join(read_data).split(delimiter) return file_array # Determines whether a line is either blank or a comment def is_blank_or_comment(line): return line.strip() == '' or line[0:2] == "//"
true
97c80a0bc24deb72d908c283df28b314454bcfc5
KHilse/Python-Stacks-Queues
/Queue.py
2,139
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None def isEmpty(self): """Returns True if Queue is empty, False otherwise""" if self.head: return False return True def enqueue(self, item): """Adds an item to the back of queue""" if self.head: current_node = self.head while current_node.next != None: current_node = current_node.next new_node = Node(item) current_node.next = new_node else: new_node = Node(item) self.head = new_node def dequeue(self): """Removes the item from the front of queue. Returns the removed item""" if self.head: popped = self.head self.head = self.head.next return popped.data return False def peek(self): """Returns the first item in the queue, but doesn't remove it""" if self.head: return self.head.data return None def size(self): """Returns the (int) size of the queue""" current_node = self.head index = 0 while current_node: current_node = current_node.next index += 1 return index def __str__(self): """Returns a string representation of all items in queue""" current_node = self.head result = "" while current_node: if result != "": result = result + ", " result = result + current_node.data current_node = current_node.next return result my_queue = Queue() print('Is Queue empty?', my_queue.isEmpty()) my_queue.enqueue('A') my_queue.enqueue('B') my_queue.enqueue('C') my_queue.enqueue('D') print("queue state:", my_queue) print('Dequeued item:', my_queue.dequeue()) print('First item:', my_queue.peek()) print('Here are all the items in the queue:', my_queue) print('The size of my stack is:', my_queue.size()) # BONUS - Implement the Queue with a Linked List
true
485458ce7505e832f81aab7520d9fa16db630e89
kalstoykov/Python-Coding
/isPalindrome.py
1,094
4.375
4
import string def isPalindrome(aString): ''' aString: a string Returns True if aString is a Palindrome String strips punctuation Returns False otherwise. ''' alphabetStr = "abcdefghijklmnopqrstuvwxyz" newStr = "" # converting string to lower case and stripped of extra non alphabet characters aString = aString.lower() for letter in aString: if letter in alphabetStr: newStr += letter # if string is one letter or empty, it is a Palindrome if len(newStr) <= 1: return True # if string has more than 1 letter else: # reversing the string revStr = '' for i in range(len(newStr), 0, -1): revStr += newStr[i-1] # if string equals to reversed string, it is a Palindrome if list(newStr) == list(revStr): return True return False # Test cases print isPalindrome("Madam") # returns True print isPalindrome("Hello World") # returns False print isPalindrome(" Madam") # returns True print isPalindrome("1") # returns True
true
db1eedd2b2ea011786f6b26d58a1f72e5349fceb
mirarifhasan/PythonLearn
/function.py
440
4.15625
4
#Function # Printing the round value print(round(3.024)) print(round(-3.024)) print(min(1, 2, 3)) #If we call the function without parameter, it uses the default value def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() #Array passing in function def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits)
true
4235ddfb49c4281b0ecbb62fa93c9098ca025273
davisrao/ds-structures-practice
/06_single_letter_count.py
638
4.28125
4
def single_letter_count(word, letter): """How many times does letter appear in word (case-insensitively)? >>> single_letter_count('Hello World', 'h') 1 >>> single_letter_count('Hello World', 'z') 0 >>> single_letter_count("Hello World", 'l') 3 """ # we need to make the whole string lowercase # normal ltr of word + if statement lowercase_word = word.lower() counter = 0 for ltr in lowercase_word: if ltr == letter: counter +=1 return counter # look into the count method here - this makes thsi a lot easier
true
99db5d93dd6673b1afa97701b1fb8d09294223c0
timseymore/py-scripts
/Scripts/set.py
485
4.125
4
# -*- coding: utf-8 -*- """ Sets numerical sets and operations on them Created on Tue May 19 20:08:17 2020 @author: Tim """ test_set = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # returns a set of numbers in given range (inclusive) # that are divisible by either 2 or 3 def set_mod_2_3(size): temp = {} index = 0 for i in range(1, size + 1): if (i % 2 == 0) or (i % 3 == 0): temp[index] = i index += 1 return temp set1000 = set_mod_2_3(1000)
true
4bdf487e4600dfd927e4419f0c25391cfbfb721c
timseymore/py-scripts
/Scripts/counting.py
2,285
4.5
4
# -*- coding: utf-8 -*- """ Counting examples of counting and recursive counting used in cominatorics We will be implementing a graph consisting of nodes and then use recursive counting to find the number of possible paths from the start node to any given node in the graph. The number of possible paths to any given node is the sum of the possible paths to all of its sub-nodes. Created on Wed May 20 17:58:07 2020 @author: Tim """ # We start by defining a simple node class. class Node: def __init__(self, name: str, subs: list): self.name = name self.subs = subs # We will now create nodes that will # represent the structure of our graph. # It is a one-directional graph, where each sub-node (child) # has an arrow pointing to the parent node (self). # Note that any given node may have any number of parent nodes. N1 = Node("N1", []) N2 = Node("N2", [N1]) N3 = Node("N3", [N1]) N4 = Node("N4", [N2, N3]) N5 = Node("N5", [N2, N4]) N6 = Node("N6", [N3]) N7 = Node("N7", [N5]) N8 = Node("N8", [N5, N7]) N9 = Node("N9", [N6, N7]) N10 = Node("N10", [N8, N9]) # Let's create a function to recursively count # the number of possible paths from start (N1) to any given node n. # This is poor style however, the function should be an inner method of Node. def num_paths(n: Node): # We define a local helper-function to recursively count the paths. # Calling num_paths will be simpler without the need # to pass an accumulator, this will help avoid errors # by ensuring the accumulator is always called starting at 0 def aux(node, acc): if node.subs == []: # This is our base case: a node with no subs has one possible path return acc + 1 else: # Sum the number of paths to each sub and return the result for sub in node.subs: acc += aux(sub, 0) return acc return aux(n, 0) # Some test cases to check that it works correctly print(num_paths(N1) == 1) print(num_paths(N2) == 1) print(num_paths(N3) == 1) print(num_paths(N4) == 2) print(num_paths(N5) == 3) print(num_paths(N6) == 1) print(num_paths(N7) == 3) print(num_paths(N8) == 6) print(num_paths(N9) == 4) print(num_paths(N10) == 10)
true
6832a42539daa56e2f4c04a1238236a2cfc31e98
mmuratardag/DS_SpA_all_weeks
/DS_SpA_W10_Recommender_System/03_19/TeachMat/flask-recommender/recommender.py
1,270
4.1875
4
#!/usr/bin/env python import random MOVIES = ["The Green Book", "Django", "Hors de prix"] # def get_recommendation(): # return random.choice(MOVIES) def get_recommendation(user_input: dict): m1 = user_input["movie1"] r1 = user_input["rating1"] m2 = user_input["movie2"] r2 = user_input["rating2"] m3 = user_input["movie3"] r3 = user_input["rating3"] """The rest is up to you....HERE IS SOME PSEUDOCODE: 1. Train the model (NMF), OR the model is already pre-trained. 2. Process the input, e.g. convert movie titles into numbers: movie title -> column numbers 3. Data validation, e.g. spell check.... 4. Convert the user input into an array of length len(df.columns), ~9742 --here is where the cosine similarity will be a bit different-- 5. user_profile = nmf.transform(user_array). The "hidden feature profile" of the user, e.g. (9742, 20) 6. results = np.dot(user_profile, nmf.components_) 7. Sort the array, map the top N values to movie names. 8. Return the titles. """ return random.choice([m1, m2, m3]) if __name__ == "__main__": """good place for test code""" print("HELLO TENSORS!") movie = get_recommendation() print(movie)
true
26fded563d3655f5f06e2cdf582d0cdc564ab9dc
yveslox/Genesisras
/practice-code-blue/programme-python/lists.py
672
4.34375
4
#!/usr/bin/python list=[1,2,3,4,5,6,7,8]; print("list[0] :",list[0]) print("list[1] :",list[1]) print("list[2:5] :",list[2:5]) #updating list list[3] = 44 print("list(after update):",list) #delete element del list[3] print("list(after delete) :",list) #length of list print("length of list : ",len(list)) #appending two lists list2= [99,100] list = list + list2 print("list (after appending another list):",list) #check if an element is a me,berof list print("Is 6 present in list?:", 6 in list) #Iterate list elements for x in list: print (x) print("") #reserse the list list.reverse() print("After Sorting: ") for x in list: print (x)
true
9bac38cd3bc1014cc19216e4cbcda36f138dfef1
Ri8thik/Python-Practice-
/creat wedge using loop/loop.py
2,269
4.40625
4
import tkinter as tk from tkinter import ttk root=tk.Tk() # A) labels #here we create a labels using loop method # first we amke a list in which all the labels are present labels=["user name :-","user email :-","age:-","gender:-",'state:-',"city:-"] #start a for loop so that it print all the labels which are given in above list:- for i in range(len(labels)): # this print the labe[0] which means a current label cur_label="label" +str(i) # here we start a simple method in which we create a label cur_label=tk.Label(root,text=labels[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_label.grid(row=i,column=0,sticky=tk.W, padx=2, pady=2) # B) Entry box # to create a loop for entry bos so that it print many entry #first we create a dictunary in which we store the variable ,and that variable will store the data of the current entry user_info={ 'name': tk.StringVar(), "email" :tk.StringVar(), "age" :tk.StringVar(), "gender" : tk.StringVar(), "state" : tk.StringVar(), "city" : tk.StringVar() } #here is the counter variable which increases the value of row as the loop start counter =0 #here is the loop for i in user_info: #this print the first entry[i] or current entry[i] cur_entry='entry' + i # here is the simple methoid to create a entry and in textvariable we create a dictonaray user_info cur_entry=tk.Entry(root,width=16,textvariable=user_info[i]) # here we use the padding padx is use for left and right , pady is used for top and bottom cur_entry.grid(row=counter,column=1,padx=2, pady=2) # here the counter increment the valuye counter+=1 def submit(): print("user_name is :- " +user_info['name'].get()) print("user_email is :- " +user_info['email'].get()) print("user_age is :- " +user_info['age'].get()) print("gender :- " +user_info['gender'].get()) print("state :- " +user_info['state'].get()) print("city :- " +user_info['city'].get()) submit_btn =ttk.Button(root,text='submit',command=submit) submit_btn.grid(row=6,columnspan=2) root.mainloop()
true
fca8a93a245b027c0cfee51200e9e603c737f5df
rchu6120/python_workshops
/comparison_operators.py
234
4.21875
4
x = [1, 2, 3] y = list(x) # create a NEW list based on the value of x print(x, y) if x is y: print("equal value and identity") elif x == y: print("equal value but unqual identity") else: print("unequal")
true
1ef7c763b40ab15b9bb07313edc9be70f9efd5d6
rchu6120/python_workshops
/logic_hw.py
852
4.375
4
############# Ask the user for an integer ### If it is an even number, print "even" ### If it is an odd number, print "odd" ### If it is not an integer (e.g. character or decimal #), continue asking the user for an input ### THIS PROGRAM SHOULND'T CRASH UNDER THESE CIRCUMSTANCES: # The user enters an alphabet # The user enters a decimal number # The user enters a non numeric character # The user enters a negative number # For example, if the user enters "a", the program should ask the user to try again and enter an integer # Topic: conditionals, user input, loops # Hint: You can use the try except: while True: try: if int(input("Please enter an integer. \n")) % 2 == 0: print("even") break else: print("odd") break except: continue
true
5f5f657ef5fad9d08ad0a1657a97cbe83535cb09
HeyChriss/BYUI-Projects-Spring-2021
/Maclib.py
1,453
4.25
4
print ("Please enter the following: ") adjective = input("adjective: ") animal = input("animal: ") verb1 = input("verb: ") exclamation = input("exclamation: ") verb2 = input("verb : ") verb3 = input("verb: ") print () print ("Your story is: ") print () print (f"The other day, I was really in trouble. It all started when I saw a very") print (f'{adjective} {animal} {verb1} sneeze down the hallway. "{exclamation}!" I yelled. But all') print (f"I could think to do was to {verb2} over and over. Miraculously,") print (f"that caused it to stop, but not before it tried to {verb3}") print (f"right in front of my family. ") # I made it my own during this part forward, I added a second part of the story asking different information # to the person to keep going with the story print () print () print () print () print ("Keep going with the second part of the story...") print ("Please enter the following: ") day = input("day of the week: ") animal1 = input("animal: ") adjective1 = input("adjective: ") exclamation1 = input("exclamation: ") verb4 = input("verb : ") place = input("place: ") print () print ("The second part is: ") print () print (f"I almost died during that time, but on {day}") print (f'I saw a {animal1} and it was so {adjective1}') print (f"I tried to {verb4} but it was useless so I hurted myself and went to the {place} ") print (f"to watch TV :) ") print ("THE END OF THE STORY!")
true
7e46e20703c0a192343772c52686b4846904537d
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/Quick_Sort.py
2,603
4.375
4
#Quick Sort Implementation ************************** def quicksort(arr): """ Input: Unsorted list of intergers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(quicksort(l)) ''' *********************** return smaller , equal , larger #For this reason the final list will be returned as a tuple instead of a list. #To stop this from happening we then concatenate the l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) this will be returned as a tuple. ************************ ''' def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l))) ****************************8 def quicksort(arr): """ Input: Unsorted list of integers Returns sorted list of integers using Quicksort Note: This is not an in-place implementation. The In-place implementation with follow shortly after. """ if len(arr) < 2: return arr else: pivot = arr[-1] smaller, equal, larger = [], [], [] for num in arr: if num < pivot: smaller.append(num) elif num == pivot: equal.append(num) else: larger.append(num) #running the quick sort algo on the smaller list will return a sorted list in th return smaller + equal + larger l=[6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] print(type(quicksort(l)))
true
1ab91009e990c5f8858a019968d8a1616a9e4c09
UnimaidElectrical/PythonForBeginners
/Algorithms/Sorting_Algorithms/selection_sort.py
2,740
4.46875
4
# Selection Sort # Selection sort is also quite simple but frequently outperforms bubble sort. # With Selection sort, we divide our input list / array into two parts: the sublist # of items already sorted and the sublist of items remaining to be sorted that make up # the rest of the list. # We first find the smallest element in the unsorted sublist and # place it at the end of the sorted sublist. Thus, we are continuously grabbing the smallest # unsorted element and placing it in sorted order in the sorted sublist. # This process continues iteratively until the list is fully sorted. def selection_sort(arr): for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # Select the smallest value if arr[j] < arr[minimum]: minimum = j # Place it at the front of the # sorted end of the array arr[minimum], arr[i] = arr[i], arr[minimum] return arr arr = [4,1,6,4,8,10,28,-3,-45] selection_sort(arr) print(arr) Insertion sort explained. we need a marker which will move through the list on the outer loop Start iteration and compasins at first element Then check if the number on the second element smaller than the number at the marker. If not we can move to the next element. Next we check the third element with the marker if it is smaller than the marker (First Element) then do a swap else move to the next element on the list. We keep checking the next element with the marker until the end of the list. l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] bubble_sort(l) def bubble_sort(arr): sort_head = True while sort_head: print("Bubble Sort: " + str(arr)) sort_head = False for num in range(len(arr)-1): if arr[num]>arr[num+1]: sort_head = True arr[num],arr[num+1]=arr[num+1],arr[num] l = [4,1,6,4,8,10,28,-3,-45] bubble_sort(l) def selection_sort(arr): spot_marker=0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] #print('Item Swapped') spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l) def selection_sort(arr): spot_marker = 0 while spot_marker < len(arr): for num in range(spot_marker,len(arr)): if arr[num] < arr[spot_marker]: arr[spot_marker],arr[num]=arr[num],arr[spot_marker] spot_marker += 1 print(arr) l = [6, 8, 1, 4, 10, 7, 8, 9, 3, 2, 5] selection_sort(l)
true
38baa3eb890530cac3a056140908e23015070428
UnimaidElectrical/PythonForBeginners
/Random_code_store/If_Else_Statement/If_Else_statement.py
2,375
4.375
4
"""This mimicks the children games where we are asked to choose our own adventure """ print("""You enter a dark room with two doors. Do you go through door #1 or door #2?""") door = input ("> ") if door == "1": print("There's a giant bear here eating a cheese cake.") print("What do you want to do?") print("1. Take the cake.") print("2. Scream at the bear.") bear = input("> ") if bear == "1": print("The bear eats your face off. Good job!") elif bear=="2": print("The bear eats your leg off. Good job!") else: print(f"Well doing, {bear} is probable better.") print("Bear runs away.") elif door == "2": print("You stare into the endless abyss at Cthulhu's retina.") print("1. Blueberries.") print("2. Yellow jacket clothespins.") print("3. Understanding revolvers yelling melodies.") insanity = input("> ") if insanity == "1" or insanity =="2": print("Your body survives powered by the mind of jello.") print("Good Job!") else: print("The insanity rots your eyes into a pool of muck.") print("Good Job!") else: print("You stumble around and fall on a knife and die. Good Job!") # Else Statements # break # continue # The else statement is most commonly used along with the if statement, but it can also follow a for or while loop, which gives it a different meaning. # With the for or while loop, the code within it is called if the loop finishes normally (when a break statement does not cause an exit from the loop). Example: for i in range(10): if i == 999: break else: print("Unbroken 1") for i in range(10): if i == 5: break else: print("Unbroken 2") # The first for loop executes normally, resulting in the printing of "Unbroken 1". # The second loop exits due to a break, which is why it's else statement is not executed. # Try # Except # The else statement can also be used with try/except statements. # In this case, the code within it is only executed if no error occurs in the try statement. # Example: #Example2: try: print(1) except ZeroDivisionError: print(2) else: print(3) try: print(1/0) except ZeroDivisionError: print(4) else: print(5) # Example 2: try: print(1) print(1 + "1" == 2) print(2) except TypeError: print(3) else: print(4)
true
0f509b10fd23df81cd306ea05a6ae07e6b9c13b3
UnimaidElectrical/PythonForBeginners
/Random_code_store/Lists/In_Operators.py
453
4.34375
4
#The In operator in python can be used to determine weather or not a string is a substring of another string. #what is the optcome of these code: nums=[10,9,8,7,6,5] nums[0]=nums[1]-5 if 4 in nums: print(nums[3]) else: print(nums[4]) #To check if an item is not in the list you can use the NOT operator #In this case the pattern doesn't matter. nums=[1,2,3] print(not 4 in nums) print(4 not in nums) print(not 3 in nums) print(3 not in nums)
true
ff97e60837bf32c1dc1f65ef8afda4f658a7116b
lchristopher99/CSE-Python
/CSElab6/turtle lab.py
2,207
4.5625
5
#Name: Jason Hwang, Travis Taliancich, Logan Christopher, Rees Hogue Date Assigned: 10/19/2018 # #Course: CSE 1284 Section 14 Date Due: 10/20/2018 # #File name: Geometry # #Program Description: Make a geometric shape #This is the function for making the circle using turtle def draw_circle(x, y, r): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.circle(r) turtle.penup() #This is the function for making the rectangle using turtle def draw_rectangle(x, y, width, height): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.left(90) turtle.forward(width) turtle.left(90) turtle.forward(height) turtle.penup() #This is the function for making the point using turtle def draw_point(x, y, size): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(size) turtle.left(180) turtle.forward(size * 2) turtle.left(180) turtle.forward(size) turtle.left(90) turtle.forward(size) turtle.left(180) turtle.forward(size * 2) #This is the function for making the line using turtle def draw_line(x1, y1, x2, y2): import turtle turtle.penup() turtle.goto(x1, y1) turtle.pendown() turtle.goto(x2, y2) turtle.penup() #This is the function for making the triangle using turtle. def draw_triangle(x, y, side): import turtle turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.left(120) turtle.forward(side) turtle.penup() #the function that will call all of the functions def main(): draw_circle(-100, -100, 200) draw_circle(100, 100, 200) draw_rectangle(10, 10, 50, 70) draw_rectangle(90, 90, 100, 150) draw_point(0, 0, 50) draw_point(70, 70, 50) draw_line(20, 20, 30, 70) draw_line(300, 200, 100, 150) draw_triangle(100, 100, 50) draw_triangle(-100, -150, 50) main()
true
5e447702f51cd3318fd5595a131da34c2bc498d5
endreujhelyi/endreujhelyi
/week-04/day-3/04.py
528
4.3125
4
# create a 300x300 canvas. # create a line drawing function that takes 2 parameters: # the x and y coordinates of the line's starting point # and draws a line from that point to the center of the canvas. # draw 3 lines with that function. from tkinter import * top = Tk() size = 300 canvas = Canvas(top, bg="#222", height=size, width=size) def line_drawer(x, y): return canvas.create_line(x, y, size/2, size/2, fill='coral') line_drawer(20, 40) line_drawer(130, 50) line_drawer(220, 100) canvas.pack() top.mainloop()
true
0c2563d42a29e81071c4a2667ace0495477ac241
endreujhelyi/endreujhelyi
/week-04/day-3/08.py
534
4.1875
4
# create a 300x300 canvas. # create a square drawing function that takes 2 parameters: # the x and y coordinates of the square's top left corner # and draws a 50x50 square from that point. # draw 3 squares with that function. from tkinter import * top = Tk() size = 300 lines = 3 canvas = Canvas(top, bg="#222", height=size, width=size) def square_drawer(x, y): return canvas.create_rectangle(x, y, x+50, y+50, fill='coral') square_drawer(20, 40) square_drawer(130, 50) square_drawer(220, 100) canvas.pack() top.mainloop()
true
dc27b4d07c81d4faed52867851a4b623ac3a7ca3
jonathan-potter/MathStuff
/primes/SieveOfAtkin.py
1,824
4.21875
4
########################################################################## # # Programmer: Jonathan Potter # ########################################################################## import numpy as np ########################################################################## # Determine the sum of all prime numbers less than an input number ########################################################################## def SieveOfAtkin(limit): """usage SieveOfAtkin(limit) This function returns a list of all primes below a given limit. It is an implimentation of the Sieve of Atkin. The primary logic is a reimplimentation of the example on Wikipedia. en.m.wikipedia/wiki/Sieve_of_Atkin""" # calculate and store the square root of the limit sqrtLimit = np.int(np.ceil(np.sqrt(limit))); # initialize the sieve isPrime = [False] * limit; # this script considers 1 to be prime. If you don't like it, # subtract 1 from the result isPrime[1:3] = [True] * 3; # impliment the sieve for x in range (1,sqrtLimit+1): for y in range(1,sqrtLimit+1): n = 4 * x**2 + y**2; if (n <= limit and (n % 12 == 1 or n % 12 == 5)): isPrime[n] = not(isPrime[n]); n = 3 * x**2 + y**2; if (n <= limit and n % 12 == 7): isPrime[n] = not(isPrime[n]); n = 3 * x**2 - y**2; if (n <= limit and x > y and n % 12 == 11): isPrime[n] = not(isPrime[n]); # for prime n: ensure that all of the multiples of n^2 are not flagged as prime for n in range(5,sqrtLimit+1): if isPrime[n]: isPrime[n**2::n**2] = [False] * len(isPrime[n**2::n**2]); # create array of prime numbers below limit primeArray = []; for n in range(limit + 1): if isPrime[n] == True: primeArray.append(n); # return the result return primeArray;
true
6733b7b848e1e271f7f3d313284348f9e9fab0a8
gyhou/DS-Unit-3-Sprint-2-SQL-and-Databases
/SC/northwind.py
2,546
4.5625
5
import sqlite3 # Connect to sqlite3 file conn = sqlite3.connect('northwind_small.sqlite3') curs = conn.cursor() # Get names of table in database print(curs.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").fetchall()) # What are the ten most expensive items (per unit price) in the database? """[('Côte de Blaye',), ('Thüringer Rostbratwurst',), ('Mishi Kobe Niku',), ("Sir Rodney's Marmalade",), ('Carnarvon Tigers',), ('Raclette Courdavault',), ('Manjimup Dried Apples',), ('Tarte au sucre',), ('Ipoh Coffee',), ('Rössle Sauerkraut',)]""" print(curs.execute(""" SELECT ProductName, SupplierId FROM Product ORDER BY UnitPrice DESC LIMIT 10;""").fetchall()) # What is the average age of an employee at the time of their hiring? (Hint: a lot of arithmetic works with dates.) # 37.22 years old print(curs.execute(""" SELECT AVG(age) FROM ( SELECT HireDate-BirthDate AS age FROM Employee GROUP BY Id);""").fetchall()) # (Stretch) How does the average age of employee at hire vary by city? """[('Kirkland', 29.0), ('London', 32.5), ('Redmond', 56.0), ('Seattle', 40.0), ('Tacoma', 40.0)]""" print(curs.execute(""" SELECT City, AVG(age) FROM ( SELECT City, HireDate-BirthDate AS age FROM Employee GROUP BY Id) GROUP BY City;""").fetchall()) # What are the ten most expensive items (per unit price) in the database and their suppliers? """[('Côte de Blaye', 'Aux joyeux ecclésiastiques'), ('Thüringer Rostbratwurst', 'Plutzer Lebensmittelgroßmärkte AG'), ('Mishi Kobe Niku', 'Tokyo Traders'), ("Sir Rodney's Marmalade", 'Specialty Biscuits, Ltd.'), ('Carnarvon Tigers', 'Pavlova, Ltd.'), ('Raclette Courdavault', 'Gai pâturage'), ('Manjimup Dried Apples', "G'day, Mate"), ('Tarte au sucre', "Forêts d'érables"), ('Ipoh Coffee', 'Leka Trading'), ('Rössle Sauerkraut', 'Plutzer Lebensmittelgroßmärkte AG')]""" print(curs.execute(""" SELECT ProductName, CompanyName FROM Supplier, ( SELECT ProductName, SupplierId FROM Product ORDER BY UnitPrice DESC) WHERE Id=SupplierId LIMIT 10;""").fetchall()) # What is the largest category (by number of unique products in it)? # Category: Confections (13 unique products) """[('Confections', 13)]""" print(curs.execute(""" SELECT CategoryName, MAX(cat_id_count) FROM Category, ( SELECT CategoryId, COUNT(CategoryId) AS cat_id_count FROM Product GROUP BY CategoryId) WHERE Id=CategoryId;""").fetchall()) # (Stretch) Who's the employee with the most territories? # Robert King with 10 territories """[('King', 'Robert', 10)]""" print(curs.execute(""" SELECT LastName, FirstName, MAX(terri_id_count) FROM Employee, ( SELECT EmployeeId, COUNT(TerritoryID) AS terri_id_count FROM EmployeeTerritory GROUP BY EmployeeId) WHERE EmployeeId=Id;""").fetchall())
true
c653a1e85345ac2bd9dabf58da510c86a43afdac
jrabin/GenCyber-2016
/Base_Day.py
309
4.21875
4
# -*- coding: utf-8 -* """ Created on Wed Jul 6 10:24:01 2016 @author: student """ #Create your own command for binary conversion #// gives quotient and % gives remainder ''' hex_digit=input("Hex input:") print(chr(int("0x"+hex_digit,16))) ''' letter=input("Enter letter:") print(hex(int(ord(letter))))
true
f7c954329701b44dd381aa844cf6f7a11ba1461e
KritiBhardwaj/PythonExercises
/loops.py
1,940
4.28125
4
# # Q1) Continuously ask the user to enter a number until they provide a blank input. Output the sum of all the # # numbers # # number = 0 # # sum = 0 # # while number != '': # # number = input("Enter a number: ") # # if number: # # sum = sum + int(number) # # print(sum) # # sum = 0 # # number = 'number' # # while len(number) > 0: # # number = input("Enter number: ") # # sum = sum + int(number) # # print(f"The sum is {sum}") number = 0 sum = 0 while number != "": sum = sum + int(number) number = input("Enter a number:") print(sum) # Q2) Use a for loop to format and print the following list: mailing_list = [ ["Roary", "roary@moth.catchers"], ["Remus", "remus@kapers.dog"], ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"], ["Biscuit", "biscuit@whippies.park"], ["Rory", "rory@whippies.park"], ] for contact in mailing_list: # print(f"{item[0]: <20} ${item[1]: .2f}") print(f"{contact[0]:} : {contact[1]}") # Q3) Use a while loop to ask the user for three names and append them to a list, use a for loop to print the list. count = 0 nameList = [] while count < 3: name = input("Enter name: ") nameList.append(name) count += 1 print() for name in nameList: print(name) #4 Ask the user how many units of each item they bought, then output the corresponding receipt groceries = [ ["Baby Spinach", 2.78], ["Hot Chocolate", 3.70], ["Crackers", 2.10], ["Bacon", 9.00], ["Carrots", 0.56], ["Oranges", 3.08] ] newList = [] groceryCost = 0 for item in groceries: n = input(f"How many {item[0]}: ") totalItemCost = item[1] * int(n) groceryCost = groceryCost + totalItemCost # print(f"{item[0]:<20} : {totalItemCost:}") newList.append([item[0], totalItemCost]) print(newList) print() print(f"====Izzy's Food Emporium====") for item in newList: # print(f"{newList[0]:<20} : {newList[1]:2f}") print(f"{item[0]:<20} : ${item[1]:.2f}") print('============================') print(f"{'$':>24}{groceryCost:.2f}")
true
dbe0e4b02b87fc67dd2e4de9cbaa7c0226f9e58e
geekidharsh/elements-of-programming
/primitive-types/bits.py
1,870
4.5
4
# The Operators: # x << y # Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). # This is the same as multiplying x by 2**y. # ex: 2 or 0010, so 2<<2 = 8 or 1000. # x >> y # Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y. # ex: 8 or 1000, so 8>>2 = 2 or 0010. # x & y # Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, # otherwise it's 0. # x | y # Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, # otherwise it's 1. # ~ x # Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. # This is the same as -x - 1. # x ^ y # Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if # that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1. # https://www.hackerearth.com/practice/notes/bit-manipulation/ # bit fiddle trick is that: # 1. numbers that are a power of 2, have only one bit set. # all other numbers will have more than one bit set i.e 1 in more that one places # in their binary representation # so 2, 4, 8, 16 etc. # 2. binary representation of (x-1) can be obtained by simply flipping all the bits # to the right of rightmost 1 in x and also including the rightmost 1. # so, x&(x-1) is basically, # will have all the bits equal to the x except for the rightmost 1 in x. # 3. def number_of_bits(x): # as in number of set bits bits = 0 while x: bits += x&1 # right shift by 1 bit every move x >>=1 return bits def pos_of_bits(x): # input: integer output: bit_pos = [] bits = 0 while x: bit_pos.append(x&1) x >>=1 return ''.join([str(i) for i in reversed(bit_pos)]) print(pos_of_bits('a'))
true
3a60bae93f01f1e9205430277f924390825c598f
geekidharsh/elements-of-programming
/binary-trees/binary-search-tree.py
1,229
4.15625
4
"""a binary search tree, in which for every node x and it's left and right nodes y and z, respectively. y <= x >= z""" class BinaryTreeNode: """docstring for BT Node""" def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right # TRAVERSING OPERATION def preorder(root): # preorder processes root before left and then finally right child if root: print(root.data) preorder(root.left) preorder(root.right) def inorder(root): # inorder processes left then root and then finally right child if root: inorder(root.left) print(root.data) inorder(root.right) def postorder(root): if root: postorder(root.right) postorder(root.left) print(root.data) # SEARCH in a Binary search tree def bst_search_recursive(root, key): if key == root.data or root is None: return root if key < root.data: return bst_search_recursive(root.left, key) if key > root.data: return bst_search_recursive(root.right, key) # TEST # ---- # sample node a a = BinaryTreeNode(18) a.left = BinaryTreeNode(15) a.right= BinaryTreeNode(21) # TRAVERSING a binary search tree inorder(a) preorder(a) postorder(a) # searching print(bst_search_recursive(a, 14))
true