blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7b2d2d37f5acf56da96b52e0665532969285978c
gnoubir/Network-Security-Tutorials
/Basic Cryptanalysis/basic-analyze-file.py
1,983
4.15625
4
#!/usr/bin/python # # computer the frequency of lowercase letters __author__ = "Guevara Noubir" import collections import argparse import string import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser(description='Analyze a file.') # ./basic-analyze-file.py file # program has one parameter the name of the file to analyze # parser.add_argument("file", type=str, help="counts characters frequency file") # parse arguments args = parser.parse_args() # known statistics of alphabet letters in English text used for comparison english_alphabet_stats = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.0236, 0.0015, 0.01974, 0.00074] letters = collections.Counter('') # opens file and processes line by line using collections module with open(args.file,'r') as f: for line in f: for word in line.split(): letters.update(word.lower()) #print letters count = 0 stats = [] # counts the total number of lowercase letters for l in string.ascii_lowercase: count += letters[l] # computes and prints frequency/probability of each lowercase letter for l in string.ascii_lowercase: stats += [float(letters[l])/count] print l, ": ", float(letters[l])/count print "\n ----------------- \n" #print letters.keys() #print letters.values() pos = np.arange(26) width = 1.0 # gives histogram aspect to the bar diagram ax = plt.axes() ax.set_xticks(pos ) ax.set_xticklabels(string.ascii_lowercase) # rects1 is english_bars = plt.bar(range(len(list(string.ascii_lowercase))), english_alphabet_stats, -width/3, color='r', alpha=0.5, align='edge') this_file_bars = plt.bar(range(len(stats)), stats, width/3, color='g', alpha=0.5, align='edge') ax.legend((english_bars[0], this_file_bars[0]), ('English Stats', args.file)) # plt.show()
true
ae9f2189f73437e8ab24932c8f44108d7cbb467d
UMBC-CMSC-Hamilton/cmsc201-spring2021
/classes_start.py
1,501
4.21875
4
""" A class is a new type ints, floats, strings, bool, lists, dictionaries class <-- not really a type a type maker. What kind of things can types have? data inside of them (member variables, instance variables) functions inside of them. """ class Lion: """ Constructor for the lion class. """ # 2x underscore init 2x underscore def __init__(self, name): self.lion_name = name self.position = '' def eat(self, food): print(self.lion_name, 'eats', food) def roar(self): print(self.lion_name, 'roars... ROAR!!!!') def run(self, destination): """ secret of self is that it knows that the first argument is actually the calling class. :param destination: :return: """ print(self.lion_name, 'has run to ', destination) self.position = destination def sleep(self, time): print(self.lion_name, 'has slept for {} hours'.format(time)) """ Each class has its own variables, it's own data. They all kind of share the functions though. We are making built-in functions for a variable type. """ leo_the_lion = Lion('Leo') hercules = Lion('Hercules') simba = Lion('Simba') simba.sleep(5) # Lion.sleep(simba, 5) # that's the secret. # self is actually "simba" hercules.eat('villager') # hercules.eat('villager') # Lion.eat(hercules, 'villager') leo_the_lion.roar() # Lion.roar(leo_the_lion)
true
0fac1e302275fd8c77181ceca7f85afdf0056bc4
mackrellr/PAsmart
/rock_paper_scissors.py
2,208
4.1875
4
import random player_choice = 0 npc_choice = 0 game_on = True # Indicate choices for win def choices(p1, p2): print() if p1 == 1: print('Player choose Rock.') if p1 == 2: print('Player choose Paper.') if p1 == 3: print('Player choose Scissors.') if p2 == 1: print('Opponent choose Rock.') if p2 == 2: print('Opponent choose Paper.') if p2 == 3: print('Opponent choose Scissors.') def winner(p1, p2): # Rock (1) beats scissors (3) if p1 == 1 and p2 == 3: print('You win. Rock crushes scissors.') if p2 == 1 and p1 == 3: print('You loose. Rock crushes scissors.') # Scissors (3) beats paper (2) if p1 == 3 and p2 == 2: print('You win. Scissors cuts paper. ') if p2 == 3 and p1 == 2: print('You loose. Scissors cuts paper.') # Paper (2) beats rock (1) if p1 == 2 and p2 == 1: print('You win. Paper covers rock.') if p2 == 2 and p1 == 1: print('You loose. Paper covers rock.') # Indicate a tie if p1 == p2: choices = ['rock', 'paper', 'scissors'] print('Tie. You both choose ' + choices[p1-1] + '.') #Loop the game until a specified number of wins while game_on: # Player input choice_bank = input('Rock [1], paper [2], scissors [3], shoot! ') if choice_bank != '1' and choice_bank != '2' and choice_bank != '3': print('Incorrect entry, please choose: ') else: player_choice = int(choice_bank) # Random computer input npc_choice = random.randrange(1, 4) choices(player_choice, npc_choice) winner(player_choice, npc_choice) # Offer to exit the game game_quit = True while game_quit: exit_game = input('Would you like to play again y/n? ') if exit_game == 'n': print('Thank you for playing!') game_quit = False game_on = False elif exit_game != 'y' and choice_bank != 'n': print('Incorrect entry.') elif exit_game == 'y': game_quit = False game_on = True
true
bde72147f0609811ecca5e12bd8a2b56f1c8d06f
kaliadevansh/data-structures-and-algorithms
/data_structures_and_algorithms/challenges/array_reverse/array_reverse.py
2,916
4.53125
5
""" Reverses input array/list in the order of insertion. """ def reverseArray(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by iterating half of the list and without using additional space. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list list_length = len(input_list) counter = 0 while counter < floor(list_length / 2): input_list[counter] += input_list[list_length - counter - 1] input_list[list_length - counter - 1] = input_list[counter] - input_list[list_length - counter - 1] input_list[counter] = input_list[counter] - input_list[list_length - counter - 1] counter += 1 return input_list def reverse_array_stack(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by using additional space of a stack and then popping elements from the stack. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list stack = [] for current_value in input_list: stack.append(current_value) reversed_list = [] list_counter = len(stack) while list_counter > 0: reversed_list.append(stack.pop()) list_counter -= 1 return reversed_list def reverse_array_iterate(input_list): """ Reverses the input array/list in the order of insertion. This method reverses the list by iterating the input list in reverse. :param input_list: The list to be reversed. Returns None for None input. :return: The reversed list """ if input_list is None or skip_reverse(input_list) is not None: return input_list reversed_list = [] for current_value in input_list[::-1]: reversed_list.append(current_value) return reversed_list def skip_reverse(input_list): """ Checks if initialized input list has 0 or 1 elements, hence reverse operation can be skipped. :param input_list: The list to be checked for skipping reverse. :return: Input list if list has 0 or 1 elements; none otherwise. """ list_length = len(input_list) if list_length == 0 or list_length == 1: return input_list def floor(input_number): """ This function is local implementation of floor function just for the scope of this problem. This method was created to satisfy the ask of not using in-built language functions. :param input_number: Number whose floor value is to be calculated.. :return: Floor value of input number. """ decimal_digits = input_number % 1 return input_number - decimal_digits
true
a41a499a78fc0dc44174812b5b3b7db1e12239b3
FranVeiga/games
/Sudoku_dep/createSudokuBoard.py
1,654
4.125
4
''' This creates an array of numbers for the main script to interpret as a sudoku board. It takes input of an 81 character long string with each character being a number and converts those numbers into a two dimensional array. It has a board_list parameter which is a .txt file containing the sudoku boards as strings. ''' import random def main(board_file): try: with open(board_file, 'r') as file: boards = file.readlines() file.close() newboards = [] for i in boards: if i.endswith('\n'): i = i.replace('\n', '') newboards.append(i) boards = newboards randomBoard = boards[random.randint(0, len(boards) - 1)] randomBoardArray = [[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]] for i in range(len(randomBoard)): x = i % 9 y = i // 9 randomBoardArray[y][x] = int(randomBoard[i]) return randomBoardArray except FileNotFoundError: print(f'Error loading board {board_file}') if __name__ == '__main__': print(main(input()))
true
828066159ed3f735e0ea6b16ce8c81b23e62ff1d
DipeshDhandha07/Data-Structure
/infix to postfix2.py
1,310
4.1875
4
# The main function that converts given infix expression # to postfix expression def infixToPostfix(self, exp): # Iterate over the expression for conversion for i in exp: # If the character is an operand, # add it to output if self.isOperand(i): self.output.append(i) # If the character is an '(', push it to stack elif i == '(': self.push(i) # If the scanned character is an ')', pop and # output from the stack until and '(' is found elif i == ')': while( (not self.isEmpty()) and self.peek() != '('): a = self.pop() self.output.append(a) if (not self.isEmpty() and self.peek() != '('): return -1 else: self.pop() # An operator is encountered else: while(not self.isEmpty() and self.notGreater(i)): self.output.append(self.pop()) self.push(i) # pop all the operator from the stack while not self.isEmpty(): self.output.append(self.pop()) print "".join(self.output) # Driver program to test above function exp = "a+b*(c^d-e)^(f+g*h)-i" obj = Conversion(len(exp)) obj.infixToPostfix(exp)
true
ca1ad7d1ad24c77156a97b54683f63dc205c2730
kaushikamaravadi/Python_Practice
/Transcend/facade.py
888
4.125
4
"""Facade Design Pattern""" class Vehicle(object): def __init__(self, type, make, model, color, year, miles): self.type = type self.make = make self.model = model self.color = color self.year = year self.miles = miles def print(self): print("vehicle type is",str(self.type)) print("vehicle make is", str(self.make)) print("vehicle model is", str(self.model)) print("vehicle color is", str(self.color)) print("vehicle year is", str(self.year)) print("vehicle miles is", str(self.miles)) class Car(Vehicle): def prints(self): Vehicle.print(self) return Vehicle.print(self) def drive(self, speed): peek = "the car is at %d" %speed return peek car = Car(30, 'SUV', 'BMW', 'X5', 'silver', 2003) print(car.print()) print(car.drive(35))
true
ff5ca971a1feac7ea7c26d34f8e3b63e4a4c2ea5
kaushikamaravadi/Python_Practice
/DataStructures/linked_list.py
2,244
4.1875
4
"""Linked List""" class Node(object): def __init__(self, data=None, next=None): self.data = data self.next = next def get_data(self): return self.data def get_next(self): return self.next def set_next(self, new_next): self.next = new_next class LinkedList(object): def __init__(self, head=None): self.head = head def add(self, data): new_node = Node(data) new_node.set_next(self.head) self.head = new_node def size(self): current = self.head count = 0 while current: count += 1 current = current.get_next() return count def search(self, data): current = self.head while current: if current.get_data() == data: return current else: current = current.get_next() return None def remove(self, data): current = self.head prev = None while current: if current.get_data() == data: if current == self.head: self.head = current.get_next() else: prev.set_next(current.get_next()) return current prev = current current = current.get_next() return None def print(self): final = [] current = self.head while current: final.append(str(current.get_data())) current = current.get_next() print('->'.join(final)) linked_list = LinkedList() while True: default = """ 1. Add 2. Size 3. Search 4. Remove 5. Print the Linked list """ print(default) option = int(input("Select any option")) if option == 1: element = input("\nEnter the element you want to add") linked_list.add(element) if option == 2: print(linked_list.size()) if option == 3: item = input("\nEnter the element you want to search") print(linked_list.search(item)) if option == 4: data1 = input("\nEnter the element you want to search") linked_list.remove(data1) if option == 5: linked_list.print()
true
a80c87614a06de6b2c9b0293520196b93418e5ea
Rokesshwar/Coursera_IIPP
/miniproject/week 2_miniproject_3.py
2,291
4.1875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random # initialize global variables used in your code range = 100 secret_num = 0 guesses_left = 0 # helper function to start and restart the game def new_game(): global range global secret_num global guesses_left secret_num = random.randrange(0, range) if range == 100 : guesses_left = 7 elif range == 1000 : guesses_left = 10 print "New game. The range is from 0 to", range, ". Good luck!" print "Number of remaining guesses is ", guesses_left, "\n" pass # define event handlers for control panel def range100(): global range range = 100 # button that changes range to range [0,100) and restarts new_game() pass def range1000(): global range range = 1000 # button that changes range to range [0,1000) and restarts new_game() pass def input_guess(guess): # main game logic goes here global guesses_left global secret_num won = False print "You guessed: ",guess guesses_left = guesses_left - 1 print "Number of remaining guesses is ", guesses_left if int(guess) == secret_num: won = True elif int(guess) > secret_num: result = "It's High Need lower!" else: result = "It's low Need higher!" if won: print "Winner Winner Chicken Dinner" new_game() return elif guesses_left == 0: print " Game Ended,Sorry You Lose. You didn't guess the number in time!" new_game() return else: print result pass # create frame frame = simplegui.create_frame("Game: Guess the number!", 250, 250) frame.set_canvas_background('Blue') # register event handlers for control elements frame.add_button("Range is [0, 100)", range100, 100) frame.add_button("Range is [0, 1000)", range1000, 100) frame.add_input("Enter your guess", input_guess, 100) # call new_game and start frame new_game() frame.start()
true
fd00acdfa7e5f6187dcef82ca53e2a34595bb3e9
erinmiller926/adventurelab
/adventure_lab.py
2,337
4.375
4
# Adventure Game Erin_Miller import random print("Last night, you went to sleep in your own home.") print("Now, you wake up in a locked room.") print("Could there be a key hidden somewhere?") print("In the room, you can see:") # The menu Function: def menu(list, question): for item in list: print(1 + list.index(item), item) return int(input(question)) items = ["backpack", "painting", "vase", "bowl", "door"] # This is the list of items in the room: key_location = random.randint(1, 4) # the key is not found. key_found = "No" loop = 1 # Display the menu until the key is found: while loop == 1: choice = menu(items, "What do you want to inspect?") print("") if choice < 5: if choice == key_location: print("You found a small key in the", items[choice-1]) key_found = "Yes" else: print("You found nothing in the", items[choice-1]) elif choice == 5: if key_found == "Yes": loop = 0 print(" You insert the key in the keyhole and turn it.") else: print("The door is locked. You need to find the key.") else: print("Choose a number less than 6.") print("You open the door to a long corridor.") print("You creep down the long corridor and tiptoe down the stairs.") print("The stairs lead to a living room.") print("You see the following:") def menu2(list, question): for item in list: print(1 + list.index(item), item) return int(input(question)) items = ["fireplace", "window", "bookcase", "closet", "door"] key_location = random.randint(1, 4) key_found = "No" loop = 1 while loop == 1: choice = menu(items, "What do you want to inspect?") if choice < 5: if choice == key_location: print("You found a small key in the", items[choice-1]) key_found = "Yes" else: print("You found nothing in the", items[choice-1]) elif choice == 5: if key_found == "Yes": loop = 0 print(" You insert the key in the keyhole and turn it.") else: print("The door is locked. You need to find the key.") else: print("Choose a number less than 6.") print("You exit the house before anyone came home. You breathe a sigh of relief.")
true
bc4cf020e12cef8167f0ce3cad98399b5d7d9f8f
michealwave/trainstation
/lesson.py
1,763
4.4375
4
# Calculation, printing, variables # Printing to the screen # The built in function print(), prints to the screen # it will print both Strings and numbers print("Printing to the screen") print("Bruh") # in quotes are called strings print('bruhg') print(6) #a number print("6") print(6 + 6) #prints 12 print("6" + "6") #string concationation; mashes 2 strings together #print("6" + 6)# error # Performing calculations # addition + # subtraction - # multiplication * # division / # exponents ** # modulo % print(4 - 2) #subtraction print(4 * 2) #multiplication print(4 / 3) # division print(4 ** 3) #exponent print("Modulo test") print(5 % 3) print(10 % 2) print(16 % 3) # Module gives remainders. # python operators follow the same order of operations as math print(4 - 2 * 2) # will give zero print((4 - 2) * 2) #will give 4 #Variables #variables are used to hold data # variables are declared and set to a value (initializing) badluck = 13 #delcared a variables called badluck and initialized it to 13 # i can print the variable using its name print("badluck = " + str(badluck)) #cast it to a string # lets do another one goodluck = "4" #string variables print("goodluck = " + goodluck) #don't have to cast because it is already a string badluck + 5 #pointless print(badluck) badluck = badluck + 5 #badluck is now 18 print(badluck) #you can also save input into variables # using input(), a prompt goes into the () name = input("What is your name?") print("Hello " + name) print(name * 10) name = name + "\n" #escape character (newline) print(name * 10) # lets try some math base = input("Enter the base number: ") exponent = input("Enter the exponent: ") print(int(base) ** int(exponent))
true
840ac0b807f67faca806e65f63fb4512c8ec1f40
niskrev/OOP
/old/NotQuiteABase.py
636
4.28125
4
# from Ch 23 of Data science from scratch class Table: """ mimics table in SQL columns: a list """ def __init__(self, columns): self.columns = columns self.rows = [] def __repr__(self): """ pretty representation of the table, columns then rows :return: """ return str(self.columns) + "\n" + "\n".join(map(str, self.rows)) def insert(self, row_values): if len(row_values) != len(self.columns): raise TypeError("wrong number of elements") row_dict = dict(zip(self.columns, row_values)) self.rows.append(row_dict)
true
36872204f3439dbafd3370cc89e3a26fb245930a
pranavnatarajan/CSE-163-Final-Project
/MatchTree.py
2,753
4.15625
4
""" Alex Eidt- CSE 163 AC Pranav Natarajan - CSE 163 AB CSE 163 A Final Project This class represents a Data Structure used to build up the bracket of the UEFA Champions League to create the bracket graphics. """ import random class MatchTree: """ Data Structure used to represent a full bracket of the UEFA Champions League with every node representing a game. """ def __init__(self, data=None, left=None, right=None): """ Initializes the MatchTree class with a left and right MatchTree Node, and a 'data' field which stores the String representing the teams facing off in that Match. """ self.left = left self.right = right self.data = data def get_winner(self, data): """ Determines the winner of a Match in the MatchTree node based on the coefficient data in 'data'. Parameter data - Pandas DataFrame representing coefficients for every team in the MatchTree bracket. Returns The winning team as a String based on whose coefficient is greater. If both coefficients are exactly the same, this is equivalent to the match going to penalty kicks to be decided. Penalty kicks have little to do with a teams strength (and thus coefficient). Penalty kicks are about who can make the big shots in the big moments and comes down to mostly luck. This behavior is simulated by randomly choosing one team if both coefficients are exactly the same. """ team1, team2 = self.data team1_coefficient = data.loc[team1].squeeze() team2_coefficient = data.loc[team2].squeeze() if team1_coefficient > team2_coefficient: return team1 elif team1_coefficient < team2_coefficient: return team2 return random.choice(self.data) def is_leaf_node(self): """ Returns True if the current MatchTree node is a leaf node (no children). Otherwise returns False. """ return self.left == None and self.right == None def __str__(self): """ Returns A String representation of the data in the MatchTree node. If the data is a tuple, this represents a match and a String of the format "Team A vs. Team B" is returned. If the data is a String, this represents the winner of the bracket and so this value is simply returned. """ if type(self.data) != str: return f'{self.data[0]}\nvs.\n{self.data[1]}' return str(self.data)
true
0e180c7692a5807f278056be53142739700d5fce
anitakumarijena/Python_advantages
/deepak.py
1,275
4.1875
4
graph ={ 'a':['c'], 'b':['d'], 'c':['e'], 'd':['a', 'd'], 'e':['b', 'c'] } # function to find the shortest path def find_shortest_path(graph, start, end, path =[]): path = path + [start] if start == end: return path shortest = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest # Driver function call to print # the shortest path print(find_shortest_path(graph, 'd', 'c')) # Python program to generate the first # path of the graph from the nodes provided graph = { 'a': ['c'], 'b': ['d'], 'c': ['e'], 'd': ['a', 'd'], 'e': ['b', 'c'] } # function to find path def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None # Driver function call to print the path print(find_path(graph, 'd', 'c'))
true
4c786e38d93357f3a768506f39993248e8414b64
Isoxazole/Python_Class
/HW2/hm2_william_morris_ex_1.py
447
4.1875
4
"""Homework2, Exercise 1 William Morris 1/29/2019 This program prints the collatz sequence of the number inputted by the user.""" def collatz(number): if number == 1: print(number) return 1 elif number % 2 == 0: print(number) return collatz(int(number/2)) else: print(number) return collatz(int((number*3) + 1)) print("Please enter an integer:") userInput = int(input()) collatz(userInput)
true
5e4d121ef247320d9f3a90162561d10694c2ab49
Isoxazole/Python_Class
/HW4/hm4_william_morris_ex_1.py
1,461
4.21875
4
""" Homework 4, Exercise 1 William Morris 2/22/19 This program has 3 classes: Rectangle, Circle, and Square. Each class has the functions to get the Area, Diagonal, and perimeter of their respective shape. At the end of this program, the perimeter of a circle with radius the half of the diagonal of a rectangle with length 20 and width 10 is calculated """ import math class Rectangle: def __init__(self, length, width): self.length = length self.width = width def getArea(self): return self.width * self.length def getDiagonal(self): return math.sqrt(self.length ** 2 + self.width **2) def getPerimeter(self): return 2 * self.length + 2 * self.width class Circle: def __init__(self, radius): self.radius = radius def getArea(self): return math.pi * self.radius ** 2 def getDiagonal(self): return self.radius * 2 def getPerimeter(self): return self.radius * 2 * math.pi class Square: def __index__(self, side_length): self.side_length = side_length def getArea(self): return self.side_length **2 def getDiagonal(self): return math.sqrt(self.length ** 2 + self.width ** 2) def getPerimeter(self): return 4 * self.side_length length = 20 width = 10 rectangle = Rectangle(length, width) radius = rectangle.getDiagonal() / 2 circle = Circle(radius) perimeter = circle.getPerimeter() print(perimeter)
true
d57991f5faa7b5b8d3ed8ade332d57c55242bb98
Ottermad/PythonBasics
/times_tables.py
564
4.125
4
# times_tables.py # Function for times tables def times_tables(how_far, num): n = 1 while n <= how_far: print(n, " x ", num, " = ", n*num) n = n + 1 # Get user's name name = input("Welcome to Times Tables. What is your name?\n") print("Hello " + name) # Get timestable and how far do you want to go times_table = int(input("Which times table to you want to know?\n")) how_far = int(input("How far do you want to go?\n")) times_tables(how_far, times_table) print("Goodbye " + name + ". Thank you for playing. \nPress RETURN to exit.")
true
7b6739be5389da8351294fa3b430002989b83b84
avin82/Programming_Data_Structures_and_Algorithms_using_Python
/basics_functions.py
2,225
4.59375
5
def power(x, n): # Function name, arguments/parameters ans = 1 for i in range(0, n): ans = ans * x return ans # Return statement exits and returns a value. # Passing values to functions - When we call a function we have to pass values for the arguments and this is done exactly the same way as assigning a value to a name print(power(3, 5)) # Like an implicit assignment x = 3 and n = 5 # Same rules apply for mutable and immutable values # Immutable values will not be affected at calling point # Mutable values will be affected def update(list, i, v): if i >= 0 and i < len(list): list[i] = v return True else: v = v + 1 return False ns = [3, 11, 12] z = 8 print(update(ns, 2, z)) print(ns) # If we pass through parameter a value which is mutable it can get updated in the function and this is sometimes called a side effect. print(update(ns, 4, z)) print(z) # If we pass through parameter a value which is immutable then the value doesn't change no matter what we do inside the function # Return value may be ignored. If there is no return, function ends when last statement is reached. For example, a function which displays an error or warning message. Such a function just has to display a message and not compute or return anything. # Scope of names # Names within a function have local scope i.e. names within a function are disjoint from names outside a function. def stupid(x): n = 17 return x n = 7 print(stupid(28)) print(n) # A function must be defined before it is invoked def f(x): return g(x + 1) def g(y): return y + 3 print(f(77)) # If we define funtion g after invoking function f we will get an error saying NameError: name 'g' is not defined # A function can call itself - recursion def factorial(n): if n <= 0: return 1 else: return n * factorial(n - 1) print(factorial(5)) # Functions are a good way to organise code in logical chunks # Passing arguments to a function is like assigning values to names # Only mutable values can be updated # Names in functions have local scope # Functions must be defined before use # Recursion - a function can call itself
true
ea834767462615e5a124b4e723e4507dcf393cec
MillaKelhu/tiralabra
/Main/Start/board.py
2,127
4.28125
4
from parameters import delay, error_message import time # User interface for asking for the board size from the user def get_board(): while True: print("Choose the size of the board that you want to play with.") print("A: 3x3 (takes three in a row to win)") print("B: 5x5 (takes four in a row to win)") print("C: 7x7 (takes four in a row to win)") print("D: 10x10 (takes five in a row to win)") print("E: 15x15 (takes five in a row to win)") print("F: 20x20 (takes five in a row to win)") print("----------------") board_letter = input("Your choice: ") print("----------------") time.sleep(delay) try: board_letter = board_letter.capitalize() except: continue board_size = 0 if board_letter == "A": board_size = 3 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "B": board_size = 5 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "C": board_size = 7 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "D": board_size = 10 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "E": board_size = 15 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break elif board_letter == "F": board_size = 20 print(str(board_size) + "x" + str(board_size), "board - good choice!") print("----------------") break else: print(error_message) print("----------------") return board_size
true
e16aa01c242c5fc654d01f889c1a3cde6551d618
elvargas/calculateAverage
/calculateAverage.py
2,865
4.4375
4
# File: calculateAverage.py # Assignment 5.1 # Eric Vargas # DESC: This program allows the user to choose from four operations. When an operation is chosen, they're allowed to choose # two numbers which will be used to calculate the result for the chosen operation. Option 5. will ask the user how # many numbers they wish to input. This function will use the number of times to run the program within a loop in # order to calculate the total and average. # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbers def multiply(num1, num2): return num1 * num2 # Function to divide two numbers def divide(num1, num2): return num1 / num2 # Function to find average of numbers def average(): return sum / count # Function allows the user to run the program until they enter a value which ends the loop. def cont(): reply = input("Continue? Y/N ") if reply == "n": return True # Main Section while True: # Prompts user to select an operation print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") print("5. Average") # Take input from the user select = input("Select an operation: ") # Addition if select == '1': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "+", number_2, "=", add(number_1, number_2)) # Subtraction elif select == '2': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "-", number_2, "=", subtract(number_1, number_2)) # Multiply elif select == '3': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "*", number_2, "=", multiply(number_1, number_2)) # Divide elif select == '4': number_1 = int(input("Enter first number: ")) number_2 = int(input("Enter second number: ")) print(number_1, "/", number_2, "=", divide(number_1, number_2)) # Average elif select == "5": sum = 0 count = int(input("How many numbers would you like to enter? ")) current_count = 0 while current_count < count: print("Number", current_count) number = float(input("Enter a number: ")) sum = sum + number current_count += 1 # Displays average after last number is entered print("The average was:", sum / count) else: print("Invalid Input") if cont(): break
true
c0e32988331e72474e7b50ea59ac3891627ebd6b
georgeescobra/algorithmPractice
/quickSort.py
1,408
4.25
4
# this version of quicksort will use the last element of the array as a pivot import random import copy def quickSort(array, low, high): if(low < high): partitionIndex = partition(array, low, high) quickSort(array, low, partitionIndex - 1) quickSort(array, partitionIndex + 1, high) # don't necessarily have to return, but doing so for the sake of the unit_test return array def partition(array, low, high): index = low - 1 pivot = array[high] for j in range(low, high): if array[j] <= pivot: index += 1 # this swaps the values of array[i] and array[j] array[index], array[j] = array[j], array[index] array[index + 1], array[high] = array[high], array[index + 1] return index + 1 def main(): unordered = [random.randint(0, 100) for i in range(50)] orig = copy.deepcopy(unordered) quickSort(unordered, 0, len(unordered) - 1) print('Sorting List of 50 Elements in Ascending Order') print('{0:5} ==> {1:5}'.format('Original','Sorted')) for orig, sorted in zip(orig, unordered): print('{0:5} ==> {1:5d}'.format(orig, sorted)) # this is the proper way of having a 'main' function in python3 # this is important for the purpose of code reusability and if this module is imported # this means that gives the ability to conditionally execute the main function is important when writing code that could be possibly used by others if __name__ == "__main__": main()
true
e18f0f34927a7aa2398152077a7f88a811466f11
klandon94/python3_fundamentals
/lambda.py
820
4.1875
4
def square(num): return num*num square(3) #Lambda is used to specify an anonymous (nameless) function, useful where function only needs to be used once and convenient as arguments to functions that require functions as parameters #Lambda can be an element in a list: y = ['test_string', 99, lambda x: x ** 2] print(y[2]) print(y[2](5)) #Lambda can be passed to another function as a callback: def invoker(callback): print(callback(2)) invoker(lambda x: 2*x) invoker(lambda y: 5+y) #Lambda can be stored in a variable: add10 = lambda x: x+10 print(add10(2)) #Returned by another function def incrementor(num): return(lambda x: num + x) incrementor(3) def map(list, function): for i in range(len(list)): list[i]=function(list[i]) return list print (map([1,2,3,4], (lambda num:num*num)))
true
1769e7ee9a9dad0296ef5fd1e189ac4f8ac1e6c6
ayush94/Python-Guide-for-Beginners
/FactorialAlgorithms/factorial.py
1,290
4.1875
4
from functools import reduce ''' Recursively multiply Integer with its previous integer (one less than current number) until the number reaches 0, in which case 1 is returned ''' def recursive_factorial(n): # Base Case: return 1 when n reaches 0 if n == 0 : return 1 # recursive call to function with the integer one less than current integer else: return n * recursive_factorial(n-1) ''' Iterative factorial using lambda and reduce function, from range 1 to number + 1 we multiply all the numbers through reduce. ''' def iterative_factorial(n): factorial = reduce(lambda x,y:x*y,range(1,n+1)) return factorial # Taking number from standard input and casting it into Integer n = int(input("Enter the number: ")) # Taking in Calculation stratergy(recursive/iterative) and removing trailing spaces and changing to lowercase stratergy = input("Enter algorithm type (r for Recursive/i for iterative): ").strip().lower() # Just a check to see if right option was entered if(stratergy != "r" and stratergy !="i"): print("wrong algorithm type opted...exiting") quit() # Factorial by opted stratergy if(stratergy == "r"): factorial = recursive_factorial(n) elif(stratergy == "i"): factorial = iterative_factorial(n) print("Factorial of entered number is: ",str(factorial))
true
e224a34ec37f50014e7dde73993710b560d54606
FilipM13/design_patterns101
/pattern_bridge.py
2,431
4.28125
4
""" Bridge. Structure simplifying code by deviding one object type into 2 hierarchies. It helps solving cartesian product problem. Example: In this case if I want to create one class for every combination of plane and ownership i'd need 16 classes (4 planes x 4 ownerships) Thanks to bridge pattern I only have 8 classes. It works even better if there where more types of planes and ownerships. here: Main hierarchy is Plane (with subclasses), it uses Ownership hierarchy to expand it's possibilities. PS. I don't care that you can't have private bomber. """ from abc import ABC, abstractmethod class Ownership(ABC): @abstractmethod def __init__(self, owner_name): self.owner_name = owner_name self.velocity_multiplier = int() def get_owner_name(self): return self.owner_name class Civil(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 3 class Private(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 7 class Military(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 10 class PublicTransport(Ownership): def __init__(self, owner_name): super().__init__(owner_name) self.velocity_multiplier = 5 class Plane(ABC): @abstractmethod def __init__(self, ownership: Ownership): self.ownership = ownership self.max_velocity = int() def fly(self): print(f'WHOOOOOOOSH! with the speed of {self.ownership.velocity_multiplier * self.max_velocity} distance units / time unit.') def get_owner_name(self): return self.ownership.get_owner_name() class Jet(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 100 class Airbus(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 50 class Bomber(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 70 class Glider(Plane): def __init__(self, ownership: Ownership): super().__init__(ownership) self.max_velocity = 30 '''#uncomment for demonstration civil_bomber = Bomber(Civil('Retired bomber pilot.')) civil_bomber.fly() print(civil_bomber.get_owner_name()) private_jet = Jet(Private('Ash Holle Rich')) private_jet.fly() print(private_jet.get_owner_name()) '''
true
78b5b3a4e8076f804716015f9ea3d8bcb419ea2f
samuelluo/practice
/bst_second_largest/bst_second_largest.py
2,041
4.125
4
""" Given the root to a binary search tree, find the second largest node in the tree. """ # ---------------------------------------- class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def bst_insert(root, val): if root is None: return Node(val) if val < root.val: root.left = bst_insert(root.left, val) elif val > root.val: root.right = bst_insert(root.right, val) return root def bst_second_largest_1(root): largest = second_largest = None queue = [root] while len(queue) != 0: node = queue.pop(0) if largest is None or node.val > largest: second_largest = largest largest = node.val elif second_largest is None or node.val > second_largest: second_largest = node.val if node.left is not None: queue.append(node.left) if node.right is not None: queue.append(node.right) return [largest, second_largest] def bst_second_largest_2(root): """ For a BST, in-order traversal will pass through the nodes in increasing order. """ bst_second_largest_2_helper(root, 0) def bst_second_largest_2_helper(root, count): if root is None: return count count = bst_second_largest_2_helper(root.right, count) count += 1 if count == 2: print("Second largest: {}".format(root.val)) count = bst_second_largest_2_helper(root.left, count) return count # ---------------------------------------- root = Node(5) root = bst_insert(root, 3) root = bst_insert(root, 2) root = bst_insert(root, 4) root = bst_insert(root, 7) root = bst_insert(root, 6) root = bst_insert(root, 8) result = bst_second_largest_1(root) print(result) bst_second_largest_2(root) print() root = Node(1) root = bst_insert(root, 2) root = bst_insert(root, 3) root = bst_insert(root, 4) root = bst_insert(root, 5) result = bst_second_largest_1(root) print(result) bst_second_largest_2(root) print()
true
620369233f7cb25553ec58246c922b11cca6bbd4
msznajder/allen_downey_think_python
/ch3_ex.py
2,743
4.6875
5
""" Exercise 1 Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display. """ def right_justify(s): print((70 - len(s)) * " " + s) right_justify("abba") """ Exercise 2 A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice: def do_twice(f): f() f() Here’s an example that uses do_twice to call a function named print_spam twice. def print_spam(): print('spam') do_twice(print_spam) Type this example into a script and test it. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument. Copy the definition of print_twice from earlier in this chapter to your script. Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four. """ def print_spam(): print("spam") def print_anything(val): print(val) def do_twice(f, val): f(val) f(val) def do_four(f, val): do_twice(f, val) do_twice(f, val) do_twice(print_anything, "ha!") do_four(print_anything, "hi!") """ Exercise 3 Write a function that draws a grid like the following: + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + | | | | | | | | | | | | + - - - - + - - - - + Hint: to print more than one value on a line, you can print a comma-separated sequence of values: print('+', '-') By default, print advances to the next line, but you can override that behavior and put a space at the end, like this: print('+', end=' ') print('-') The output of these statements is '+ -'. A print statement with no argument ends the current line and goes to the next line. """ def print_square(): print("+" + " -" * 4 + " +" + " -" * 4 + " +") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("+" + " -" * 4 + " +" + " -" * 4 + " +") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("/" + " " * 9 + "/" + " " * 9 + "/") print("+" + " -" * 4 + " +" + " -" * 4 + " +") print_square()
true
3cf8c28b06e50bf446701066958e4e04079e777d
evural/hackerrank
/cracking/chapter1/is_unique_bitwise.py
535
4.15625
4
# 1. Initialize a checker variable to 0 # 2. For each character in the text, shift left bits of 1 # 3. If bitwise AND of this value returns a number other than 0, return False # 4. Bitwise OR this value with the checker variable def is_unique(text): checker = 0 for c in text: val = ord(c) - ord("a") shifted = 1 << val if checker & shifted != 0: return False checker = checker | shifted return True if __name__ == "__main__": text = raw_input() print is_unique(text)
true
70e9075afd47443a993e4be807274629de87329d
Kevin8523/scripts
/python/python_tricks/class_v_instance_variables.py
1,110
4.15625
4
# Class vs Instance Variable Pitfalls # Two kind of data attributes in Python Objects: Class variables & instance variables # Class Variables - Affects all object instance at the same time # Instance Variables - Affects only one object instance at a time # Because class variables can be “shadowed” by instance variables of the same name, # it’s easy to (accidentally) override class variables in a way that introduces bugs class Dog: num_legs = 4 # <- Class Variable def __init__(self,name): self.name = name # <- Instance Variable jack = Dog('Jack') jill = Dog('Jill') jack.name, jill.name jack.num_legs, jill.num_legs #Error Example: This will change the Class Dog.num_legs = 6 jack.num_legs, jill.num_legs Dog.num_legs = 4 jack.num_legs = 6 jack.num_legs, jack.__class__.num_legs # Another example of good vs bad implementation # Good class CountedObject: num_instances = 0 def __init__(self): self.__class__.num_instances += 1 # Bad # WARNING: This implementation contains a bug class BuggyCountedObject: num_instances = 0 def __init__(self): self.num_instances += 1 # !!!
true
701c22b62921af1315710489d3f1935a28079b07
burgonyapure/cc1st_siw
/calc.py
494
4.28125
4
def f(x): return { '+': int(num1) + int(num2), '-': int(num1) - int(num2), '*': int(num1) * int(num2), '/': int(num1) / int(num2) }.get(x, "Enter a valid operator (+,-,*,/)") while True: num1 = input("\nEnter a number,or press a letter to exit\n") if num1.isdigit() != True: break y = input("Enter the operator\n") num2 = input("Enter the 2nd number\n") if num2.isdigit() != True: print("The 2nd NUMBER has to be a NUMBER as well") continue print("Result:", f(y))
true
0e76971f4c57f194f05cbccf3803771fa24c9e02
hack-e-d/codekata
/sign.py
216
4.25
4
#to find if positive ,negative or zero n=int(input()) try: if(n>0): print("Positive") elif(n<0): print("Negative") else: print("Zero") except: print("Invalid Input")
true
a8c28d2602f9400fae0baad00135c1612187f4f9
tasnimz/labwork
/LAB 3.py
1,934
4.1875
4
##LAB 3 ##TASK 1 ##TASK 2 ##TASK 3 st = []; # Function to push digits into stack def push_digits(number): while (number != 0): st.append(number % 10); number = int(number / 10); # Function to reverse the number def reverse_number(number): # Function call to push number's # digits to stack push_digits(number); reverse = 0; i = 1; # Popping the digits and forming # the reversed number while (len(st) > 0): reverse = reverse + (st[len(st) - 1] * i); st.pop(); i = i * 10; # Return the reversed number formed return reverse; # Driver Code number = 39997; # Function call to reverse number print(reverse_number(number)); # This code is contributed by mits ##TASK 4 def check(my_string): brackets = ['()', '{}', '[]'] while any(x in my_string for x in brackets): for br in brackets: my_string = my_string.replace(br, '') return not my_string # Driver code string = "{[]{()}}" print(string, "-", "Balanced" if check(string) else "Unbalanced") ##TASK 5 ##TASK 6 from queue import Queue # Utility function to print the queue def Print(queue): while (not queue.empty()): print(queue.queue[0], end = ", ") queue.get() # Function to reverse the queue def reversequeue(queue): Stack = [] while (not queue.empty()): Stack.append(queue.queue[0]) queue.get() while (len(Stack) != 0): queue.put(Stack[-1]) Stack.pop() # Driver code if __name__ == '__main__': queue = Queue() queue.put(10) queue.put(20) queue.put(30) queue.put(40) queue.put(50) queue.put(60) queue.put(70) queue.put(80) queue.put(90) queue.put(100) reversequeue(queue) Print(queue)
true
56a99d737a1ae86f6b31a180c5bc9a319bf06461
Alenshuailiu/Python-Study
/first.py
202
4.1875
4
num=input('Enter a number ') print('The number you entered is ',num) num=int(num) if num > 10: print('you enter a number > 10') elif num > 5: print('you enter a number >5 <10') else: print('Others')
true
0501089bafc9bc2a488e9c4cf2e0689e26db6ff7
jenyton/Sample-Project
/operators.py
551
4.34375
4
##Checking the enumerate function print "##Checking the enumerate function##" word="abcde" for item in enumerate(word): print item for item in enumerate(word,10): print item mylist=["apple","mango","pineapple"] print list(enumerate(mylist)) ##Checking the Zip function print "##Checking the Zip function##" name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] roll_no = [ 4, 1, 3, 2 ] marks = [ 40, 50, 60, 70 ] zipped=zip(name,roll_no,marks) print "zipped value" print zipped print "Unzipped value" n,r,m=zip(*zipped) print n print r print m
true
c2fbe51a4c53f968c64cf470c86ac1cf6b4b448d
TardC/books
/Python编程:从入门到实践/code/chapter-10/cats&dogs.py
361
4.15625
4
def print_file(filename): """Read and print a file.""" try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: # msg = "The file " + filename + " does not exist!" # print(msg) pass else: print(contents) print_file('cats.txt') print_file('dogs.txt')
true
b295d0857648ad8e09a8a484e58d4745ebe74b69
ChastityAM/Python
/Python-sys/runner_up.py
561
4.15625
4
#Given participants score sheet for University, find the runner up score #You're given n scores, store them in a list and find the score of the #runner up. list_of_numbers = [2, 3, 6, 6, 5] print(sorted(list(set(list_of_numbers)))[-2]) #or list2 = [2, 3, 6, 6, 5] def second_place(list2): list2.sort(reverse=True) first_place_score = list2[0] for elem in list2: if elem < first_place_score: return_string = "Congrats for second place with score of {}".format(elem) return return_string print(second_place(list2))
true
9673488c7cfc5abd1e0339bd5815615780fa8b07
ChastityAM/Python
/Python-sys/lists.py
721
4.21875
4
list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8] a = list_of_numbers[5] #selecting an index b = list_of_numbers[2:5] #slicing the list #doesn't include last index given in printout print(a) print(b) list_of_numbers[5] = 77 list_of_numbers.append(10) list_of_numbers.pop(4) #removes at this index, if not indicated, will remove last one list_of_numbers.reverse() print(list_of_numbers) fruits = ["apple", "blueberry", "cherry", "mango", "banana"] print(fruits) fruits[3] = "pineapple" #reassigning slot 3 print(fruits) first_element = fruits[0] print(first_element) last_element = fruits[-1] print(last_element) print(len(fruits)) fruits.insert(2, "guava")#add to list at the index you chose print(fruits)
true
c4c1bc5ac2c4e5d28656af5dc987968d34c2feaa
ChastityAM/Python
/Python-sys/sqrt.py
231
4.25
4
import math #Create a function that takes a number n from the user. #Return a list containing the square of all numbers between 1 and n num1 = int(input("Please enter a number: ")) def sq_root(num1): return math.sqrt(num1)
true
0005a28c25142263623a6c52686bd0d1ef6def3f
afcarl/PythonDataStructures
/chapter4/exercise_7.py
410
4.25
4
def is_divisible_by_n(x,n): if type(x) == type(int()) and type(n)==type(int()): if x % n == 0: print "yes,"+str(x)+" is divisible by "+ str(n) else: print "no,"+str(x)+" is not divisible by "+str(n) else: print "invalid input" num1 = input("Please input a number to check:") num2 = input("Please input a divisor to check:") is_divisible_by_n(num1,num2)
true
4a118fbc0b36030195ebc7067b6feb98de8c4945
afcarl/PythonDataStructures
/chapter6/exercise_3.py
606
4.3125
4
def print_multiples(n, high): #initialize and iterator i = 1 #while the iterator is less than high, print n*i and a tab while i <= high: print n*i, '\t', i += 1 print #print a new line def print_mult_table(high): #initialize an interator i = 1 #while the iterator is less than high, do print_multiples while i <= high: print_multiples(i, high)#start from i=1 to high i += 1 #increment high #print_mult_table will start on line 1 and then it will continue to print out lines of integers until it reaches high. print print_mult_table(7)
true
4bad22567b2966e77af73848c19bb95542360a1a
gadi42/499workspace
/Lab4/counter.py
916
4.46875
4
def get_element_counts(input_list): """ For each unique element in the list, counts the number of occurrences of the element. :param input_list: An iterable of some sort with immutable data types :return: A dictionary where the keys are the elements and the values are the corresponding number of occurrences. """ unique_elements = set(input_list) elem_counts = {} for elem in unique_elements: elem_counts[elem] = count_element(input_list, elem) return elem_counts def count_element(input_list, target): """ Given a list and a target, counts how many times the target element occurs in the input list. :param input_list: An iterable of some sort :param target: An immutable data type :return: A non-negative integer """ count = 0 for elem in input_list: if elem == target: count += 1 return count
true
8874c382f717ef3828bda2da5763cb2d833f655b
mentekid/myalgorithms
/Permutations/permutations.py
1,092
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Computes all possible permutations of [0...N-1] for a given N If you need the permutations of another array, just use N = len(alist) and then print alist[perm] for perm in p Author: Yannis Mentekidis Date: April 28, 2015 """ from time import clock import sys def all_permutations(N): """Recursively find permutations """ if len(N)==1: return [N] permutations = [] for i in range(len(N)): p = all_permutations(N[0:i]+N[(i+1):]) for per in p: per.insert(0, N[i]) permutations.append(per) return permutations def main(): if len(sys.argv) < 2: num = 5 #default else: if int(sys.argv[1]) > 10: print "I don't like pain, so I'm only doing up to 10" num = 10 else: num = int(sys.argv[1]) N = range(num) start = clock() p = all_permutations(N) time = clock() - start # print p print "Found all ", len(p), " permutations of ", N print "Time: %fs" %(time) if __name__ == "__main__": main()
true
567c3c71afd8baa107f1d3a3a9a130edbb2401f9
Coder2100/mytut
/13_1_input_output.py
2,484
4.4375
4
print("7.1. Fancier Output Formatting") year = 2016 event = 'referendum' print(f"Result of the {year} {event} was BREXIT.") print("The str.format()") yes_votes =42_572_654 no_votes =43_132_495 percentage_yes = yes_votes/(no_votes + yes_votes) results = '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage_yes) print(results) print("The str() function is meant to return representations of values which are fairly human-readable,") print("while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax).") s = 'Hello World.' print(str(s))#str print(repr(s))# intepretor representation print(str(1/7)) x = 10 * 3.25 y = 200 * 200 s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' hello = 'hello, world\n' print(s) hellos = repr(hello) print(hellos) print(repr((x, y, ('spam', 'eggs')))) import math print(f"The value of pi is approximately {math.pi:.3f}.") table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} for name, phone in table.items(): print(f"{name:10} ===> {phone:10d}") animals = 'eels' print(f'My hovercraft is full of {animals}.') print(f"My hovercraft is full of {animals!r}.") print('We are the {} who say "{}!"'.format('knight', 'Ni')) print('{0} and {1}'.format('spam', 'eggs')) #spam and eggs print('{1} and {0}'.format('spam', 'eggs')) #eggs and spam print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')) table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table)) table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) for x in range(1, 11): print('{0:3d} {1:4d} {2:5d}'.format(x, x*x, x*x*x)) print("Manual String Format") for x in range(1, 11): print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') print(repr(x*x*x).rjust(4)) #The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. # There are similar methods str.ljust() and str.center(). print("There is another method, str.zfill(), which pads a numeric string on the left with zeros") # It understands about plus and minus signs: print('12'.zfill(5)) print("Old string formatting %s,s as placeholder to the right") import math print('The value of pi is approxitaley %5.3f.' %math.pi)
true
46a0a26d0c0ae7ae5eefcf51f5ef47e26d0d175f
gstroudharris/PythonAutomateTheBoringStuff
/Lessons/lists.py
866
4.28125
4
#purpose: place items in a list, put them in a function, then call them myLists = [['Grant', 'Dana', 'ListItem3'], [10, 20, 35]] #index evaluates to a single item at a time print((myLists[0][0]) + str((myLists[1][-2]))) #slice will evaluate to a a whole list print(myLists[1:2]) #replace an item in the list myLists[1][0] = 'replaced' print(myLists) #extend the list by assigning new entries myLists[1][1:3] = ['with', 'some', 'new', 'words'] print(myLists) #de-assign an item with del del myLists[1][-2] print(myLists) #see how long a list is with len function print(len(myLists)) #multiply the list by two and print print(myLists * 2) #list a str print(list('helloooooo')) #see if an item is in the list with 'in', or 'not in' for the opposite searchWord = input('what word should we find in a name list? ') print(searchWord in ['Grant', 'bagel'])
true
802a63767ddf4ac4449b11045c4e5ee1b2f69e04
Hoverbear/SPARCS
/week4/board.py
1,386
4.125
4
def draw_board(board): """ Accepts a list of lists which makes up the board. Assumes the board is a list of rows. (See my_board) """ # Draw the column indexes. print(" ", end="") for index, col in enumerate(board): # Print the index of each column. # Note: sep="", end="" prevent python from creating a new line. print(" C" + str(index) + " ", sep="", end="") print("") # Creates a line break. for index, row in enumerate(board): # Print the row border. print(" " + ("+----" * 8) + "+", sep="") # Print the row index. print("R" + str(index) + " ", sep="", end="") # Print each cell for cell in row: print("| " + str(cell) + " ", sep="", end="") print("|") # Finishes the row. # Print the end border. print(" " + ("+----" * 8) + "+", sep="") my_board = [ ["br", "bk", "bb", "bq", "bk", "bb", "bk", "br"], ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "], ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"], ["wr", "wk", "wb", "wq", "wk", "wb", "wk", "wr"] ] print(my_board) # draw_board(my_board)
true
2157ab6936bd0e03959d122e9cc4a0c6908081fd
Hoverbear/SPARCS
/week2/2 - Loops.py
2,579
4.90625
5
# Loops! Loops! Loops! # The above is an example of a loop. Loops are for when you want to do something repeatedly, or to work with a list. # First, some useful things for us to know. my_range = range(10) # This creates an "iterator" which is sort of like a list, in fact, we can use a cast to make a list out of it. print(list(my_range)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # We're not going to get into what iterators actually are quite yet, so lets just think of them as lists. # A normal range range(10) # 0 to 10 (Not including 10!) # Specify a starting point. range(5,10) # 5 to 10 (Not including 10!) # By steps. range(0,10,2) # [0,2,4,6,8] (Again, no 10) # Okay, now that we know how to use ranges, lets try looping! for number in range(10): print(str(number)) # Holy jeez, this prints out 0 to 9! for number in range(0, 10, 2): another_list = list(range(number, 10)) print(another_list) # What do you think this prints? # Ranges are cool, and useful, but what if I wanted to use one of those handy list things? for item in ["My", "Handy", "List"]: print("One item of the list is: " + item) # Well isn't that useful! Lets try some more! # So loops are handy, but what if we don't know how many times we want to loop? For example, I want to loop until the user inputs "Potato". # Thankfully, there's something called a "while" loop. while input("Enter 'Potato' to finish the loop: ") != "Potato": print("That's not 'Potato', I'll keep going.") print("You got out of the loop!") # Okay, that works, our tool box is growing really big now! There's just one more thing about loops that we should talk about: What if I want to finish early? # For example: We want loop through a list of names and say hi to everyone, except if we see "Selena Gomez", then we should stop, because she's magic. names = ["Simon", "Andrew", "Frosty", "Oscar", "Fred", "Selena Gomez", "Someone who doesn't get printed"] for name in names: if name == "Selena Gomez": print("OMG IT'S SELENA GOMEZ.") break print("Hello there, " + name + "!") # *** CHALLENGE TIME *** # Okay, here's a fun problem... Actually, this is an interview question for hiring REAL programmers. # Here's the problem: # For all the numbers from 0 to 100 (not including 100), # If a number is divisible by 3, print out "Fizz" # If a number is divisible by 5, print out "Buzz" # Otherwise, just print out the number. # Hint: You'll want to use the modulo operator we talked about earlier. (4 % 2 == 0, or "The remainder of 4 divided by 2 is zero") # *** END OF CHALLENGE TIME *** # Congratulations! Lets cover more about lists!
true
3428bb3e2794381738752bb1a368b196fcebee13
14E47/Hackerrank
/30DaysOfCode/day9_recursion3.py
302
4.125
4
#!/bin/python3 import math import os import random import re import sys # Complete the factorial function below. def factorial(n): if n<=1: return 1 else: fac = n*factorial(n-1) return fac n = int(input("Enter factorial no. :")) result = factorial(n) print(result)
true
0d19a01a43ef753af9eb1f9f09817c86e99f0dec
jacobbathan/python-examples
/ex8.10.py
344
4.25
4
# a string slice can take a third index that specifies the 'step size' # the number of spaced between successive characters # 2 means every other character # 3 means every third # fruit = 'banana' # print(fruit[0:5:2]) def is_palindrome(string): print(string == string[::-1]) is_palindrome('racecar') is_palindrome('apple')
true
e857a43a220a5e158610933d8f478046e6559ae8
sheikh210/LearnPython
/functions/challenge_palindrome_sentence.py
345
4.1875
4
def is_palindrome(string: str) -> bool: return string[::-1].casefold() == string.casefold() def is_sentence_palindrome(sentence: str) -> bool: string = "" for char in sentence: if char.isalnum(): string += char return is_palindrome(string) print(is_sentence_palindrome("Was it a car, or a cat, I saw"))
true
e4e6df7f0136d45eaa671d592b74fe4767774cfe
sheikh210/LearnPython
/functions/challenge_fizz_buzz.py
1,549
4.3125
4
# Write a function that returns the next answer in a game of Fizz Buzz # You start counting, in turn. If the number is divisible by 3, you say "fizz" instead of the number # If the number if divisible by 5, you say "buzz" instead of the number # If the number is divisible by 3 & 5, you say "fizz buzz" instead of the number # The function should return the correct word ("fizz", "buzz" or "fizz buzz"), or the number if not # divisible by 3 or 5 # The function will always return a string # # Include a for loop to test your function for values from 1-100, inclusive def fizz_buzz(number: int) -> str: """ Function to return "fizz" if param `number` is divisible by 3 and not divisible by 5. Function to return "buzz" if param `number` is divisible by 5 and not divisible by 3. Function to return "fizz buzz" if param `number` is divisible by 3 and divisible by 5. Else function returns number :param number: Number to be checked if divisible by 3 and/or 5 :return: "fizz", "buzz", "fizz buzz" or number passed as argument """ if number % 15 == 0: return "fizz buzz" elif number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" else: return str(number) # PLAY FIZZ BUZZ AGAINST THE COMPUTER! for i in range(1, 101): if i % 2 != 0: print(fizz_buzz(i)) else: user_input = str(input()) if user_input != fizz_buzz(i): print("YOU LOSE!") break else: print("WELL DONE, YOU REACHED 100!")
true
7f5ade077d195863562b3d90d89cf9bebd1d715b
sheikh210/LearnPython
/data_structures/sets/sets_intro.py
1,506
4.25
4
# Sets are unordered and DO NOT contain any duplicate values - Think of sets like a collection of dictionary keys # Elements in a set MUST be immutable (hashable) # DEFINING A SET # ********************************************************************************************************************** # Method 1 - Declaring a set literal farm_animals = {'sheep', 'cow', 'hen'} for animal in farm_animals: print(animal) print('*' * 25) # Method 2 - Passing a tuple literal to the set() constructor wild_animals = set(['lion', 'tiger', 'panther', 'elephant', 'hare']) for animal in wild_animals: print(animal) print('*' * 25) # Method 2.1 - Passing a tuple variable to the set() constructor squares_tuple = (4, 6, 9, 16, 25) squares = set(squares_tuple) print(squares) print('*' * 25) # Method 2.2 - Passing a range to the set() constructor even = set(range(0, 40, 2)) print(even) print('*' * 25) # ADDING TO A SET # ********************************************************************************************************************** farm_animals.add('horse') wild_animals.add('horse') print(farm_animals) print(wild_animals) print('*' * 25) # REMOVING FROM A SET # ********************************************************************************************************************** # discard() - Doesn't throw error farm_animals.discard('horse') print(farm_animals) # remove() - Throws exception if value doesn't exist wild_animals.remove('horse') print(wild_animals) print('*' * 25)
true
0a24d97defcca7fe24bcaec53337ba790151a76f
crystalballz/LearnPythonTheHardWay
/ex3.py
700
4.46875
4
print "I will now count my chickens:" # Hens and Roosters are counted separately print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 # Not too many eggs since there are more Roosters than Hens print "Now I will count the eggs:" print 3 + 2 + 1 - 5+ 4 % 2 - 1 / 4 + 6 # Verifies if the statement that follows is true or false print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." # These lines below are demonstrating the comparator math equations print "Is it greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2
true
64c14de2c423cebafdbd7cc8b4869bd3724c0a4e
ninsamue/sdet
/python/act_4.py
1,487
4.25
4
print("ROCK PAPER SCISSORS") print("-------------------") Name1 = input("Enter Player 1 Name : ") Name2 = input("Enter Player 2 Name : ") player1Score=0 player2Score=0 play="Y" while play=="Y": player1Choice = input(Name1+"'s choice - Enter rock/paper/scissors : ").lower() player2Choice = input(Name2+"'s choice - Enter rock/paper/scissors : ").lower() if player1Choice == player2Choice: print("It's a tie") elif player1Choice=="rock" and player2Choice=="paper": print(Name2, "wins the round") player2Score+=1 elif player1Choice=="rock" and player2Choice=="scissors": print(Name1, "wins the round") player1Score+=1 elif player1Choice=="paper" and player2Choice=="rock": print(Name1, "wins the round") player1Score+=1 elif player1Choice=="scissors" and player2Choice=="rock": print(Name2, "wins the round") player2Score+=1 elif player1Choice=="paper" and player2Choice=="scissors": print(Name2, "wins the round") player2Score+=1 elif player1Choice=="scissors" and player2Choice=="paper": print(Name1, "wins the round") player1Score+=1 else: print("Invalid Input. You have not entered rock/paper/scissors") play=input("Do you want to continue playing(Y/N) : ") print("Final Score") print("-----------") print(Name1+"'s score ",player1Score) print(Name2+"'s score ",player2Score)
true
4cc104ae49f21d9ca55166c2aa5149e646dfda4d
mrparkonline/ics4u_solutions
/10-06-2020/letterHistogram.py
1,080
4.3125
4
# Write a program that reads a string and returns a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. Case should be ignored. def letterHistogram(word): ''' letterHistogram tracks the occurance of each alpha characters argument -- word : string return -- dictionary ''' cleaned_word = list(map(str.lower, word)) #cleaned_word = sorted(cleaned_word) cleaned_word.sort() # print(cleaned_word) table = {} # empty dictionar # Key --> each alpha letter # Value --> the number of occurance for item in cleaned_word: if item in table: # item/the alpha character is a key that exist in table table[item] += 1 else: if item.isalpha(): table[item] = 1 # end for return table # end of letterHistogram table = letterHistogram("The quick brown fox jumps over the lazy dog") for character, count in table.items(): print(character, count)
true
5e018f447d9d13832317ee5720012440a9c73c7c
mrparkonline/ics4u_solutions
/09-14-2020/factoring.py
731
4.3125
4
# 09/14/2020 # Factoring Program num = int(input('Enter a number you want the factors for: ')) # While Loop Solution divisor = 1 while divisor <= num: # we are checking all numbers from 1 to inputted num if num % divisor == 0: # when num is divided by divisor the remainder is 0 # therefore, divisor is a factor of num print(divisor, 'is a factor of', num) divisor += 1 # end of while print('I am outside of while loop') # For Loop Solution for i in range(1, num+1): if num % i == 0: print(i, 'is a factor of', num) # end of for print('I am now outside of the for loop') # Thought: which is the better solution? # Can I program a better solution?
true
78fcf013af9f568d0314b181d721acb49cb0f59a
mrparkonline/ics4u_solutions
/10-06-2020/numDict.py
1,333
4.34375
4
''' Q4a) Write a Python program to sum all the items in a dictionary Q4b) Write a Python program to multiply all the items in a dictionary Q5a) Create a function that sorts a dictionary by key → Create a sorted list of keys. Q5b) Create a function that sorts a dictionary by value → Create a sorted list of values. ''' from random import seed from random import randrange seed(1) # this allow us to generate the same random numbers # at every run test = {randrange(1,1000000) : randrange(1,100) for x in range(20)} print(test) # q4a) Sum up all the values in a dictionary total_sum = sum(test.values()) print('The total_sum is:', total_sum) # q4b) Multiply all the number def multiplyDict(table): ''' multiplyDict returns the total product of all values in table argument -- table : dictionary return -- integer ''' total_product = 1 for value in table.values(): total_product *= value return total_product # end of multiplyDict print('The total product is:', multiplyDict(test)) # q5a) List of the keys sorted sorted_test_keys = sorted(test.keys()) print('Keys of test sorted:', sorted_test_keys) # q5b) List of the values sorted sorted_test_values = sorted(test.values()) print('Values of test sorted:', sorted_test_values)
true
3c91e7f0397bac3d0f7684e95642afbf6183a74d
mrparkonline/ics4u_solutions
/10-19-2020/binarySearch.py
1,119
4.15625
4
# Binary Search Non recursive def binSearch(data, target): left = 0 right = len(data) - 1 while left <= right: middle = (left + right) // 2 if data[middle] == target: return middle elif data[middle] < target: left = middle + 1 else: # data[middle] > target: right = middle - 1 # end of while return -1 # end of binSearch # Recursive Binary Search def r_binSearch(data, target, i=0): if not data: return -1 elif len(data) == 1 and data[0] != target: return -1 else: middle = (len(data)-1) // 2 if data[middle] == target: return middle+i elif data[middle] < target: return r_binSearch(data[middle+1:], target, middle+i+1) else: return r_binSearch(data[:middle], target, i) # end of r_binSearch from random import randrange test = [randrange(-100,100) for i in range(20)] test.sort() print('Testing List:', test) print(binSearch(test, 42)) print(r_binSearch(test, 42))
true
71c8bdc6bf5b8561a8306cf147b782a3266d8bf5
ask-ramsankar/DataStructures-and-Algorithms
/stack/stack using LL.py
1,217
4.15625
4
# creates a node for stack class Node: def __init__(self, data, prev=None): self.data = data self.prev = prev self.next = None class Stack: # initialize the stack object with the top node def __init__(self, data): self.top = Node(data) # push the data to the stack def push(self, data): self.top.next = Node(data, self.top) self.top = self.top.next # deletes the top node from the stack def pop(self): if self.isEmpty(): return "! Stack is Empty" self.top = self.top.prev # To check if stack has a prev node or not if self.top is not None: self.top.next = None # returns the data in the top node def reveal(self): if self.isEmpty(): return "! Stack is Empty" return self.top.data # To check whether the stack is empty or not def isEmpty(self): return not bool(self.top) if __name__ == "__main__": stack = Stack(Node(10)) for value in range(20, 101, 10): stack.push(value) while not stack.isEmpty(): print(stack.reveal()) stack.pop()
true
6857698560aa61ddccd54c02d71f57b57be8644c
ask-ramsankar/DataStructures-and-Algorithms
/queue/queue using LL.py
1,050
4.125
4
# Node of the queue class Node: def __init__(self, data): self.data = data self.next = None class Queue: # Initialize the queue with the first node def __init__(self, data): self.first = Node(data) # add a node to the queue at last def enqueue(self, data): current = self.first if current is None: self.first = Node(data) else: while current.next: current = current.next current.next = Node(data) # deletes first node from the queue def dequeue(self): self.first = self.first.next # return the data in the first node def reveal(self): return self.first.data # check whether the queue is empty or not def isEmpty(self): return not bool(self.first) if __name__ == "__main__": queue = Queue(10) for data in range(20, 101, 10): queue.enqueue(data) while not queue.isEmpty(): print(queue.reveal()) queue.dequeue()
true
1d86a1f0c018922cff28368903e4a99a1eea139f
jodr5786/Python-Crash-Course
/Chapter 4/4-10.py
329
4.1875
4
# Slices my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'fish', 'lobster'] friend_foods = my_foods[:] print("\nThe first 3 items in my list are:") print(my_foods[:3]) print("\nThe items in the middle of my list are:") print(my_foods[1:5]) print("\nThe last 3 items in the list are:") print(my_foods[-3:])
true
9073f99a3d78244b516d34730f0321e01e80f341
ravindra-lakal/Python_new
/mak.py
912
4.3125
4
################################### #1 Find the last element of a list. list = ['a','b','c','d'] #validation list =[] print list[-1:] #print "list[4]",list[4] #2 Find the last but one element of a list. list =['z','w','e','i','t','l','e','t','z','t','e','s'] #validation list=[1] print list[-2:-1] #3 1.03 (*) Find the K'th element of a list. list = ['a','b','c','d','e','f','g'] print list[3] #4 somelist = ["a", "b", "c", "d"]; print len(somelist) #5 reverse the list list = ['a','b','c','d'] #print list[::-1] list.reverse() print list #5 Addition of 2 numbers a= input("enter no") # b=raw_input("enter no") print a ################################### #6 check string Find out whether a list is a palindrome # name = raw_input("Enter a string: ") # rev_str = reversed(name) # if list(name) == list(rev_str): # print("It is palindrome") # else: # print("It is not palindrome")
true
000e177fda7bf009742ef757bdd466249e42bd9a
nyeddi/Adv-Python
/class_method_.py
1,745
4.46875
4
class Shape(object): # this is an abstract class that is primarily used for inheritance defaults # here is where you would define classmethods that can be overridden by inherited classes @classmethod def from_square(cls, square): # return a default instance of cls return cls() class Square(Shape): def __init__(self, side=10): self.side = side @classmethod def from_square(cls, square): return cls(side=square.side) class Rectangle(Shape): def __init__(self, length=10, width=10): self.length = length self.width = width @classmethod def from_square(cls, square): return cls(length=square.side, width=square.side) class RightTriangle(Shape): def __init__(self, a=10, b=10): self.a = a self.b = b self.c = ((a*a) + (b*b))**(.5) @classmethod def from_square(cls, square): return cls(a=square.side, b=square.side+2) class Circle(Shape): def __init__(self, radius=10): self.radius = radius @classmethod def from_square(cls, square): return cls(radius=square.side/2) class Circle1(Shape): def __init__(self, radius=10): self.radius = radius @staticmethod def from_square(square): return Circle1(radius=square.side/2) class Hexagon(Shape): def __init__(self, side=10): self.side = side #https://stackoverflow.com/questions/5738470/whats-an-example-use-case-for-a-python-classmethod square = Square(3) for polymorphic_class in (Square, Rectangle, RightTriangle, Circle, Hexagon): this_shape = polymorphic_class.from_square(square) print(this_shape.__class__)
true
c21643f5c58676f77da8ffbc14d3dc488c5b0d8e
saadkang/PyCharmLearning
/basicsyntax/indexvstring.py
2,088
4.40625
4
""" We will see how the index works in python """ nameOfAString = "This is for educational purposes only" # The : in the [] is has no starting and ending index so it will print the whole String print("There is nothing before or after the : so it will print complete String: "+nameOfAString[:]) # In the example below there is a number in front of the : so the starting index is 1 # There is no number after the : so it will print rest of the index print("There is 1 in front of : and nothing after, so it will start at index 1 and print everything: "+nameOfAString[1:]) # In the example below there is no starting index so it will print all, but there is an ending index # We learned previously that the ending index is exclusive so that will not get printed print("There is nothing in front of the : and 9 after, so It will print all the index and stop at 8: "+nameOfAString[:9]) # So the cool this is the index can be started from either side, if you choose to start from the # right side then the index will starts from -1, -2, -3,..,-37 # So in the example below the -37 is the first index on the far left hand side "T" print("Numbering index is a circle starting from left is 0, and starting from right is -1: "+nameOfAString[-37]) print("So now I'm trying to put -1:-1 and what to see what prints: "+nameOfAString[-1:-1]) # Nothing printed on the console, I guess the reason for that is, it did start with -1 index which is the starting # index and then it looked at the ending index which is also -1 and ending index is exclusive so nothing gets printed # Now let's talk about the skip part # The second : is for skipping an index, in the example below there is nothing after the : so nothing will be skipped print(nameOfAString[::]) # The example below is saying to skip nothing so it is the same thing as above print(nameOfAString[::1]) # This is skipping two index and printing the third one on the console print(nameOfAString[::3]) # To reverse the String you can just type -1 after the second : print("Reverse the value of a String and you get: "+nameOfAString[::-1])
true
445befab60ef2ad7e87ec1b5ce54925ace4977b8
saadkang/PyCharmLearning
/basicsyntax/tuplesdemo.py
1,493
4.5
4
""" Tuple Like list but they are immutable that means you can't change them """ # What the above line in green is trying to say is that list (also called Array in Java) can be changed # Like in the example below: # The list or Array is defined by the [] my_list = [1, 2, 3] print(my_list) my_list[0] = 0 print(my_list) print('*'*40) # The tuple is immutable so can't be changed and they are defined by () my_tuple = (1, 2, 3) print(my_tuple) # So if we try to change the index of a tuple we will get the 'assignment not supported' error # So I'm not going to try that here, just know you can't change it. # But you can access different index of the tuple print('*'*40) print(my_tuple[0]) # And we can also do slicing or skipping with the tuple print('*'*40) print(my_tuple[1:]) print('*'*40) # We can also find out the index of the items in the tuple # Let's say we want to find out the index of item or data '2' in the tuple # we can just type it in the print statement print("The index of the data '2' in the tuple 'my_tuple' is: %s" % my_tuple.index(2)) # The next thing we can do with the tuple is find how many times a entry is repeated in the tuple print('*'*40) print("'1' appeared in the tuple 'my_tuple' exactly %s times" % my_tuple.count(1)) # To understand this count() method let's create a new tuple and use it in examples print('*'*40) my_second_tuple = (1, 2, 3, 4, 3, 6, 3, 8, 3) print("'3' appeared in the tuple 'my_second_tuple' exactly %s times" % my_second_tuple.count(3))
true
bf1a776903b0befb342dd7b8a8ea0b26d2b307dd
cnrmurphy/python-lessons
/exercises/session_1/calc.py
2,685
4.21875
4
''' Exercise: Implement a basic calculator that supports add,subtract,multiply,divide Basic requirements: four functions that perform the aforementioned operations will suffice. Extending: Implement a function, calculator, that takes 3 inputs: operation (string), num_a, and num_b. the function, calculator, should perform the inputed operation as defined in the basic requirements and pass num_a and num_b to the respective function. I.e. if calculator is called with the arguments: "add", 5, 10 then the add function should be called with 5 and 10 and return 15. If an operation is not recognized i.e "pow" return the following string: "Operation not recognized!". Considerations: What happens if you try to divide by 0? Can you figure out a way to handle this case gracefully (without the programming crashing). Expectations: All tests should pass. If all tests pass you should see your programm output: "All cases pass!" Tests: the test functions should evaluate to True when called with the respective function ''' # Program -> your code goes below # Tests def test_add(add_function): expected_output = 15 result = add_function(10,5) assert (result == expected_output), f'Add does not output the expected sum: 10 + 15 != {result}' def test_subtract(subtract_function): expected_output = 5 result = subtract_function(10,5) assert (result == expected_output), f'Subtract does not output the expected difference: 10 - 5 != {result}' def test_multiply(multiply_function): expected_output = 50 result = multiply_function(10, 5) assert (result == expected_output), f'Multiply does not output the expected product: 10 * 5 != {result}' def test_divide(divide_function): expected_output = 2 result = divide_function(10,5) assert (result == expected_output), f'Divide does not output the expected quotient: 10 / 5 != {result}' # Add the name of your functions to the respective test arguments below # I.e. if your add function is called add_nums, call the test like: test_add(add_nums) # Note for clarification: It may be confusing to be passing a function name as a function parameter. # This is valid in programming languages and it is called a first class function. When you define a function # it's almost as if your assinging a block of code to that function namespace, like you would assign some data # to a variable. So below we pass the name of the function, which is a reference, and we can execute that function # when we call it with the normal syntax, using paren (), within our test functions. test_add(add) test_subtract(subtract) test_multiply(multiply) test_divide(divide) print("All cases pass!")
true
a5c1932418534132648d77c240e64e839244fd70
aditparekh/git
/python/lPTHW/ex3.py
460
4.375
4
print 'I will not count my chickens:' print "Hens", 25+30/6 print "Roosters", 100-25*3%4 print 'Now I will coung the eggs:' print 3+2+1-5+4%2-1/4+6 print 4//3 print "is it true that 3+2<5-7" print 3+2<5-7 print "Waht is 3+2?",3+2 print "Waht is 5-7?",5-7 print "Ph, that's why it's False" print "How abot some more" print"Is it greater?",5>-2 #check to see if it true or false print "Is it greater or equal?",5>=-2 print "Is it less or equal?",5<=-2
true
2badc0380cce0cef6f0b76a76d6164e6f6b51d39
aditparekh/git
/python/lPTHW/ex25.py
837
4.28125
4
def break_words(stuff): """This function will break up words for us""" words = stuff.split(" ") return words def sort_words(words): """Sorts the words""" return sorted(words) def print_first_word(words): """Prints the firs word after popping it off""" word=words.pop(0) print word def print_last_words(words): """Prints the last words after popping it off""" word=words.pop(-1) print word def sort_sentence(sentence): """takes a full sentence and returns the sorted value""" words=break_words(sentence) return sort_words(words) def print_first_and_last(sentence): """prints the first and last word of the sentnce""" words=break_words(sentence) print_first_word(words),print_last_words(words) def print_first_and_last_sorted(sentence): words=sort_sentence(sentence) print_first_word(words),print_last_words(words)
true
d96410728328d7382eefaae6929001873fefa702
ajaymatters/scripts-lab
/script-lab/python-scripts/PartA7/pa7.py
519
4.15625
4
def AtomicDictionary(): atomic = {"H":"Hydrogen", "He":"Helium", "N":"Nitrogen"}; x = input("Enter symbol ") y = input("Enter element name ") if x in atomic.keys(): print("Key already exists. Value will be updated") else: print("New Key with Value added") atomic[x] = y print(atomic) print("Number of elements in dict:",len(atomic)) x = input("Enter symbol for searching ") if x in atomic.keys(): print("Element exists in dict with value "+ atomic[x]) else: print("Element not present in dict")
true
45c036e33d642d8ada09272dec7152a87dea512b
Sridhar-S-G/Python_programs
/Extract_numbers_from_String.py
370
4.125
4
''' Problem Statement A string will be given as input, the program must extract the numbers from the string and display as output Example 1: Input: Tony Stark's daughter says 143 3000 Output: 143 3000 Example 2: Input: There4 I think you will be satis5ed with this tutorial Output: 4 5 ''' #Solution Code import re s=input() results= re.findall(r'\d+',s) print(*results)
true
3c4f4279850d8e2f0bb240fa3c2703b54f2796bc
simiss98/PythonCourse
/UNIT_1/Module1.2/MOD01_1-2.2_Intro_Python.py
1,583
4.21875
4
#creating name variable name = "Petras" # string addition print("Hello " + name + "!") # comma separation formatting print("Hello to",name,"who is from Vilnius.") print("Hello to","Petras","who is from Vilnius.") # [ ] use a print() function with comma separation to combine 2 numbers and 2 strings print("I was born at 1990. After",2,"years I will be",30,"years old.") # [ ] get user input for a street name in the variable, street print("enter Steet name") street= input() # [ ] get user input for a street number in the variable, st_number print("enter street number") st_number=input() # [ ] display a message about the street and st_number print("My home address is ",street,st_number,) # [ ] define a variable with a string or numeric value company="Bazaarvoice" # [ ] display a message combining the variable, 1 or more literal strings and a number print("I am working with",company,"for",3.5,"months.") # [ ] get input for variables: owner, num_people, training_time - use descriptive prompt text owner=input("Enter a name for contact person for training group: Python Academy") num_people = input("Enter the total number attending the course:") training_time = "5:00 PM" # [ ] create a integer variable min_early and "hard code" the integer value (e.g. - 5, 10 or 15) min_early = 10 # [ ] print reminder text using all variables & add additional strings - use comma separated print formatting print("Reminder:","Python Academy training is scheduled at",training_time,"for",owner,"group of",num_people,"attendees.","Please arrive",min_early,"early for the first class.")
true
6c19170153ee9669fbafe02192606989d031e7a5
simiss98/PythonCourse
/UNIT_1/Module1.1/MOD01_1-1.4.py
2,115
4.375
4
Task1 #creating x,y and z integer variables and then adding then calculating sum of 3 integers. x=1 y=2 z=3 x+y+z # displaying sum of float and integer. 65.7+4 #creating string name variable and then using print just for fun to display both strings. name="Evaldas" print("This notebook belongs to "+name) #creating sm_number and big_number as integers, then displaying sum of those variables. sm_number=4 big_number=5 sm_number+big_number #creating a string value to the variable first_name and add to the string ", remember to save the notebook frequently.". first_name="Evaldas" fn=first_name #Task2 #adding additional string to the variable new_msg and then printing variable new_msg. new_msg = "My favorite food is"+" a Brisket, because Brisket is a KING!" print(new_msg) #adding additional integers to the variable new_sum and then printing new_sum variable. new_sum =0+1-(57+23)*6+999 print(new_sum) #creating 2 string variables and then printing them together. new_msg="Hello World!" new_msg_2=new_msg+" Hello Students!!" print(new_msg_2) #Task3 #fixing the variable: total_cost in order to print total_cost. total_cost = 3 + 45 print(total_cost) #fixing the variable: schoold_num in order to print school_num. school_num = "123" print("the street number of Central School is " + school_num) #Hypothesis - When printing float+integer the outome is printed as float variable. print(type(3.3)) print(type(3)) print(3.3 + 3) #Task4 # Opening and closing quotes must be the same in order to print a string, e.g 'text' and "text". print('my socks do not match') #pront was miss-spelled to display a variable print should be used instead. print("my socks match now") #for printing anything we should add(). Brackets must open and close. print("Save the notebook frequently") #print command is case sensitive for printing variables, we must pay extra attention when typing varianles name inside (). student_name = "Alton" print(student_name) #integers cannot be printed with string together, we must use String+String or Int_Int to print something. total = "3" print(total + " students are signed up for tutoring")
true
5d22d099a117896b83c84babf34a3916a06504fc
Futi7/AnagramChecker
/main.py
1,949
4.1875
4
class AnagramChecker: list_of_strings = [] first_string_keys = {} second_string_keys = {} list_of_keys = [first_string_keys, second_string_keys] def __init__(self, first_string, second_string): self.list_of_strings.append(first_string) self.list_of_strings.append(second_string) def check_if_anagrams(self): for string, keys in zip(self.list_of_strings, self.list_of_keys): for char in sorted(string): if char not in keys: keys[char] = 1 else: keys[char] = keys.get(char) + 1 if self.list_of_keys[0] == self.list_of_keys[1]: print("Is anagram") else: self.check_required_deletions() def check_required_deletions(self): chars_to_delete = [0,0] first_keys, second_keys = self.list_of_keys for key in first_keys: if key in second_keys: if first_keys[key] > second_keys[key]: chars_to_delete[0] += (first_keys[key] - second_keys[key]) elif first_keys[key] < second_keys[key]: chars_to_delete[1] += (second_keys[key] - first_keys[key]) else: chars_to_delete[0] += first_keys[key] for key in second_keys: if key not in first_keys: chars_to_delete[1] += second_keys[key] print("remove " + str(chars_to_delete[0]) + " characters from '" + self.list_of_strings[0] + "' and " + str(chars_to_delete[1]) + " characters from '" + self.list_of_strings[1] + "'") if __name__ == "__main__": first_string = input("Enter first string:\n") second_string = input("Enter second string:\n") anagramChecker = AnagramChecker(first_string, second_string) print("First:"+anagramChecker.list_of_strings[0]+ "\nSecond:"+anagramChecker.list_of_strings[1]) anagramChecker.check_if_anagrams()
true
9498fe8866498ef6be30b8d8967dad971f09d801
charanchakravarthula/python_practice
/Baics.py
499
4.3125
4
# variable assignment var = 1 print(var) # multiple values assignment to a variable var1,var2 =(1,2) print(var1,var2) #ignoring unwanted values var1,__,__=[1,2,3] print(var1) var1=var2=var3=1 print(var1,var2,var3) # knowing the type of the varible i.e data type of variable var1=[1,2,3] var2=('a',"b","c") var3=1 var4=1.0 var5={'a':1,"b":2} var6={1,2,3} print(type(var1),type(var2),type(var3),type(var4),type(var5),type(var6),sep="\n") # get the memory id of a variable print(id(var1))
true
e3e76c37ff817bae9836c142f0a7113ede554505
bang103/MY-PYTHON-PROGRAMS
/PYTHONINFORMATICS/DictDayOfWeek.py
871
4.25
4
#Exercise 9.2 in Python for INformatics #Exercise 9.2 Write a program that categorizes each mail message by which day of #the week the commit was done. To do this look for lines which start with *From*, #then look for the third word and then keep a running count of each of the days #of the week. At the end of the program print out the contents of your dictionary #(order does not matter). import string filename = "mbox-short.txt" try: fhand=open(filename,"r") except: print "File %s does not exist"%(filename) exit() DaysOfWeek=dict() for line in fhand: if len(line)== 0: continue if line.startswith("From:"): continue if line.startswith("From"): words=line.split() day=words[2] DaysOfWeek[day]= DaysOfWeek.get(day,0)+1 for day in DaysOfWeek: print day, DaysOfWeek[day] fhand.close()
true
adc3327fe24e67694446fd98f023306cafd012d2
bang103/MY-PYTHON-PROGRAMS
/WWW.CSE.MSU.EDU/STRINGS/Cipher.py
2,729
4.25
4
#http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/ #implements encoding as well as decoding using a rotation cipher #prompts user for e: encoding d: decoding or q: Qui import sys alphabet="abcdefghijklmnopqrstuvwxyz" print "Encoding and Decoding strings using Rotation Cipher" while True: output=list() inp=raw_input("Input E to encode, D to decode and Q to quit---> ") if inp.lower()=="e": #encode while True: #input rotation inp2=raw_input("Input the rotation: an integer between 1 and 25 ---> ") if inp2.isdigit()== False: print " !!Error: Non digits!! The roatation is a whole number between 1 and 25" elif int(inp2)>=1 and int(inp2)<=25: rotation=int(inp2) break else: print " Error! The roatation is a whole number between 1 and 25" cipher = alphabet[rotation:]+ alphabet[:rotation] instring=raw_input("Input string to be encoded---> ") for char in instring: if char in alphabet: index=alphabet.find(char) output.append(cipher[index]) else: output.append(char) outputstring = "".join(output) print "The encoded string---> ",outputstring elif inp.lower()=="d": #decode and find rotation instring=raw_input( "Enter string to be decoded---> ") word=raw_input( "Enter a word in the original(decoded) string ---> ") rotation=0 found=False for char in alphabet: output=list() rotation +=1 cipher=alphabet[rotation:]+alphabet[:rotation] #decode encoded text with current rotation for ch in instring: if ch not in cipher: output.append(ch) elif ch in cipher: index=cipher.find(ch) output.append(alphabet[index]) outputstring="".join(output) if word in outputstring: #IMPORTANT: This statement works only if we join the list into a string found=True break else: continue if found == True: print "The rotation is %d"%(rotation) print "The decoded string is ---> ", outputstring else: print "Cannot be decoded with rotation cipher: try another sentence" elif inp.lower()=="q": print "Bye! See you soon" break
true
27e4ef0d8bb177a902727eabc24249c933fbb6e2
AO-AO/pyexercise
/ex8.py
653
4.4375
4
""" Define a function called anti_vowel that takes one string, text, as input and returns the text with all of the vowels removed. For example: anti_vowel("Hey You!") should return "Hy Y!". """ def anti_vowel(text): result = "" lenth = len(text) for i in xrange(0, lenth): if i == 0: result = result + text[i] elif i == lenth - 1: result = result + text[i] elif text[i] == ' ': result = result + text[i] elif text[i - 1] == ' ' or text[i + 1] == ' ': result = result + text[i] return result result = anti_vowel("ni hao sunasdlfk kekendfa!") print result
true
6dad0e0b1ac99cd489e20a297b8b9929a6d8b77e
Trollernator/Lesson
/app.py
929
4.25
4
#variable #data types int, float, str #input(), print(), type() # len() shows the lenght of str # upper() makes the letters BIG # lower() makes the letters smol # capitalize() captitalize the first letter # replace() replace certain letters # FirstName="Tom" # print(FirstName.find("enter search")) # a=58 # b=108 # if a>b : print("A") # else: print("B") # a = int(input("a number:")) # b = int(input("b number:")) # if a==b:print("a and b are equal") # else:print("a and b are NOT equal") # a = int(input("a number:")) # # b = int(input("b number:")) # if a<100: print("a is smaller than 100") # elif a<1000: print ("a is smaller than 1000") # else:print("a is greater than 100") a=int(input("a number:")) if a>100:print("true") else:print("false") # a=int(input("a number:")) # if a<100 and a>9: #and, or, not # print("2 digit number") # else: # print("not 2 digit number") if a%3==0:print("true") else:print("false")
true
df6dc1e87f1a2861224107bbba1c901a0b89e094
rajeshvermadav/XI_2020
/character_demo.py
376
4.3125
4
#program to display indivual character name = input("Enter any name") print("Lenght of the string is :", len(name)) print("Location or memmory address of the Character :",len(name)-1) print("Character is :", name[len(name)-6]) print("Substring is :",name[1]) print("Substring is :",name[-1]) print("Substring is :",name[::1]) print("Reverse string:", name[::-1])
true
cdc710c7c64c2029fa2b53f210689162fcaf1931
acs/python-red
/leetcode/two-sum/two-sum.py
746
4.15625
4
from typing import List, Tuple def twoSum(nums, target): twoSumTargetTuples = [] for (i, number) in enumerate(nums): for otherNumber in nums[i+1:]: print(number, otherNumber) # Move this logic to a function if (number + otherNumber) == target: if [number, otherNumber] not in twoSumTargetTuples and [otherNumber, number] not in twoSumTargetTuples: twoSumTargetTuples.append([number, otherNumber]) return twoSumTargetTuples if __name__ == '__main__': listToSum = [1, 2, 1, 0, 3] listSolution = [(1, 2)] target = 3 solution = twoSum(listToSum, target) if solution != listSolution: print(f'{solution} is not {listSolution}')
true
7f8b3ceeff28f59b0b186d3b3dbd8a7bafd24fdc
Environmental-Informatics/building-more-complex-programs-with-python-roccabye
/Program_7.1.py
2,669
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jan 28 09:55:50 2020 Lab Assignment02 ThinkPython 2e, Chapter 7: Exercise 7.1 This program finds the Square Root of a number by using the famous newton's Method approach and using the function from 'math' library. And compares the absolute values estimated from the two approach. @author: tiwari13 (Alka Tiwari) """ # Importing the required module import math # creating a function to compute sqaure root of 'a' using Newton's method. def mysqrt(a): x= a/5 #Initial estimate of square root of 'a' while True: y=(x + a/x)/2 # equation to estimate square root using newton's method. if abs(y-x)<0.0000001: # the absolute magnitude difference between 'x' and 'y' is set to 0.0000001 return(x) break x=y def test_square_root(): ''' This function tests Newton's method by comparing it with a built in function math.sqrt(). And prints a table with number ranging from 1 to 9 and second column gives Newton's method estimate of sqaure root and third column has math.sqrt() estimate and fourth colum shows the difference in the magnitude of column two and three to compare the estimates from two methods. ''' header = ['a', 'mysqrt(a)', 'math.sqtr(a)', 'diff'] # Creates the header of the table print ('{:<8s}{:<30s}{:<30s}{:<30s}'.format(header[0], header[1], header[2], header[3])) print ('{:<8s}{:<30s}{:<30s}{:<30s}'.format('-','--------','------------','----')) # to represent --- as shown in table for first row after the header. for a in range (1,10): # First Column of the table gives vallue of 'a' from 1 to 9 my_sqrt = mysqrt(a) # Second Column - Finding Square root of 'a' Using Newton's method math_sqrt = math.sqrt(a) # Third Column - Finding Square root of 'a' Using built in function diff = abs(my_sqrt - math_sqrt) # Fourth Column - to compare the estimates. lt = [a, math_sqrt, math_sqrt, diff] print ('{:<8.1f}{:<30s}{:<30s}{:<30s}'.format(lt[0], str(lt[1]), str(lt[2]), str(lt[3]))) test_square_root()
true
d6aa20a31894a3f6e94e0d964de05c0e2c232f50
RuthieRNewman/hash-practice
/hash_practice/exercises.py
2,735
4.125
4
#This is a solution that I worked out with a study group hosted by a TA and Al. It was working #until I made some changes and now I cant seem to figure out what I did or how it was #really working in the first place. I will continue to work on it but I didnt feel it was worthy #turning in fully. def anagram_helper(word1, word2): if sorted(word1) == sorted(word2): return True else: return False def grouped_anagrams(strings): hash_set = {} temp_array_strings = [] anagrams = [] for i, word1 in enumerate(strings): if word1 in hash_set: continue temp_array_strings.append(word1) hash_set[word1] = 1 for j, word2 in enumerate(strings): if anagram_helper(word1, word2): if word2 not in hash_set: temp_array_strings.append(word2) hash_set[word2] = 1 anagrams.append(temp_array_strings) print(anagrams) temp_array_strings = [] return anagrams def top_k_frequent_elements(nums, k): """ This method will return the k most common elements In the case of a tie it will select the first occuring element. Time Complexity: ? Space Complexity: ? """ freq_map = {} k_freq_elements = [] if nums: for num in nums: if num not in freq_map: freq_map[num] = 1 else: freq_map[num] += 1 for i in range(0,k): key_with_max_val = max(freq_map, key=freq_map.get) k_freq_elements.append(key_with_max_val) del freq_map[key_with_max_val] return k_freq_elements def valid_sudoku(table): """ This method will return the true if the table is still a valid sudoku table. Each element can either be a ".", or a digit 1-9 The same digit cannot appear twice or more in the same row, column or 3x3 subgrid Time Complexity: ? Space Complexity: ? """ for row in range(0,9): row_map = {} for col in range(0,9): tile = table[row][col] if tile == ".": continue elif tile not in row_map: row_map[tile] = 1 else: return False for col in range(0,9): col_map = {} for row in range (0,9): tile = table[row][col] if tile == ".": continue elif tile not in col_map: col_map[tile] = 1 else: return False return True
true
9958cd212de0d2c36d608a088f100429c95dd6ff
jadeaxon/hello
/Python/generator.py
772
4.46875
4
#!/usr/bin/env python # Python has special functions called generators. # All a generator is is an object with a next() method that resumes where it left off each time it is called. # Defining a function using yield creates a factory method that lets you create a generator. # Instead of using 'return' to return a value, you use 'yield'. # That's it! def g(step, max_steps): i = 0 steps = 0 # Steps completed. while True: if steps >= max_steps: break yield i i += step steps += 1 generator = g(3, 10) print generator.next() print generator.next() print generator.next() print generator.next() print generator.next() print generator.next() print # Generators work well in for loops. for value in g(5, 30): print value
true
711b0da87e3c90aa3fd25c9d902d2c8433d796ea
jadeaxon/hello
/Python 3/interview/singly_linked_list.py
2,260
4.21875
4
#!/usr/bin/env python3 """ A singly-linked list class that can be reversed in place. Avoids cycles and duplicate nodes in list. """ class Node(object): """A node in a singly-linked list.""" def __init__(self, value): self.next = None self.value = value class SinglyLinkedList(object): """A singly-linked list of nodes.""" def __init__(self): self.head = None self.tail = None def append(self, node): """Append a node to the end this list. No duplicates or cycles allowed.""" # Do not allow duplicate nodes in the list. n = self.head while n: if n == node: raise ValueError("illegal append of duplicate node") n = n.next if self.tail: self.tail.next = node self.tail = node node.next = None # Prevent cycles. if not self.head: self.head = node def reverse(self): """Reverse this list in place.""" head = self.head if head is None: return # Size 0. if head.next is None: return # Size 1. new_head = head.next while new_head: # A -> B -> C # h # n temp = new_head.next new_head.next = head if head == self.head: head.next = None head = new_head new_head = temp # A <- B C # t # h # n #---- # A <- B <- C # t # h # n self.tail = self.head self.head = head def __str__(self): """Render this list as a string.""" s = "" n = self.head s += "s[" while n: s += n.value n = n.next if n: s += " -> " s += "]" return s # Create a list and reverse it. sll = SinglyLinkedList() node1 = Node("A") node2 = Node("B") node3 = Node("C") node4 = Node("D") sll.append(node1) sll.append(node2) sll.append(node3) sll.append(node4) try: sll.append(node2) except ValueError: print("Okay, not adding duplicate node.") print(sll) sll.reverse() print(sll)
true
ea91e41e939909b6d58f425c36b4f4203ce7de72
jadeaxon/hello
/Python/LPTHW/example33.py
315
4.15625
4
#!/usr/bin/env python i = 0 numbers = [] while i < 6: print "At the top, i is %d." % i numbers.append(i) # i++ -- Are you joking? No ++ operator!!! i += 1 print "Numbers now: ", numbers print "At the bottom, i is %d" % i print "The numbers: " for number in numbers: print number
true
af1558e78172d696613b99a8a110d69ba8751db2
SheezaShabbir/Python-code
/Date_module.py
546
4.4375
4
#Python Dates #A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects. #Example #Import the datetime module and display the current date: import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) print(x) x = datetime.datetime(2020, 5, 17) #The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone) #but they are optional, and has a default value of 0, (None for timezone). print(x)
true
f07443f0174818f2a9abadcd724ce6b60d9ebdd1
SheezaShabbir/Python-code
/finaltestithink.py
889
4.1875
4
def str_analysis(pass_argument): if(pass_argument.isdigit()): int_conversion=int(pass_argument) if(int_conversion>90): printvalue=str(int_conversion)+" "+"is pretty big number." return printvalue elif(int_conversion<90): printvalue=str(int_conversion)+" "+"is pretty small number than expected." return printvalue else: printvalue=str(int_conversion)+" "+"is number between expected." return printvalue elif(pass_argument.isalpha()): printvalue=pass_argument+" "+"is all alphabetical characters!" return printvalue else: printvalue=pass_argument+" "+"neither all alpha nor all digit." return printvalue while True: stro=input("enter a word or a digit:") if(stro!=""): print(str_analysis(stro)) break
true
6a20b87f76f5e01dab9552208c1a42b197199e9a
jmavis/CodingChallenges
/Python/DecimalToBinary.py
1,796
4.3125
4
#--------------------------------------------------------- # Author: Jared Mavis # Username: jmavis # Problem name: Decimal To Binary # Problem url: https://www.codeeval.com/open_challenges/27/ #--------------------------------------------------------- import sys import math #--------------------------------------------------------- # Function definitions #--------------------------------------------------------- def FindLargestPowerOf2(num): """ Will find the largest power of 2 that will fit inside the given number.""" return (math.floor(math.log(num,2))) # end FindLargestPowerOf2() def DecimalToBinary(num): """ Will convert the given decimal number to binary. *Note bin(num) will give the binary representation but for fun I made this function. """ currentPower = FindLargestPowerOf2(num) currentNumber = num while (currentPower >= 0): powerOf2 = math.pow(2, currentPower) currentPower -= 1 if (powerOf2 <= currentNumber): currentNumber -= powerOf2 sys.stdout.write('1') else: sys.stdout.write('0') print # end DecimalToBinary() def ParseLine(line): """ Reads the line and will call CountNumOneBits with the appropriate arguments""" DecimalToBinary(int(line)) # end ParseLine() def ReadFile(file): """ Reads in and parses the lines of the given file""" for line in file.readlines(): line = line.rstrip() #remove endline ParseLine(line) #end ReadFile() #--------------------------------------------------------- # Running Test Cases #--------------------------------------------------------- test_cases = open(sys.argv[1], 'r') ReadFile(test_cases) test_cases.close()
true
b2d2dd3baed364c81e22d193586c21f0abbd56d0
jmavis/CodingChallenges
/Python/Star.py
898
4.4375
4
#------------------------------------------------------------------------------ # Jared Mavis # jmavis@ucsc.edu # Programming Assignment 2 # Star.py - Creates an n-pointed star based on user input #------------------------------------------------------------------------------ import turtle numPoints = int(input("Enter an odd integer greater than or equal to 3: ")) if (numPoints < 3 or numPoints%2 == 0): raise ValueError("Enter an odd integer greater that or equal to 3") angle = (180 - (180 / numPoints)) window = turtle.Screen() window.title(str(numPoints)+"-pointed star") drawer = turtle.Turtle() drawer.pensize(2) drawer.color("blue", "green") drawer.backward(150) drawer.speed(0) drawer.begin_fill() for i in range(numPoints): drawer.forward(300) drawer.dot(10, "red") drawer.right(angle) drawer.end_fill() drawer.hideturtle() window.mainloop();
true
daaf1572ef7bf3971cd3a1e27c3397622aa0a172
schoentr/data-structures-and-algorithms
/code-challanges/401_code_challenges/linked_list/linked_list.py
2,852
4.25
4
from copy import copy, deepcopy class LinkedList(): head = None def __init__(self, iterable=None): """This initalizes the list """ self.head = None if iterable: for value in iterable: self.insert(value) def __iter__(self): """This makes the linked list iterable """ current = self.head while current: yield current.value current = current._next def __add__(self, iterable): """This makes it able to add an iterable to the linked-list """ new_list = deepcopy(self) for value in iterable: new_list.insert(value) return new_list def __iadd__(self, value): """This method makes it able to use "+="to add value to linked list Arguments: value -- [data to be added to the linked list] """ self.insert(value) return self def insert(self, value): """This Method inserts a value into the Linked List Arguments: value -- the value being expresessed as value in the node """ node = Node(value) if not self.head: self.head = node else: current = self.head while current._next: current = current._next current._next = node def includes(self, value): """[summary] Arguments: value -- [the value being expressed as value in the node] Returns: [Boolean] -- [True if value is in the Linked list // False if not in list] """ current = self.head while current._next: if current.value == value: return True current = current._next return True def print(self): """ This method prints the values of all nodes in the list Returns: [string] -- [ A string containg comma seperated values of the list] """ output = '' current = self.head while current: output += current.value + ', ' current = current._next return output def find_from_end(self, value): length = 0 curr = self.head while curr: length += 1 curr = curr._next distance = length - value - 1 curr = self.head if length > value: for x in range(0, distance): curr = curr._next return curr.value else: return 'exception' class Node(): def __init__(self, value): """Creates all nodes for the list Arguments: value -- [Any value you want to be held in the node] """ self.value = value self._next = None
true
78a6e7972a8960932922e1aad5982183086a8670
schoentr/data-structures-and-algorithms
/code-challanges/401/trees/fizzbuzz.py
809
4.15625
4
from tree import BinaryTree def fizzbuzz (self, node = None): """ This Method traverses across the tree in Order. Replacing the value if divisable by 3 to Fizz, if divisibale by 5 to buzz and if divisiable by both 3 and 5 to fizzbuzz """ rtn = [] if node is None: node= self.root if node.child_left: rtn += self.fizzbuzz(node.child_left) if (int(node.value) % 3 == 0) and (node.value % 5 == 0) : node.value = 'fizzbuzz' elif int(node.value) % 3 is 0: node.value = 'fizz' elif int(node.value) % 5 is 0: node.value = 'buzz' rtn.append(node.value) if node.child_right: rtn += self.fizzbuzz(node.child_right) return rtn
true
8e3a079278d9a5c59df34cbbe77c2b10a47449f6
schoentr/data-structures-and-algorithms
/code-challanges/401_code_challenges/sorts/radix_sort/fooradix_sort.py
2,103
4.125
4
def radix_sort(inpt_list, base=10): """This sort takes in a list of positive numbers and returns the list sorted in place. Arguments: inpt_list {[list]} -- [Unsorted List] Keyword Arguments: base {int} -- [description] (default: {10}) Returns: [list] -- [Sorted List] """ if inpt_list == []: return def key_factory(digit, base): """This fuction creates the keys. Arguments: digit {[type]} -- [description] base {[type]} -- [description] Returns: [type] -- [description] """ def key(alist, index): """This helper function takes in the unsorted list and and index and returns the digit at that location. Arguments: alist {list} -- [unsorted list] index {int} -- [index of list to be evaluated] Returns: [int] -- [the digit that is in the place being evaluated] """ return ((inpt_list[index]//(base**digit)) % base) return key largest = max(inpt_list) exp = 0 while base**exp <= largest: # checks to see if all values have been covered inpt_list = count_sort(inpt_list, key_factory(exp, base)) exp = exp + 1 return inpt_list def count_sort(inpt_list, key): """ This sorts a list by counting the number of occurances a given digt occurs, Arguments: inpt_list {list} key {int} list_range {int} Returns: [list] """ list_range = 9 count_list = [0]*(list_range + 1) for i in range(len(inpt_list)): count_list[key(inpt_list, i)] = count_list[key(inpt_list, i)] + 1 count_list[0] = count_list[0] - 1 for i in range(1, list_range + 1): count_list[i] = count_list[i] + count_list[i - 1] result = [None]*len(inpt_list) for i in range(len(inpt_list) - 1, -1, -1): result[count_list[key(inpt_list, i)]] = inpt_list[i] count_list[key(inpt_list, i)] = count_list[key(inpt_list, i)] - 1 return result
true
c0a814a1761bd9b11510500386eee4044f4f3d75
abhinab1927/Data-structures-through-Python
/ll.py
1,631
4.21875
4
class Node: def __init__(self,val): self.next=None self.value=val def insert(self,val): if self.value: if self.next is None: self.next=Node(val) else: self.next.insert(val) else: self.value=val def print_ll(self): if self.value: while self.next!= None: print(self.value) self=self.next print(self.value) else: print("LL is empty") def delete(self,val): i=0 while self.value!=val and self.next!=None: i+=1 self=self.next if self.next!=None: print("position is ",i)#find the index of value self=n1 for j in range(0,i-1): #travel to the node before it self=self.next k=self #Store the previous position in a variable l=self k=k.next.next #take another variable and store the next value of the element to be deleted l.next=k '''Eliminate the current node by pointing the next value of the previous node to the next value of the element to be deleted''' else: print("Element Not found") n1=Node(5) n1.insert(12) n1.insert(4) n1.insert(6) n1.insert(15) print("Before deleting") n1.print_ll() n1.delete(6) print("After deleting") n1.print_ll() n1.delete(163)
true
e556737d693fb598ee89751696aa05ff4b791e9a
moemaair/Problems
/stacks/python/sort_stack.py
2,680
4.1875
4
from Stack import Stack from Stack import build_stack_from_list """ Sort Stack Write a method to sort a stack in ascending order Approaches: 1) 3 stacks - Small, Large, Current 2) Recursive - Sort and Insertion Sort """ def sort_stack_recursive(stack): if len(stack) == 0: return elem = stack.pop() sort_stack_recursive(stack) insert(stack, elem) def insert(stack, elem): """Insertion Sort for Stacks!""" if len(stack) == 0: stack.append(elem) else: top = stack.pop() #To reverse a stack just remove this conditional if top >= elem: stack.append(top) stack.append(elem) else: insert(stack, elem) stack.append(top) def sort_stack(stack): large = Stack() small = Stack() while not stack.is_empty() or not small.is_empty(): while not stack.is_empty(): value = stack.pop() if large.is_empty() or small.is_empty(): if stack.peek() is None: large.push(value) elif value > stack.peek(): large.push(value) small.push(stack.pop()) else: large.push(stack.pop()) small.push(value) elif value > large.peek(): small.push(large.pop()) large.push(value) else: small.push(value) tmp = stack stack = small small = tmp return large #Tests def test_sort_stack(): inputstack = build_stack_from_list([3,4,1]) outputstack = sort_stack(inputstack) answerstack = build_stack_from_list([4,3,1]) assert answerstack.equals(outputstack) == True def test_sort_stack_big(): inputstack = build_stack_from_list([3,6,2,9,10,4,1,-4,6]) outputstack = sort_stack(inputstack) outputstack.display() answerstack = build_stack_from_list([10,9,6,6,4,3,2,1,-4]) assert answerstack.equals(outputstack) == True def test_sort_stack_1_element(): inputstack = build_stack_from_list([3]) outputstack = sort_stack(inputstack) answerstack = build_stack_from_list([3]) assert answerstack.equals(outputstack) == True def test_sort_stack_empty(): inputstack = build_stack_from_list([]) outputstack = sort_stack(inputstack) answerstack = build_stack_from_list([]) assert answerstack.equals(outputstack) == True def test_sort_stack_recursive(): s1 = [8,3,1,4,2,5,9,7,6] outputstack = [9,8,7,6,5,4,3,2,1] sort_stack_recursive(s1) assert s1 == outputstack if __name__ == "__main__": test_sort_stack() test_sort_stack_1_element() test_sort_stack_empty() test_sort_stack_big() test_sort_stack_recursive()
true
176d58d5bd2b5c3148c3882d9010a9be36568071
moemaair/Problems
/strings/python/is_rotation.py
2,181
4.375
4
#Cases """ 1) Empty string 2) Normal is rotation 1-step 3) Normal is rotation multistep 4) Normal no rotation same chars 5) 1,2,3+ length 6) Strings not same length == False """ #Approaches """ 1) Submethod called "rotate" which rotates string one-place, main method rotates str2 len(str1) times, checks if strings are equal 2) Loop through str1 one time, if str2[i] == str1[i] then increment both and keep going. If you reach a str2[i] that doesn't match str1[i], you start from beginning, where str1[i] == str2[i+1]. If you reach end of str1 with all equal, return True """ def rotate_string(str1): #rotate 1 place if len(str1) < 2: return str1 return str1[-1] + str1[:-1] def is_rotation(str1, str2): if len(str1) != len(str2): return False if len(str1) == 0: return True i = 0 while i < len(str1): if str1 == str2: return True str2 = rotate_string(str2) i+=1 return False def is_rotation_loops(str1, str2): if len(str1) != len(str2): return False if len(str1) == 0: return True attempts = len(str1) str1_pos = 0 str2_pos = 0 str2_start = 0 are_rotations = True while attempts > 0 and str1_pos < len(str1): are_rotations = True if str2_pos == len(str1): str2_pos = 0 if str1[str1_pos] != str2[str2_pos]: are_rotations = False str2_start += 1 str2_pos = str2_start str1_pos = 0 attempts -= 1 else: str1_pos += 1 str2_pos += 1 return are_rotations #Tests def test_rotate_string(): assert rotate_string("ABC") == "CAB" assert rotate_string("BA") == "AB" assert rotate_string("") == "" assert rotate_string("A") == "A" def test_is_rotation(): assert is_rotation("ABC","CAB") == True assert is_rotation("ABC","BCA") == True assert is_rotation("","") == True assert is_rotation("AABB", "ABAB") == False assert is_rotation("A","A") == True def test_is_rotation_loops(): assert is_rotation_loops("ABC","CAB") == True assert is_rotation_loops("ABC","BCA") == True assert is_rotation_loops("","") == True assert is_rotation_loops("AABB", "ABAB") == False assert is_rotation_loops("A","A") == True if __name__ == "__main__": test_rotate_string() test_is_rotation() test_is_rotation_loops()
true
e37c22e6e03c1a576b264ae00769edbf084fcc4b
moemaair/Problems
/graphs/python/pretty_print.py
1,411
4.125
4
from Graph import Graph from Graph import build_test_graph from Vertex import Vertex """ Pretty Print Starting with a single Vertex, implement a method that prints out a string representation of a Graph that resembles a visual web Approach: 1) Using BFS, extract all unique vertices from the graph into set 2) Loop through vertices, plot each vertex into a arbitrary coordinates in matrix 3) Rearrange vertices in matrix until correctly positions 4) Pass matrix into format string method to print output """ def extract_vertices(vertex): """ Input: starting Vertex, value to find Output: return closest Vertex that contains value Graph is a digraph. So it has cycles. Values can repeat. """ neighbors = [] visited = set() #all unique elements neighbors.append(vertex) while len(neighbors) > 0: vertex = neighbors.pop(0) for neighbor in vertex.neighbors: if neighbor not in visited: neighbors.append(neighbor) visited.add(neighbor) return visited def plot_to_array(vertices): return [] def pretty_print(vertices_arr=[]): print vertices_arr def test_pretty_print(): graph = build_test_graph() graph.pretty_print() vertices = graph.vertices v1 = vertices[0] #A v2 = vertices[1] #B v3 = vertices[2] #C v4 = vertices[3] #D v5 = vertices[4] #E vertices_set = extract_vertices(graph.vertices[0]) print vertices_set if __name__ == "__main__": test_pretty_print()
true
469a59d991f878a9a668df228b310a9d633a60f4
moemaair/Problems
/stacks/python/stacks_w_array.py
1,569
4.125
4
from Stack import Stack from Node import Node """ Stacks with Array Implement 3 stacks using a single array Approaches 1) Index 0, 3, 6.. first stack. 1, 4, 7.. second stack. 2, 5, 8.. third stack. """ class StacksWithArray(object): def __init__(self): self.array = [None for x in range(99)] # Represent next available open position self.stack_positions = { 0 : 0, 1 : 1, 2 : 2 } self.INCREMENT = 3 def push(self, stackno, value): """ Find the current open position in array of the stack (0-2) requested by client Add value, then increment to next open position """ index = self.stack_positions[stackno] self.array[index] = value self.stack_positions[stackno] += self.INCREMENT print "stack positions = " + str(self.stack_positions) print "array values = " + str(self.array) def pop(self, stackno): index = self.stack_positions[stackno] if index > stackno: self.stack_positions[stackno] -= self.INCREMENT index = self.stack_positions[stackno] value = self.array[index] self.array[index] = None print "stack positions = " + str(self.stack_positions) print "array values = " + str(self.array) return value #Tests def test_basic_ops(): stack = StacksWithArray() stack.push(0,"A") stack.push(1,"B") stack.push(2,"C") stack.push(0,"A") stack.push(0,"A") stack.push(0,"A") stack.pop(0) stack.pop(0) stack.pop(0) stack.push(0,"A") stack.pop(1) stack.pop(1) stack.pop(1) stack.pop(2) stack.pop(2) stack.pop(0) stack.pop(0) stack.pop(0) if __name__ == "__main__": test_basic_ops()
true
1043391288e9b6b26e2feeff248cee4ebefcc085
moemaair/Problems
/stacks/python/evaluate_expression.py
2,374
4.3125
4
from Stack import Stack """ Evaluate Expression Evaluate a space delimited mathematical that includes parentheses expression. e.g. "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )" == 101 Approaches: 1) Use two stacks, one for operators, one for operands. If you get to close paren?, then pop last two operands off and combine using last operator. Pop operator and continue. At end of string, pop result of operands Questions: 1) Supported operators? 2) Always balanced parenthesese + equations? 3) Empty or one element equations? 4) Integers only? Examples: (1 + 1) 2 ___ ___ (1 + (2 * 5) + 3) 14 ___ ___ ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) ) 101 ___ ___ """ def evaluate_exp(exp): SUPPORTED_OPERATORS = "+*-//" OPERANDS_REGEX = "" #For now we assume if NOT operator, then operand operators_stack = Stack() operands_stack = Stack() exp_list = exp.split() #splits by space default for char in exp_list: if char in SUPPORTED_OPERATORS: operators_stack.push(char) elif char == ")": right_operand = operands_stack.pop() left_operand = operands_stack.pop() operator = operators_stack.pop() operands_stack.push(math_mapper(operator, left_operand, right_operand)) elif char == "(": continue #do nothing else: operands_stack.push(int(char)) #assume operand, convert to int #return final remaining on operands stack return operands_stack.pop() def math_mapper(operator, left_operand, right_operand): if operator == "+": return left_operand + right_operand elif operator == "-": return left_operand - right_operand elif operator == "*": return left_operand * right_operand elif operator == "/": return left_operand / right_operand elif operator == "//": return left_operand // right_operand elif operator is None: #Only one value left, return right operand return right_operand else: raise Exception("Unknown operator " + operator) # Tests def test_evaluate_exp(): exp1 = "( 1 )" exp2 = "( 1 + 1 )" exp3 = "( ( 1 + ( 2 * 5 ) ) + 3 )" exp4 = "( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )" exp5 = "( ( 1 + ( 2 * 5 ) ) - 3 )" exp6 = "( ( 1 - ( 10 / 5 ) ) * ( 3 + 6 ) )" assert evaluate_exp(exp1) == 1 assert evaluate_exp(exp2) == 2 assert evaluate_exp(exp3) == 14 assert evaluate_exp(exp4) == 101 assert evaluate_exp(exp5) == 8 assert evaluate_exp(exp6) == -9 if __name__ == "__main__": test_evaluate_exp()
true
8ba5229b9bf24c36eec6fc113b1b020064b8ed87
artopping/nyu-python
/course2/session2/classses_session2.py
710
4.4375
4
#!/usr/bin/env python3 #Classes: storage of data and set of functions that define the class # class has a function and data (local to itself) # when you want to use it< instance= MyClass()> class MyClass: pass #obect my_circle as instance of Class circle # think of class as bucket...lot of room, for data storage and defs # class Circle: pi = 3.14159 def __init__(self, radius=1): #self is container that everything is placed in self.radius=radius def area(self): #return self.radius**2 *3.14159 return self.radius**2 * Circle.pi #using the global class if __name__=='__main__': my_circle = Circle(2) print (my_circle.area()) my_circle.radius=10 print (2*3.14159*my_circle.radius)
true
89db7f6519f2542bec43ceecaa3be231b1e429af
vivekgupta8983/python3
/range.py
269
4.21875
4
#!/usr/bin/python3 #range functions returns a sequence for number start from o and ends ta specific number #range(start, stop, step) # for i in range(100): # print(i) # for i in range(2, 10, 2): # print(i) my_range = range(1, 10) print(my_range.index(3))
true
064cb46b734706c23c60ce872fb16fccecee22a4
nikileeyx/learning_python
/2. Dictionary and List/2002_codeReusing.py
842
4.34375
4
#The Code Reusing 1.0 by @codingLYNX ''' Note: In this question, 0 is considered to be neither a positive number nor negative number. You are to implement the following three functions with the following specifications: is_odd(x) returns True if the input parameter x is odd, False otherwise. is_negative(x) returns True if the input parameter x is negative, False otherwise. is_even_and_positive(x) returns True if the input parameter x is even AND positive, False otherwise. ''' def is_odd(x): if x%2 == 0: return False else: return True def is_negative(x): if x < 0: return True else: return False def is_even_and_positive(x): if x == 0: return False elif is_odd(x) or is_negative(x): return False else: return True
true
690f4504114a972a0c3aa1b2021b820880eff724
kmurphy13/algorithms-hw
/dac_search.py
736
4.1875
4
# Kira Murphy # CS362 HW2 def dac_search(lst: list, key) -> bool: """ Function that searches for an item in an unsorted array by splitting the array into halves and recursively searching for the item in each half :param lst: The unsorted array :param key: The item being searched for :return: True if the item is in the list, false otherwise """ if len(lst) == 1: if lst[0] == key: return True else: return False return dac_search(lst[:len(lst)//2], key) or dac_search(lst[len(lst)//2:len(lst)], key) if __name__ == "__main__": lst = [138, 0, 3, 36, 29, 13, 9, 12, 110, 1, 0, 12, 5, 0, 1, 0, 1, 1, 4, 11, 52, 12, 2, 1, 2, 4, 99] print(dac_search(lst,99))
true