blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
526e53e4c97cbc694fe7c776e1199144d7c540ff
eliasdabbas/advertools
/advertools/word_tokenize.py
2,752
4.53125
5
""" .. _word_tokenize: Tokenize Words (N-grams) ======================== As word counting is an essential step in any text mining task, you first have to split the text into words. The :func:`word_tokenize` function achieves that by splitting the text by whitespace. Another important thing it does after splitting is to trim the words of any non-word characters (commas, dots, exclamation marks, etc.). You also have the option of specifying the length of the words that you want. The default is 2, which can be set through the :attr:`phrase_len` parameter. This function is mainly a helper function for :ref:`word_frequency <word_frequency>` to help with counting words and/or phrases. """ from .regex import WORD_DELIM def word_tokenize(text_list, phrase_len=2): """Split ``text_list`` into phrases of length ``phrase_len`` words each. A "word" is any string between white spaces (or beginning or end of string) with delimiters stripped from both sides. Delimiters include quotes, question marks, parentheses, etc. Any delimiter contained within the string remains. See examples below. :param text_list: List of strings. :param phrase_len: Length of word tokens, defaults to 2. :return tokenized: List of lists, split according to :attr:`phrase_len`. >>> t = ['split me into length-n-words', ... 'commas, (parentheses) get removed!', ... 'commas within text remain $1,000, but not the trailing commas.'] >>> word_tokenize(t, 1) [['split', 'me', 'into', 'length-n-words'], ['commas', 'parentheses', 'get', 'removed'], ['commas', 'within', 'text', 'remain', '$1,000', 'but', 'not', 'the', 'trailing', 'commas']] The comma inside "$1,000" as well as the dollar sign remain, as they are part of the "word", but the trailing comma is stripped. >>> word_tokenize(t, 2) [['split me', 'me into', 'into length-n-words'], ['commas parentheses', 'parentheses get', 'get removed'], ['commas within', 'within text', 'text remain', 'remain $1,000', '$1,000 but', 'but not', 'not the', 'the trailing', 'trailing commas']] >>> word_tokenize(t, 3) [['split me into', 'me into length-n-words'], ['commas parentheses get', 'parentheses get removed'], ['commas within text', 'within text remain', 'text remain $1,000', 'remain $1,000 but', '$1,000 but not', 'but not the', 'not the trailing', 'the trailing commas']] """ if isinstance(text_list, str): text_list = [text_list] split = [text.lower().split() for text in text_list] split = [[word.strip(WORD_DELIM) for word in text] for text in split] return [[' '.join(s[i:i + phrase_len]) for i in range(len(s) - phrase_len + 1)] for s in split]
true
92cb8099b670c5861621f7cb2d264f40144c6205
jtwong1/math361
/python-code/week1to3/intro_vectorize.py
1,719
4.34375
4
"""Vectorization (in numpy) and append vs. pre-allocation example. Calculates x*sin(x) for a large number of x's. - Note that the vectorized operation is much faster than a for loop. - Appending tends to be a bit slower than pre-allocating. - the numpy array append is *extremely slow* (its not recommended for use) """ import numpy as np from time import perf_counter as timer if __name__ == '__main__': nvals = 10**6 print("computation for {} values: \n".format(nvals)) # 1. vectorized calculation using numpy arrays x = np.linspace(0.0, 1.0, nvals) start = timer() y = np.sin(x)*x # np arith. operations are vectorized! end = timer() print('vectorized time: {:.4} s\n'.format(end-start)) # 2. not vectorized; using a for loop but pre-allocating space start = timer() y = np.zeros(nvals) for n in range(0, nvals): # for loop is slower than vectorized version y[n] = np.sin(x[n])*x[n] end = timer() print('for loop time: {:.4} s\n'.format(end-start)) # 3. not vectorized; growing a python list per iteration start = timer() y = [] for n in range(0, nvals): # append for python lists is fast... y.append(np.sin(x[n])*x[n]) end = timer() print('python list append time: {:.4} s\n'.format(end-start)) # 4. not vectorized; growing a numpy array (AVOID THIS!) # (numpy arrays are not intended to be variable size) nvals = 50000 start = timer() y = np.array([]) for n in range(0, nvals): # ... but append for numpy arrays is NOT FAST y = np.append(y, np.sin(x[n])*x[n]) end = timer() print('np.append time (for n={}): {:.4} s\n'.format(nvals, end-start))
true
c3839667a5ac0d42cf7aeedaa77fd44f342827b5
jtwong1/math361
/python-code/week1to3/hw2_template.py
1,669
4.34375
4
""" HW 2 template code: - newton's method - example for the reivew problem. """ import numpy as np import matplotlib.pyplot as plt def make_2d_array(): """ quick example for review: creating 2d arrays and indexing. """ # version 1: list of lists (rows) v1 = [[0 for j in range(3)] for k in range(3)] # version 2: numpy array v2 = np.zeros((3, 3)) # slight variation on v1: v3 = [[0]*3 for k in range(3)] # note indexing scheme differs for nump arrays print("(1,1) element: {}, {}", v1[1][1], v2[1, 1]) return v1, v2, v3 def newton(f, df, x, tol, max_iter=50): """ ... Inputs: ... Returns: x: the approximate root it: the number of iterations taken seq: the sequence of iterates """ it = 0 # (you can rename these; placeholder values) seq = [1, 2, 3, 4] while False: pass # ...newton's method here... return x, it, seq def func(x): return x**3 - 2 def dfunc(x): return 3*x**2 if __name__ == '__main__': # ---- Problem C2b ---- exact = 2**(1.0/3) x0 = 1 x, it, seq = newton(func, dfunc, x0, 1e-12) plt.figure(figsize=(3.5, 3)) # plot size is in inches nvals = np.arange(0, len(seq)) plt.plot(nvals, seq, '.-k', markersize=8) # see plotting example for formatting info # note that the log-log plot command is plt.loglog(...) # (use that to ensure the output has a nice size/format when submitting) # (the figure is submitted with the written portion's pdf) # placeholder print statement print('answer: {:.16f} in {} iterations.'.format(x, it))
true
25c3f21e5aeb6ab6116f09f43ee24598c05c895c
Cheese229/DataAssignmentCIS
/color_change.py
2,123
4.28125
4
""" Code source here: https://stackoverflow.com/questions/40160808/python-turtle-color-change Trying to see how this person uses turtle.stamp to change the color of their turtles I cannot seem to make sense out of it, or at least be able to use some sort of form out of this ;-; """ from turtle import Turtle, Screen from random import randrange, choice from collections import namedtuple from math import ceil GRID = 15 # GRID by GRID of squares SIZE = 30 # each square is SIZE by SIZE INCREASE = 1.5 # how much to lighten the square's color WHITE = [255, 255, 255] # color at which we stop changing square DELAY = 100 # time between calls to change() in milliseconds DARK = 32 # range (ceil(INCREASE) .. DARK - 1) of dark colors def change(): block = choice(blocks) blocks.remove(block) color = [min(int(primary * INCREASE), WHITE[i]) for i, primary in enumerate(block.color)] # lighten color turtle.color(color) turtle.setposition(block.position) turtle.clearstamp(block.stamp) stamp = turtle.stamp() if color != WHITE: blocks.append(Block(block.position, color, stamp)) # not white yet so keep changing this block if blocks: # stop all changes if/when all blocks turn white screen.ontimer(change, DELAY) HALF_SIZE = SIZE // 2 screen = Screen() screen.colormode(WHITE[0]) screen.register_shape("block", ((HALF_SIZE, -HALF_SIZE), (HALF_SIZE, HALF_SIZE), (-HALF_SIZE, HALF_SIZE), (-HALF_SIZE, -HALF_SIZE))) screen.tracer(GRID ** 2) # ala @PyNuts turtle = Turtle(shape="block", visible=False) turtle.speed("fastest") turtle.up() Block = namedtuple('Block', ['position', 'color', 'stamp']) blocks = list() HALF_GRID = GRID // 2 for x in range(-HALF_GRID, HALF_GRID): for y in range(-HALF_GRID, HALF_GRID): turtle.goto(x * SIZE, y * SIZE) color = [randrange(ceil(INCREASE), DARK) for primary in WHITE] turtle.color(color) blocks.append(Block(turtle.position(), color, turtle.stamp())) screen.ontimer(change, DELAY) screen.exitonclick()
true
965d37e82c4b4d75020c5ac1501d653e0da7e733
AadityaAgarwal/NumberGuessing
/NumberGuessing.py
534
4.1875
4
chance=5 ans=8 print("number Guessing Game") print("Choose a number (between 0-9)") while (chance>=0): inputAnswer=int (input("Enter Your Guess:- ")) if(inputAnswer<=7): chance-=1 print("Guess a number greater then ",inputAnswer ) elif(inputAnswer==8): print("Congratulations!! You won") break elif(inputAnswer==9): print("Enter a number less than 9") chance-=1 if(chance==0): print("You lost....the correct answer is ",ans) break
true
2360adde9f7da57626a0efc9e672dadcd5f7486d
prayas2409/Machine_Learning_Python
/Week2/StringQ4.py
615
4.21875
4
flag: bool = True while flag: try: string1 = input("Enter a string") # checking if the length is more than 3 if string1.__len__() < 3: print("no change") else: if string1.endswith("ing"): # if already has ing string1 += 'ly' else: string1 += 'ing' print(string1) except IndexError: print(string1) except Exception as e: print("Process stopped because %s" % e) print("To exit press 0 else press any other number") if input() == 0: flag = False
true
1eb262666fee0981fe5baf531ced23961431c54b
crwandle/AutoRockClimber
/decisionengine/min_heap.py
1,443
4.28125
4
import heapq class MinHeap(object): """ Class to keep track of where everything is in the priority queue. """ def __init__(self): self.heap = [] self.items = {} self.counter = 0 def is_empty(self): """Returns whether priority queue is true or not. Returns: bool: True if empty """ return not self.counter > 0 def insert(self, item, priority): """Inserts item and into the priority queue with its priority. Args: item (char || tuple): Node to be inserted priority (int): Priority of given item """ if item in self.items: self.remove(item) entry = [priority, item, True] self.counter += 1 self.items[item] = entry heapq.heappush(self.heap, entry) def remove(self, item): """Removes item from heap Args: item (char || tuple): Node to be removed """ entry = self.items[item] entry[-1] = False self.counter -= 1 def del_min(self): """Pops the node with the highest priority. Returns: char || tuple: The node with highest priority """ while self.heap: _, item, is_active = heapq.heappop(self.heap) if is_active: self.counter -= 1 del self.items[item] return item
true
96b0f6d10c1b6f643defb23f2bdebdeeb837724e
npmitchell/lepm
/lepm/timing.py
1,458
4.125
4
from timeit import default_timer as timer import sys '''Custom functions for handling timing of function execution ''' def timefunc(func, *args, **kwargs): """Time a function. Parameters ---------- func : function the function to time, which accepts arguments *args and **kwargs. Note that the function cannot have a kwarg called 'iterations' *args : arguments passed to func arguments passed to func **kwargs : keyword arguments passed to func keyword arguments passed to func iterations : int or None (default=3) The number of times to run the function, to get best and worst time (similar to timeit) Returns ------- result : output of func shortest : float the shortest time to execute, out of 'iterations' iterations longest : float the longest time to execute, out of 'iterations' iterations """ try: iterations = kwargs.pop('iterations') except KeyError: iterations = 3 shortest = sys.maxsize longest = 0.0 for _ in range(iterations): start = timer() result = func(*args, **kwargs) shortest = min(timer() - start, shortest) longest = max(timer() - start, longest) print('Best of {} {}(): {:.9f}'.format(iterations, func.__name__, shortest) + ', ' + 'Worst of {} {}(): {:.9f}'.format(iterations, func.__name__, longest)) return result, shortest, longest
true
774c287a0ea1908c42f418aa51f463d670b642bb
RickXie747/UNSW-18S1-COMP9021-
/Quiz6/Quiz6_2.py
2,687
4.28125
4
# Defines two classes, Point() and Triangle(). # An object for the second class is created by passing named arguments, # point_1, point_2 and point_3, to its constructor. # Such an object can be modified by changing one point, two or three points # thanks to the method change_point_or_points(). # At any stage, the object maintains correct values # for perimeter and area. # # Written by *** and Eric Martin for COMP9021 from math import sqrt class PointError(Exception): def __init__(self, message): self.message = message class Point(): def __init__(self, x=None, y=None): if x is None and y is None: self.x = 0 self.y = 0 elif x is None or y is None: raise PointError('Need two coordinates, point not created.') else: self.x = x self.y = y # Possibly define other methods class TriangleError(Exception): def __init__(self, message): self.message = message class Triangle: def __init__(self, *, point_1, point_2, point_3): if (point_1.y - point_2.y) * (point_1.x - point_3.x) == (point_1.y - point_3.y) * (point_1.x - point_2.x): raise TriangleError('Incorrect input, triangle not created.') self.point_1 = point_1 self.point_2 = point_2 self.point_3 = point_3 self.perimeter, self.area = self.get_perimeter_area() def change_point_or_points(self, *, point_1=None, point_2=None, point_3=None): point_1 = point_1 if point_1 else self.point_1 point_2 = point_2 if point_2 else self.point_2 point_3 = point_3 if point_3 else self.point_3 if (point_1.y - point_2.y) * (point_1.x - point_3.x) != (point_1.y - point_3.y) * (point_1.x - point_2.x): self.point_1 = point_1 self.point_2 = point_2 self.point_3 = point_3 else: print('Incorrect input, triangle not modified.') self.perimeter, self.area = self.get_perimeter_area() def get_perimeter_area(self): distance_p1p2 = sqrt((self.point_1.x - self.point_2.x) ** 2 + (self.point_1.y - self.point_2.y) ** 2 ) distance_p1p3 = sqrt((self.point_1.x - self.point_3.x) ** 2 + (self.point_1.y - self.point_3.y) ** 2) distance_p2p3 = sqrt((self.point_2.x - self.point_3.x) ** 2 + (self.point_2.y - self.point_3.y) ** 2) half_perimeter = (distance_p1p2 + distance_p1p3 + distance_p2p3) / 2 area = sqrt(half_perimeter * (half_perimeter - distance_p1p2) * (half_perimeter - distance_p1p3) \ * (half_perimeter - distance_p2p3)) return distance_p1p2 + distance_p1p3 + distance_p2p3,area
true
834b74bd014798e1e4d046329701447d14d9dd80
raychenon/algorithms
/python3/algorithms/leetcode/rotate_matrix.py
769
4.125
4
#!/bin/python3 from typing import List def rotate(matrix: List[List[int]]) -> None: """ https://leetcode.com/problems/rotate-image Time complexity: O(n^2) Space complexity: O(1) :param matrix: :return: """ n = len(matrix[0]) # in Python // is floor division to divide then round down for i in range(n // 2 + n % 2): for j in range(n // 2): temp = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - i - 1][n - j - 1] # matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = matrix[i][j] matrix[i][j] = temp if __name__ == "__main__": assert rotate([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
false
984b94a305bd42c760dd5f405b2927c57f9f0f6f
Sheersha-jain/Tree
/all-path-tree.py
1,053
4.15625
4
# print all the path from root to leaf of binary tree. class Root: def __init__(self, value): self.left = None self.right = None self.key = value def printpath(parent_node): path = [] printpathtrail(parent_node, path, 0) def printpathtrail(parent_node, path, path_length): if parent_node is None: return 0 if len(path)>path_length: path[path_length]=parent_node.key else: path.append(parent_node.key) path_length += 1 if parent_node.left is None and parent_node.right is None: printfinalpath(path, path_length) else: printpathtrail(parent_node.left, path, path_length) printpathtrail(parent_node.right, path, path_length) def printfinalpath(ints, len): for i in ints[0:len]: print(i, " ", end="") print() if __name__ == "__main__": root_node = Root(1) root_node.left = Root(2) root_node.right = Root(3) root_node.left.right = Root(55) root_node.left.right.left = Root(900) print(printpath(root_node))
true
8c60e441224076c52b1f182a17e2ee954c548202
ChristopherSClosser/code-katas
/src/mult_3_5.py
437
4.25
4
"""Kata: Multiples of 3 and 5. List all the natural numbers that are multiples of 3 or 5. - **URL**: [challenge url](https://www.codewars.com/kata/multiples-of-3-and-5) #1 Best Practices Solution by zyxwhut & others def solution(number): return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0) """ def solution(num): """Run(s) nice and fast.""" return sum(set(list(range(0, num, 3)) + list(range(0, num, 5))))
true
4b70e45b7bce4bcc481988c29d68e1b3da3ba041
AnGela-CoDe/Task-three
/One.py
1,466
4.1875
4
a=int(input('Введите координату точки по оси OX неравную нулю ')) """Попросим пользователя ввести первую координату неравную нулю с помощью функции input.Это будет наша первая переменная а, которая имеет целочисленный тип.""" b=int(input('Введите координату точки по оси OY неравную нулю ')) """Попросим пользователя ввести вторую координату неравную нулю с помощью функции input.Это будет наша вторая переменная b, которая имеет целочисленный тип.""" if a==0 or b==0: print('Просьба ввести координаты неравные нулю !') if a>0 : if b>0: print('Точка находится в первой четверти') else: print('Точка находится в четвёртой четверти') else: if b>0: print('Точка находится во второй четверти') else: print('Точка находится в третьей четверти') """Определив знак переменных, выводим номер четверти, в которой находится точка с помощью функции print."""
false
0730da36901113cda49d40fe551035a4d19acb0d
i-me-you/m.i.t-600-answers
/6.0001/ps1/ps1b.py
1,453
4.15625
4
#mit-introduction to computer science and programming using python 6.0001 #problem set 1 B answer """Writeaprogramtocalculatehowmanymonthsitwilltakeyoutosaveupenoughmoneyforadown payment. given the following parameters""" total_cost = float(input('Total cost of \'your\' dream home: ')) portion_down_payment = 0.25 * total_cost current_savings = 0.0 r = 0.04 annual_salary = float(input('Enter \'your\' annual salary: ')) portion_saved = float(input('Enter the percent of \'your\' salary to be saved, as a decimal: ')) monthly_salary = annual_salary / 12 portion_saved_month = portion_saved * monthly_salary #annual_salary / 12 number_of_months = 0 increment = (current_savings * r / 12) + portion_saved_month semi_annual_raise = float(input('Enter \'your\' semi annual raise, as a decimal: ')) monthly_salary = annual_salary / 12 ho = 0 #what loop to use homie? while,for while current_savings < portion_down_payment: current_savings += (current_savings * r / 12) + portion_saved_month number_of_months += 1 if number_of_months % 6.0 == 0: annual_salary += semi_annual_raise * annual_salary monthly_salary = annual_salary / 12 current_savings += (current_savings * r /12) + portion_saved * (annual_salary / 12) print ('The number of months it\'ll take to save up for a down payment is: ', number_of_months) #wrong output ..why.?
true
50e3e44bb7e2e70dde071f52df95693520e52de4
hamziqureshi/Python-Basics
/Question_21.py
1,113
4.71875
5
''' #----------------------------------------# Question 21 Level 3 Question£º A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 ¡­ The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: If the following tuples are given as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output of the program should be: 2 ''' import math num = [0,0] while 1: x = input("Enter input:") if not x: break x = x.split(" ") a = x[0] n = int(x[1]) if a == "UP": num[0] += n elif a == "DOWN": num[0] -= n elif a == "RIGHT": num[1] += n elif a == "LEFT": num[1] -= n else: pass print(num) print(int(round(math.sqrt(num[0]**2+num[1]**2))))
true
3464504993ebc5ba1e867cf5d5da3651d30b6494
hamziqureshi/Python-Basics
/Question_4.py
523
4.3125
4
#----------------------------------------# #Question 4 #Level 1 #Question: #Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #Suppose the following input is supplied to the program: #34,67,55,33,12,98 #Then, the output should be: #['34', '67', '55', '33', '12', '98'] #('34', '67', '55', '33', '12', '98') x = input("Enter sequence:") y = x.split() #y = list(x) print("List",y) z = tuple(y) print("Tuple",z)
true
90de55f3670f9243af00a1cd28ddcf817e8a599c
edmondyuen917/Track
/JsonTest.py
2,112
4.15625
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 19 12:30:13 2021 @author: edmond """ # Python program to demonstrate # Conversion of JSON data to # dictionary # importing the module import json import csv import os import sys # Opening JSON file def ReadConfig(filename): try: if not os.path.isfile(filename): print("File not exist: ", filename) return dict() with open(filename) as json_file: data = json.load(json_file) return data except FileNotFoundError: print("File Not Found Error") def WriteConfig(d, filename): app_json = json.dumps(d) with open(filename, "w") as f: f.write(app_json) def dict2csv(filename): csv_columns = ['No', 'Name', 'Country'] dict_data = [ {'No': 1, 'Name': 'Alex', 'Country': 'India'}, {'No': 2, 'Name': 'Ben', 'Country': 'USA'}, {'No': 3, 'Name': 'Shri Ram', 'Country': 'India'}, {'No': 4, 'Name': 'Smith', 'Country': 'USA'}, {'No': 5, 'Name': 'Yuva Raj', 'Country': 'India'}, ] try: csvfile = filename with open(csvfile, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: print("I/O error") # Function to convert a CSV to JSON # Takes the file paths as arguments def csv2json(csvFilePath, jsonFilePath): # create a dictionary data = {} # Open a csv reader called DictReader with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) # Convert each row into a dictionary # and add it to data for rows in csvReader: # Assuming a column named 'No' to # be the primary key key = rows['Name'] data[key] = rows # Open a json writer, and use the json.dumps() # function to dump data with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4))
true
8e8f98a3f0be7c9add7eb7de0d399ce361592e45
oaldri/comp110-21f-workspace
/lessons/dictionaries.py
1,155
4.46875
4
"""Demonstrations of dictionary capabilities.""" # Declaring the type of a dictionary schools: dict[str, int] # Initialize to an empty dictionary schools = dict() # Set a key-value pairing in the dictionary schools["UNC"] = 19_400 schools["Duke"] = 6_717 schools["NCSU"] = 26_150 # Print a dictionary literal representation print(schools) # Access a value by its key -- "lookup" print(f"UNC has {schools['UNC']} students") # Remove a key-value pair from a dictionary. # by its key schools.pop("Duke") # Test for the existance of a key is_duke_present: bool = "Duke" in schools print(f"Duke is present {is_duke_present}") # Update/ Reassign a key-value pair schools["UNC"] = 20000 schools["NCSU"] += 200 print(schools) # Demonstration of dictionary literals # Empty dictionary literal schools = {} # same as dict() print(schools) # Alternatively, initialize key-value pairs schools = {"UNC": 19400, "Duke": 6717, "NCSU": 26150} print(schools) # What happens when a key does not exist? # print(schools["UNCC"]) # Example looping over keys of a dict for school in schools: print(f"key: {school} -> Value: {schools[school]}")
true
2108814f7ae442e47380ef996381c37582a89e03
Fjohnpaul/RFID-Project
/SQL/DatabaseWSQL.py
1,968
4.1875
4
import sqlite3 # Testing Ground for MySqlLite https://www.youtube.com/watch?v=byHcYRpMgI4 #Connect to database conn = sqlite3.connect("customer.db") ## This will create a table or find one #create a cursor pointerCursor = conn.cursor() #_---------------------------------------------------------------------------------- #Create a table ##m """""" = DocString #pointerCursor.execute("""CREATE TABLE customers ( # firstName text, # lastName text, # email text #NOTE, This to create a table that doesn't exist. Because it was made already, we don't need to run it. # ) #""") #DataTYPES #Null - Does it exist? #INTERGER - Whole Numbers #REAL - 1.3 , 2.555 #TEXT - Text dug #BLOB - "Store as it is?" #_---------------------------------------------------------------------------------- #_---------------------------------------------------------------------------------- #many_customer_input = [ # # ('Wes'), ('Brown'), ('Wes@gmail.com') # # ] #pointerCursor.executemany("INSERT INTO customers VALUES (?,?,?)", many_customer_input) #_---------------------------------------------------------------------------------- #_---------------------------------------------------------------------------------- ## How to insert one value at a time #pointerCursor.execute("INSERT INTO customers VALUES('John', 'Smith', 'Test@gmail.com')") print("inserted Dummy Line") #_---------------------------------------------------------------------------------- #_---------------------------------------------------------------------------------- #Query The Database pointerCursor.execute("SELECT * FROM customers") #pointerCursor.fetchone() #pointerCursor.fetchmany(3) print(pointerCursor.fetchall()) #_---------------------------------------------------------------------------------- conn.commit() ##Need this to commit something to a database/Command #Close our Connection - kinda similar to file openning conn.close()
true
6376ccd7faf07f9f9b6b576b0df7b8ba573a9ca9
Hopeguy/1FA661-Introduction-to-Python-for-Physicists-and-Engineers
/lab-2.py
2,453
4.40625
4
import numpy as np import math #Question 1 my_arr = np.array([1,2,3,4]) print(my_arr[1]) print(my_arr[1:3]) my_arr[1] = 6 my_arr[2:3] = 42 my_arr = np.array([[1,2,3],[1,2,3]]) print(my_arr[1,2]) """ first arg is the row, and second is the collum, or you can see it as the first argument gives you the element in the "big list" and the second arguments gives the element in the list that you got from the "big list" """ print(my_arr.shape) print(my_arr.ndim) #dim = 0 = "scalar, dim = 1 = "vector", dim = 2 ="matrix" print(my_arr.size) #gives total amount of elements including elements in the lists whitin lists print(len(my_arr)) #gives the total elements in the "big list"/"top list" #Question 2 matrix = np.random.random((10,10)) #the random values are distributed between 0 and 1 vector = np.ones(20) #creates a vector with ones as each elements. identity = np.identity(5) #Creates an identity matrix of shape NxN #Question 3 A = np.random.random((4,4)) #Gives an 4x4 matrix with random numbers B = np.random.random((4,4)) C = A + B #Adds each value of each element between two matrix C2 = np.add(A,B) #Same as above but with different syntax A2 = A + 6 #Adds 6 to each element in an matrix B2 = B*2 #Double the value of each element in an matrix #Question 4 Test = np.array([[1,2,3],[1,2,3],[1,2,3]]) print(np.sum(Test)) print(np.min(Test)) print(np.matmul(Test,Test)) print(np.multiply(Test,Test)) #Question 5 - Slicing Matrix_2 = np.random.random((10,10)) print(Matrix_2[0,0]) Matrix_2[9,9] = -1 print(Matrix_2[1,:]) #shows all values in the second row print(Matrix_2[:,2]) #shows all values in collum 2 "third collum" Matrix_2[1,:] = 0 #Question 6 def L2(vector): Total = 0 for i in vector: Total = Total + i**2 L2 = math.sqrt(Total) return L2 vector = np.array([3,4]) # for any vector finds the L2 norm print(L2(vector)) print(np.linalg.norm(vector)) #Question 7 Matrix_3 = np.random.random((10,10)) -0.5 New_Matrix_3 = np.where(Matrix_3 > 0,Matrix_3, Matrix_3*0) #Question 8 R1 = np.random.random((10, 10)) R2 = R1 < 0.5 #gives an matrix where each value lower than 0.5 is true print(R1) print(R1[R2]) #prints all the values in R1 that is true, aka all values below 0.5 print(R1[~R2]) #prints all the values in R1 that is false, aka all values above 0.5 R1[R2] = -1 print(R1) #now prints the whole R1, where all the values that were true, aka below 0.5 are instead -1
true
0074c2e9728a01938ad4703bef9cfb15008e49f9
sljudge/sample_code
/python/midterm/triangular_numbers.py
530
4.15625
4
def is_triangular(k): """ k, a positive integer returns True if k is triangular and False if not """ # 1 1 # 1+2 3 # 1+2+3 6 # 1+2+3+4 10 # 1+2+3+4+5 15 # 1+2+3+4+5+6+7 28 # 1+2+3+4+5+6+7+8 36 # 1+2+3+4+5+6+7+8+9 45 x = 1 total = 1 while total < k: total = (total + (x+1)) x += 1 if k == total: return True elif k != total: return False is_triangular(1)
false
d72455c89c3314203c416239c9e0e577404a7286
rasmuskkilp/python_basics
/homework_python_1.py
1,048
4.28125
4
# declare some strings # prompt user for his/her name prompt_name = input('what is your name?') # Save it to some variables with good names name_1 = prompt_name # prompt the user for some random number between 0 - 99 prompt_num = input('enter number between 0-99') # store it in a variable called: user_chosen_num user_chosen_num = prompt_num # print a nice welcome message using user name print(f'welcome to python {name_1}!') # request the users last_name prompt_last_name = input('WHat is your surname?') last_name = prompt_last_name # Print a nice message welcoming the user using their first and last name print(f'Welcome {name_1} {last_name}') # As for the users age prompt_age =input('what is your age?') age = prompt_age # print a message of the users age and what year they were born in print(f'Your age is {age} and your date of birth is : {2019-int(age)}') # Compare the users input to the number they chose at the start and compare it print(f'your chosen number was {float(user_chosen_num) - float(age)} different from your age ')
true
4a3e18bca56c35d118923a1aa02ed15d1b9dc7e4
SarahStamps/Assignment-2
/code.py
2,119
4.3125
4
import numpy as np import math as m import matplotlib.pyplot as plt """ Make sure you make this module as modular as you can. That is add as many functions as you can. 1) Have a main function 2) A function to capture user input, this could be inside your "main" function 3) A function to calculate the projectile motion 4) A function to display the graph Make sure you use docstring to document your module and all your functions. Make sure your python module works in dual-mode: by itself or import to other module """ # NOTE: You may need to run: $ pip install matplotlib GRAVITY = -9.8 # Function to calculate projectile motion def main(): x0 = float(input("initial x position: ")) vx0 = float(input("initial x velocity: ")) # TODO: capture input y0 = float(input("initial y position: ")) vy0 = float(input("initial y velocity: ")) # TODO: capture input ax = 0.0 ay = GRAVITY # define a constant delt = 0.1 t = 0.0 intervals = 170 x = [] y = [] for i in range(intervals): x.append(projectile_motion(x0,vx0,t,ax)) y.append(projectile_motion(y0,vy0,t,ay)) t = t + delt if y[i] < 0.0: # exits when y value is less than 0 break print("number of points", i) plot_data(x, y) def projectile_motion(position,velocity,initial_time,acceleration): """ calculate x and y using projectile motion param position: position param velocity: velocity param initial_time: initial time param acceleration: acceleration """ return position + velocity*initial_time + 0.5*acceleration*initial_time**2 # formula for position # Function to plot data def plot_data(x, y): """ function plots x and y pairs param x: x coordinate param y: y coordinate """ plt.plot(x, y) plt.xlabel('time') plt.ylabel('distance') plt.show() # set module for dual mode if __name__ == "__main__": main()
true
9e62fc7fbc9ec80c0ae251a9e6f70c8b36f0caa8
EoghanDelaney/Problem-Sets
/begins-width-t.py
809
4.15625
4
# For this problem I used the Python documentation http://strftime.org/ # Once datetime can determine the day of the week in string format the rest is straightforward import time from datetime import datetime date = datetime.now() # using datetime get today's date day = date.strftime("%A") # get the day of the week in text format "Thursday" daylet = day[0] # get the first letter of the day # Now an "if statement" to compare the output from daylet if daylet == "T": print ("Yes - Today begins with the letter T:" + day) else: print ("No - Today " + day + " dose not start with the letter T") # The above was my original attempt, however upon completing the remainder of the questions # I believe the following is valid also for cleaner code # daylet = (datetime.now().strftime("%A"))[0]
true
9d77d1f4910685ef00b65283d9b618a7511f9429
khanmaster/python_dev
/01_python_dev/06_OOP/04_OOP_four_pillars/animal.py
945
4.59375
5
# creating Animal class class Animal: # __init__ to declare attributes def __init__(self): self.alive = True self.spine = True self.alive = True self.lungs = True # create methods of our animal def breathe(self): return "keep breathing to stay alive" # create methods of our animal def move(self): return "left right and centre" # create methods of our animal def eat(self): return "nom nom nom.... " # Now we have 3 within the class and 4 attributes/variables # if we instantiate our animal class with cat object cat will be able to ABSTRACT methods cat = Animal() # Let's abstract breathing method from Animal class #print(cat.breathe()) # breathing is now ABSTRACTED the user does not know how breath is implemented # how it works but they can use the method to achieve taking breath # NEXT - Inheritance # Let's create a file called reptile.py
true
b6e035f8b953e317d719ab2432393f2b213358c5
subahan983/Basic-programs-in-python
/Object Oriented Programming/Constructor.py
371
4.40625
4
# This program shows the use of constructor without any parameters. class MyClass: def __init__(self): print('I am in constructor') def hello(self): print('I am in hello method') obj = MyClass() # Creating an object reference to MyClass class which invokes the default constructor. obj.hello() # Calling the hello method in the MyClass class.
true
c814d8780ffa5dfc6647b98b4e19f000967a5866
IkeyBenz/InterviewProblems
/linked_list_problems.py
640
4.28125
4
from rotate_linked_list import LinkedList def middle_from_linked_list(lst: LinkedList): ''' Given a singly linked list, finds the middle value in the list ''' middle = len(lst) // 2 for index, val in enumerate(lst): if index == middle: return val if __name__ == '__main__': # 1. Find middle value in linked list of odd length lst = LinkedList([1, 2, 3, 4, 5, 6, 7, 8, 9]) print(middle_from_linked_list(lst)) # Prints 5 # 4. Rotate a list by k nodes lst = LinkedList(['A', 'B', 'C', 'D', 'E', 'F']) lst.rotate(4) print(lst) # Prints "E -> F -> A -> B -> C -> D"
true
3e33cfe5e2968aa0cfa00d523eed8ced5709e460
Awang1993/cp1404practicals
/Prac_05/hex_colours.py
651
4.21875
4
""" CP1404 Practical Hex Colours """ HEX_COLOURS = {"aliceblue": "#ff0f8ff", "beige": "#f5f5dc", "black": "#000000", "blanchedalmond": "#ffebcd", "blueviolet": "#8a2be2", "brown": "#a52a2a", "chocolate": "#d2691e", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "darkgreen": "#006400"} print(HEX_COLOURS.keys()) user_colour = input("Please choose a colour: ").lower() while user_colour != "": if user_colour in HEX_COLOURS: print(user_colour, "is", HEX_COLOURS[user_colour]) else: print("Sorry, the colour you chose is not listed.") user_colour = input("Please choose a colour: ").lower()
false
f6dbc972c0411551baddca50e1f4614eb64e3ef1
RZaga09/practicepython
/31.py
1,291
4.28125
4
# Let’s say the word the player has to guess is “EVAPORATE”. # For this exercise, write the logic that asks a player to guess a letter and # displays letters in the clue word that were guessed correctly. # For now, let the player guess an infinite number of times until they get the entire word. # As a bonus, keep track of the letters the player guessed and display a different message if the player tries to guess that letter again. # Remember to stop the game when all the letters have been guessed correctly! word = 'EVAPORATE' blanks = ['_' for _ in range(0, len(word))] letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] while 1 == 1: guess = input('Guess a letter! ') if guess.upper() not in letters: print('Already chosen!') elif guess.upper() in word: letters.remove(guess.upper()) indeces = [i for i, j in enumerate(word) if j == guess.upper()] for i in indeces: blanks[i] = guess.upper() else: letters.remove(guess.upper()) print('Not correct!') hangman = (''.join(blanks)) print(hangman) if hangman == word: print('YOU WIN') break
true
361f466ae1ba3516331eb2be91fd345599e3f7b8
RZaga09/practicepython
/6.py
300
4.28125
4
# Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) print('Type a word') word = input() c = ([i for i in word]) d = list(reversed(c)) print('Palindrome') if d == c else print('Not')
true
0aa94e3c8a14c88934dc4fbf009e5f680e0e7d23
bambit21/packtpub---learning-python
/chapter02/lists_examples.py
2,435
4.4375
4
print("empty list created by []: ", []) print("empty list created by list(): ", list()) print("list: ", [1, 2, 3]) list_comprehension = """ list comprehension [x + 5 for x in [2, 3, 4]] gives: """ print(list_comprehension, [x + 5 for x in [2, 3, 4]]) list_from_tuple = """ list from a tuple (1, 2, 3) list((1, 2, 3)) gives: """ print(list_from_tuple, list((1, 2, 3))) list_from_string = """ list from a string 'hello' list('hello') gives: """ print(list_from_string, list('hello')) print('\n------------------------------\n') a = [1, 2, 1, 3] print("list a =", a) a.append(13) print("a.append(13), a:", a) print("count '1' in the list a by a.count(1):", a.count(1)) a.extend([5, 7]) print("\nextend list a by another list or sequence" "\nby a.extend([5, 7]). a:", a, "\n") print("position of '13' in the list by a.index(13):", a.index(13)) a.insert(0, 17) print("\ninsert '17' at position 0" "\nby a.insert(0, 17). a:", a, "\n") print("pop - remove and return" "\nlast element by a.pop():", a.pop(), "\nelement at position 3 by a.pop(3):", a.pop(3)) print("\nnow list a looks like this:", a) a.remove(17) print("\nremove '17' from list by a.remove(17). a:", a) a.reverse() print("\nreverse list by a.reverse(). a:", a) a.sort() print("sort list by a.sort(). a:", a) a.clear() print("\nremove all elements from the list" "\nby a.clear(). a:", a) print('\n------------------------------\n') a = list('hello') print("a = list('hello'):", a) a.append(100) print("a.append(100). a:", a) a.extend((1, 2, 3)) print("a.extend((1, 2, 3)). a:", a) a.extend('...') print("a.extend('...'). a:", a) print('\n------------------------------\n') a = [1, 3, 5, 7] print("list a:", a) print("min(a):", min(a)) print("max(a):", max(a)) print("sum(a):", sum(a)) print("number of elements by len(a):", len(a)) b = [6, 7, 8] print("\nlist a:", a, "\nlist b:", b) print("a + b:", a + b) print("a * 2:", a * 2) print('\n------------------------------\n') from operator import itemgetter a = [(5, 3), (1, 3), (1, 2), (2, -1), (4, 9)] print("list a:", a) print("sorted(a):", sorted(a)) print("sorted(a, key=itemgetter(0)):\n", sorted(a, key=itemgetter(0))) print("sorted(a, key=itemgetter(0, 1)):\n", sorted(a, key=itemgetter(0, 1))) print("sorted(a, key=itemgetter(1):\n", sorted(a, key=itemgetter(1))) print("sorted(a, key=itemgetter(1), reverse=True):\n", sorted(a, key=itemgetter(1), reverse=True))
false
8b9e0ca6cba1fd44a050a5addf04defef958cd67
SwagatikaM/python
/arrays.py
364
4.125
4
numbers = [2, 4, 6, 1, 8, 9, 22, 54, 5, 3] numbers.sort() print(numbers[-1]) max = numbers[0] for number in numbers: if number > max: max = number print(max) #Matrix in Python - 2D array matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print(matrix[0][1]) for row in matrix: for item in row: print(item)
true
c75bdb64a75593edb993866273a9ff4e47c8b442
daiyomiura/study_python
/editor/tutorial/numpy/numpy_tutorial.py
2,418
4.53125
5
# Basic data Types # Numbers x = 3 print(type(x)) # Prints "<class 'int'>" print(x) # Prints "3" print(x + 1) # Addition: prints "2" print(x - 1) # Subtraction: prints "2" print(x * 2) # Multiplication: prints "6" print(x ** 2) # Exponentiation: prints "9" x += 1 print(x) # Prints "4" y = 2.5 print(type(y)) # Prints "<class 'float'>" print(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25" # Booleans t = True f = False print(type(t)) # Prints "<class 'bool'>" print(t and f) # Logical AND; prints "False" print(t or f) # Logical AND; prints "True" print(not t) # Logical NOT; prints "False" print(x != f) # Logical XOR; prints "True" # Strings hello = 'hello' # String literals can use single quotes world = "world" # or double quotes; it does not matter. print(hello) # Prints "hello" print(len(hello)) # String length; Prints "5" hw = hello + ' ' + world # String concatenation print(hw) # prints "hello world" hw12 = '%s %s %d' % (hello, world, 12) # sprintf style string formating. print(hw12) # prints "hello world 12" # String objects have a bunch of useful methods; for example: s = "hello" print(s.capitalize()) # Capitalize a string; prints "Hello" print(s.upper()) # Convert a string to uppercase; prints "HELLO" print(s.rjust(7)) # Right-justify a string, padding with spaces; prints " print(s.center(7)) # Center a string, padding with spaces; prints " hello " print(s.replace('l', '(ell)')) # Replace all instances of one substring with another; # prints(he(ell)(ell)o) print(' world'.strip()) # Strip leading and trailing whitespace; prints "world" # Containers # Python includs several built-in container types: lists, dictionaries, sets, and tuples. # Lists # A list is the Python equivalent of an array, but is resizeable and can contain elements of different types: xs = [3, 1, 2] # Create list print(xs, xs[2]) # Prints "[3, 1, 2 ] 2" print(xs[-1]) # Negative indices count from the end of the list; prints "2" xs[2] = 'foo' # Lists can contain elements of different types print(xs) # Prints "[3, 1, 'foo']" xs.append('bar') # Add a new element to the end of the list print(xs) # Prints "[3, 1, 'foo', 'bar']" x = xs.pop() # Remove and return the last element of the list print(x, xs) # Prints "bar [3, 1, 'foo']"
true
3cd09eb6a5fffe3d41f0398a7386921ff6b1a2aa
AKippins/Olivia-Asteris-Tutoring
/Lesson 7/leap_year.py
1,396
4.4375
4
# Write a function which decides if any year entered from the keyboard is a leap year. # Write a main function which takes the year from the user and calls the function, # outputting the results to the user. # When we get a problem # Break the problem down. # We get more managable pieces # Get it into terms we can understand # Find a solution # Scale up # Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, # but these centurial years are leap years if they are exactly divisible by 400. For example, # the years 1700, 1800, and 1900 are not leap years, but the years 1600 and 2000 are. # TODO: Ask the user for the year. Doneish. # TODO: Year mod 100 to see if it's a centurial year. If so, then we mod 400 to see if it is a leap year. Done. # TODO: Using modulo by 4 if equal to 0 then it is a leap year. Done # TODO: Print to the user. Done # TODO: Make our main function. Done def leap_year_finder(year): year = int(year) if year % 100 == 0 and year % 400 == 0: print("It's a leap year") elif year % 100 == 0 and not year % 400 == 0: print("It's not a leap year") elif year % 4 == 0: print("It's a leap year") else: print("It's not a leap year") if __name__ == "__main__": year = int(input('Enter a year')) # year = "2000" leap_year_finder(year)
true
14e964ba83beb3c677695f542f1dedac09f5af8d
chixujohnny/Leetcode
/Leetcode2019/数据结构/MergeSort.py
838
4.125
4
# coding: utf-8 # 归并排序 # 一张图看懂归并排序: https://www.cnblogs.com/wyongbo/p/Devide.html def MergeSort(data): if len(data) == 1 or len(data) == 0: # 递归出口 return data left = MergeSort(data[:len(data)/2]) right = MergeSort(data[len(data)/2:]) ret = [] i, j = 0, 0 while i<len(left) or j<len(right): if i<len(left) and j<len(right): if left[i] <= right[j]: ret.append(left[i]) i += 1 else: ret.append(right[j]) j += 1 elif j == len(right): ret.append(left[i]) i += 1 elif i == len(left): ret.append(right[j]) j += 1 return ret if __name__ == '__main__': data = [2,4,7,5,8,1,3,6] print MergeSort(data)
false
14621287b75601be3d7940f16ba8fb033194b790
memermaid/code_in_place
/KhansoleAcademy/khansole_academy.py
760
4.25
4
""" Program randomly generates a simple addition problem for the user until the user has gotten 3 problems correct in a row. """ import random def main(): correct = 0 while correct != 3: num1 = random.randint(1, 100) num2 = random.randint(1, 100) total = num1 + num2 print("What is", num1, "+", num2, "?") answer = int(input("Your answer: ")) if answer == total: correct += 1 print("Correct! You've gotten {} correct in a row.".format(correct)) if correct == 3: print("Congratulations! You mastered addition.") else: print("Incorrect. The expected answer is", total) correct = 0 if __name__ == '__main__': main()
true
5e5a7773427b450fdee458e1571dcc8dc64deb91
alexandrelff/mundo2
/ex063.py
478
4.125
4
# Escreva um programa que leia um número N inteiro qualquer e mostre na tela os N primeiros elementos # de uma sequência de Fibonacci. #Ex.: 0 -> 1 -> 1 -> 2 -> 3 -> 5 -> 8 print('==*== Sequência de Finonacci ==*==') n = int(input('Quantos termos você deseja mostrar: ')) f1 = 0 f2 = 1 print('{} ➜ {}'.format(f1, f2), end='') n -= 2 while n != 0: f3 = f1 + f2 print(' ➜ {}'.format(f3), end='') n -= 1 f1 = f2 f2 = f3 print('\nPrograma finalizado.')
false
37c94143ede465e55d462458b7ec34f42bbd1037
alexandrelff/mundo2
/ex065.py
824
4.15625
4
# Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os # valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar # a digitar valores. n = int(input('Digite um valor: ')) maior = menor = soma = n count = 1 resp = '' while resp != 'N': resp = str(input('Deseja continuar? (S/N) ')).strip().upper() if resp == 'S': n = int(input('Digite um valor: ')) soma += n count += 1 if n > maior: maior = n if n < menor: menor = n media = soma / count print('Você digitou {} valores.\n' 'A média entre eles é igual a {}.\n' 'O maior valor digitado foi {}, e o menor valor foi {}.'.format(count, media, maior, menor))
false
39f3e4ca6d3552d9973a5a8e1145d5835c3a959b
brianshukwit/mind-palace
/python/practice_section/Vowel Replace.py
398
4.1875
4
# Vowel Replace def translate(phrase): translation = "" for vowel in phrase: if vowel.lower() in "aeiou": if vowel.isupper(): translation = translation + "X" else: translation = translation + "x" else: translation = translation + vowel return translation print(translate(input("Enter a phrase: ")))
true
bf54becd482780326318177d66150b2b463bed11
rohitmi0023/cs_programs
/sort/insertion_sort/insertion_sort.py
1,017
4.46875
4
def insertion_sort_func(lists): # n - 1 iterations starting from the 1 index i.e. 2nd element for i in range(1, len(lists)): # Picked up card to be the key key = lists[i] j = i - 1 # i - 1 iterations till the key is greater while j >= 0 and key < lists[j]: # shifting the compared element by index 1 lists[j+1] = lists[j] # decreamenting j to go more leftwards j = j - 1 # placing the picked up value just before we found that the key # is more than the compared element, remember that the compared # element is j lists[j+1] = key return lists # User defined length of the list SIZE = input("Enter the number of elements ") # Creating an empty list LISTS = [] for k in range(0, SIZE): element = input('Enter the number: ') # appending each user defined value into the list LISTS.append(element) print('Using Insertion Sort', insertion_sort_func(LISTS))
true
2e63dfa75f3246438e7360a9973b60a3f7b497e0
erdodule/pytasks
/task5.py
217
4.1875
4
print("Input your height: ") height_ft = int(input("Feet: ")) height_inch = int(input("Inches: ")) height_inch += height_ft * 12 height_cm = round(height_inch * 2.54, 1) print("Your height is : %d cm." % height_cm)
true
eed40b347d7a715004ea8835d8c830803673b55b
shubhomedia/Learn_Python
/functions/nested_function.py
356
4.125
4
#nested function def add(x,y,z): # simple function sum = x + y + z return sum #nested function def outer(a): def nested(b): return b * a; a = nested(a) return a print(outer(10)) # nested function like loop def f(a): def g(b): def h(c): return a * b * c return h return g print(f(5)(2)(3))
true
f3337e74454542e570b2a4076288ac2502cca3dd
shubhomedia/Learn_Python
/format_method.py
488
4.28125
4
# print somethings and using format method. print("Today I Had {0} cups of {1}".format(2,"coffee")) print("prices: ({x},{y},{z})".format(x = 10,y = 1.50, z = 5)) print("The {vehicle} had {0} crashes in {1} months".format(5,6, vehicle = 'car')) print('{:<20}'.format("text")) # create space after text print('{:>20}'.format("text")) # create space before text #user define look print(""" Hello user this is new look so on """) #same print(''' hello ''')
true
1ffa1a3d9e99756729b47ad46f01cfa1797bc50c
1Duan2Fei3/Python_Test
/python初级/01-HelloWorld.py
664
4.1875
4
# 这是第一个单行注释 #print("hello world") '''a=21 b=10 c=0 c=a+b print("1-c的值为:",c) c=a-b print("2-c的值为:",c) c=a*b print("3-c的值为:",c) c=a/b print("4-c的值为:",c) c=a%b print("5-c的值为:",c) #修改变量a,b,c a=2 b=3 c=a**b print("6-c的值为:",c) a=10 b=5 c=a//b print("7-c的值为:",c)''' account='DuanFei' passwd=050121 # 定义西瓜价格变量 price = 5.5 # 定义购买重量 weight = 3.5 # 计算金额 money = price * weight print(money) # 定义西瓜价格变量 price = 5.5 # 定义购买重量 weight = 3.5 # 计算金额 money = price * weight # 只要买西瓜就返 5 元 money = money - 5 print(money)
false
8c09e38d84223d70888b71b53794c418ce475a9e
CodingGuruInTraining/2905_Lab_1_Simple_Game
/Part_1_Guess_Number.py
949
4.15625
4
# This program runs a simple guessing game. # Import random library import random def main(): # Gets a random number between 1 and 10 randomNumber = random.randint(1, 10) # Displays introduction message and instruction print("Greetings! Pick a number, any number ") print("between 1 and 10.") # Continues asking User for input till the correct # Answer is given while True: usersChoice = int(input()) correctChoice = compareValues(randomNumber, usersChoice) # Breaks loop if correct choice is made if correctChoice == True: break # Function that compares values and displays result. def compareValues(randomNumber, userChoice): correct = False if randomNumber == userChoice: correct = True print("Correct!") elif randomNumber > userChoice: print("Nope, too low.") else: print("Nope, too high.") return correct main()
true
545ac6219b1ed7a139d707593a3c403e747c9e5b
soultalker/gaoyuecn
/Python123/io_input.py
332
4.15625
4
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Enter text: ') for i in range(len(something)): if something[i] in (' ','.') del something[i] if is_palindrome(something): print('YES,This is a palindrome') else: print('No,it is not a palindrome')
false
cab358d0045e80a13819031c4f10db7fe51091fe
Evgeniy-analyst/hyperskill.org-projects
/Topics/Invoking a function/Longest word/main.py
218
4.21875
4
word1 = input() word2 = input() # How many letters does the longest word contain? count = 1 if (len(word1) > len(word2)) and count == 1: print(len(word1)) count += 1 else: print(len(word2)) count += 1
false
1d80cd21ba7bd03945ed5e589425d1a1c6d1cf90
jayudhandha/python-exercise-m1-batch
/IfElseExample.py
1,041
4.25
4
# Conditional operators & Conditional expressions # a = 10 # Indendation # if a >= 5 and a <=20: # print("a is greater then 5") # else : # print("a is not greater then 5") # Get the user marks # Print it's grades based on following things # If marks are greater then 80 then Grade A # If marks are betwee 60 & 80 then Grade B # If marks are betwee 35 & 60 then Grade C # If marks are less then 35 then Fail # Elia # Nikita # a=int(input("enter your marks: ")) # if(a>=80): # print("grade A") # # elif(a<80 and a>=60): # elif 60 < a <=80: # print("grade B") # elif 35 <= a <=60: # print("grade C") # else: # print("FAIL") # Check whether the given number is odd or even name = "Jayesh Dhandha" # if 'Dhan' in name: if 'D' in name: print('D exist') else: print("D not exist") # nested if else if ('D' in name) and ('z' not in name): # if 'D' in name: # if 'z' not in name: print('D exist and z does not exist') else: print("D not exist")
false
80471aec3a589611d0c03529dbe0027a63710a88
jayudhandha/python-exercise-m1-batch
/OperatorsExample.py
756
4.1875
4
# Arithmatic operators #+,-,*,/,%,//,** #a = 10 #b = 3 #print(a+b) #print(a-b) #print(a*b) #print(a/b) #print(a%b) #print(a//b) #print(a**b) # To do the power of any number # Assignment Operators # =, +=, -=, %=, //=, **= # a = 5 #a = a + 5 # a += 5 # a -=2 # a = a - 2 # Bitwise operator #0 1 -> 00 01 10 11 -> 2**2 #0 0 1 -> 2**3 -> 8 #8 4 2 1 # 1 -> 0001 -> 0100 -> 4 # 2 -> 0010 # ---- # 0011 -> 3 #a = 1 #b = 2 #print(a|b) #print(a<<2) # c = 4 # print(c>>2) # 3 -> 0011 # 7 -> 0111 # Operator precedence answer = 10+20*2-5-7+10+15 # * + - # Elia: 33 # Nikita: 13 # Rahi: 13 print(answer)
false
b64548d3f4730408a09f7ff5be1ee5a1adc61487
CaCampos/ProjetoPython
/Aula 15.12.py
2,455
4.125
4
numero1_ex1 = int(input("Digite um número inteiro: ")) numero2_ex1 = int(input("Digite outro número inteiro: ")) numero3_ex1 = int(input("Digite outro número inteiro: ")) def pegar_maior_valor(*numeros): return max(numeros) maior_valor = pegar_maior_valor(numero1_ex1, numero2_ex1, numero3_ex1) print("O maior valor entre os números {}, {} e {} é o {}.".format(numero1_ex1, numero2_ex1, numero3_ex1, maior_valor)) numero1_ex2 = int(input("Digite um número inteiro: ")) numero2_ex2 = int(input("Digite outro número inteiro: ")) numero3_ex2 = int(input("Digite outro número inteiro: ")) def pegar_menor_valor(*numeros): return min(numeros) menor_valor = pegar_menor_valor(numero1_ex2, numero2_ex2, numero3_ex2) print("O menor valor entre os números {}, {} e {} é o {}.".format(numero1_ex2, numero2_ex2, numero3_ex2,menor_valor)) numero1_ex3 = int(input("Digite um número inteiro positivo: ")) numero2_ex3 = int(input("Digite outro número inteiro positivo: ")) numero3_ex3 = int(input("Digite outro número inteiro positivo: ")) numero4_ex3 = int(input("Digite um número inteiro negativo: ")) numero5_ex3 = int(input("Digite outro número inteiro negativo: ")) numero6_ex3 = int(input("Digite outro número inteiro negativo: ")) modulo_numero4_ex3 = abs(numero4_ex3) modulo_numero5_ex3 = abs(numero5_ex3) modulo_numero6_ex3 = abs(numero6_ex3) print(modulo_numero4_ex3, modulo_numero5_ex3, modulo_numero6_ex3) def pegar_maior_valor(*numeros): return max(numeros) maior_valor = pegar_maior_valor(numero1_ex3, numero2_ex3, numero3_ex3, numero4_ex3, numero5_ex3, numero6_ex3) print("O maior valor entre os números {}, {}, {}, {}, {} e {} é o {}.".format(numero1_ex3, numero2_ex3, numero3_ex3,numero4_ex3,numero5_ex3,numero6_ex3, maior_valor)) def pegar_menor_valor(*numeros): return min(numeros) menor_valor = pegar_menor_valor(numero1_ex3, numero2_ex3, numero3_ex3, numero4_ex3, numero5_ex3, numero6_ex3) print("O menor valor entre os números {}, {}, {}, {}, {} e {} é o {}.".format(numero1_ex3, numero2_ex3, numero3_ex3,numero4_ex3,numero5_ex3,numero6_ex3, menor_valor)) def checar_tipo_variavel(variavel): tipo = type(variavel) if tipo == int: print("Variável formatada: {:05d}".format(variavel)) elif tipo == float: print("Variável formatada: {:.2f}".format(variavel)) elif tipo == str: print("Variável formatada: {:>10}".format(variavel)) else: print("Esse tipo de variável não está mapeado.")
false
f0478e2c331842b6994d4c10fcb3e16ce1bfa201
sagelga/prepro59-python
/24_ChangeSpeedUnit.py
332
4.34375
4
"""This program will convert m/s into different unit of speed""" def converter(): """This should work""" speed = float(input()) print("%.4f" %(speed * 3.2808) + " foot per second.") print("%.4f" %(speed * 2.2369) + " miles per hour.") print("%.4f" %(speed * 3.6000) + " kilometer per hour.") converter()
true
f058403b1d87563cfbb22a85c0e6c5c5ab350670
dshapiro1dev/RuCoBo
/src/examples/loops/PizzaShop.py
2,280
4.40625
4
# Make an application that keeps building a pizza order until the person says quit # Create lists with common yes & no responses yes = ['y', 'yes', 'yeah', 'please', 'okay', 'absolutely'] no = ['n', 'no', 'nope', 'never', 'please no'] done = ['all done', 'quit', 'nothing', 'no more', 'stop', 'no', 'none', 'done'] # Create list of available toppings for a pizza toppings = ['pepperoni', 'mushrooms', 'extra cheese', 'sausage', 'bacon', 'anchovies', 'peppers', 'olives', 'sardines', 'anchovies', 'steak', 'broccoli', 'chicken', 'pineapple'] order = [] plainPizza = input("welcome to Boz's pizza, let's start your pizza order do you want a plain pizza?") # If the person says that want a cheese pizza, place the order and end the script if plainPizza in yes: print("Okay your cheese pizza will be right up!") # If the person says they don't want a chese pizza, go through this loop to collect topping orders elif plainPizza in no: n = 0 # Limit a pizza to just 5 orders while n < 5: # Have a specific message for the first order if n == 0: topping = input("Okay, let's get some toppings. What would you like?") else: topping = input("anything else?") # check to see if the topping is in the list of toppings if topping in toppings: # check to see if the person has already added this topping to the pizza if topping in order: print("You already added that to your pizza") else: print(f"Okay, adding {topping}") order.append(topping) n += 1 # check to see if the person gave an indication they are done adding toppings to the pizza elif topping in done: print("okay, let's get that order together") break else: print("Sorry I don't think we have that as a topping") if order: print("So that's a pizza with", end=" ") for item in order: # this silly check is to see if we're on the last item in the list, if so, we don't put a comma after it and # remain grammatically correct if item == order[-1]: print(f"{item}", end=" ") else: print(f"{item}, and", end=" ")
true
44226989b0c45fbde02f81ed968032401bb30864
dshapiro1dev/RuCoBo
/src/examples/loops/SandwichShop.py
769
4.1875
4
# Make a list of sandwiches that can be ordered with a quanity, have a random flow of orders until exhausted from random import choice # Create a list of sandwiches that are available, with a quantity for each sandwiches = {'turkey': 5, 'blt': 5, 'meatball': 5, 'veggie': 5, 'italian': 5} print("The deli is open & taking orders!") n = 0 missedOrders = 0 # loop through this process, as long as there is at least one sandwich still available while n < sum(list(sandwiches.values())): order = choice(list(sandwiches.keys())) if sandwiches[order] > 0: print(f"Order for {order}") sandwiches[order] -= 1 else: print(f"We're all out of {order}") missedOrders += 1 print(f"The deli is closed. We missed {missedOrders} orders")
true
2fde6515a4576929b0d26bf44695af803752f23e
lukasbasista/Daily-coding-problem
/012/main.py
1,140
4.375
4
""" This problem was asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2 What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. """ def factorial(x): if x == 0 or x == 1: return 1 return x * factorial(x-1) def comb(n, k): return factorial(k) / (factorial(k - n) * factorial(n)) def foo(n): if n == 0: return 0 if n == 1: return 1 count = 1 for i in range(1, n//2 + 1): md = n - (i * 2) count += comb(i, i + md) return round(count) def foo2(n, X): s = [0 for _ in range(n + 1)] s[0] = 1 for i in range(1, n + 1): s[i] += sum(s[i - x] for x in X if i - x >= 0) return s[n] print(foo(7)) print(foo2(4, [1,2,3]))
true
eccae2e9512884fe5ede94d2d1741696c2a0feb9
ejrach/exercises-mosh
/Project-GuessingGame.py
474
4.125
4
secret_number = 9 tries = 0 guess_limit = 3 #while loops can have else blocks while tries < guess_limit: guessed_number = int(input('Enter your guess: ')) tries += 1 if guessed_number == secret_number: print("You win!") break #this runs if the while loop finishes without a break happening. In #this case, if the while loop terminates without a correct guess, then #we print a message that the user lost. else: print('Sorry, you lose :(')
true
0c341450dc9108bf7b1ddb90320170e0988f9150
ejrach/exercises-mosh
/2DLists.py
346
4.125
4
#[ # 1 2 3 # 4 5 6 # 7 8 9 # ] # 2D lists matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] #to access the first row, second column (item with value of 2) print(matrix[0][1]) # to modify that value matrix[0][1] = 20 print(matrix[0][1]) # to print the items in a 2D list for row in matrix: for item in row: print(item)
true
1f99fd8d47fedffaff9d145440897677a5da27f7
sarozzx/Python_practice_2
/10.py
577
4.34375
4
# Write a function that takes camel-cased strings (i.e. # ThisIsCamelCased), and converts them to snake case (i.e. # this_is_camel_cased). Modify the function by adding an argument, # separator, so it will also convert to the kebab case # (i.e.this-is-camel-case) as well. def change_cam(str): str1=str[0].lower() for letter in str[1:]: if letter.isupper(): str1+="_"+letter.lower() else: str1+=letter print("Snake Case: ",str1) str2=str1.replace("_","-") print("Kebab Case: ",str2) change_cam("ThisIsCamelCased")
true
f838b0055927daaf601553dc97838df244874f83
Chrybear/CSC-310-HW1
/HW1 problem 2.py
923
4.21875
4
# Homework problem #2 # setting up the funtion to check if the sequence of int values has a pair whose product is odd. # I am assuming that, in the event a sinlge int is entered, it should return "False" since there is no # pair with which to test with. def isodd(nums): #main function to test if it is odd last = len(nums) x = 0 while x < last: y = x + 1 while y < last: if (nums[x] * nums[y]) % 2 != 0: return True y += 1 x += 1 return False # calling the function oddish = [] #variable that is tested print('When finished entering values hit Ctrl+d') while True: try: uinput = int(input('Enter an integer: ')) oddish.append(uinput) except EOFError: break print('It is', isodd(oddish), 'That there are values in ',oddish, ' that can produce an odd number when multiplied together')
true
b95d96973ee0a20295f4d733786ebba1b230d450
swang2000/BinaryTree
/Onesibling.py
1,255
4.25
4
''' Print all nodes that don’t have sibling 2.1 Given a Binary Tree, print all nodes that don’t have a sibling (a sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling). Root should not be printed as root cannot have a sibling. For example, the output should be “4 5 6” for the following tree. Binary Tree Recommended: Please solve it on “PRACTICE” first, before moving on to the solution. This is a typical tree traversal question. We start from root and check if the node has one child, if yes then print the only child of that node. If node has both children, then recur for both the children. ''' import CdataS.BT.BianrySearchTree as tree def onesibling(root): if root == None: return if root.left_child and root.right_child is None: print (root.left_child.value) onesibling(root.left_child) elif root.right_child and root.left_child is None: print (root.right_child.value) onesibling(root.right_child) else: onesibling(root.left_child) onesibling(root.right_child) return bst = tree.BST() bst.insert(5) bst.insert(3) bst.insert(2) bst.insert(2.5) bst.insert(4) bst.insert(8) bst.insert(6) onesibling(bst.root)
true
aab31341d17d79236fdd421d0c51447f2d9f08f0
swang2000/BinaryTree
/MiniBTdepth.py
783
4.125
4
''' Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node. ''' import CdataS.BianrySearchTree as BST def miniBTdepth(bt): if bt == None: return 0 if bt.left_child == None and bt.right_child == None: return 1 if bt.left_child and bt.right_child == None: return miniBTdepth(bt.left_child) + 1 if bt.right_child and bt.left_child == None: return miniBTdepth(bt.right_child) + 1 if bt.left_child and bt.right_child: return min(miniBTdepth(bt.left_child) + 1, miniBTdepth(bt.right_child) + 1) bst = BST.BST() bst.insert(8) bst.insert(7) bst.insert(9) bst.insert(6) bst.insert(5) bst.insert(4) depth = miniBTdepth(bst.root)
true
d2ef2fba24ef60c79c5efc51335cfd0b9a8aefc0
muditabysani/Linked-List-1
/Problem1.py
1,396
4.125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList1(self, head): # Time Complexity : O(n) where n is the number of elements in the array # Space Complexity : O(n) because we are storing the entire linked link into an array and reversing that and creating a new linkedlist # Accepted on Leetcode if head == None or head.next == None: return head l = [] temp = head while temp != None: l.append(temp.val) temp = temp.next l = l[::-1] res = ListNode(l[0]) temp = res for i in l[1:]: n = ListNode(i) temp.next = n temp = temp.next return res def reverseList2(self, head): # Time Complexity : O(n) where n is the number of elements in the Linked list # Space Complexity : Constant space actually we are not using extra space we are just changing the direction of the links # Accepted on Leetcode if head == None or head.next == None: return head current = head new = old = None while current != None: new = current.next current.next = old old = current current = new return old def reverseList3(self, head): if head == None or head.next == None: return head cur = head while cur.next != None: temp = cur.next cur.next = temp.next temp.next = head head = temp cur = head return head
true
18dd46c324550c461a3b8fbf9b66a17d34fbe00f
divs17/1BM17CS133
/even.py
536
4.15625
4
numbers = [] n = int(input("Enter number of elements: \t")) for i in range(1, n+1): allElements = int(input("Enter element:")) numbers.append(allElements) print("all the elements ", numbers) even_lst=[] for j in numbers: if j % 2 == 0: even_lst.append(j) print("even elements ", even_lst) ''' ============== Enter number of elements: 4 Enter element:2 Enter element:4 Enter element:5 Enter element:7 all the elements [2, 4, 5, 7] even elements [2, 4] >>> '''
true
b8fad9b81c4cb91c929c5541eee8753c22bbb6dd
praveenmathew/Python_Scripts
/Mini_Project_1.py
425
4.21875
4
#Based on challenges put up by https://www.teclado.com/30-days-of-python/python-30-day-3-project #Simple script to read, calculate data with minimal arithmetic and display to output. name = input("Please enter employee name: ").strip().title() hourly_wage = float(input("Please enter hourly_wage: ")) work_hours = float(input("Please enter hours worked: ")) print(f"{name} earned ${hourly_wage * work_hours} this week")
true
7a57a87ea88d1ef21c0925c63cbea5e492ccfdc5
AkhileshPandeyji/Python_All
/Python_Basics/Python_listcomp_generators.py
1,544
4.40625
4
# list comprehensions : [expression] # Are lists that are loaded and retrieved whole once at a time and then executed. # They contain sequential data that follows some rule. xyz = [i for i in range(10)] print(xyz) print(type(xyz)) # Generators : (expression) # types:generator variable ,generator function # Are lists that are loaded whole somewhere and then one item is retrieved at a time in # a stream and then loaded into the memory. # They also contain the sequential data that follows some rule. xyz = (i for i in range(10)) print(xyz) print(type(xyz)) gen_list = [] for i in xyz: print(i) gen_list.append(i) print(gen_list) # Advance Concepts on generators and list Comprehensions # Nested list comprehension and generators # conversion from gen to list # list comp and gen using expression if # nested list comp x = [[i for i in range(5)] for ii in range(5)] print(x) # x= [[i for i in range(5)]for ii in range(5)] is equivalent to x=[] for ii in range(5): x.append([]) for i in range(5): x[ii].append(i) print(x) # nested generators y = ((i for i in range(5))for ii in range(5)) print(y) for i in y: for a in i: print(a) # convert a generator to list comp z = list(y) print(z) # list comp and gen with if expression r = [5, 7, 10,15, 20, 24, 28, 30, 32, 35] def divisible_by5(j): if j % 5 == 0: return True else: return False xy = [i for i in r if divisible_by5(i)] print(xy) ty = (i for i in r if divisible_by5(i)) print(ty) for i in ty: print(i)
true
5d8ff7c96d5a30133fc831978736661f524540c7
AkhileshPandeyji/Python_All
/Python_Basics/PythonVariables.py
722
4.25
4
#printing to the console print("Hello World!!") #Numerical Variables num1 = -34 #int num2 = 23.04 #float/double num3 = (34+23)-24 #expressional value num4 = 23+45j #complex no print(num1,num2,num3,num4) #string Variables string1 = "Akhilesh Pandey" string2 = string1 string3 = string1+" "+ string2 #character variables char1 = "c" char2 = 't' print(string1,string2,string3) print(char1,char2) '''' #input from a user input1 = input("Enter your name:") print(input1) ''' '''' #type Casting input2 = input("Enter some numeric value:") input2 = float(input2) input2 = 2*input2 print(input2) ''' #singleLine Comment #multiline Comments """ eggergrwegwegeg """ ''' etehehehehe ''' #operations on strings print(len(string1))
true
66f0216a5edae920f79833bd710ae11c7771efe9
hitesh091/Interactive_PyGames
/Guess the number.py
2,687
4.21875
4
#==========To run, click the link below================# ######################################################## http://www.codeskulptor.org/#user29_gahmhlJRV57Hnja.py ######################################################## # 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 import math # initialize global variables used in your code num_range=100 guess_num=-1 s_number=-1 attempts_left=-1 range_=1 # helper function to start and restart the game def new_game(): # remove this when you add your code global s_number s_number= random.randrange(0,num_range) # define event handlers for control panel def range100(): # button that changes range to range [0,100) and restarts global num_range global attempts_left,range_ range_=1 num_range=100 attempts_left=7 new_game() print "New Game. Range is [0,100) " print "Number of remaining guesses is ",attempts_left print # remove this when you add your code def range1000(): # button that changes range to range [0,1000) and restarts global num_range,attempts_left,range_ num_range=1000 range_=2 attempts_left=10 new_game() print "New Game. Range is [0,1000) " print "Number of remaining guesses is ",attempts_left print # remove this when you add your code def input_guess(guess): # main game logic goes here global attempts_left,s_number global range_ guess_num= int(guess) attempts_left=attempts_left-1 print "Guess was ", guess if((attempts_left==0)and(not(guess_num==s_number))): print 'Computer Wins!' print 'Secret Number was',s_number print if(range_==1): range100() else: range1000() print "Number of remaining guesses ", attempts_left if(guess_num>s_number): print "Higher!" print elif(guess_num<s_number): print "Lower!" print else : print "Correct!" print if(range_==1): range100() else: range1000() # remove this when you add your code # create frame frame= simplegui.create_frame("Guess The Number",200,200) # register event handlers for control elements frame.add_button("Range is [0,100) ",range100,200) frame.add_button("Range is [0,1000) ",range1000,200) frame.add_input("Enter the guess ",input_guess,200) # call new_game and start frame range100() frame.start() # always remember to check your completed program against the grading rubric
true
a4ad8c133db07113449d53de801f18a5e60dfaf4
Amatuer-/Test
/MSDS/Partition.py
2,011
4.125
4
def swap(a, i, j): assert 0 <= i < len(a), f'accessing index {i} beyond end of array {len(a)}' assert 0 <= j < len(a), f'accessing index {j} beyond end of array {len(a)}' a[i], a[j] = a[j], a[i] def simplePartition(a, pivot): # print(pivot) n = len(a) i = -1 j = 0 for j in range(n-1): # print(a[i]) if a[j] <= pivot: swap(a,i+1 , j) i +=1 swap(a , i+1 , n-1) return i+1 ## To do: partition the array a according to pivot. # Your array must be partitioned into two regions - <= pivot followed by elements > pivot ## If an element at the beginning of the array is already <= pivot in the beginning of the array, it should not ## be moved by the algorithm. # your code here def boundedSort(a, k): for j in range(1, k): simplePartition(a, j) if __name__ == '__main__': a = [1, 3, 6, 1, 5, 4, 1, 1, 2, 3, 3, 1, 3, 5, 2, 2, 4] print(a) simplePartition(a, 1) print(a) assert (a[:5] == [1, 1, 1, 1, 1]), 'Simple partition test 1 failed' simplePartition(a, 2) print(a) assert (a[:5] == [1, 1, 1, 1, 1]), 'Simple partition test 2(A) failed' assert (a[5:8] == [2, 2, 2]), 'Simple Partition test 2(B) failed' simplePartition(a, 3) print(a) assert (a[:5] == [1, 1, 1, 1, 1]), 'Simple partition test 3(A) failed' assert (a[5:8] == [2, 2, 2]), 'Simple Partition test 3(B) failed' assert (a[8:12] == [3, 3, 3, 3]), 'Simple Partition test 3(C) failed' simplePartition(a, 4) print(a) assert (a[:5] == [1, 1, 1, 1, 1]), 'Simple partition test 4(A) failed' assert (a[5:8] == [2, 2, 2]), 'Simple Partition test 4(B) failed' assert (a[8:12] == [3, 3, 3, 3]), 'Simple Partition test 4(C) failed' assert (a[12:14] == [4, 4]), 'Simple Partition test 4(D) failed' simplePartition(a, 5) print(a) assert (a == [1] * 5 + [2] * 3 + [3] * 4 + [4] * 2 + [5] * 2 + [6]), 'Simple Parition test 5 failed' print('Passed all tests : 10 points!')
true
20cd76884e972c00bb302984da2ba376d1a3ee16
LiLi-scripts/python_basic-1
/lesson5/practice_3.py
360
4.1875
4
""" Написать программу, которая принимает строку и выводит строку без пробелов и ее длину. """ def main(): string = input('Enter a string: ') string = cut_space(string) print(string, len(string)) def cut_space(string): return string.replace(' ', '') main()
false
33d79b2be6141fe735856e48f0326f3a3985410d
Krithip/Project97
/Project97.py
486
4.375
4
import random number = random.randint(1, 10) chances = 3 print("guess a number between 1 to 10") while chances>0: guess = int(input("enter your guess")) if(guess == number): print("Congratulations! You guessed correctly!") break elif guess<number: print("Your guess was wrong. Guess a higher number") else: print("Your guess was wrong. Guess a lower number") chances = chances - 1 if chances == 0: print("You lose")
true
6106000262c8c27de6702c31b99f56de5f3b51eb
BLINDICY/hello-world
/Sample.py 9.py
898
4.375
4
''' build a calculator that provides the amount of miles per gallon miles per gallon = miles driven/gallons used ''' print("This program calculates mpg.") miles_driven = float(input("Enter miles driven:")) gallons_used = float(input("Enter gallons used:")) mpg = miles_driven / gallons_used print("Your miles per gallon is", mpg) ''' build a calculator that provides the amount of miles per gallon miles per gallon = miles driven/gallons used ''' while True: print("This program calculates mpg.") miles_driven = float(input("Enter miles driven:")) gallons_used = float(input("Enter gallons used:")) mpg = miles_driven / gallons_used print("Your miles per gallon is", mpg) user_input = input("Would you like to perform a new calculation? Y/N:") if user_input == "Y" or user_input == "y": continue else: break
true
cde9221790009053236741a029ec71856bed9af2
solouniverse/Python
/DS/Recursion/Prog_Factorial.py
437
4.1875
4
# Iterative def ifact(n): res = 1 while n > 0: res *= n n -= 1 return res # Recursive def rfact(n): if n == 1: return 1 else: return n * rfact(n-1) if __name__ == "__main__": number = int(input("Please enter a number: ")) print(f"Factorial of {number} by iterative method is {ifact(number)}\n") print(f"Factorial of {number} by recursive method is {rfact(number)}\n")
false
72a4de9fb48040ec09c2462995f5d2b23787e4c2
solouniverse/Python
/B2BSWE/Patterns/Prog_Number_Columns.py
285
4.15625
4
n = int(input("Enter no of test runs: ")) while n > 0: rows = int(input("Enter no of rows: ")) columns = int(input("Enter no of columns: ")) for row in range(1, rows+1): for col in range(1, columns+1): print(col, end=" ") print() n = n - 1
true
9e3b9f1020c13c8227c0e73824b0ca82e40ec692
pavel-prykhodko96/source
/Python/CrashCourse/Chapter7/7_4_to_7_7.py
660
4.15625
4
#7_4 # ~ toppings = [] # ~ while True: # ~ topping = input('Please add the topping to the pizza: ') # ~ if topping != 'quit': # ~ toppings.append(topping) # ~ print("Your pizza consists of: ") # ~ for value in toppings: # ~ print(" " + value) # ~ else: # ~ break #7_5 while True: age = input('Please enter you age: ') if age == 'quit': break else: age = int(age) if age < 3: price = 'free' elif age < 12: price = '12$' else: price = '15$' print('The cost of your movie ticket is ' + price)
true
8c11d5edfd289216a3f3117453c8cd34e60fbe10
pablodarius/mod02_pyhton_course
/Python Exercises/02c.py
1,160
4.3125
4
import unittest # Desarrolle un algoritmo que permita leer tres valores y almacenarlos en las variables A, B, y C respectivamente. # El algoritmo debe indicar cual es el menor. Asumiendo que los tres valores introducidos por el teclado son valores distintos def smallest(a,b,c): if (a < b and a < c): result = "The smallest is A: %s" % (a) elif (b < c): result = "The smallest is B: %s" % (b) else: result = "The smallest is C: %s" % (c) return result A = 0 B = 0 C = 0 while (A == B or A == C or B == C): A = input("Introduce a number: ") B = input("Introduce another number: ") C = input("Introduce the last number: ") if (A == B or A == C or B == C): print("The three numbers must be different.") print(smallest(A,B,C)) class testing(unittest.TestCase): def test01(self): self.assertEqual(smallest(1, 2, 3), "The smallest is A: 1") def test02(self): self.assertEqual(smallest(4, 3, 2), "The smallest is C: 2") def test03(self): self.assertEqual(smallest(3, 1, 2), "The smallest is B: 1") if __name__ == "__main__": unittest.main()
false
fea8fde6eeb32ae954958a698bf2996b3674c356
pablodarius/mod02_pyhton_course
/Python Exercises/01.py
700
4.125
4
import unittest # Desarrolle un algoritmo que permita leer dos valores distintos, determinar cual de los dos valores es el mayor y escribirlo def greater(a, b): if a > b: result = "The greater is A: %s" % (a) else: result = "The greater is B: %s" % (b) return result A = 0 B = 0 while A==B: A = input("Introduce a number: ") B = input("Introduce another number: ") print(greater(A, B)) class testing(unittest.TestCase): def test01(self): self.assertEqual(greater(1, 2), "The greater is B: 2") def test02(self): self.assertEqual(greater(2, 1), "The greater is A: 2") if __name__ == "__main__": unittest.main()
false
efae9153863c81157544a6782296173897256c99
mscerba/engeto_python
/cv_65.py
1,079
4.125
4
""" Cílem tohoto cvičení je vytvořit funkci, která příjímá list dvou nebo více stringů jako vstup a vrací boolean hodnotu, která nám říká, jestli všechny prvky uvnitř listu jsou anagramy, nebo ne. #1 Pokud vložíme prázdný string, výstup by měl být False. #2 Pokud vložíme list s jedním slovem, výstup by měl být True. Příklad fungující funkce: all_anagrams(['ship', 'hips']) True all_anagrams(['ship', 'hips', 'name']) False all_anagrams(['ship']) True all_anagrams([]) False """ def all_anagrams(words): if bool(words) == False: return False elif len(words) == 1: return True else: word_select = list(words.pop()) word_len = len(word_select) for word in words: counter = 0 for i in word_select: if i not in word: return False else: counter += 1 if word_len == counter: break return True words = ['ship', 'hips', 'psih'] print(all_anagrams(words))
false
57adfacdab7cfcf5e3bc2a9daeed3e5dc053dcd9
ayazhemani/hackerrank-py
/python2/implementation/sequenceEquation/sequenceEquation.py
727
4.15625
4
"""Solution for HackerRank challenge: Sequence Equation """ def sequence_equation(seq): """Given a set of numbers, return the second index lookup (index of index) of the range of the sequence. Args: seq (int[]): Initial sequence of numbers Returns: int[]: Second index array of sequence """ result = [] for i in xrange(len(seq)): temp = seq.index(seq.index(i + 1) + 1) + 1 result.append(temp) return result def main(): """Receives input from stdin, provides output to stdout. """ raw_input() sequence = map(int, raw_input().split(' ')) for result in sequence_equation(sequence): print result if __name__ == '__main__': main()
true
36d954c35eabba69f32f92161814abd1048918c7
CRTC-Computer-Engineering/CRTC-Python-Examples
/CodeHS/6/4/9/Temperature-Converter-Travis.py
609
4.28125
4
# Write your function for converting Celsius to Fahrenheit here. # Make sure to include a comment at the top that says what # each function does! def convert_celsius_to_fahrenheit(num): return float((num - 32) / 1.8) # Now write your function for converting Fahrenheit to Celsius. def convert_fahrenheit_to_celsius(num): return float((1.8 * num) + 32) # Now change 0C to F: print convert_celsius_to_fahrenheit(0) # Change 100C to F: print convert_celsius_to_fahrenheit(100) # Change 40F to C: print convert_fahrenheit_to_celsius(40) # Change 80F to C: print convert_fahrenheit_to_celsius(80)
true
1ec63bcdda5d67149c28e27954daddc5cf92ffa4
CRTC-Computer-Engineering/CRTC-Python-Examples
/CodeHS/3/5/9/Recipe-Joe.py
1,245
4.25
4
""" This program made by Joe S """ servings = -1 # Set the servings to a null value shopping_list = ["mixed greens", "blueberries", "walnuts"] # Create a list of all the things we need to shop for object_list = [] # Create an empty list where we will store objects class ingredient(): # This class defines the ingredient object def __init__(self, name, qty): # This init function takes the name and qty, and asigns it to the object in question self.name = name self.qty = qty def list_total(self): # This function lists the content of the current item in a human readable way print("Total ounces of " + self.name + ": " + str(float(self.qty) * servings)) for listitem in shopping_list: # For every item on our shopping list print("Enter ingredient 1: " + str(listitem)) object_list.append(ingredient(listitem, input("Ounces of " + str(listitem) + ": "))) # Create a new object, add it to our list using inputs from the user servings = float(input("Enter total number of servings: ")) # Ask the user for the total number of servings print("") # Print a blank line for item in object_list: # For every object in our object list item.list_total() # call that objects respective list_total function
true
690c29e0c6e1a46ab3daa4416834c8840f210732
LeeAhYeong/Python_Class
/chapter03/05_draw_bar_graph.py
1,031
4.125
4
''' (1) turtle.color('red') -> 선과 칠하는 색 모두 빨간색 turtle.color('red','blue') -> 선의 색: 빨간색 칠하는 색: 파란색 (2) tutle.pencolor('red') -> 선의 색만 빨간색 tutle.fillcolor('red') -> 칠하는 색만 빨간색 * 주의 사항: begin_fill() 그리고 end_fill()과 같이 써야함 예) turtle.fillcolo('red') turtle.begin_fill() 도형 그리기 turtle.end_fill() ''' import turtle as t def draw_bar(height): t.begin_fill() t.forward(width) t.left(90) t.forward(height) t.write(str(height)) t.left(90) t.forward(width) t.left(90) t.forward(height) t.end_fill() # 도형 그리고 색칠 완료 t.left(90) # 화살표 위치 재조정 t.forward(width) t.color('blue','red') height_list = [120,66,309,220,156,23,98] width = 30 for i in range (0,7): #0,1,2,3,4,5,6 draw_bar(height_list[i]) #for detail in data : # for 변수 in [120,56,309,220,156,23,98] # drawBar(detail) t.done()
false
f71b4619ed6666733e8a63703de90f46cf51b1fa
r-luis/Python-CursoemVideo
/Download/PythonExercicios/ex037.py
726
4.34375
4
'''Escreva um programa que leia um número inteiro qualquer e pela para o usuárui escolher qual será a base de conversão: - 1 para binário; - 2 para octal; - 3 para hexadecimal''' num = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para conversão: [1] para Binário [2] para Octal [3] para Hexadecimal''') escolha = int(input('Sua opção: ')) if escolha == 1: print('{} convertido para binário é igual a {}'.format(num, bin(num)[2:])) elif escolha == 2: print('{} convertido para octal é igual a {}'.format(num, oct(num)[2:])) elif escolha == 3: print('{} convertido para hexadecimal é igual a {}'.format(num, hex(num)[2:])) else: print('Opção errada, tente novamente.')
false
04c6c639cc9d4d637624d7908d924755b3583223
JacobRuter/RockPaperScissors
/RockPaperScissors/RockPaperScissors.py
967
4.1875
4
import random; play = True; over = False; choices = ['rock', 'paper', 'scissors']; Userchoice = input() #Variable to take in user input print ("My choice is ", Userchoice) Computerchoice = choices[random.randint(0, 2)] print ("The computer choose ", Computerchoice) while (play == True): if Userchoice == 'rock' : if Computerchoice == 'rock' : print('You have Tied') elif Computerchoice == 'paper' : print('You lose') elif Computerchoice == 'scissors' : print('You Win') if Userchoice == 'paper' : if Computerchoice == 'paper' : print('You have Tied') elif Computerchoice == 'scissors' : print('You lose') elif Computerchoice == 'rock' : print('You Win') if Userchoice == 'scissors' : if Computerchoice == 'scissors' : print('You have Tied') elif Computerchoice == 'rock' : print('You lose') elif Computerchoice == 'paper' : print('You Win')
true
93bcaa902b4ecd7145c644255e0c4cb2773d2def
Mahii143/python-workshop
/CO4 questions/q no 10.py
594
4.46875
4
''' Q10: You must implement the function ''appendStringToFile'' which accepts two string values F and S. F represents a filename and S represents a string. The program must open the file F and append the string S with the existing content. ''' #function defined to append user input string into an existing file def appendStringToFile(A, B): file = open(A, 'a') file.write(" ") file.write(B) file.close() file = open(A, "r") print(file.readline()) F = input().strip() S = input().strip() #called the function to append the string a = appendStringToFile(F,S)
true
b3f753950bf61692794ac5404e32e386ff7c7bd3
avishith/cyber_mol
/cyber.py
2,362
4.21875
4
front1=" => " front2=". what is " end=" ?" index=1 key = ["firewall","phishing Attack","RAT","RAT","internet","VPN","APN","DDos Attack","Carding","Tail os","Dark net","vires","kali Linux","hosting","server","database","ip address", "clints & servers","git hub","RDP","anti-vires","Vulnerability","http","https","SSL","URL","Keystroke logging","Metasploit","NMAP","BIN","NETFLIX","nord VPN"," CC Generator","block chain", "cryptocurrency","google SEO","anonymous in hacking","SQL","SQL injections","steganography","Man In The Middle Attacks","cyber crime","port numbers","Beta Test","RDBMS"," IMEI","Cyber bulling", "‘OCR’","Algorithm","malicious activity","Cloud computing"] qus = [] c=5 d=12 m=10 y="2020" print(" \n 1.view all qustions \n 2.view quistions datewise \n 3. find with date") want=input("\n =>enter your choise :- ") if want=="2": for i in key: if i not in qus: if(c%5==0): print("") print(str(d)+'/'+str(m)+'/'+str(y)) print("") d=d+1 qus.append(i) Q = front1+str(index) + front2 + i + end print(Q) index=index+1 c=c+1 if want=="3": count=1 c=1 day=int(input(' =>which Date(example:12) :-')) print(str(day)+'/'+str(m)+'/'+str(y)) for i in key: if i not in qus: if day==d: qus.append(i) Q = front1+str(index) + front2 + i + end print(Q) index=index+1 if count==5: break count=count+1 else: qus.append(i) if(c%5==0): d=d+1 c=c+1 if want=="1": print("\n") for i in key: if i not in qus: qus.append(i) Q = front1+str(index) + front2 + i + end print(Q) index=index+1 # for i in key: # if i not in qus: # if(c%5==0): # print("") # print(str(d)+'/'+str(m)+'/'+str(y)) # print("") # d=d+1 # qus.append(i) # Q = front1+str(index) + front2 + i + end # print(Q) # index=index+1 # c=c+1
false
4f66a7f53d1cb9f4ca033bed66d6acae5093009f
Ankitapalle/Basic_python_projects
/gp_btw_dates.py
409
4.15625
4
"""Write a Python program to calculate number of days between two dates. Sample dates : (2014, 7, 2), (2014, 7, 11) Expected output : 9 days""" from datetime import date n = int(input("Enter date")) a = int(input("Enter month")) b = int(input("Enter year")) c = int(input("Enter date")) d = int(input("Enter month")) e = int(input("Enter year")) x = date(b,a,n) y = date(e,d,c) z = y - x print(z.days)
true
ec70323d0512171030f9ab08e660a5cfb76ca41a
Ankitapalle/Basic_python_projects
/Examination_schedule.py
404
4.125
4
"""Write a Python program to display the examination schedule. (extract the date from exam_st_date). exam_st_date = (11, 12, 2014) Sample Output : The examination will start from : 11 / 12 / 2014""" date = int(input("Enter the date - ")) month = int(input("Enter the month - ")) year = int(input("Enter the year - ")) exam_st_date = (date,month,year) print("The date of exam is %i/%i/%i"%exam_st_date)
true
f06c60a554755dcfbe2be586435232ffc4f1024b
antondelchev/For-Loop---More-Exercises
/04. Grades.py
1,189
4.125
4
students_attended = int(input()) students_b_grade = 0 students_c_grade = 0 students_d_grade = 0 students_f_grade = 0 grades_total = 0 for i in range(1, students_attended + 1): grade = float(input()) if grade < 3.0: students_f_grade += 1 grades_total += grade elif 3 <= grade <= 3.99: students_d_grade += 1 grades_total += grade elif 4 <= grade <= 4.99: students_c_grade += 1 grades_total += grade elif 5 <= grade <= 6: students_b_grade += 1 grades_total += grade students_b_grade_percent = students_b_grade / students_attended * 100 students_c_grade_percent = students_c_grade / students_attended * 100 students_d_grade_percent = students_d_grade / students_attended * 100 students_f_grade_percent = students_f_grade / students_attended * 100 average_grade = grades_total / students_attended print(f"Top students: {students_b_grade_percent:.2f}%") print(f"Between 4.00 and 4.99: {students_c_grade_percent:.2f}%") print(f"Between 3.00 and 3.99: {students_d_grade_percent:.2f}%") print(f"Fail: {students_f_grade_percent:.2f}%") print(f"Average: {average_grade:.2f}")
true
04a5ace1194b9db6a3a8ea58ca650626b782ff9d
jlehenbauer/python-projects-public
/codesignal/is_tandem_repeat.py
1,688
4.15625
4
''' Easy Codewriting 300 Determine whether the given string can be obtained by one concatenation of some string to itself. Example For inputString = "tandemtandem", the output should be isTandemRepeat(inputString) = true; For inputString = "qqq", the output should be isTandemRepeat(inputString) = false; For inputString = "2w2ww", the output should be isTandemRepeat(inputString) = false. Input/Output [execution time limit] 4 seconds (py3) [input] string inputString Guaranteed constraints: 2 ≤ inputString.length ≤ 20. [output] boolean true if inputString represents a string concatenated to itself, false otherwise. ''' def isTandemRepeat(inputString): for i in range(1, len(inputString)): if inputString[:i] == inputString[i:]: return True return False def isTrackingTandemRepeat(inputString): for i in range(1, len(inputString)): if inputString[:i] == inputString[i:2*i]: word = inputString[:i] split_string = inputString[i:] while len(split_string) > 0: print(split_string[:i]) if split_string[:i] == word: split_string = split_string[i:] else: break if len(split_string) == 0: return int(len(inputString)/len(word)) return 1 print(isTandemRepeat("tandemtandem")) print(isTrackingTandemRepeat("tandemtandem")) print(isTandemRepeat("nonononona")) print(isTrackingTandemRepeat("nonononano")) print(isTandemRepeat("hellohell")) print(isTrackingTandemRepeat("hellohell")) print(isTandemRepeat("whynot?")) print(isTrackingTandemRepeat("whynot?")) isTandemRepeat("")
true
b394479bbb7c1c248674b05a22dcdbfebaa16425
ravigummadi/dailyprogrammer
/C98_Easy.py
995
4.25
4
# Write a program that reads two arguments from the command line: # a symbol, +, -, *, or / # a natural number n (≥ 0) # And uses them to output a nice table for the operation from 0 to n, like this (for "+ 4"): # + | 0 1 2 3 4 # ------------------- # 0 | 0 1 2 3 4 # 1 | 1 2 3 4 5 # 2 | 2 3 4 5 6 # 3 | 3 4 5 6 7 # 4 | 4 5 6 7 8 # If you want, you can format your output using the reddit table syntax: # |+|0|1 # |:|:|: # |**0**|0|1 # |**1**|1|2 # Becomes this: # + 0 1 # 0 0 1 # 1 1 2 def operate(op1, op2, operator): if operator == "+": return op1+op2 elif operator == "*": return op1*op2 def main(): operator = "+" n = 5 print("%s | " % operator,end="") for i in range(0,n): print("%d " % i, end="") print() for i in range(0,n): print("---", end="") print() for i in range(0,n): print("%d | " % i, end="") for j in range(0,n): print("%d " % operate(i,j,operator), end="") print() if __name__ == '__main__': main()
false
00a03f3210dbaf9b12012c1e3e181943246b9c6d
parlizz/home_work_3
/dz_3_3.py
537
4.125
4
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, # и возвращает сумму наибольших двух аргументов. def my_func(arg_1, arg_2, arg_3): print(f'Сумма двух наибольших аргументов равна: {arg_1 + arg_2 + arg_3 - min([arg_1, arg_2, arg_3])}') my_func( int(input('аргумент 1: ')), int(input('аргумент 2: ')), int(input('аргумент 3: ')), )
false
16fa3cf6ec4321de8975fb0851e2e2aee5edfe41
SrikanthGoli/data-structures-algorithms
/algorithms/binary_search.py
808
4.1875
4
# Binary Search - O(logN) def binarySearch_recursive(key, input, left, right): """Searches the given element recursively""" if right >= left: mid = (left+right)//2 if input[mid] == key: return mid elif key < input[mid]: return binarySearch_recursive(key, input, left, mid) else: return binarySearch_recursive(key, input, mid+1, right) return False def binarySearch_iterative(key, input): """Searches the given element iteratively""" left = 0 right = len(input)-1 while right >= left: mid = (left + right)//2 if key == input[mid]: return mid elif key < input[mid]: right = mid-1 elif key > input[mid]: left = mid+1 return False
true
3f424498d47958d4364e9eb0d01aca776f14295e
CSCD01/team_14-project
/pandas_demo/netflix-example.py
1,659
4.1875
4
import pandas as pd from functools import reduce import os # author: Dax Patel # script to analyze netflix data # for given list of actors and actresses, we use # pandas to extract and manipulate data to compare # different stars' presence on Netflix per year # data source: https://www.kaggle.com/shivamb/netflix-shows/ # # In this script we # 1. Create a table dataset from CSV # 2. print the dataset # 3. perform dataset manipulation by adding a column for year_added # 4. perform dataset string search using regex filter # 5. perform data analysis function for aggregating movie titles per star # netflix titles data, with corresponding meta data, 6236 rows fname = './netflix_titles.csv' # read the csv as data frame object df = pd.read_csv(fname) # example list of starts to draw analysis from stars = ['Jon Hamm','Ellie Kemper', 'Morgan Freeman'] # extract just the year and save it as a column df['year_added'] = pd.DatetimeIndex(df['date_added']).year # build a regex to search within the cast column and return relevant rows containing # all stars in the list, and don't search inside the cells with invalid values # initialize list of data frames for all stars result = [] # for each start get a sum of their starring occurrences by year for star in stars: data = df[df['cast'].str.contains(star, case=False, na=False)] res = data.groupby(data['year_added'])['show_id'].count().reset_index(name=star) result.append(res) # apply outer join for all data frames stars_by_releases = reduce(lambda left,right: pd.merge(left,right,how='outer',on='year_added').fillna(0), result) # print by year print(stars_by_releases.sort_values(by=['year_added']))
true
44703d92c60a9d908b23321761753c8d528ff612
Isaac-Newt/python-learning
/Pre College/Scripts/Games/battleship_2.py
1,456
4.34375
4
from random import randint # Create "board" list board = [] # Create board layout for x in range(5): board.append(["0"] * 5) # Prints the board def print_board(board): for row in board: print " ".join(row) # Begin the game print "Let's play Battleship!" print_board(board) # Choose random row/col def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board) - 1) # Assign hiding spot for ship ship_row = random_row(board) ship_col = random_col(board) # To be used for debugging # print ship_row # print ship_col # Guessing Sequence begins # User gets 4 turns for turn in range(4): print "Turn", turn + 1 # Prompt for guesses guess_row = int(raw_input("Guess Row: ")) guess_col = int(raw_input("Guess Col: ")) # Do after guess if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You sunk my battleship!" else: if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4): print "Oops, that's not in the ocean!" elif (board[guess_row][guess_col] == "X"): print "You already guessed that one!" else: print "You missed my battleship!" # Put "X" on guessed spot board[guess_row][guess_col] = "X" print_board(board) if turn == 3: print "Game Over" break
true
522cafc9302be7a16c69ac9a75d98d0619de5554
DiegoAbrego/edai_practica10
/5.for.py
406
4.25
4
for x in [1,2,3,4,5]: #se itera el valor de x automaticamente recorriendo la lista print (x) #funcion range genera una lista #se genera la lista que inicia en 0 y hasta antes del numero indicado for x in range(5): print(x) #en este caso inicia en el -5 y llega hasta el 1 for x in range(-5,2): print(x) for num in ["uno","dos","tres","cuatro"]: print (num) input()
false
7e59aa1b5711c74f54ce50048fab5cc39259db63
hesham9090/Algorithms
/Bubble_Sort.py
707
4.34375
4
""" Bubble Sort Sorts a given array by bubble sort Input: An array data[0..n − 1] of orderable elements Output: Array data[0..n − 1] sorted in ascending order """ def bubble_sort(data): array_len = len(data) for i in range(array_len): for j in range(array_len - 1): if data[j] > data[j+1]: data[j] , data[j + 1] = data[j+1] , data[j] return data data = [100,12,90,19,22,8,12] data2 = [9] data3 = [10,9,8,7,6,5,4,3,2,1] test_case1 = bubble_sort(data) test_case2 = bubble_sort(data2) test_case3 = bubble_sort(data3) print(test_case1) print(test_case2) print(test_case3) """ Time Complexity Analysis O(n^2) """
false
46a3d854709790ed430be3b8682c6c89997b1418
NdeyJobe/games
/batteryship.py
2,443
4.21875
4
"""In this project I will build a simplified, one-player version of the classic board game Battleship! In this version of the game, there will be a single ship hidden in a random location on a 5x5 grid. The player will have 10 guesses to try to sink the ship.""" from random import randint from time import sleep board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) print "Welcome to the Northvolt battery ship!!!" sleep(2) print "We are transporting our battery packs to the Atlas Copco mines." sleep(3) print "For security reasons we are transporting real packs together with fake ones." sleep(3) print "The packs are arranged in rows and columns as shown below: " sleep(2) print_board(board) sleep(1) print "We challenge you to locate a real pack amongst the 25 packs and we will reward you with a muffin..." sleep(3) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_row print ship_col for turn in range(4): guess_row = int(raw_input("Guess row of real pack:")) guess_col = int(raw_input("Guess column of real pack:")) if guess_row == ship_row and guess_col == ship_col: print "Congratulations! You found a real pack! If you are already one of us you deserve a promotion. If you are not, please check our career page at http://northvolt.com/career. You definately belong with us." break else: if (guess_row < 0 or guess_row > 4) or (guess_col \ < 0 or guess_col > 4): print "Oops, that pack is not even in our ship." elif(board[guess_row][guess_col] == "X"): print "You guessed that one already." else: print "You missed!!! This is Northvolt security you tried to mess with." sleep(2) print "Try hacking again..." board[guess_row][guess_col] = "X" if turn == 3: print "We gave you four chances, we missed them all. Go take a nap, and next time dont mess with Northvolt security!" break print "That was turn:" print turn sleep(3) print "The correct location of a real pack was" print_board(board) sleep(2) print "We are giving you another chance to locate a real pack. This is turn:" print (turn + 1)
true
53472c77a29981867a423bdde548904235b8a3bb
estraviz/pybites-exercises
/251_Introducing_Pandas_Series/series.py
1,462
4.1875
4
""" Bite 251. Introducing Pandas Series """ import string import pandas as pd def basic_series() -> pd.Series: """Create a pandas Series containing the values 1, 2, 3, 4, 5 Don't worry about the indexes for now. The name of the series should be 'Fred' """ return pd.Series([1, 2, 3, 4, 5], name='Fred') def float_series() -> pd.Series: """Create a pandas Series containing the all the values from 0.000 -> 1.000 e.g. 0.000, 0.001, 0.002... 0.999, 1.000 Don't worry about the indexes or the series name. """ return pd.Series([x/1000 for x in range(1001)]) def alpha_index_series() -> pd.Series: """Create a Series with values 1, 2, ... 25, 26 of type int64 and add an index with values a, b, ... y, z so index 'a'=1, 'b'=2 ... 'y'=25, 'z'=26 Don't worry about the series name. """ return pd.Series(list(range(1, 27)), index=[chr(x) for x in range(97, 123)]) class MyClass: def __init__(self, name): self.name = name def get_name(self): return self.name def object_values_series() -> pd.Series: """Create a Series with values A, B, ... Y, Z of type object and add an index with values 101, 102, ... 125, 126 so index 101='A', 102='B' ... 125='Y', 126='Z' Don't worry about the series name. """ list_of_objects = [MyClass(chr(i)) for i in range(65, 91)] return pd.Series([x.name for x in list_of_objects], index=list(range(101, 127)))
true
b1fba1d30c2f5c5b71191eee152dcfc3d4ee9cb7
evans-osinaike/Introduction-to-Python-Programming
/password_generator.py
1,131
4.125
4
# TODO: First import the `random` module import random as r # We begin with an empty `word_list` word_file = "word_list.txt" word_list = [] # We fill up the word_list from the `word_list.txt` file with open(word_file,'r') as words: for line in words: # remove white space and make everything lowercase word = line.strip().lower() # don't include words that are too long or too short if 3 < len(word) < 8: word_list.append(word) # TODO: Add your function generate_password below # It should return a string consisting of three random words # concatenated together without spaces def generate_password(word_list): count = 0 #Iteration counter password = '' while count < 3: #pick random index on the list i = r.randrange(0,len(word_list)) # update the current password phrase password += word_list[i] count += 1 return password # Now we test the function print(generate_password(word_list)) def generate_password(): return r.choice(word_list) + r.choice(word_list) + r.choice(word_list) def generate_password(): return ''.join(r.sample(word_list,3))
true
c10a647cfdd8ae8f692af04ca3aac8c81cf22c39
MrDrewShep/Python_fundamentals
/review_of_fundamentals.py
2,372
4.125
4
# Want to edit items? LIST # Strict set of sequence? TUPLE # Want everything to be unique? SET # List # CRUD my_list = [2, 4, 3] # create first_item = my_list[0] # read #nested_item = my_list[0][2] # read within a nested list my_slice = my_list[-2::] # returns last 2 print(my_slice) my_slice = my_list[::-1] # Start at beginning, work backwards my_list.append(6) # update my_list.append([10, 11, 12]) # update my_list.insert(2, 8) my_list.extend([10, 11, 12]) my_list.pop() # update, pop last off the list, and return it my_list[1] = 777 # insert, as indexed print(my_list) print(my_list) my_list.remove(777) # remove a specific item del my_list # delete # Loops # Ability to iterate over an interable, or until a condition becomes False x=0 for i in range(10): x += 1 if i >= 7: break # this will technically end the loop if i > 8: continue # continue will goto the next iteration of the loop a = i + i # this line never fires n = 8 while n >= 0: print("not yet") n -= 1 print("finally done") # Dictionary # key value collection, unordered and mutable {} my_dictionary = { "name":"drew shep", "age": 31 } #my_dictionary.get() my_dictionary["name"] = "mr squiggles" my_dictionary["hobby"] = "python" print(my_dictionary) my_dictionary.update({ "hobby": "golf", "age" : 33 }) # hobby was added, age was updated print(my_dictionary) my_dictionary.keys() my_dictionary.values() my_dictionary.items() # grabs key/value pairs in a list of tuples # Functions def func_name(param1, param2): func_name(arg1, arg2) # Classes # A custom, datatype object that holds attributes and methods class Animal: def __init__(self, kingdom): self.kingdom = kingdom def get_kingdom(self): return self.kingdom class Human(Animal): def __init__(self, kingdom, name, age): super().__init__ # Takes the Human we just created and also initializes them as an animal self.name = name self.age = age def speak(self): return f'Hello, I am {self.name}' me = Human("camelot", "drewbie", 31) print(me.get_kingdom()) # Virtual environments # isolated environment in python used to test and share projects in order to keep dependencies local
true
a5ab872c39cd51102f50ae41ba23171e7b5c24c4
Rohini110/Assignment
/PPL Assignment/Assignment_3/square.py
634
4.1875
4
import turtle class square(): def __init__(self,a = 5): self.__side = a def get_side(self): return self.__side def find_area(self): return (self.__side * self.__side) def find_perimeter(self): return(4 * self.__side) def draw(self): t = turtle.Turtle() t.forward(self.__side) t.left(90) t.forward(self.__side) t.left(90) t.forward(self.__side) t.left(90) t.forward(self.__side) t.left(90) turtle.done() s = square(200) print("Length of the side of square is ",s.get_side(),"cm") print("Area of square is ",s.find_area(),"sq.cm") print("Perimeter of square is",s.find_perimeter(),"cm") s.draw()
false