blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a723af9a1faae81b098e9b79025f031a0f8b2038
PhaniMandava7/Python
/FirstPythonProj/GetInputFromKeyboard.py
337
4.21875
4
greeting = "Hello" # name = input("Please enter your name") # print(greeting + ' ' + name) # names = name.split(" ") # for i in names: # print(i) print("This is just a \"string 'to test' \"multiple quotes") print("""This is just a "string 'to test' "multiple quotes""") print('''This is just a "string 'to test' multiple quotes''')
true
6c7d41a18476a461fbceec79924b253d39f9f311
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-12_version1.py
2,415
4.28125
4
''' Exercise 10.12. Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled”. Solution: http://thinkpython2.com/code/interlock.py 1. Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs! 2. Can you find any words that are three-way interlocked; that is, every third letter forms a word, starting from the first, second or third? ''' def load_words(dict_filename): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print(f"Loading word list from file {dict_filename}...") # in_file: file in_file = open(dict_filename, 'r') # line: string # wordlist: list of strings wordlist = in_file.read().split() print(" ", len(wordlist), "words loaded.") return wordlist def in_bisect(word, words_list): first_id = 0 last_id = len(words_list) - 1 while first_id <= last_id: mid_id = (first_id + last_id) // 2 if words_list[mid_id] == word: return mid_id elif words_list[mid_id] < word: first_id = mid_id + 1 else: last_id = mid_id - 1 return -1 def interlock_two_words(word1, word2): L = [' '] * (len(word1) + len(word2)) L[::2] = list(word1) L[1::2] = list(word2) return ''.join(L) def main(): # Плохая, негодная, тупая, медленная версия # Bad, inadequate, stupid, slow version. dict_filename = 'words.txt' words_list = load_words(dict_filename) interlocked_words = [] for size in range(2, 10): size_words = list(filter(lambda w: len(w) == size, words_list)) size_interlocked_words = [] print(f'Size = {size}, words: {len(size_words)}') for word1 in size_words: for word2 in size_words: if in_bisect(interlock_two_words(word1, word2), words_list) > -1: size_interlocked_words.append((word1, word2, interlock_two_words(word1, word2))) interlocked_words.extend(size_interlocked_words) print(size_interlocked_words) print(interlocked_words) if __name__ == '__main__': main()
true
1a63f54074f8a96a4a3585950a253a25d068a0d0
paalso/learning_with_python
/18 Recursion/18-7.py
976
4.15625
4
# Chapter 18. Recursion # http://openbookproject.net/thinkcs/python/english3e/recursion.html # Exercise 7 # =========== # Write a function flatten that returns a simple list containing all the values # in a nested list from testtools import test def flatten(nxs): """ Returns a simple list containing all the values in a nested list """ flattened = [] for e in nxs: if type(e) == list: flattened.extend(flatten(e)) else: flattened.append(e) return flattened def main(): test(flatten([2,9,[2,1,13,2],8,[2,6]]) == [2,9,2,1,13,2,8,2,6]) test(flatten([[9,[7,1,13,2],8],[7,6]]) == [9,7,1,13,2,8,7,6]) test(flatten([[9,[7,1,13,2],8],[2,6]]) == [9,7,1,13,2,8,2,6]) test(flatten([["this",["a",["thing"],"a"],"is"],["a","easy"]]) == ["this","a","thing","a","is","a","easy"]) test(flatten([]) == []) if __name__ == '__main__': main()
true
4e13a17fdcaa1022e51da4c4bb808571a02d6177
paalso/learning_with_python
/26 Queues/ImprovedQueue.py
2,311
4.1875
4
# Chapter 26. Queues # http://openbookproject.net/thinkcs/python/english3e/queues.html class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) class ImprovedQueue: def __init__(self): self.head = self.tail = None self.size = 0 def insert(self, cargo): node = Node(cargo) if self.is_empty(): self.head = self.tail = node else: self.tail.next = node self.tail = self.tail.next self.size += 1 def remove(self): if not self.is_empty(): self.size -= 1 cargo = self.head.cargo # * чтобы отцепить ссылку next удаляемого node от queue - нужно ли? current_head = self.head # * self.head = self.head.next current_head.next = None # * if self.is_empty(): self.tail = None def is_empty(self): return self.size == 0 def __str__(self): tokens = [] current = self.head while current: tokens.append(str(current)) current = current.next return "[{}]".format(", ".join(tokens)) def print_info(self): print("queue: {}, head: {}, tail: {}, len: {}" .format(self, self.head, self.tail, self.size)) def main(): print("Creating new Queue:") q = ImprovedQueue() q.print_info() print("\nAdding new nodes (1, 2, 3) to the Queue:") q.insert(1) q.print_info() q.insert(2) q.print_info() q.insert(3) q.print_info() print("\nRemoving nodes from the Queue:") print("removed node: {}".format(q.remove())) q.print_info() print("removed node: {}".format(q.remove())) q.print_info() print("removed node: {}".format(q.remove())) q.print_info() print("removed node: {}".format(q.remove())) q.print_info() print("\nAdding new nodes (999, 66, 'xxx', (1, 'z')) to the Queue:") q.insert(999) q.insert(66) q.insert('xxx') q.insert((1, 'z')) q.print_info() if __name__ == "__main__": main()
true
ec0915fa2463fb1da2bb9ad4a5b55793d40fac93
paalso/learning_with_python
/09 Tuples/9-01_1.py
1,138
4.5
4
## Chapter 9. Tuples ## http://openbookproject.net/thinkcs/python/english3e/tuples.html ## Exercise 1 ## =========== # We’ve said nothing in this chapter about whether you can pass tuples as # arguments to a function. Construct a small Python example to test whether this # is possible, and write up your findings. import sys def distance_to_center(p): """ Get the distance to the origin a cartesian coordinate space """ sum = 0 for c in p: sum += c * c return sum ** 0.5 def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(distance_to_center((3, 4)) == 5) test(distance_to_center((3, 4, 0)) == 5) test(distance_to_center((1, 1, 1)) == 1.7320508075688772) test(distance_to_center((0, 0, 1, 0)) == 1) test_suite()
true
e66ceb92103c0c595bbaa0f6bc829e2208b34dba
paalso/learning_with_python
/18 Recursion/18-11/litter.py
1,729
4.21875
4
# Chapter 18. Recursion # http://openbookproject.net/thinkcs/python/english3e/recursion.html # Exercise 11 # ============ # Write a program named litter.py that creates an empty file named trash.txt in # each subdirectory of a directory tree given the root of the tree as an argument # (or the current directory as a default). Now write a program named cleanup.py # that removes all these files. import os, sys def get_dirlist(path): """ Return a sorted list of all entries in path. This returns just the names, not the full path to the names. """ return sorted(os.listdir(path)) def create_files(path=None, filename='trash.txt'): """ Creates an empty file named trash.txt in each subdirectory of a directory tree given the root of the tree as an argument (or the current directory as a default) """ if not path: path = os.getcwd() dirlist = get_dirlist(path) full_filename = os.path.join(path, filename) newfile = open(full_filename, 'w') newfile.close() print('{} created'.format(full_filename)) for f in dirlist: full_name = os.path.join(path, f) if os.path.isdir(full_name): create_files(full_name, filename) def main(): ## if len(sys.argv) > 2: ## print('Usage: python litter.py [directory]') ## exit(1) ## ## if len(sys.argv) == 1: ## dirname = None ## else: ## dirname = sys.argv[1] ## if not os.path.exists(dirname): ## print(f"Directory {dirname} doesn't exist") ## exit(2) ## create_files() create_files('d:\Projects\_testdir') if __name__ == '__main__': main()
true
9ef73be5b8fdf09a171cff7e27c68773fda9963e
paalso/learning_with_python
/06 Fruitful functions/6-9.py
1,849
4.21875
4
##Chapter 6. Fruitful functions ##http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html ## Exercise 9 ## =========== ##Write three functions that are the “inverses” of to_secs: ##hours_in returns the whole integer number of hours represented ##by a total number of seconds. ##minutes_in returns the whole integer number of left over minutes ##in a total number of seconds, once the hours have been taken out. ##seconds_in returns the left over seconds represented ##by a total number of seconds. ##You may assume that the total number of seconds passed ##to these functions is an integer... import sys def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def hours_in(time_in_seconds): """ returns the whole integer number of hours represented by a total number of seconds.""" return time_in_seconds // 3600 def minutes_in(time_in_seconds): """ returns the whole integer number of left over minutes in a total number of seconds, once the hours have been taken out.""" return (time_in_seconds - hours_in(time_in_seconds) * 3600) // 60 def seconds_in(time_in_seconds): """ returns the left over seconds represented by a total number of seconds.""" return time_in_seconds % 60 def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(hours_in(9010) == 2) test(minutes_in(9010) == 30) test(seconds_in(9010) == 10) test(hours_in(43499) == 12) test(minutes_in(43499) == 4) test(seconds_in(43499) == 59) test_suite()
true
1ada77a6b13c07c35793d86d7dd8671356910c09
paalso/learning_with_python
/ADDENDUM. Think Python/09 Case study - word play/9-6.py
1,370
4.15625
4
''' Exercise 9.6. Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical order (double letters are ok). How many abecedarian words are there? ''' def is_abecedarian(word): """ Returns True if the letters in a word appear in alphabetical order (double letters are ok) """ word = word.lower() for i in range(1, len(word)): if word[i] < word[i - 1]: return False return True def load_words(dict_filename): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print(f"Loading word list from file {dict_filename}...") # in_file: file in_file = open(dict_filename, 'r') # line: string # wordlist: list of strings wordlist = in_file.read().split() print(" ", len(wordlist), "words loaded.") return wordlist print() # words = load_words("words_3000.txt") words = load_words("words.txt") words_qty = len(words) abecedarian_words = list(filter(is_abecedarian, words)) abecedarian_words_qty = len(abecedarian_words) print(abecedarian_words) print("Abecedarian words number: {}, {}%". format(abecedarian_words_qty, round(abecedarian_words_qty / words_qty * 100, 1)))
true
32ec6ec6910b4cb9806e82cfdd8eb22e902c8827
paalso/learning_with_python
/04 Functions/4_4_ver0_0.py
1,339
4.28125
4
##4. http://openbookproject.net/thinkcs/python/english3e/functions.html ##4. Draw this pretty pattern: import turtle import math def make_window(colr, ttle): """ Set up the window with the given background color and title. Returns the new window. """ w = turtle.Screen() w.bgcolor(colr) w.title(ttle) return w def make_turtle(colr, sz): """ Set up a turtle with the given color and pensize. Returns the new turtle. """ t = turtle.Turtle() t.color(colr) t.pensize(sz) return t def draw_poly(t, n, side): """Make a turtle t draw a regular polygon""" for i in range(n): t.forward(side) t.left(360 / n) def draw_square(t, side): """Make a turtle t draw a square""" for i in range(4): t.forward(side) t.left(90) ## ----- Main ----------------------------------------------------- wn = make_window("lightgreen", "Drawing a pretty pattern") tortilla = make_turtle("blue", 3) square_side = 200 shift = (2 ** 0.5) * square_side * math.sin(9 * math.pi / 180) for i in range(5): draw_square(tortilla, square_side) tortilla.right(2 * 18) tortilla.penup() tortilla.forward(shift) tortilla.left(3 * 18) tortilla.pendown() wn.mainloop()
true
c9b466df940ce854e8b362a48c71ab720025b83b
paalso/learning_with_python
/ADDENDUM. Think Python/10 Lists/10-9.py
2,446
4.125
4
''' Exercise 10.9. Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why? ''' def load_words(dict_filename): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print(f"Loading word list from file {dict_filename}...") # in_file: file in_file = open(dict_filename, 'r') # line: string # wordlist: list of strings wordlist = in_file.read().split() print(" ", len(wordlist), "words loaded.") return wordlist def count_time(func, *args): import time start_time = time.time() func(*args) return time.time() - start_time def load_words1(dict_filename): """ Returns a list of words from the file 'dict_filename' using the append method """ print(f"Loading word list from file {dict_filename}...") # in_file: file in_file = open(dict_filename, 'r') wordlist = [] # wordlist: list of strings # line: string for line in in_file: wordlist.append(line) print(" ", len(wordlist), "words loaded.") return wordlist def load_words2(dict_filename): """ Returns a list of words from the file 'dict_filename' using the idiom t = t + [x] """ print(f"Loading word list from file {dict_filename}...") # in_file: file in_file = open(dict_filename, 'r') wordlist = [] # wordlist: list of strings # line: string for line in in_file: wordlist += [line] print(" ", len(wordlist), "words loaded.") return wordlist def main(): dict_filename = 'words.txt' t1 = count_time(load_words1, dict_filename) t2 = count_time(load_words2, dict_filename) t3 = count_time(load_words, dict_filename) ## words = load_words2(dict_filename) ## print(words) print(f'Time of loading the dictionary "{dict_filename}":') print(f'using the append method: {t1}') print(f'using the the idiom t = t + [x]: {t2}') print(f'using the the read().split() method: {t3}') # https://towardsdatascience.com/3-techniques-to-make-your-python-code-faster-193ffab5eb36 if __name__ == '__main__': main()
true
3638b74fdff0456af03fd38137c7eceae3ddacb1
paalso/learning_with_python
/ADDENDUM. Think Python/13 Case study - data structure/13-6.py
1,209
4.21875
4
''' Exercise 13.5. Write a function named choose_from_hist that takes a histogram as defined in Section 11.2 and returns a random value from the histogram, chosen with probability in proportion to frequency. For example, for this histogram: >>> t = ['a', 'a', 'b'] >>> hist = histogram(t) # {'a': 2, 'b': 1} your function should return 'a' with probability 2/3 and 'b' with probability 1/3. ''' def histogram(text): import collections return dict(collections.Counter(text)) def choose_from_hist(histogram): import random ## probabilities = { key : histogram[key] / values_number ## for key in histogram } start_num = 0 partition = dict() for key in histogram: end_num = start_num + histogram[key] segment = start_num, end_num partition[key] = segment start_num = end_num random_num = random.randrange(sum(histogram.values())) for key, segment in partition.items(): start, end = segment if start <= random_num < end: return key def main(): s = 'ab' d = histogram(s) print(d) print(choose_from_hist(d)) if __name__ == '__main__': main()
true
7783505fb7040ceefdd5794f88507f573b4d6bcf
paalso/learning_with_python
/07 Iterations/7-1.py
923
4.28125
4
## Chapter 7. Iteration ## http://openbookproject.net/thinkcs/python/english3e/iteration.html ## Exercise 1 ## =========== ## Write a function to count how many odd numbers are in a list. import sys def count_odds(lst): counter = 0 for n in lst: if n % 2 == 1: counter += 1 return counter def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg) def test_suite(): """ Run the suite of tests for code in this module (this file). """ test(count_odds([]) == 0) test(count_odds([1, 2, 4, 5]) == 2) test(count_odds([0, 2, 4, 6]) == 0) test(count_odds([1, 1, 1, 1, 1]) == 5) test_suite()
true
e0dbd51a977024665d2211a0f4f82f3a7d5ce224
paalso/learning_with_python
/24 Linked lists/linked_list.py
1,471
4.21875
4
# Chapter 24. Linked lists # http://openbookproject.net/thinkcs/python/english3e/linked_lists.html class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) def print_backward(self): if self.next is not None: tail = self.next tail.print_backward() print(self.cargo, end=" ") def print_list(self): print('[',end='') node = self while node != None: print(f'{node}',end='') if node.next is None: break print(', ',end='') node = node.next print(']') class LinkedList: def __init__(self, *items): self.length = 0 self.head = None def print_list(self): if self.head is not None: self.head.print_list() else: print('[]') def print_backward(self): if self.head is not None: print("[", end=" ") self.head.print_backward() def add_first(self, cargo): node = Node(cargo) ## node.next = self.head #зачем так? node.next = None self.head = node self.length += 1 llist = LinkedList() llist.print_list() llist.add_first(0) llist.print_list() ##n = Node() ##print(n) ##n.print_list() ##n.print_backward()
true
6dfea9839760f8124ac74143ec886b836d85fa38
mattwfranchi/3600
/SampleCode/BasicTCPEchoClient.py
1,035
4.21875
4
from socket import * # Define variables that hold the desired server name, port, and buffer size SERVER_NAME = 'localhost' SERVER_PORT = 3602 BUFFER_SIZE = 32 # We are creating a *TCP* socket here. We know this is a TCP socket because of # the use of SOCK_STREAM # It is being created using a with statement, which ensures that the socket will # be cleaned up correctly when the socket is no longer needed (once the with block has been exited) with socket(AF_INET, SOCK_STREAM) as s: # Connect to a server at the specified port using this socket s.connect((SERVER_NAME, SERVER_PORT)) # Loop forever... while True: # Read in an input statement from the user message = input('Input: ') # Send the message the user wrote into the socket s.send(message.encode()) # Wait to receive a response from the server, up to 128 bytes in length response = s.recv(BUFFER_SIZE) # Print that response to the console print(response.decode())
true
086a3773b74c93e12755271fa0cf25d24399cb60
hsinjungwu/self-learning
/100_Days_of_Code-The_Complete_Python_Pro_Bootcamp_for_2021/day-12.py
756
4.15625
4
#Number Guessing Game Objectives: from art import logo import random print(logo) print("Welcome to the Number Guessing Game!\nI'm thinking of a number between 1 and 100.") ans = random.randint(1, 100) attempts = 5 if input("Choose a difficulty. Type 'easy' or 'hard': ").lower() == "easy": attempts = 10 while attempts > 0: print(f"You have {attempts} attempts remaining to guess the number.") guess = int(input("Make a guess: ")) if guess == ans: print(f"You got it! The answer was {ans}.") break else: attempts -= 1 if guess < ans: print("Too low") else: print("Too high") if attempts == 0: print(f"Answer = {ans}. You've run out of guesses, you lose.") else: print("Guess again.")
true
f3ff778147002322c07f7163b50fc1f8f825e220
Pattrickps/Learning-Data-Structures-Using-Python
/data-structures/implement stack using linked list.py
863
4.28125
4
# Implement Stack using Linked List class node: def __init__(self,node_data): self.data=node_data self.next=None class stack: def __init__(self): self.head=None def push(self,data): new_node=node(data) new_node.next=self.head self.head=new_node def pop(self): if self.head==None: print("sorry the stack is empty") else: print("the poped element is", self.head.data) self.head=self.head.next def peek(self): print(self.head.data) def printstack(self): l=self.head while(1): if l==None: break print (l.data,end=" ") l=l.next obj=stack() obj.push(1) obj.push(2) obj.push(3) obj.printstack() print("\n") obj.pop() print("\n") obj.printstack()
true
8fc847aa8f077e7abec82c05c2f109b324e489ef
code-lucidal58/python-tricks
/play_with_variables.py
528
4.375
4
import datetime """ In-place value swapping """ # swapping the values of a and b a = 23 b = 42 # The "classic" way to do it with a temporary variable: tmp = a a = b b = tmp # Python also lets us use this a, b = b, a """ When To Use __repr__ vs __str__? """ # Emulate what the std lib does:hand today = datetime.date.today() # Result of __str__ should be readable: print(str(today)) # Result of __repr__ should be unambiguous: print(repr(today)) # Python interpreter sessions use__repr__ to inspect objects: print(today)
true
467335edf1eafb7cdcf912fe46a75d3f6c712c08
ugo-en/some-python-code
/extra_old_code/square.py
326
4.5
4
# Step1: Prompt the user to enter the length of a side of the square length = int(input("Please Enter the LENGHT of the Square: ")) # Step2: Multiply the length by itself and assign it to a variable called area area = length * length # Step3: Display the area of the square to the user print("Your area is: ",area)
true
3653c4987ee75687f3ad08710e803d8724ad244e
ugo-en/some-python-code
/extra_old_code/bmi_calcuator.py
680
4.375
4
#Opening remarks print("This app calculates your Body Mass Index (BMI)") #Input variables weight = float(input("Input your weight in kg but don't include the units: ")) height = float(input("Input your height in m but don't include the units: ")) #Calculate the bmi rnd round off to 1 decimal place bmi = weight / (height * height) bmi = round(bmi, 1) #Print bmi print("Your BMI is: ", bmi) #Determine the person's status if bmi < 18.5: print("You're underweight") elif bmi >= 18.5 and bmi <= 24.9: print("You're normal") elif bmi >= 25.9 and bmi <= 29.9: print("You're overweight") else : print("You're obese") #Closing remarks print("Thanks")
true
72d67c1ccb8703467153babbd8baae6c15ca226a
ankurt04/ThinkPython2E
/chapter4_mypolygon.py
1,086
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 2 10:45:14 2017 @author: Ankurt.04 """ #Think Python - End of Chapter 4 - In lessson exercises import turtle import math bob = turtle.Turtle() def square(t, length): i = 0 while i <= 3: t.fd(length) t.lt(90) i +=1 #function to draw a polygon of n sides, each side lenght long def polygon(t, length, n): angle = 360.0/n i = 0 while i <= n: t.fd(length) t.lt(angle) i += 1 #function to draw a circle of radius r def circle(t, r): #pi = 3.14 circum = 2*math.pi*r length = 1 n = circum / length polygon(t, length, n) def arc(t, r, angle): #pi = 3.14 circum = 2*math.pi*r desired_circum = circum * (angle/360.0) length = 1 n = int(desired_circum / length) step_angle = angle / n for i in range(n): t.fd(length) t.lt(step_angle) polygon(bob, length = 70, n = 6) #names of parameters can be included in the argument list arc(bob, 50, 180)
true
f1a1d08fa7136a770ca44fbe8dfbf8ffc4eee38e
katelevshova/py-algos-datastruc
/Problems/strings/anagrams.py
1,721
4.15625
4
# TASK ''' The goal of this exercise is to write some code to determine if two strings are anagrams of each other. An anagram is a word (or phrase) that is formed by rearranging the letters of another word (or phrase). For example: "rat" is an anagram of "art" "alert" is an anagram of "alter" "Slot machines" is an anagram of "Cash lost in me" Your function should take two strings as input and return True if the two words are anagrams and False if they are not. You can assume the following about the input strings: No punctuation No numbers No special characters Note - You can use built-in methods len(), lower() and sort() on strings. ''' # Code def anagram_checker(str1, str2): """ Check if the input strings are anagrams of each other Args: str1(string),str2(string): Strings to be checked Returns: bool: Indicates whether strings are anagrams """ # TODO: Write your solution here # Clean strings clean_str_1 = str1.replace(" ", "").lower() clean_str_2 = str2.replace(" ", "").lower() if len(clean_str_1) == len(clean_str_2): if sorted(clean_str_1) == sorted(clean_str_2): return True return False pass # Test Cases print("Pass" if (anagram_checker('rat', 'art')) else "Fail") print("Pass" if not (anagram_checker('water', 'waiter')) else "Fail") print("Pass" if anagram_checker('Dormitory', 'Dirty room') else "Fail") print("Pass" if anagram_checker('Slot machines', 'Cash lost in me') else "Fail") print("Pass" if not (anagram_checker('A gentleman', 'Elegant men')) else "Fail") print("Pass" if anagram_checker('Time and tide wait for no man', 'Notified madman into water') else "Fail")
true
e56c99d2a16d2819a3209bf3cc27ea86ae2c8fa0
katelevshova/py-algos-datastruc
/Problems/stacks_queues/balanced_parentheses.py
1,469
4.125
4
""" ((32+8)∗(5/2))/(2+6). Take a string as an input and return True if it's parentheses are balanced or False if it is not. """ class Stack: def __init__(self): self.items = [] def size(self): return len(self.items) def push(self, item): """ Adds item to the end """ self.items.append(item) def pop(self): """ Removes and returns the last value """ if self.size() == 0: return None else: return self.items.pop() def equation_checker(equation_str): print(equation_str) """ Check equation for balanced parentheses Args: equation(string): String form of equation Returns: bool: Return if parentheses are balanced or not """ stack = Stack() for char in equation_str: if char == "(": stack.push(char) elif char == ")": if stack.pop() is None: return False if stack.size() == 0: return True else: return False def test_case_1(): actual_result = equation_checker("((32+8)∗(5/2))/(2+6).") assert actual_result def test_case_2(): actual_result = equation_checker("()(()) ))))))).") assert actual_result == False def test_case_3(): actual_result = equation_checker("())((") assert actual_result == False def test(): test_case_1() test_case_2() test_case_3() test()
true
edbf5b7c45bd43917d56099a020e9f82a21a0f64
nsuryateja/python
/exponent.py
298
4.40625
4
#Prints out the exponent value eg: 2**3 = 8 base_value = int(input("enter base value:")) power_value = int(input("enter power value:")) val = base_value for i in range(power_value-1): val = val * base_value #Prints the result print(val) #Comparing the result print(base_value ** power_value)
true
0d760ab53b3b0cb5873064ab0ed74b54a1962db1
Cookiee-monster/nauka
/Scripts/Python exercises from GIT Hub/Ex 9.py
567
4.34375
4
#! Python 3 # Question 9 # Level 2 # # Question£º # Write a program that accepts sequence of lines as input and prints the # lines after making all characters in the sentence capitalized. # Suppose the following input is supplied to the program: # Hello world # Practice makes perfect # Then, the output should be: # HELLO WORLD # PRACTICE MAKES PERFECT lines = [] while True: line = input("Input the line of text. Leave blank if You like to finish") if line: lines.append(line) else: break text = '\n'.join(lines) print(text.upper())
true
07bcdd9aaac7533bca685a1e4bc17f21db3733da
Cookiee-monster/nauka
/Scripts/Python exercises from GIT Hub/Ex 19.py
1,181
4.6875
5
#! Python 3 # Question: # You are required to write a program to sort the (name, age, height) tuples by ascending order where name is string, # age and height are numbers. The tuples are input by console. The sort criteria is: # 1: Sort based on name; # 2: Then sort based on age; # 3: Then sort by score. # The priority is that name > age > score. # If the following tuples are given as input to the program: # Tom,19,80 # John,20,90 # Jony,17,91 # Jony,17,93 # Json,21,85 # Then, the output of the program should be: # [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')] #dsafasfsadf #dsadsadasdas users_list = [] raw_input = input("Input the name of user, their age and score in the pattern Name,Age,Score: ") while raw_input: users_list.append(tuple(raw_input.split(","))) raw_input = input("Input the name of user, their age and score in the pattern Name,Age,Score: ") def sort_score(item): return item[2] def sort_age(item): return item[1] def sort_name(item): return item[0] users_list.sort(key=sort_score) users_list.sort(key=sort_age) users_list.sort(key=sort_name) print(users_list)
true
d863997509ddc1bcf91d2217c99681040b2855a6
Fantendo2001/FORKERD---University-Stuffs
/CSC1001/hw/hw_0/q2.py
354
4.21875
4
def display_digits(): try: # prompts user for input num = int(input('Enter an integer: ')) except: print( 'Invalid input. Please enter again.' ) else: # interates thru digits of number and display for dgt in str(num): print(dgt) while True: display_digits()
true
b0b82289495eb50db5191c439cf4f5aa2589c839
karreshivalingam/movie-booking-project
/movie ticket final.py
2,810
4.125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: global f f = 0 #this t_movie function is used to select movie name def t_movie(): global f f = f+1 print("which movie do you want to watch?") print("1,Acharya ") print("2,vakeel saab ") print("3,chicchore") print("4,back") movie = int(input("choose your movie: ")) if movie == 4: # in this it goes to center function and from center it goes to movie function and it comes back here and then go to theater center() theater() return 0 if f == 1: theater() # this theater function used to select screen def theater(): print("which screen do you want to watch movie: ") print("1,SCREEN 1") print("2,SCREEN 2") print("3,SCREEN 3") a = int(input("chosse your screen: ")) ticket = int(input("number of ticket do you want?: ")) timing(a) # this timing function used to select timing for movie def timing(a): time1 = { "1": "11.00-2.00", "2": "2.15-4.15", "3": "4.20-7.20", "4": "7.30-10.30" } time2 = { "1": "11.00-2.00", "2": "2.15-4.15", "3": "4.20-7.20", "4": "7.30-10.30" } time3 = { "1": "11.00-2.00", "2": "2.15-4.15", "3": "4.20-7.20", "4": "7.30-10.30" } if a == 1: print("choose your time:") print(time1) t = input("select your time:") x = time1[t] print("successfull!, enjoy movie at "+x) elif a == 2: print("choose your time:") print(time2) t = input("select your time:") x = time2[t] print("successfull!, enjoy movie at "+x) elif a == 3: print("choose your time:") print(time3) t = input("select your time:") x = time3[t] print("successfull!, enjoy movie at "+x) return 0 def movie(theater): if theater == 1: t_movie() elif theater == 2: t_movie() elif theater == 3: t_movie() elif theater == 4: city() else: print("wrong choice") def center(): print("which theater do you wish to see movie? ") print("1,Asian Uppal") print("2,Miraj cinemas") print("3,Inox") print("4,back") a = int(input("choose your option: ")) movie(a) return 0 # this function is used to select city def city(): print("Hi welcome to movie ticket booking: ") print("where you want to watch movie?:") print("1,Uppal") print("2,L.B Nagar") print("3,Juble hills") place = int(input("choose your option: ")) if place == 1: center() elif place == 2: center() elif place == 3: center() else: print("wrong choice") city() # it calls the function city
true
c31091af418177da7206836e40939b51c8f5afa0
meenapandey500/Python_program
/asset.py
497
4.125
4
def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print(KelvinToFahrenheit(273)) print(int(KelvinToFahrenheit(505.78))) print(KelvinToFahrenheit(-5)) '''When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. The syntax for assert is − assert Expression[, Arguments]'''
true
9847bcc11fc8fb376684ec283eb6c13eabf4e44e
nengvang/s2012
/lectures/cylinder.py
957
4.375
4
# Things we need (should know) # # print # Display a blank line with an empty print statement # print # Display a single item on a separate line # print item # Display multiple items on a line with commas (,) separated by spaces # print item1, item2, item3 # print item, # # raw_input([prompt]) # Prompt users for text-based (str) information # Optional message # Blocking call # value = raw_input('Enter your name: ') # value = raw_input() # # Data Types # int, str, float, bool, list, dict # Each holds a different type of information and has related operators # Each also provides a creation/conversion function import math height = float(raw_input('Enter the height of the cylinder: ')) radius = float(raw_input('Enter the radius of the cylinder: ')) volume = 2 * math.pi * radius ** 2 * height print 'The volume of a cylinder with height', height, 'and radius', radius, print 'is', volume
true
578de93ccb0c029d5ada5b837358451bc4612faa
stechermichal/codewars-solutions-python
/7_kyu/printer_errors_7_kyu.py
1,260
4.28125
4
"""In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m. The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm meaning that the printer used three times color a, four times color b, one time color h then one time color a... Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm with letters not from a to m. You have to write a function printer_error which given a string will return the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression. The string has a length greater or equal to one and contains only letters from ato z. Examples: s="aaabbbbhaijjjm" error_printer(s) => "0/14" s="aaaxbbbbyyhwawiwjjjwwm" error_printer(s) => "8/22""""" def printer_error(s): count_error = 0 my_set = 'abcdefghijklm' for i in s: if i not in my_set: count_error += 1 return f"{count_error}/{len(s)}"
true
954696eccde542040c6abd120b33878fead05e65
stechermichal/codewars-solutions-python
/5_kyu/simple_pig_latin_5_kyu.py
453
4.3125
4
"""Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. Examples pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway !""" def pig_it(text): text_list = text.split() for i, value in enumerate(text_list): if value.isalpha(): text_list[i] = value[1:] + value[0:1] + 'ay' return ' '.join(text_list)
true
c062245d21b75405560e771c16b1811bd17d76b8
NiteshPidiparars/Python-Tutorials
/PracticalProblem/problem4.py
1,081
4.3125
4
''' Problem Statement:- A palindrome is a string that, when reversed, is equal to itself. Example of the palindrome includes: 676, 616, mom, 100001. You have to take a number as an input from the user. You have to find the next palindrome corresponding to that number. Your first input should be the number of test cases and then take all the cases as input from the user. Input: 3 451 10 2133 Output: Next palindrome for 451 is 454 Next palindrome for 10 is 11 Next palindrome for 2311 is 2222 ''' ''' Author: Harry Date: 15 April 2019 Purpose: Practice Problem For CodeWithHarry Channel ''' def next_palindrome(n): n = n+1 while not is_palindrome(n): n += 1 return n def is_palindrome(n): return str(n) == str(n)[::-1] if __name__ == "__main__": n = int(input("Enter the number of test cases\n")) numbers = [] for i in range(n): number = int(input("Enter the number:\n")) numbers.append(number) for i in range(n): print( f"Next palindrome for {numbers[i]} is {next_palindrome(numbers[i])}")
true
b5e59ae88dabef206e1ca8eba2a3029d5e71d632
phriscage/coding_algorithms
/factorial/factorial.py
889
4.46875
4
#!/usr/bin/python2.7 """ return a factorial from a given number """ import sys import math def get_factorial(number): """ iterate over a given number and return the factorial Args: number (int): number integer Returns: factorial (int) """ factorial = 1 for n in range(int(number), 1, -1): factorial *= n return factorial def math_factorial(number): """ user the built-in math.factorial to return factorial Args: number (int): number integer Returns: factorial (int) """ return math.factorial(int(number)) def main(): """ run the main logic """ #number = raw_input() if len(sys.argv) < 2: print "Argument required." sys.exit(1) number = sys.argv[1] print get_factorial(number) print math_factorial(number) if __name__ == '__main__': main()
true
4eb679fa74d8e2bf33d3e58984f4c861ad0b7827
gauravarora1005/python
/Strings Challenges 80-87.py
1,973
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: first_name = input("enter your first name: ") f_len = len(first_name) print("Length of First Name ", f_len) last_name = input("Enter the last name: ") l_len = len(last_name) print("Length for last name is: ", l_len) full_name = first_name + " " + last_name full_len = len(full_name) print("Your name is ", full_len, " characters long") # In[4]: sub = input("Enter your fvt subject: ") for letter in sub: print(letter, end = "-") # In[6]: name = input("Enter your name in upper case: ") while not name.isupper(): print("not in upper, try again") name = input("Enter your name in upper case: ") print("All in upper") # In[11]: car_num = input("Enter your car num plate number: ") state = car_num[0:2] rest_num = car_num[2:] u_state = state.upper() modified_number = u_state+rest_num #print(state) #print(rest_num) print(modified_number) # In[12]: vowels = 'aeiou' count = 0 name = input("enter the name: ") for letter in name: if letter in vowels: count = count+1 print(count) # In[13]: #either create vowels as string or list. both will work vowels = ['a','e','i','o','u'] count = 0 name = input("enter the name: ") for letter in name: if letter in vowels: count = count+1 print(count) # In[15]: password = input("Please enter the password: ") confirm = input("Please confirm the password: ") if password == confirm: print("Thank you") elif password.lower() == confirm.lower(): print("Please enter in same case") else: print("Incorrect") # In[22]: name = input("Please enter the name: ") for i in range (len(name)-1,0-1, -1): #range gives the numeric and stop/2nd argument is not inclusive print(name[i]) length = len(name) position =1 for i in name: new_position = length - position letter = name[new_position] print(letter) position = position+1 # In[ ]:
true
2d44b738e87fd3acc226f5c0a9d980ed58d30beb
kseet001/FCS
/Homework5/homework_qn1.py
2,248
4.125
4
# Homework 5 - Question 1 # Encrypt the following plaintext P (represented with 8-bit ASCII) using AES-ECB, # with the key of 128-bit 0. You may use an existing crypto library for this exercise. # P = SUTD-MSSD-51.505*Foundations-CS* from Crypto.Cipher import AES from binascii import hexlify, unhexlify plaintext = "SUTD-MSSD-51.505*Foundations-CS*" key = '\x00' * 16 def int_to_bytes(x): return x.to_bytes((x.bit_length() + 7) // 8, 'big') def int_from_bytes(xbytes): return int.from_bytes(xbytes, 'big') def encrypt(key, plaintext): encryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB) return encryptor.encrypt(plaintext.encode('utf-8')) def decrypt(key, ciphertext): decryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB) return decryptor.decrypt(ciphertext) # AES requires that plaintexts be a multiple of 16, so we have to pad the data def pad(data): return data + b"\x00" * (16 - len(data) % 16) def solve_1a(): ciphertext = encrypt(key, plaintext) print("\nQuestion 1a)") print("C : %s" % (hexlify(ciphertext))) def solve_1b(): ciphertext = encrypt(key, plaintext) print("\nQuestion 1b)") C = hexlify(ciphertext) C1 = C[0:32] C2 = C[32:] P1 = decrypt(key, unhexlify(C2+C1)) print("P1 : %s" % (P1.decode("utf-8")[:16])) def solve_1c(): ciphertext = encrypt(key, plaintext) C = hexlify(ciphertext) C1 = C[0:32] C2 = C[32:] # Convert to int, increment by 1 and convert back to bytes C2_modified = int_from_bytes(C2) + 1 C2_modified = int_to_bytes(C2_modified) print("\nQuestion 1c)") #print("Original ciphertext: %s" % (unhexlify(C1+C2))) # for debugging purpose #print("Modified ciphertext: %s" % (unhexlify(C1+C2_modified))) # for debugging purpose - shows that it has been incremented by 1 P2 = decrypt(key, unhexlify(C1+C2_modified)) print("P2 : %s" % (P2)[16:]) P2 = decrypt(key, unhexlify(C1 + C2)) # for debugging purpose print("P2 : %s" % (P2)[16:]) # for debugging purpose def main(): print("\nP : %s" % (plaintext.encode())) print("Key : %s" % (key.encode())) solve_1a() solve_1b() solve_1c() if __name__ == "__main__": main()
true
133249b5665e99fb2291cff6ab49e0c1cb6c800c
vijaynchakole/Proof-Of-Concept-POC-Project
/Directory Operations/Directory_File_Checksum.py
2,950
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 01:02:26 2020 @author: Vijay Narsing Chakole MD5 hash in Python Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases. There are many hash functions defined in the “hashlib” library in python. Here we are talking about explanation and working of MD5 hash. MD5 Hash This hash function accepts sequence of bytes and returns 128 bit hash value, usually used to check data integrity but has security issues. Functions associated : encode() : Converts the string into bytes to be acceptable by hash function. digest() : Returns the encoded data in byte format. hexdigest() : Returns the encoded data in hexadecimal format. Explanation : The below code takes file data string and converts it into the byte equivalent using encode() so that it can be accepted by the hash function. The md5 hash function encodes it and then using hexdigest(), hexadecimal equivalent encoded string is printed. """ from sys import * import os import hashlib # set current working directory os.chdir("C:/Users/hp/PycharmProjects") def hashfile(file_path, blocksize = 1024): afile = open(file_path, 'rb') hasher = hashlib.md5() buffer = afile.read(blocksize) while(len(buffer)>0): hasher.update(buffer) buffer = afile.read(blocksize) afile.close() return hasher.hexdigest() def DisplayChecksum(path): flag = os.path.isabs(path) if flag == False : path = os.path.abspath(path) exists = os.path.isdir(path) if exists: for folder, subfolder,file in os.walk(path): print("Current folder is "+ folder) for filename in file : path = os.path.join(folder, filename) file_hash = hashfile(path) print(path) print(file_hash) print(" ") else: print("Invalid Path") #path = "college" #DisplayChecksum(path) def main(): print("inside main") #path = "college" print("Application Name "+argv[0]) string = argv[1].lower() if (len(argv)<2): print("Invalid Number of arguments ") if(string == '-h'): print("Script is designed for traverse specific directory ") exit() if (string == '-u'): print("Usage : Application Name Absolutepath directory") exit() try: path = argv[1] DisplayChecksum(path) except ValueError: print("Error : invalid datatype of input ") except Exception: print("Error : invalid input ") if __name__ == "__main__": main()
true
ed39c3de6ac1d1296c487fa8206493b46f3c8998
KrishnaRauniyar/python_assignment_II
/f16.py
1,567
4.125
4
# Imagine you are creating a Super Mario game. You need to define a class to represent Mario. What would it look like? If you aren't familiar with SuperMario, use your own favorite video or board game to model a player. from pynput import keyboard def controller(key): is_jump = False if str(key) == 'Key.right': move.right() elif str(key) == 'Key.left': move.left() elif str(key) == 'Key.up': is_jump = True move.jump() elif str(key) == 'Key.esc': end.score() end.menu() return False if is_jump == True: move.gravity() class Startgame: def startmenu(self): a = input('Enter s to start game : ') if a == 's': print('Game started.') return True else: return False def background(self): print('background is moving.') def showmario(self): print('mario is ready to play.') class Move: def right(self): print('moving right by 5.') def left(self): print('moving left by 5.') def jump(self): print('mario jumping.') def gravity(self): print('gravity enable.') class Gameover: def score(self): print('your score : ', 1512) def menu(self): print('Game over!!!') start = Startgame() move = Move() end = Gameover() if start.startmenu() == True: start.background() start.showmario() print('Enter escape to exit') with keyboard.Listener(on_press=controller) as listener: listener.join()
true
4969f9c7fdbf0a5239bbf1e1e4d226b5ed336196
KrishnaRauniyar/python_assignment_II
/f4.py
629
4.25
4
# Create a list. Append the names of your colleagues and friends to it. Has the id of the list changed? # Sort the list. # What is the first item on the list? What is the second item on the list? # no id of list is not changed def checkId(string): arr = [] print("The is before append: ", id(arr)) for i in range(len(string)): arr.append(string[i]) print("The id after append", id(arr)) arr.sort() return print("The two names are {}".format(arr[0:2])) print(checkId(["rahul", "krishna", "pakka", "gaurav", "anil", "ramita"])) print("The id before and after append remains the same")
true
73181b0a6495350ba3b6bfd29da0f000da2ca5f2
Data-Analisis/scikit-learn-mooc
/python_scripts/parameter_tuning_sol_01.py
2,951
4.375
4
# %% [markdown] # # 📃 Solution for introductory example for hyperparameters tuning # # In this exercise, we aim at showing the effect on changing hyperparameter # value of predictive pipeline. As an illustration, we will use a linear model # only on the numerical features of adult census to simplify the pipeline. # # Let's start by loading the data. # %% from sklearn import set_config set_config(display='diagram') # %% import pandas as pd df = pd.read_csv("../datasets/adult-census.csv") target_name = "class" numerical_columns = [ "age", "capital-gain", "capital-loss", "hours-per-week"] target = df[target_name] data = df[numerical_columns] # %% [markdown] # We will first divide the data into a train and test set to evaluate # the model. # %% from sklearn.model_selection import train_test_split data_train, data_test, target_train, target_test = train_test_split( data, target, random_state=42) # %% [markdown] # First, define a logistic regression with a preprocessing stage to scale the # data. # %% from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression model = Pipeline(steps=[ ("preprocessor", StandardScaler()), ("classifier", LogisticRegression()), ]) model # %% [markdown] # Now, fit the model on the train set and compute the model's accuracy on the # test set. # %% model.fit(data_train, target_train) accuracy = model.score(data_test, target_test) print(f"Accuracy of the model is: {accuracy:.3f}") # %% [markdown] # We will use this model as a baseline. Now, we will check the effect of # changing the value of the hyperparameter `C` in logistic regression. First, # check what is the default value of the hyperparameter `C` of the logistic # regression. # %% print(f"The hyperparameter C was: {model[-1].C}") # %% [markdown] # Create a model by setting the `C` hyperparameter to `0.001` and compute the # performance of the model. # %% model = Pipeline(steps=[ ("preprocessor", StandardScaler()), ("classifier", LogisticRegression(C=0.001)), ]) model # %% model.fit(data_train, target_train) accuracy = model.score(data_test, target_test) print(f"Accuracy of the model is: {accuracy:.3f}") # %% [markdown] # We observe that the performance of the model decreased. Repeat the same # experiment for `C=100` # %% model = Pipeline(steps=[ ("preprocessor", StandardScaler()), ("classifier", LogisticRegression(C=100)), ]) model # %% model.fit(data_train, target_train) accuracy = model.score(data_test, target_test) print(f"Accuracy of the model is: {accuracy:.3f}") # %% [markdown] # We see that the performance of the model in this case is as good as the # original model. However, we don't know if there is a value for `C` in the # between 0.001 and 100 that will lead to a better model. # # You can try by hand a couple of values in this range to see if you can # improve the performance.
true
efc2a9bba1db46e90da4f3d1dffaa98ff3fc76ef
LingyeWU/unit3
/snakify_practice/3.py
837
4.1875
4
# This program finds the minimum of two numbers: a = int(input()) b = int(input()) if a < b: print (a) else: print (b) # This program prints a number depending on the sign of the input: a = int(input()) if a > 0: print (1) elif a < 0: print (-1) else: print (0) # This program takes the coordinates of a rook and a destination and determines whether it is possible for it to move: x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if x1 == x2 or y1 == y2: print ("YES") else: print ("NO") # This program determines if a chocolate bar with dimensions n by m would be able to be divided into a bar with k squares. n = float(input()) m = float(input()) k = float(input()) portion = n * m if k < portion and ((k % n == 0) or (k % m == 0)): print("YES") else: print("NO")
true
4bee428ac8e0dd249deef5c67915e62ba1057997
Matshisela/Speed-Converter
/Speed Convertor.py
1,100
4.34375
4
#!/usr/bin/env python # coding: utf-8 # ### Converting km/hr to m/hr and Vice versa # In[1]: def kmh_to_mph(x): return round(x * 0.621371, 2) # return to the nearest 2 decimal places def mph_to_kmh(x): return round(1/ 0.621371 * x, 2) # return to the nearest 2 decimal places # In[2]: speed_km = float(input("What is the speed in km/hr?:")) g = kmh_to_mph(speed_km) print("The speed in miles/hr is {}".format(g)) # In[3]: speed_m = float(input("What is the speed in miles/hr?:")) g = mph_to_kmh(speed_m) print("The speed in km/hr is {}".format(g)) # ### Converting km/hr to metres/sec and Vice versa # In[4]: def kmh_to_ms(x): return round(1/ 3.6 * x, 2) # return to the nearest 2 decimal places def ms_to_kmh(x): return round(3.6 * x, 2) # return to the nearest 2 decimal places # In[5]: speed_ms = float(input("What is the speed in metres/s?:")) g = ms_to_kmh(speed_ms) print("The speed in km/hr is {}".format(g)) # In[6]: speed_kmh = float(input("What is the speed in km/hr?:")) g = kmh_to_ms(speed_kmh) print("The speed in metres/sec is {}".format(g))
true
5f90cf3ee2b9a95d877d3a61a5f4691535c182f3
s-andromeda/PreCourse_2
/Exercise_4.py
1,469
4.5
4
# Python program for implementation of MergeSort """ Student : Shahreen Shahjahan Psyche Time Complexity : O(NlogN) Memory Complexity : O(logN) The code ran successfully """ def mergeSort(arr): if len(arr) > 1 : # Getting the mid point of the array and dividing the array into 2 using the mid point mid = len(arr)//2 L = arr[: mid] R = arr[mid :] # passing these two arrays to sort or get divided again mergeSort(L) mergeSort(R) # this function merges the two arrays back again merge(L, R, arr) def merge(L, R, arr): i = 0 j = 0 k = 0 # checking if the element of the both arrays. The smaller one will get saved everytime. while(i<len(L) and j<len(R)): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # When we run out of either of the arrays, we will shift the remaining of the other arrays to the arr while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 # Code to print the list def printList(arr): print(arr) # driver code to test the above code if __name__ == '__main__': arr = [12, 11, 13, 5, 6, 7] print ("Given array is", end="\n") printList(arr) mergeSort(arr) print("Sorted array is: ", end="\n") printList(arr)
true
1bdfb1dfe2b1d5c7b707a38f071a7167f6f514e8
arpitsomani8/Data-Structures-And-Algorithm-With-Python
/Stack/Representation of a Stack using Dynamic Array.py
1,517
4.125
4
# -*- coding: utf-8 -*- """ @author: Arpit Somani """ class Node: #create nodes of linked list def __init__(self,data): self.data = data self.next = None class Stack: # default is NULL def __init__(self): self.head = None # Checks if stack is empty def isempty(self): if self.head == None: return True else: return False # add item to stack def push(self,data): if self.head == None: self.head=Node(data) else: newnode = Node(data) newnode.next = self.head self.head = newnode # Remove element from stack def pop(self): if self.isempty(): return None #make a new top element after popping else: poppednode = self.head self.head = self.head.next poppednode.next = None return poppednode.data #top element in stack def peek(self): if self.isempty(): return None else: return self.head.data def display(self): fnode = self.head if self.isempty(): print("Stack Underflow") else: while(fnode != None): print(fnode.data,end = " ") fnode = fnode.next return mystack = Stack() q=int(input("How many total elements to push:")) for i in range (0,q): a=int(input("Enter "+str(i+1)+" element to push:")) mystack.push(a) print(" ") mystack.display() print("\nBefore pop, Top (peek) element is ",mystack.peek()) mystack.pop() mystack.display() print("\nAfter pop, Top (peek) element is ", mystack.peek())
true
b6d143eb55b431f047482aaf881c025382483c0a
SHIVAPRASAD96/flask-python
/NewProject/python_youtube/list.py
432
4.1875
4
food =["backing","tuna","honey","burgers","damn","some shit"] dict={1,2,3}; for f in food: #[: this is used print how many of the list items you want to print depending on the number of items in your list ] print(f,"\nthe length of",f,len(f)); print("\n"); onTeam =[20,23,23235,565]; print("Here are the people of the team Valour"); for i in onTeam: print(i); continue; print("hello"); print("Done");
true
60fc8a28c92e1cf7c9b98260f1dee89940929d68
tsaiiuo/pythonNLP
/set and []pratice.py
1,015
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 23 15:24:16 2021 @author: huannn """ #list[item1,item2....] a=['apple','melon','orange','apple'] a.append('tomato') a.insert(3, 'tomato') print(a) a.remove('apple') print(a) a.pop(0)#pop out a certain position print(a) a1=['fish','pork'] #a.append(a1) will be['fish'....] a.extend(a1) print(a) print(a.index('fish'))#find the index print(a.count('tomato'))#count q a.reverse()#tenet print(a) a.sort()#abc order print(a) a2=a.copy() print(a2) #set function b=set(a2)#make a set from a list print(b) #b.remove('apple')#if the set doesnt exist item will be error need use discard b.discard('apple') print(b) b.update(a)#use update to append a list print(b) set1={'1','2','3'} set2={'3','4','5'} print(set1|set2)#same as below #print(set1.union(set2)) print(set1-set2)#remove item appear in set2 print(set1&set2) print(set1.difference(set2))#set1 be base for fruit in a:#string item print(fruit) a.clear() print(f"final list:{a}")
true
152e7b7430ded1d3593c2ec9b3a2cec89d7d270d
pawarspeaks/HACKTOBERFEST2021-2
/PYTHON/PasswordGen.py
606
4.125
4
import string import random #Characters List to Generate Password characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") def password_gen(): #Length of Password from the User length = int(input("Password length: ")) #Shuffling the Characters random.shuffle(characters) #Picking random Characters from the given List password = [] for i in range(length): password.append(random.choice(characters)) #Shuffling the Resultant Password random.shuffle(password) #Converting the List to String #Printing the List print("".join(password)) #Invoking the function password_gen()
true
de91aed8808c9c1562ace961b39d5e2f6d3d20bc
leolanese/python-playground
/tips/list-comprehensions.py
318
4.34375
4
# Python's list comprehensions vals = [expression for value in collection if condition] # This is equivalent to: vals = [] for value in collection: if condition: vals.append(expression) # Example: even_squares = [x * x for x in range(10) if not x % 2 even_squares # [0, 4, 16, 36, 64]
true
ee2d5fa2d85740d0219040b80426b1ef57087857
datasciencecampus/coffee-and-coding
/20191112_code_testing_overview/02_example_time_test.py
1,166
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Nov 11 10:28:55 2019 @author: pughd """ from datetime import datetime class TestClass: # Difficult to automate test this as depends on time of day! def test_morning1(self): assert time_of_day() == "Night" # Far easier to test def test_morning2(self): assert time_of_day_2(9) == "Morning" assert time_of_day_2(13) == "Afternoon" assert time_of_day_2(0) == "Night" assert time_of_day_2(19) == "Evening" def time_of_day_2(hour): # Return approproiate description if hour >= 0 and hour < 6: return 'Night' elif hour >= 6 and hour < 12: return "Morning" elif hour >= 12 and hour < 18: return "Afternoon" else: return "Evening" def time_of_day(): # Get the current hour hour = datetime.now().hour # Return approproiate description if hour >= 0 and hour < 6: return 'Night' elif hour >= 6 and hour < 12: return "Morning" elif hour >= 12 and hour < 18: return "Afternoon" else: return "Evening"
true
7042b216761fe26ce8ffa3e913f54a0508d19ca4
sreelekha11/Number-Guessing
/NumberGuessingGame.py
1,254
4.40625
4
#Creating a simple GUI Python Guessing Game using Tkinter and getting the computer to choose a random number, check if the user guess is correct and inform the user. import tkinter import random computer_guess = random.randint(1,10) def Check(): user_guess = int(number_guess.get()) #Determine higher, lower or correct if user_guess < computer_guess: msg="Higher!" elif user_guess > computer_guess: msg="Lower!" elif user_guess == computer_guess: msg="Correct!" else: msg="Something went Wrong..." #Show the Result label_result["text"]= msg #Create root window root = tkinter.Tk() root.title("Number Guessing Game") #Create Widgets label_title=tkinter.Label(root, text="Welcome to the Number Guessing Game!") label_title.pack() label_result=tkinter.Label(root, text="Good Luck!") label_result.pack() button_check=tkinter.Button(root, text="Check", fg="green", command=Check) button_check.pack(side="left") button_reset=tkinter.Button(root, text="Reset", fg="red", command=root.quit) button_reset.pack(side="right") number_guess=tkinter.Entry(root, width=3) number_guess.pack() #Start the main events loop root.mainloop()
true
80372221944fbf2c560fd597e48d5e447a0bd4dd
henrikac/randomturtlewalk
/src/main.py
1,077
4.375
4
"""A Python turtle that does a random walk. Author: Henrik Abel Christensen """ import random from turtle import Screen from typing import List from argparser import parser from tortoise import Tortoise args = parser.parse_args() def get_range(min_max: List[int]) -> range: """Returns a range with the turtles min max choices. If the input is None then range(-25, 26) is returned. Parameters ---------- min_max : List[int] Returns ------- min_max : range """ if min_max is None: return range(-25, 26) minimum = min_max[0] maximum = min_max[1] if minimum == maximum: raise ValueError('min and max must be different') if minimum > maximum: raise ValueError('min must be lower than max') return range(minimum, maximum) CHOICES = list(get_range(args.range)) MOVES = [(random.choice(CHOICES), random.choice(CHOICES)) for _ in range(args.steps)] screen = Screen() screen.mode('logo') # <--- DO NOT CHANGE THIS! t = Tortoise(visible=args.hide) for move in MOVES: t.step(move) screen.exitonclick()
true
53f1f2049a3a31a4a63a0fc38fb77d1466e3ffa3
therealrooster/fizzbuzz
/fizzbuzz.py
740
4.21875
4
def fizzbuzz(): output = [] for number in range (1, 101): if number % 15 == 0: output.append('Fizzbuzz') elif number % 3 == 0: output.append('Fizz') elif number % 5 == 0: output.append('Buzz') else: output.append(number) return output #print(fizzbuzz()) #1. create a method called fizzbuzz #2. create an output array called output #3. iterate from 1 to 100, each number is called number #3a. if NUMBER is a multiple of 3, append "FIZZ" to output #3b. if NUMBER is multiple of 5, append "BUZZ" to output #3c. if NUMBER is multiple of 3 and 5, append "FIZZBUZZ" to output #3d. otherwise append NUMBER #4. return OUTPUT
true
81c8b00713bdc7169f2dcaf7051c1dc376385a5a
zeyuzhou91/PhD_dissertation
/RPTS/bernoulli_bandit/auxiliary.py
1,561
4.15625
4
""" Some auxiliary functions. """ import numpy as np def argmax_of_array(array): """ Find the index of the largest value in an array of real numbers. Input: array: an array of real numbers. Output: index: an integer in [K], where K = len(array) """ # Simple but does not support random selection in the case of more than one largest values. ind = int(np.argmax(array)) return ind def argmin_of_array(array, num): """ Return the indices of the the lowest num values in the array. Inputs: array: a numpy array. num: an integer. Output: idx: a numpy array of integer indices. """ idx = np.argpartition(array, num) return idx def map_to_domain(x): """ Map each number in the given array to [0,1]^K, if it is outside of that interval. Input: x: an numpy array of shape (N,K) Output: y: an numpy array of shape (N,K) """ y = np.copy(x) if np.ndim(x) == 1: (N,) = np.shape(x) for i in range(N): if y[i] < 0: y[i] = 0 elif y[i] > 1: y[i] = 1 else: pass elif np.ndim(x) == 2: (N,K) = np.shape(x) for i in range(N): for j in range(K): if y[i][j] < 0: y[i][j] = 0 elif y[i][j] > 1: y[i][j] = 1 else: pass return y
true
b87cafe0bec26f966a8c027f0aa4e3311be3a18f
chris4540/algorithm_exercise
/basic/arr_search/rotated_arr/simple_approach.py
1,736
4.3125
4
""" https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-pivoted-array/ 1) Find out pivot point and divide the array in two sub-arrays. (pivot = 2) /*Index of 5*/ 2) Now call binary search for one of the two sub-arrays. (a) If element is greater than 0th element then search in left array (b) Else Search in right array (1 will go in else as 1 < 0th element(3)) 3) If element is found in selected sub-array then return index Else return -1. """ from typing import List def find_pivot_idx(arr: List[int]) -> int: """ Find the pivot point using binary search Example: >>> find_pivot_idx([3, 4, 5, 6, 1, 2]) 3 # becasue arr[3] is 6 >>> find_pivot_idx([3, 4, 5, 6, 7, 8, 1, 2]) 55 """ def _find_pivot_idx_rec(arr: List[int], low: int, high: int): # base cases for recussion if high < low: return -1 # cannot find if high == low: return high # ---------------------------- mid = (low + high) // 2 print("mid=", mid) assert mid < high # consider if we pin-point the pivot if (arr[mid] > arr[mid+1]): return mid if (arr[mid-1]> arr[mid]): return mid-1 if arr[low] >= arr[mid]: return _find_pivot_idx_rec(arr, low, mid-1) # if arr[mid+1] >= arr[high]: return _find_pivot_idx_rec(arr, mid+1, high) # ------------------- ret = _find_pivot_idx_rec(arr, 0, len(arr)-1) if ret == -1: raise ValueError("Cannot find the pivot point.") return ret if __name__ == '__main__': arr = [3, 4, 5, 6, 7, 8, 1, 2] res = find_pivot_idx(arr) print(res)
true
4a3368612d71c0d50ea714669551caf6922696ba
Sakshipandey891/sakpan
/vote.py
285
4.3125
4
#to take age as input & print whether you are eligible or not to vote? age = int(input("enter the age:")) if age==18: print("you are eligible for voting") elif age>=18: print("you are eligible for voting") else: print("you are not eligible for voting")
true
d4fc59edb7222118899818e3a6bfb3e84d57797e
MikhaelMIEM/NC_Devops_school
/seminar1/1.py
574
4.21875
4
def reverse_int(value): reversed_int = 0 while value: reversed_int = reversed_int*10 + value%10 value = value // 10 return reversed_int def is_palindrome(value): if value == reverse_int(value) and value%10 != 0: return 'Yes' else: return 'No' if __name__ == '__main__': while True: try: val = abs(int(input())) except ValueError: print('Value is not integer') continue except KeyboardInterrupt: break print(is_palindrome(val))
true
b4b5b23dff3ef54135b31a52c397ab7bb347c298
ashwani99/ds-algo-python
/sorting/merge_sort.py
1,092
4.34375
4
def merge_sort(arr): l = len(arr) return _merge_sort(arr, 0, l-1) def _merge_sort(arr, start, end): if start < end: mid = (start+end)//2 _merge_sort(arr, start, mid) _merge_sort(arr, mid+1, end) merge(arr, start, mid, end) return arr def merge(arr, start, mid, end): result = [] left = start right = mid+1 # compare and fill while both left and right array are not empty while left <= mid and right <= end: if arr[left] <= arr[right]: result.append(arr[left]) left += 1 else: result.append(arr[right]) right += 1 # if left has some left put all in result while left <= mid: result.append(arr[left]) left += 1 # if right has some left put all in result while right <= end: result.append(arr[right]) right += 1 # replacing values into the original array for i in range(len(result)): arr[i+start] = result[i] if __name__ == '__main__': print(merge_sort([5, 4, 3, 2, 1, -9, 5, 3]))
true
7024125f920382245e33eae4f71d857d6b3f24b7
shensleymit/HapticGlove
/Haptic Feedback Code/RunMe2.py
1,725
4.375
4
################################################# # This asks the user which function they would # # like to see, and loads that one. Ideally, # # this won't be needed, and instead the choice # # of function and the function will all be part # # of one file. # ################################################# if __name__ == '__main__': print "What function do you want? Here are your choices." print "2^x" print "sin(x)" print "y = x" print "y = x^2" print "xz plane" print "yz plane" retry = True while retry == True: #continually prompts user until they pick a recognized function choice = raw_input("Please pick one of these! Hit enter after typing your choice here: ").lower() if choice == "2^x": retry = False print "Loading..." execfile("exp.py") #executes the file that corresponds to the picked function elif choice == "sin(x)" or choice == "sinx": #can interpret it with or without parentheses retry = False print "Loading..." execfile("sinx.py") elif choice == "y = x" or choice == "y=x": retry = False print "Loading..." execfile("x.py") elif choice == "y = x^2" or choice == "y=x^2": retry = False print "Loading..." execfile("x2.py") elif choice == "yz plane": retry = False print "Loading..." execfile("xplane.py") elif choice == "xz plane": retry = False print "Loading..." execfile("yplane.py") else: print "I'm sorry, I didn't get that."
true
9d272a9c8c1733568d01335040bc94a3bec2eb1c
aaronbushell1984/Python
/Day 1/Inputs.py
1,596
4.3125
4
# Python has Input, Output and Error Streams # Python executes code sequentially - Line by Line # Python style guide https://www.python.org/dev/peps/pep-0008/ # Add items to input stream with input - Print variable to output stream name = input('enter your name: ') print("Your name is", name) # Input takes input and outputs as a string by default. To add to age then use int(x) to cast to number age = int(input("enter your age:")) print("Your age is", age) # += adds and assigns to variable in shorthand, -= subtracts and assigns, *= multiplies and assigns age += 10 print("Your age in a decade will be", age) # Built-in functions with parameters example print(max(5,2,9,4)) print(min(5,2,9,4)) # Functions can be assigned to a variable maximum = print(max(5,2,9,4)) print(maximum) # Indent blocks - MUST BE INDENTED if maximum > 8: print("maximum is greater than 8") """ TO ACCESS PYTHON KEYWORDS - Enter Python compiler in terminal (type python) IMPORT A LIBRARY FOR KEYWORD Enter - import keyword Enter - print(keyword.kwlist) 'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield' """ # NB. DO NOT USE VARIABLES OR FILE NAMES WITH KEYWORDS # NB. PYTHON WILL PRODUCE AN INDENT ERROR IF A SPACE PRECEDES FUNCTION # NB. VARIABLES MUST NOT START WITH A NUMBER, ARE CASE SENSITIVE # NB. CONVENTION is to_use_variable_with_lowercase_underscores
true
e24d82a2699dd90ef9551b67975fad2f77bd84a1
bolducp/MIT-6.00SC-OpenCourseWare-Solutions
/Set 1/problem_2.py
1,235
4.15625
4
# Problem Set 1, Problem 2: Paying Off Debt in a Year def get_outstanding_balance(): outstanding_balance = round(float(raw_input("Enter the outstanding balance on the credit card: ")), 2) return outstanding_balance def get_annual_interest_rate(): annual_interest_rate = round(float(raw_input("Enter the annual interest rate as a decimal: ")), 2) return annual_interest_rate def main(): starting_balance = get_outstanding_balance() annual_interest_rate = get_annual_interest_rate() monthly_interest_rate = annual_interest_rate/12.0 min_monthly_payment = 10.0 outstanding_balance = starting_balance while outstanding_balance > 0: months = 0 min_monthly_payment += 10.0 outstanding_balance = starting_balance for month in range(1, 13): if outstanding_balance > 0: outstanding_balance = outstanding_balance * (1 + monthly_interest_rate) - min_monthly_payment months += 1 print "\n" + "RESULT" print "Monthly payment to pay off debt in 1 year:", min_monthly_payment print "Number of months needed:", months print "Balance:", round(outstanding_balance, 2) if __name__ == "__main__": main()
true
93fb4f4dab9e74fa1da1499eaa5f874cb2710e15
danielblignaut/movie-trailer-application
/media.py
1,185
4.15625
4
class Movie() : """ This class provides a way to store movie related data """ VALID_RESTRICTIONS = ["G", "PG", "PG-13", "R"] def __init__(self, title, storyline, image_poster, youtube_trailer, rating, restriction) : self.title = title self.storyline = storyline self.image_poster = image_poster self.youtube_trailer = youtube_trailer if(Movie.check_rating(rating)) : self.rating = rating else : self.rating = "N/A" if(Movie.check_restriction(restriction)) : self.restriction = restriction.upper() else : self.restriction = "N/A" '''this static method provides a way to check if the movies's age restriction is valid ''' @staticmethod def check_restriction(restriction) : for static_restriction in Movie.VALID_RESTRICTIONS : if(static_restriction == restriction.upper()) : return True return False '''this static method provides a way to check if the movies's rating is valid ''' @staticmethod def check_rating(rating) : if(rating >= 0 and rating <= 5) : return True return False
true
2134dde3da45d97bed30599df119beb184f15eaa
kwahome/python-escapade
/fun-with-problems/in_place_string_reverse.py
1,685
4.3125
4
# -*- coding: utf-8 -*- #============================================================================================================================================ # # Author: Kelvin Wahome # Title: Reversing a string in-place # Project: python-escapade # Package: fun-with-problems # # # Write a function to reverse a string in-place # # Since strings in Python are immutable, first convert the string into a list of characters, do the in-place reversal on that list, and # re-join that list into a string before returning it. This isn't technically "in-place" and the list of characters will cost O(n)O(n)O(n) # additional space, but it's a reasonable way to stay within the spirit of the challenge. If you're comfortable coding in a language with # mutable strings, that'd be even better! # #============================================================================================================================================ import sys def reverse_string(string): string = list(string) # walk towards the middle, from both sides for left in range(len(string) / 2): right = -left - 1 # swap the front char and back char string[left], string[right] = \ string[right], string[left] return ''.join(string) def main(): proceed = False print "Reversing a string with an in-place function" print "------------------------------------------" string = raw_input("Enter the string to reverse: ") print "\n" print "Original string: " print string print "\n" print "Reversed string:" print "\n" print reverse_string(string) print "\n" if __name__ == "__main__": try: sys.exit(main()) except Exception: print "An error has occured"
true
9485759ef1b43b19642b35039ec0e5a0e5408f36
raylyrainetwstd/MyRepo
/M07_Code_Fixed.py
2,458
4.1875
4
#this function takes an input from a user in response to a question #if the user input is not a number, is_num doesn't accept the user input def is_num(question): while True: try: x = int(input(question)) break except ValueError: print("That is not a number") continue return x #this function asks the user about information about their pet #The user will answer in strings, except for when asked for pet's age class cat(): def __init__(self): self.name = input("\nWhat is your pet's name?\n") self.type = input(f"What type of pet is {self.name}?\n").lower() self.color = input(f"What color is {self.name}?\n").lower() self.age = is_num(f"How old is {self.name}?\n") #This function asks the user their name and about one of their pets #after getting info on the pet, the program asks the user if they want to add info about another pet #the program will continue to add pets to the pet list until the user says they don't wanna add more #The program then writes a new txt file listing the user and all the pets the user talked about def main(): pet = [] response = "y" name = input("Hello! What is your name?\n") while response != "n": pet.append(cat()) while True: response = input("\nDo you have another pet? Y|n: ").lower() if response == "y" or response == "": break elif response == "n": break else: print("\nYou did not make a correct response, please use a 'Y' for yes and a 'n' for no.") continue num_pets = len(pet) with open('My_Pet_List.txt','w') as file: if num_pets == 1: file.write(f"{name} has one pet, it's name is {pet[0].name}.\n\n") else: file.write(f"{name} has {num_pets} pets. Those pet's names are:") count = 0 for i in pet: count += 1 if count == 1: file.write(f" {i.name}") elif count != 1: file.write(f", {i.name}") file.write(".\n\n") for i in pet: file.write(f"{i.name} is a {i.color} {i.type} and is {i.age} years old.\n") #this is in here for security #this is making sure that the program isn't opening up any other projects if __name__ != "__main__": main() else: exit
true
91cd8ab16e42d87249023a65929e46bc756e857a
raylyrainetwstd/MyRepo
/SDEV120_M02_Simple_Math.py
452
4.1875
4
#get two numbers from user #add, subtract, multiply, and divide the two numbers together and save the values to variables #print the results on one line num1 = int(input("Please type a number: ")) num2 = int(input("Please type another number: ")) addition = str((num1 + num2)) subtraction = str((num1 - num2)) multiplication = str((num1 * num2)) division = str((num1 / num2)) print(addition + " " + subtraction + " " + multiplication + " " + division)
true
3042a58e9d3deadaad9caa2291f2a672798b482d
cuichacha/MIT-6.00.1x
/Week 2: Simple Programs/4. Functions/Recursion on non-numerics-1.py
621
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 15 20:54:15 2019 @author: Will """ def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' if aStr=="": return False if char==aStr[int(len(aStr)/2)]: return True elif char>aStr[int(len(aStr)/2)] and int(len(aStr)/2)!=0: return isIn(char, aStr[int(len(aStr)/2):]) elif char<aStr[int(len(aStr)/2)] and int(len(aStr)/2)!=0: return isIn(char, aStr[0:int(len(aStr)/2)]) else: return False
true
f1f4ca1185dda31236ba9bd5ceded47043312d59
enireves/converter
/andbis.py
462
4.25
4
weather = input("What's the weather like? ") temperature = input("What temperature is it? ") if weather == "rainy" and temperature == "cold" : print("Take an umbrella and a warm jacket.") elif temperature == "warm": print("Take an umbrella and a shirt.") elif weather == "sunny" and temperature == "cold": print("Take sunglasses and a warm jacket.") elif temperature == "warm": print("Take sunglasses and a shirt.") else : print("Stay home!")
true
083a2d404922c25ca29310ead58938ebcf613db7
quangvinh86/python-projecteuler
/PE-010/summation_of_primes.py
949
4.125
4
""" Solution to Project Euler problem 10 @author: vinh.nguyenquang @email: quangvinh19862003@gmail.com """ import math UPPER_LIMIT = 2000000 def is_prime(number): if number <= 1: return False elif number <= 3: return True elif not number % 2: return False max_range = int(math.sqrt(number)) + 1 for counter in range(3, max_range, 2): if not number % counter: return False return True def calc_summation_of_primes(): sum_of_prime = 2 number = 3 while number <= UPPER_LIMIT: if is_prime(number): sum_of_prime += number number += 2 return sum_of_prime if __name__ == "__main__": import time start = time.time() ## result = calc_summation_of_primes() ## done = time.time() elapsed = done - start print("Prime sum of all primes below {} is {}".format(UPPER_LIMIT, result)) print("elapsed time: {}s".format(elapsed))
true
cc7bf998dc1b446c9bbe4b5f1455c5e62b7c8276
FrankCardillo/practice
/2016/codewars/python_practice/digital_root.py
577
4.21875
4
# A digital root is the recursive sum of all the digits in a number. # Given n, take the sum of the digits of n. # If that value has two digits, continue reducing in this way until a single-digit number is produced. # This is only applicable to the natural numbers. def digital_root(n): total = 0 stringified = str(n) for char in stringified: total += int(char) if total <= 9: return total else: stringified_total = str(total) total = 0 for char in stringified_total: total += int(char) return total
true
b7fab26d44f16a123f15142f6aac5cd697abcf58
fearlessfreap24/codingbatsolutions
/Logic-2/make_chocolate.py
572
4.125
4
def make_chocolate(small, big, goal): # not enough bricks if big * 5 + small < goal: return -1 # not enough small bricks goalmod = goal % 5 if goalmod > small: return -1 # enough small bricks if big < goal // 5: return goal - (big * 5) if big >= goal // 5: return goal % 5 if __name__ == "__main__": print(make_chocolate(4, 1, 9)) # 4 print(make_chocolate(4, 1, 10)) # -1 print(make_chocolate(4, 1, 7)) # 2 print(make_chocolate(6, 2, 7)) # 2 print(make_chocolate(7, 1, 12)) # 7
true
58724808401d4280a852997f06a00f4480d75aeb
Maidou0922/Maidou
/阶乘.py
421
4.15625
4
b=int(input("pls input number:")) def fact(a): result=1 if a < 0: return("Error") # should be Error elif a == 0 or a==1: return(str(a)) while a > 1: tmp=a*(a-1) result=result*tmp a -=2 return result #return after loop print(fact(b)) print("") # #fact of 5 should be 120, not 20, 5*4*3*2*1 = 120 , pls check your logic of func
true
73f05af982732d91004c84a6686e2116e2e1b705
rinkeshsante/ExperimentsBackup
/Python learning-mosh/Python Files/learn_02.py
1,123
4.15625
4
# from the python mega course # to run the entire code remove first ''' pair from code # create text file named test.txt containg multiple lines # file handling opening t& reading the file ''' file = open("test.txt", "r") content = file.readlines() # file.read() for all content reading # file.seek(0) to readjustng the reading pointer print(content) content = [i.rstrip('\n') for i in content] # to remove \n from numbers print(content) file.close() ''' # creating new file or rewrite existing one ''' file = open('test1.txt', 'w') file.write("line 1\n") file.write("line 2\n") file.close() ''' # appending existing files ''' file = open('test1.txt', 'a') file.write("line 3\n") file.write("line 4\n") file.close() ''' # notes # r+ => both reading and writing , add at beginning of text # w+ => writing and reading , create if it don't exist i.e. it overwrites # a+ => add at the end # with method no need to close ''' with open('test1.txt', 'a+') as file: file.seek(0) # to bring pointer at start content = file.read() file.write("line 5\n") file.write("line 6\n") print(content) '''
true
f09c699d0bf7d7486a1f0f881eee9f61686d6403
axentom/tea458-coe332
/homework02/generate_animals.py
1,713
4.34375
4
#!/usr/bin/env python3 import json import random import petname import sys """ This Function picks a random head for Dr. Moreau's beast """ def make_head(): animals = ["snake", "bull", "lion", "raven", "bunny"] head = animals[random.randint(0,4)] return head """ This Function pulls two random animals from the petname library and mashes their bodies together for Dr. Moreau's beast """ def make_body(): body1 = petname.name() body2 = petname.name() body = body1 + "-" + body2 return body """ This Function creates an even number between 2-10 inclusive to be the number of arms in Dr. Moreau's beast """ def make_arms(): arms = random.randint(1,5) * 2 return arms """ This function creates a multiple of three between 3-12 inclusive to be the nuber of legs in Dr. Moreau's beast """ def make_legs(): legs = random.randint(1,4) * 3 return legs """ This function creates a non-random number of tails equal to the sum of arms and legs This function REQUIRES the presence of a legs and arms int variable """ def make_tails(arms_str, legs_str): tails = int(arms_str) + int(legs_str) return tails def create_animal(): head = make_head() body = make_body() arms = make_arms() legs = make_legs() tails = make_tails(arms, legs) animal = {'head': head, 'body': body, 'arms': arms, 'legs': legs, 'tails': tails} return animal def main(): animals_list = {} animals_list['animal'] = [] for i in range(0,20): animal = create_animal() animals_list['animal'].append(animal) with open(sys.argv[1], 'w') as out: json.dump(animals_list, out, indent=2) if __name__ == '__main__': main()
true
84db20f7bfcaa6dd31784c4b6b23739fdc1a249d
Arjun-Pinpoint/InfyTQ
/Programming Fundamentals using Python/Day 3/Assignment 22.py
557
4.125
4
''' Write a Python program to generate the next 15 leap years starting from a given year. Populate the leap years into a list and display the list. Also write the pytest test cases to test the program. ''' #PF-Assgn-22 def find_leap_years(given_year): list_of_leap_years=[] count=0 while(count<15): if(given_year%400==0 or given_year%4==0): list_of_leap_years.append(given_year) count+=1 given_year+=1 return list_of_leap_years list_of_leap_years=find_leap_years(2000) print(list_of_leap_years)
true
030f3b5229cd74842dd83ad861f3463d5e1681e6
Arjun-Pinpoint/InfyTQ
/Programming Fundamentals using Python/Day 7/Assignment 47.py
1,317
4.3125
4
''' Write a python function, encrypt_sentence() which accepts a message and encrypts it based on rules given below and returns the encrypted message. Words at odd position -> Reverse It Words at even position -> Rearrange the characters so that all consonants appear before the vowels and their order should not change Note: 1. Assume that the sentence would begin with a word and there will be only a single space between the words. 2. Perform case sensitive string operations wherever necessary. Also write the pytest test cases to test the program. Sample Input Expected Output the sun rises in the east eht snu sesir ni eht stea ''' #PF-Assgn-47 def encrypt_sentence(sentence): sentence=sentence.split() res="" for i in range(len(sentence)): if i%2==0: word=sentence[i] reverse=word[::-1] res+=reverse+" " else: vowels="aeiouAEIOU" word=sentence[i] vowel="" non_vowel="" for w in word: if w in vowels: vowel+=w else: non_vowel+=w res+=non_vowel+vowel+" " return res sentence="The sun rises in the east" encrypted_sentence=encrypt_sentence(sentence) print(encrypted_sentence)
true
e4d361c009cd1a4cd312d9ebd6cf5cdd5019c954
JRobinson28/CS50-PSets
/pset7/houses/import.py
933
4.125
4
from cs50 import SQL from sys import argv, exit from csv import reader, DictReader db = SQL("sqlite:///students.db") def main(): # Check command line args if len(argv) != 2: print("Exactly one commmand line argument must be entered") exit(1) # Open CSV file given by command line arg with open(argv[1], "r") as csvfile: reader = DictReader(csvfile) # Loop through students for row in reader: nameSplit = ((row["name"]).split()) # Insert None where there is no middle name if (len(nameSplit) == 2): nameSplit.insert(1, None) # Insert each student into students table of students.db using db.execute db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?, ?, ?, ?, ?)", nameSplit[0], nameSplit[1], nameSplit[2], row["house"], row["birth"]) main()
true
7157f20e3565c8ec175b673725fd2073ad8ae33e
fennieliang/week3
/lesson_0212_regex.py
1,082
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 25 14:40:57 2021 @author: fennieliang """ #useful links for regular expression #http://python-learnnotebook.blogspot.com/2018/10/python-regular-expression.html #https://www.tutorialspoint.com/python/python_reg_expressions.htm #regular expression import re string = 'I bet you’ve heard of Harry James Poter for 11,000,000.00 times.' #string = "We are leaving in Taipei City in Taiwan" ''' #match capital words #matches = re.finditer('([A-Z][a-z]+\s)', string) #matches = re.finditer('([A-Z][a-z]+\s+[A-Z][a-z]+\s)', string) matches = re.finditer('([A-Z][a-z]+\s){1,}', string) for word in matches: print (word[0]) try names with first and last names or even middle names then a find_name function to the class ''' #match money style digits #matches = re.finditer('(\d+\s)', string) #matches = re.finditer('(\d+\.\d\d\s)', string) matches = re.finditer('(\d+,){0,}(\d+.)(\d+)', string) for digit in matches: print (digit[0]) ''' try big money with decimals add a find_digit function to the class '''
true
d32aa6fa40b6dd5c0201e74f53d5bd581d6a3fe9
josephcardillo/lpthw
/ex19.py
1,825
4.375
4
# creating a function called cheese_and_crackers that takes two arguments. def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses.") print(f"You have {boxes_of_crackers} boxes of crackers.") print("Get a blanket.\n") print("We can just give the function numbers directly:") # calls this function, and passes two integers into it: cheese_and_crackers(20, 30) print("OR, we can use variables from our script:") # sets two variables to integers amount_of_cheese = int(input("How many cheeses? ")) amount_of_crackers = int(input("How many crackers? ")) # calls function and passes in the variables we just set cheese_and_crackers(amount_of_cheese, amount_of_crackers) print("We can even do math inside too:") # calls function and passes two arguments in the form of addition cheese_and_crackers(10 + 20, 5 + 6) print("And we can combine the two, variables and math:") # calls function and passes in two arguments that are a combination of variables and integers added together cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # creating my own function def my_function(book, music, food): print(f'my favorite book is {book}.') print(f'I like listening to {music}') print(f'I love to eat {food}') # call the function and pass three arguments to it my_function("crime and punishment", "philip glass", "pizza") # set three variables to something using the input function favorite_book = input("What's your favorite book? ") favorite_music = input("What's your favorite music? ") favorite_food = input("What's your favorite food? ") # call the function again, passing in these new variables my_function(favorite_book, favorite_music, favorite_food) from sys import argv script, book, music, food = argv my_function(book, music, food)
true
7f97672e9989079ecf723aad9f71c57952440e35
josephcardillo/lpthw
/ex15.py
795
4.375
4
# imports argv module from sys from sys import argv # the two argv arguments script, filename = argv # Using only input instead of argv # filename = input("Enter the filename: ") # Opens the filename you gave when executing the script txt = open(filename) # prints a line print(f"Here's your file {filename}:") # The read() function opens the filename that's set to the txt variable print(txt.read()) print("Type the filename again:") txt.close() # prompt to input the filename again file_again = input("> ") # sets variable txt_again equal to the open function with one parameter: the variable file_again txt_again = open(file_again) # prints the content of the example15_sample.txt file by calling the read function on the txt_again variable. print(txt_again.read()) txt_again.close()
true
6fb99f7f646c260eb763fc5804868a9bcf529971
Shubham1744/HackerRank
/30_Days_of_code/Day_1_Data_Types/Solution.py
777
4.25
4
int_2 = int(input()) double_2 = float(input()) string_2 = input() # Read and save an integer, double, and String to your variables. sum_int = i + int_2 sum_double = d + double_2 sum_string = s + string_2 # Print the sum of both integer variables on a new line. # Print the sum of the double variables on a new line. # Concatenate and print the String variables on a new line print(sum_int) print(sum_double) print(sum_string) # Declare second integer, double, and String variables. # Read and save an integer, double, and String to your variables. # Print the sum of both integer variables on a new line. # Print the sum of the double variables on a new line. # Concatenate and print the String variables on a new line # The 's' variable above should be printed first.
true
ad07b60b0c4d663663a286ca854833a903e3ee6a
Philiplam4516/TRM
/Python Workshop/Advnaced Python/Codes/Functions/Functions/F05.py
431
4.125
4
''' Write a program to get a circle radius from terminal, and then compute the area of the circle by a function ''' PI = 3.14 def compute_circle_area(radius): return radius*radius*PI def main(): print("Enter a circle radius (m)") radius=input() radius = float(radius) # type cast from string to float area = compute_circle_area(radius=radius) print("area of the circle is {:.5f} m2".format(area)) return main()
true
307cabfc949ee7f6af494726552b2228f09249d5
jahanzebhaider/Python
/if\else/else.py
1,841
4.15625
4
#THIS CODE WILL PRINT THR HONDA CAR WITH UPPER CASE AND REST WITH LOWER CASE ALPHABETS cars=['audi','bmw','honda','toyota','suzuki'] for car in cars: if car =='Honda': print(car.upper()) else: print(car.lower()) # checking nother of checking in list if 'ponks' in cars: print("it's not their") elif 'bmw' not in cars: print('it is their') names=['ali','ahmed','muetaza'] if names !='ali': print('their is no ali present in list') #checking if for numerical value no=17 if no ==17: print('no is present') else: print('no is not present') marks=80 if marks>70 and marks<100: print('A') else: print('Fail') #price for diff student age=input('Enter your age') age=int(age) if age<5: print("YOU ARE NOT ELIGIBLE") elif age<10: price=10 print('your age is ' + str(age) +".Your admission fees is"+ str(price)) elif age<18: price=0 print('your age is ' + str(age) +".Your admission fees is"+ str(price)) #using in statement in if condition pizza=['mashroom','cheese'] if 'mashroom' in pizza: print('pizza is ready') elif 'pepproni' in pizza: print('pizza will take time') else: print('pizza') #alien game 0.1 alien_colour=['red','yellow','green'] if 'green' in alien_colour: print('You Earned 5 points') elif 'yellow' in alien_colour: print('Your earned 10 points') elif 'red' in alien_colour: print('you earned 15 ponts') #stages of life age=89 if age<2: print('you are a baby') elif age >=2 and age<4: print('toddller') elif age >=4 and age<13: print('kid') elif age >=13 and age<20: print('teenager') elif age >=20 and age<65: print('addult') else: print('Elder') #favorite food favorite_food=['banana','apple','mango']
true
5db7c26589e626757b3bd3c34f6470a4667b4508
TheCoderIsBibhu/Spectrum_Internship
/Task1(PythonDev)/prgm2.py
232
4.25
4
#2 Given a number find the number of zeros in the factorial of the number. num=int(input("Enter a Number: ")) i=0 while num!=0: i+=int(num/5) num=num/5 print("The Number of zeros in factorial of the number is ",i)
true
c33def97afff545464952faa066c663e1d472491
RyanMolyneux/Learning_Python
/tutorialPointWork/lab5/test2.py
1,186
4.5625
5
#In this session we will be working with strings and how to access values from them. print("\nTEST-1\n----------------------------\n"); """Today we will test out how to create substrings, which will involve slicing of an existing string.""" #Variables variable_string = "Pycon" variable_substring = variable_string[2:-1] #Note minus 1 is a short hand index for the end of the string. if(len(variable_string) == len(variable_substring)): print("\n\n'variable substring' is not a substring of 'variable_string'"); else: print("\n\nvariable substring is a stubstring of variable string."); print("\nTEST-2\n------------------------------\n"); #Updating String """This is better well known as concatinating to a string two ways of doing this are during print or as assignment , assignment is some what permanant as long as you do not reinitialise the string but print is not permenant as soon as you exit the print method that concatinated value is gone.""" variable_string_permanent = variable_string +" is On!!!."; print("\n\nPrint using temporary concatination : ",variable_string+" is On!!!"); print("\n\nPrint using permenant re assignment : ",variable_string_permanent);
true
20d19ed63a0dd22c377a915facdb707c2b069732
RyanMolyneux/Learning_Python
/pythonCrashCourseWork/Chapter 8/8-8-UserAlbums.py
844
4.1875
4
#Chapter 8 ex 8 date : 21/06/17. #Variables albums = [] #Functions def make_album(artistName,albumTitle,num_tracks = ""): "Creates a dictionary made up of music artist albums." album = {"artist" : artistName,"album title": albumTitle} if num_tracks: album["number of tracks"] = num_tracks return album #Body print("\n--------------------------------------\n\tStore Your Favourites Today\n--------------------------------------\n\nExample ",make_album("Jimmo","Jambo","3")) for album in range(0,3): albums.append(make_album(input("\n\nPlease enter artist name : "),input("Please enter album title :"))) if(input("Do you wish to quit : ") == "q"): print("\nThank you for using Favorites come back soon Goodbye") break while albums: print("\nAlbums\n---------------------------\n",albums.pop())
true
01cb8a39730aca55603be93355359da08d0a453e
RyanMolyneux/Learning_Python
/pythonCrashCourseWork/Chapter 10/ex10/main.py
526
4.25
4
"""This will be a basic program which just consists of code counting the number of times 'the' appears in a text file.""" #Chapter 10 ex 10 DATE:17/07/18. #Import - EMPTY #Variables file_name = "" text = "" #Objects - EMPTY #Functions - EMPTY #Body file_name = input("\n\nPlease enter name of the file & rember extensions.\nInput : ") with open(file_name) as fileObject: text = fileObject.read() print("\n\nThe number times 'the' has been used in ",file_name," is ",str(text.lower().count("the")))
true
4bc87ec0732a1bbae109667d396bc02610ecb6c7
Gustacro/learning_python
/become_python_developer/3_Ex_Files_Learning_Python/Exercise Files/Ch3/calendars_start.py
1,776
4.25
4
# # Example file for working with Calendars # # import the calendar module import calendar # create a plain text calendar c = calendar.TextCalendar(calendar.SUNDAY) # st = c.formatmonth(2019, 12, 0, 0) # "formatmonth" method allow format a particular month into a text string # print(st) # create an HTML formatted calendar # hc = calendar.HTMLCalendar(calendar.SUNDAY) # st = hc.formatmonth(2019,12) # print(st) # loop over the days of a month # zeros mean that the day of the week is in an overlapping month # for i in c.itermonthdays(2019, 12): # print(i) # zeros at start and end, are the days that belongs to another month # The Calendar module provides useful utilities for the given locale, # such as the names of days and months in both full and abbreviated forms # for name in calendar.month_name: # print(name) # for day in calendar.day_name: # print(day) # Calculate days based on a rule: For example, consider # a team meeting on the first Friday of every month. # To figure out what days that would be for each month, # we can use this script: print("Team meeting will be on: ") for m in range(1,13): # loop over all the months # Get and array of weeks that represent each one of the months cal= calendar.monthcalendar(2019, m) # Specify year, m = month number # create variables that represent week one and week two where the first FRIDAY will fall into weekone = cal[0] weektwo = cal[1] # let's check if the first FRIDAY falls into the first week of the month or in the second week if weekone[calendar.FRIDAY] != 0: # if the first FRIDAY = zero, it means that that Friday belongs to another month meetday = weekone[calendar.FRIDAY] else: meetday = weektwo[calendar.FRIDAY] print('%10s %2d' % (calendar.month_name[m], meetday))
true
a212f533bf41ef324030787837c59924207f7b9d
bansal-ashish/hackerR
/Python/Introduction/division.py
1,753
4.34375
4
#!/usr/bin/env python """ In Python, there are two kinds of division: integer division and float division. During the time of Python 2, when you divided one integer by another integer, no matter what, the result would always be an integer. For example: >>> 4/3 1 In order to make this a float division, you would need to convert one of the arguments into a float. For example: >>> 4/3.0 1.3333333333333333 Since Python doesn't declare data types in advance, you never know when you want to use integers and when you want to use a float. Since floats lose precision, it's not advised to use them in integral calculations. To solve this problem, future Python modules included a new type of division called integer division given by the operator //. Now, / performs float division, and // performs integer division. In Python 2, we will import a feature from the module __future__ called division. >>> from __future__ import division >>> print 4/3 1.3333333333333333 >>> print 4//3 1 Note: The __ in __future__ is a double underscore. Task Read two integers and print two lines. The first line should contain integer division, a//b. The second line should contain float division, a/b. You don't need to perform any rounding or formatting operations. Input Format The first line contains the first integer, aa. The second line contains the second integer, bb. Output Format Print the two lines as described above. Sample Input 4 3 Sample Output 1 1.3333333333333333 """ from __future__ import division, print_function def main(): """Division challenge.""" first_int = int(raw_input()) second_int = int(raw_input()) print(first_int // second_int) print(first_int / second_int) if __name__ == '__main__': main()
true
35815caac7564a6be04e75a3af3b12139b97eced
jaredcooke/CP1404Practicals
/prac1/fromscratch.py
442
4.15625
4
number_of_items = int(input("Number of items: ")) total_cost = 0 while number_of_items <= 0: print("Invalid number of items!") number_of_items = int(input("Number of items: ")) for i in range(number_of_items, 0, -1): price_of_item = float(input("Price of item: ")) total_cost += price_of_item if total_cost > 100: total_cost = round(total_cost * 0.9, 2) print("Total price for", number_of_items, "items is $", total_cost)
true
8369dabbbe5680471488c495cf5a9b8599e11ea8
orbache/pythonExercises
/exercise1.py
541
4.40625
4
#!/usr/bin/python __author__ = "Evyatar Orbach" __email__ = "evyataro@gmail.com" '''Exercise 1 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old. ''' from datetime import datetime year = datetime.now().strftime("%Y") name = raw_input("Please enter your name\n") age = raw_input("Please enter your age\n") print("Hi %s,\nIn 100 year from now you will be %s and the year is going to be %s" %(name, str(int(age) + 100), str(int(year) + 100)))
true
3bd707a6c0b5a2ffb1657ae2ac8465452aa30d6d
orbache/pythonExercises
/exercise14.py
747
4.5625
5
#!/usr/bin/python __author__ = "Evyatar Orbach" __email__ = "evyataro@gmail.com" '''Exercise 14 Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: My name is Michele Then I would see the string: Michele is name My shown back to me. ''' import string str = raw_input("Please enter your string\n") def delimiterHandler(v_str,v_delimiter): return string.split(str,v_delimiter, ) def reverseString(v_list): newList = [] i = len(v_list)-1 while i >= 0: newList.append(v_list[i]) i -= 1 return ' '.join(newList) print reverseString(delimiterHandler(str,' '))
true
b71c8353038c7cac83a834e5b047cc735648b371
abelar96/PythonPrograms
/HW2.py
425
4.21875
4
##Diego Abelar Morales def distance(s, h): return s * h speed = int(input("What is the speed of the vehicle in mph?: ")) hours = int(input("How many hours has it traveled: ")) print("Hours Distanced Traveled") print("------------------------------") for time in range(1, 1 + hours): distance(speed, time) print(time, " ", distance(speed, time)) print("Average mph: ", (speed * hours)/hours)
true
0d58826718124173c580fddc80ab18717d8db13e
Vaishnav95/bridgelabz
/testing_programs/vending_notes.py
758
4.40625
4
''' Find the Fewest Notes to be returned for Vending Machine a. Desc -> There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be returned by Vending Machine. Write a Program to calculate the minimum number of Notes as well as the Notes to be returned by the Vending Machine as a Change b. I/P -> read the Change in Rs to be returned by the Vending Machine c. Logic -> Use Recursion and check for largest value of the Note to return change to get to minimum number of Notes. d. O/P -> Two Outputs - one the number of minimum Note needed to give the change and second list of Rs Notes that would given in the Change ''' from utils import Util amount = int(input("Enter the amount: ")) notes = Util() resulting_notes = notes.vending_machine(amount)
true
de3f20a97b1f6ad9a4f09553914f7a0b4b55ee54
Vaishnav95/bridgelabz
/algorithm_programs/sort_merge.py
700
4.15625
4
''' Merge Sort ​ - ​ Write a program to do Merge Sort of list of Strings. a. Logic -> ​ To Merge Sort an array, we divide it into two halves, sort the two halves independently, and then merge the results to sort the full array. To sort a[lo, hi), we use the following recursive strategy: b. Base case: If the subarray length is 0 or 1, it is already sorted. c. Reduction step: Otherwise, compute mid = lo + (hi - lo) / 2, recursively sort the two subarrays a[lo, mid) and a[mid, hi), and merge them to produce a sorted result. ''' from utils import Util elements_number = int(input("Enter number of elements : ")) merge_object = Util() result_array = merge_object.merge_sort(elements_number)
true
6c802e64c761ee9de46c355b25dad866c867ded1
Vaishnav95/bridgelabz
/logical_programs/tic_tac_toe.py
630
4.25
4
''' Cross Game or Tic-Tac-Toe Game a. Desc -> Write a Program to play a Cross Game or Tic-Tac-Toe Game. Player 1 is the Computer and the Player 2 is the user. Player 1 take Random Cell that is the Column and Row. b. I/P -> Take User Input for the Cell i.e. Col and Row to Mark the ‘X’ c. Logic -> The User or the Computer can only take the unoccupied cell. The Game is played till either wins or till draw... d. O/P -> Print the Col and the Cell after every step. e. Hint -> The Hints is provided in the Logic. Use Functions for the Logic... ''' from utils import Util cross_object = Util() play = cross_object.cross_game()
true
f2784c8cc19167c649f41b9f077b127c8eb04cbe
svshriyansh/python-starter
/ex2fiborecur.py
244
4.15625
4
def fib(n): if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) + fib(n-2) m = int(input("Enter the number to find its fibonacci: ")) for Num in range(1, m+1): print(fib(Num),end=' ')
true
a2380c2f8ea772778259ae69c8851a5ebffffb8e
itodotimothy6/CTCI
/Arrays-&-Strings/1.4/solution.py
1,566
4.25
4
# Given a string, write a function to check if it is a permutation of a # palindrome. A palindrom is a word or phraze that is the same forwards and # backwards. A permutation is a rearrangement of letters. A palindrome does not # need to be linited to just dictionary words. # Note: a maximum of one character should have an odd count for a string # permutation to be a palindrome # O(n) time : O(1) space def palindrome_permutation(s): table = {} for char in s: curr = char.lower() if ord('a') <= ord(curr) and ord(curr) <= ord('z'): table[curr] = table.get(curr, 0) + 1 odd_count = 0 for char in table: if table[char] % 2 != 0: odd_count += 1 if odd_count > 1: return False else: return True # O(n) time O(1) space def count_set_bits(n): total = 0 while n: total += n & 1 n = n >> 1 return total def palindrome_permutation_using_bitmask(s): mask = 0 for char in s: if ord(char.lower()) < ord('a') or ord(char.lower()) > ord('z'): continue char_ascii = ord(char.lower()) - ord('a') if mask & (1 << char_ascii): mask = mask & ~(1 << char_ascii) else: mask = mask | (1 << char_ascii) if count_set_bits(mask) > 1: return False return True def main(): s = "Tact Coa" assert palindrome_permutation(s) == True assert palindrome_permutation_using_bitmask(s) == True print("Passed all test cases!") if __name__ == '__main__': main()
true
f2ce02fe4a649be8b2646c34427984151f68b8be
23devanshi/pandas-practice
/Automobile Dataset/Exercises.py
2,191
4.34375
4
# Exercises taken from : https://pynative.com/python-pandas-exercise/ import pandas as pd import numpy as np #pd.display df = pd.read_csv('D:/Python tutorial/Pandas Exercises/1 Automobile Dataset/Automobile_data.csv') df.shape #: From given data set print first and last five rows print(df.head()) print(df.tail()) #Question 2: Clean data and update the CSV file #Replace all column values which contain ‘?’ and n.a with NaN. df.replace(('?','n.a'), np.nan, inplace = True) print(df) #Question 3: Find the most expensive car company name #Print most expensive car’s company name and price. print(df.sort_values('price', ascending=False).loc[0, 'company']) #Question 4: Print All Toyota Cars details print(df[df.company == 'toyota'].describe()) #Question 5: Count total cars per company df.company.value_counts() #Question 6: Find each company’s Higesht price car print(df[df.groupby('company').price.transform('max') == df.price]) #Question 7: Find the average mileage of each car making company df.groupby('company')['average-mileage'].mean() #Question 8: Sort all cars by Price column print(df.sort_values('price', ascending=False)) #Question 9: Concatenate two data frames using the following conditions GermanCars = {'Company': ['Ford', 'Mercedes', 'BMV', 'Audi'], 'Price': [23845, 171995, 135925 , 71400]} japaneseCars = {'Company': ['Toyota', 'Honda', 'Nissan', 'Mitsubishi '], 'Price': [29995, 23600, 61500 , 58900]} cars = pd.concat([pd.DataFrame(GermanCars), pd.DataFrame(japaneseCars)], axis = 0) cars.Company = cars.Company.str.strip() print(cars) #Question 10: Merge two data frames using the following condition #Create two data frames using the following two Dicts, Merge two data frames, and append the second data frame as a new column to the first data frame. Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]} car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower': [141, 80, 182 , 160]} meta = pd.DataFrame(Car_Price).merge(pd.DataFrame(car_Horsepower), left_on = 'Company', right_on = 'Company', how = 'inner') print(meta)
true
554e1ac6391e6f8582fcf1e48f3d724e4d992c42
Romeo2393/First-Code
/Comparison Operator.py
220
4.21875
4
temperature = 30 temperature = int(input("What's the temperature outside? ")) if temperature > 30: print("It's a hot day") elif temperature < 10: print("Its a cold day") else: print("Enjoy your day")
true
84e23d7bb5df3549b754b9785c6c4a906f504a97
zacniewski/Decorators_intro
/05_decorators_demystified.py
1,460
4.1875
4
"""The previous example, using the decorator syntax: @my_shiny_new_decorator def another_stand_alone_function(): print "Leave me alone" another_stand_alone_function() #outputs: #Before the function runs #Leave me alone #After the function runs Yes, that's all, it's that simple. @decorator is just a shortcut to: another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function) """ """Decorators are just a pythonic variant of the decorator design pattern. There are several classic design patterns embedded in Python to ease development, like iterators. Of course, you can cumulate decorators:""" def bread(func): def wrapper(): print "</''''''\>" func() print "<\______/>" return wrapper def ingredients(func): def wrapper(): print "#tomatoes#" func() print "~salad~" return wrapper def sandwich(food="--ham--"): print food sandwich() #outputs: --ham-- sandwich = bread(ingredients(sandwich)) sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/> #Using the Python decorator syntax: @bread @ingredients def sandwich(food="--ham--"): print food sandwich() #outputs: #</''''''\> # #tomatoes# # --ham-- # ~salad~ #<\______/> #The order you set the decorators MATTERS: @ingredients @bread def strange_sandwich(food="--ham--"): print food strange_sandwich() #outputs: ##tomatoes# #</''''''\> # --ham-- #<\______/> # ~salad~
true
f170a6023f6c27d8c4e1b77ff865275fa33dd551
david-ryan-alviola/winter-break-practice
/hackerRankPython.py
1,977
4.40625
4
# 26-DEC-2020 # Print Hello, World! to stdout. print("Hello, World!") # Given an integer, , perform the following conditional actions: # If is odd, print Weird # If is even and in the inclusive range of 2 to 5, print Not Weird # If is even and in the inclusive range of 6 to 20, print Weird # If is even and greater than 20, print Not Weird n = input() if (n % 2 == 0): if (n >= 2 and n <= 5): print("Not Weird") elif (n >=6 and n <= 20): print("Weird") else: print("Not Weird") else: print("Weird") # The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where: # The first line contains the sum of the two numbers. # The second line contains the difference of the two numbers (first - second). # The third line contains the product of the two numbers. print(a + b) print(a - b) print(a * b) # The provided code stub reads two integers, a and b, from STDIN. # Add logic to print two lines. The first line should contain the result of integer division, a//b . The second line should contain the result of float division, a/b . # No rounding or formatting is necessary. print(a//b) print(a/b) # 30-DEC-2020 # The provided code stub reads an integer, n, from STDIN. For all non-negative integers i < n, print i^2. if n >= 0: for i in range(n): print(i * i) # Given a year, determine whether it is a leap year. If it is a leap year, return the Boolean True, otherwise return False. # Note that the code stub provided reads from STDIN and passes arguments to the is_leap function. It is only necessary to complete the is_leap function. def is_leap(year): leap = False if(year % 4 == 0 and year % 100 > 0): leap = True else: if (year % 100 == 0 and year % 400 == 0): leap = True return leap # Print the list of integers from 1 through n as a string, without spaces. for i in range(n): print(i + 1, end="")
true
701c8ac9df8e1544c22b63d94e2894fbf20ab04c
PaulGG-Code/Security_Python
/Simple_File_Character_Calculator.py
242
4.1875
4
#open file in read mode file = open("D:\data.txt", "r") #read the content of file data = file.read() #get the length of the data number_of_characters = len(data) print('Number of characters in text file :', number_of_characters)
true