blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
f7f0a8f33e0fef38681833506dc13f7298313781 | Take-Me1010/kivy_graphWriter | /libs/textentry.py | 473 | 3.578125 | 4 | from kivy.uix.textinput import TextInput
class TextEntry(TextInput):
'''
single line text input.
its height is 30 by default.
if you want to change it, call like this; TextEntry(height=35)
'''
def __init__(self, **kwargs):
super().__init__(multiline=False, **kwargs)
self.size_hint_y = kwargs.get("size_hint_y", None)
self.height = kwargs.get("height", 30)
def on_enter(self):
pass |
60fac5b7c3ddf5db445aea489bf409635613eccc | e8johan/adventofcode2018 | /5/5b.py | 653 | 3.53125 | 4 | polymer = raw_input()
def length(polymer):
while True:
found = False
for i in range(len(polymer)-1):
if not polymer[i] == polymer[i+1] and polymer[i].lower() == polymer[i+1].lower():
polymer = polymer[:i] + polymer[i+2:]
found = True
break
if not found:
break
return len(polymer)
alphabeth = "abcdefghijklmnopqrstuvwxyz"
polymers = {}
min_len = len(polymer)
for c in alphabeth:
print c
polymers[c] = filter(lambda x: not x.lower() == c, polymer)
l = length(polymers[c])
if l < min_len:
min_len = l
print min_len
|
8e5843c466834ef6b50b5e56a4a9a36dcadc37f8 | deividas-pelakauskas/visual-maze-solver | /maze.py | 9,953 | 4.21875 | 4 | import random
class Maze:
cell = "c" # cell marking on maze
unv_cell = "u" # unvisited cell marking on maze
wall = "w" # wall marking on maze
def __init__(self, width, height):
self.width = width
self.height = height
self.maze = [[self.unv_cell for i in range(self.width)] for j in range(self.height)]
self.walls = []
self.path = [] # to record path how maze is generated for visualisation later
self.start_pos = 0 # starting coordinate for maze
self.exit_pos = 0 # exit coordinate for maze
def generate_full_maze(self):
# Generates full maze including start and exit positions
self.starting_position() # set starting position and walls around it
self.generate_maze() # generates walls and passages
self.remaining_walls() # marks remaining unvisited cells as walls
self.set_entrance_exit() # set entrance point for the maze
def generate_maze(self):
# Main function that generates maze
while self.walls:
# select random wall from existing walls
random_wall = self.walls[(random.randint(0, len(self.walls) - 1))]
if random_wall[1] != 0: # check if it is not the first column on the left
# check if on the left next to the generated previously random wall there as an unvisited cell
# check if there is a cell next to random wall on the right
if self.maze[random_wall[0]][random_wall[1] - 1] == self.unv_cell and self.maze[random_wall[0]][random_wall[1] + 1] == self.cell:
if self.surrounding_cell_count(random_wall) < 2: # get number of surrounding cells
# turn wall into passage if there are less than two surround cells
self.maze[random_wall[0]][random_wall[1]] = self.cell
# record new cell for visualisation
self.path.append(random_wall)
# mark surrounding walls as part of maze
# mark upper, bottom and left walls, because there is a cell on the right
self.mark_upper_wall(random_wall)
self.mark_bottom_wall(random_wall)
self.mark_left_wall(random_wall)
# remove processed wall from the walls list and continue to next iteration
self.delete_wall(random_wall)
continue
if random_wall[0] != 0: # check if it is not the first row of the maze
if self.maze[random_wall[0] - 1][random_wall[1]] == self.unv_cell and self.maze[random_wall[0] + 1][random_wall[1]] == self.cell:
if self.surrounding_cell_count(random_wall) < 2:
self.maze[random_wall[0]][random_wall[1]] = self.cell
self.path.append(random_wall)
self.mark_upper_wall(random_wall)
self.mark_left_wall(random_wall)
self.mark_right_wall(random_wall)
self.delete_wall(random_wall)
continue
if random_wall[0] != self.height - 1: # check if it is not a last row of the maze
if self.maze[random_wall[0] + 1][random_wall[1]] == self.unv_cell and self.maze[random_wall[0] - 1][random_wall[1]] == self.cell:
if self.surrounding_cell_count(random_wall) < 2:
self.maze[random_wall[0]][random_wall[1]] = self.cell
self.path.append(random_wall)
self.mark_bottom_wall(random_wall)
self.mark_left_wall(random_wall)
self.mark_right_wall(random_wall)
self.delete_wall(random_wall)
continue
if random_wall[1] != self.width - 1: # check if it is not the last column of the maze
if self.maze[random_wall[0]][random_wall[1] + 1] == self.unv_cell and self.maze[random_wall[0]][random_wall[1] - 1] == self.cell:
if self.surrounding_cell_count(random_wall) < 2:
self.maze[random_wall[0]][random_wall[1]] = self.cell
self.path.append(random_wall)
self.mark_right_wall(random_wall)
self.mark_bottom_wall(random_wall)
self.mark_upper_wall(random_wall)
self.delete_wall(random_wall)
continue
# if none of the conditions are met, delete wall from the list anyway
for wall in self.walls:
if wall[0] == random_wall[0] and wall[1] == random_wall[1]:
self.walls.remove(wall)
def starting_position(self):
# Pick random starting position and mark walls around it
first_row = random.randint(0, self.height - 1) # starting position (coordinate) in a row
first_col = random.randint(0, self.width - 1) # starting position (coordinate) in a column
# Make sure that starting position is not on the edge of the maze
if first_row == 0:
first_row = 1
if first_row == self.height - 1:
first_row -= 1
if first_col == 0:
first_col = 1
if first_col == self.width - 1:
first_col -= 1
# Mark starting position as a cell
self.maze[first_row][first_col] = self.cell
self.path.append(list([first_row, first_col]))
# Mark walls around starting cell in the grid
self.maze[first_row - 1][first_col] = self.wall
self.maze[first_row + 1][first_col] = self.wall
self.maze[first_row][first_col - 1] = self.wall
self.maze[first_row][first_col + 1] = self.wall
# Add walls around starting cell to the walls list
self.walls.append([first_row - 1, first_col])
self.walls.append([first_row + 1, first_col])
self.walls.append([first_row, first_col - 1])
self.walls.append([first_row, first_col + 1])
def surrounding_cell_count(self, wall):
# Count how many cells around given wall there is
# this is used to make sure that every attempt to make a passage does not have more than one cell around it
cell_count = 0
if self.maze[wall[0] - 1][wall[1]] == self.cell:
cell_count += 1
if self.maze[wall[0] + 1][wall[1]] == self.cell:
cell_count += 1
if self.maze[wall[0]][wall[1] - 1] == self.cell:
cell_count += 1
if self.maze[wall[0]][wall[1] + 1] == self.cell:
cell_count += 1
return cell_count
def mark_upper_wall(self, wall):
# Mark as wall above cell after another wall was turned into a passage
if wall[0] != 0:
if self.maze[wall[0] - 1][wall[1]] != self.cell:
self.maze[wall[0] - 1][wall[1]] = self.wall
if [wall[0] - 1, wall[1]] not in self.walls:
self.walls.append([wall[0] - 1, wall[1]])
def mark_bottom_wall(self, wall):
# Mark as wall below cell after another wall was turned into a passage
if wall[0] != self.height - 1:
if self.maze[wall[0] + 1][wall[1]] != self.cell:
self.maze[wall[0] + 1][wall[1]] = self.wall
if [wall[0] + 1, wall[1]] not in self.walls:
self.walls.append([wall[0] + 1, wall[1]])
def mark_left_wall(self, wall):
# Mark as wall left to cell after another wall was turned into a passage
if wall[1] != 0:
if self.maze[wall[0]][wall[1] - 1] != self.cell:
self.maze[wall[0]][wall[1] - 1] = self.wall
if [wall[0], wall[1] - 1] not in self.walls:
self.walls.append([wall[0], wall[1] - 1])
def mark_right_wall(self, wall):
# Mark as wall right to cell after another wall was turned into a passage
if wall[1] != self.width - 1:
if self.maze[wall[0]][wall[1] + 1] != self.cell:
self.maze[wall[0]][wall[1] + 1] = self.wall
if [wall[0], wall[1] + 1] not in self.walls:
self.walls.append([wall[0], wall[1] + 1])
def delete_wall(self, random_wall):
# Delete random wall from the list if it is in the list
for wall in self.walls:
if wall[0] == random_wall[0] and wall[1] == random_wall[1]:
self.walls.remove(wall)
def remaining_walls(self):
# Function marks remaining unvisited cells as walls
for row in range(self.height):
for col in range(self.width):
if self.maze[row][col] == self.unv_cell:
self.maze[row][col] = self.wall
def set_entrance_exit(self):
# Sets starting point and exit point on the maze and saves starting point for solving algorithm
# get second row indexes where cells are located
entrance_indexes = [index for index in range(len(self.maze[1])) if self.maze[1][index] == "c"]
# get one before last row indexes where cells are located
exit_indexes = [index for index in range(len(self.maze[self.height - 2])) if self.maze[self.height - 2][index] == "c"]
# select random index for entrance point
random_entrance = random.choice(entrance_indexes)
# select random index for exit point
random_exit = random.choice(exit_indexes)
# mark starting point
self.maze[0][random_entrance] = "s"
# mark exit point
self.maze[self.height - 1][random_exit] = "e"
# record starting point for solving algorithms
self.start_pos = random_entrance
self.exit_pos = random_exit
self.path.append([0, random_entrance])
self.path.append([len(self.maze) - 1, random_exit]) |
bc25ebeb96cf7e05820e7fe85f63b363e4a58895 | ai2-education-fiep-turma-2/05-python | /solucoes/Natalia/bash_py04.py | 256 | 3.90625 | 4 | n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))
print ("soma = ", n1 + n2)
print ("diferença = ", n1 - n2)
print ("produto = ", n1 * n2)
print ("quociente = ", n1 / n2)
print ("resto da divisão = ", n1 % n2)
|
9d0a2d27e6dcf6e61f14e3f8ad7aed72d879626a | benrose258/Python | /Python 3.6 Files/Classwork/CS 115/spiral - part of turtle.py | 444 | 3.8125 | 4 | '''
Created on Feb 16, 2017
@author: Ben Rose
'''
import turtle
def squareSpiral(walls):
def squareSpiralHelper(distance,initial,count):
if count == walls:
turtle.done()
else:
turtle.left(90) #Moves the turtle left 90 degrees
turtle.forward(distance)
return squareSpiralHelper(distance+initial * (count % 2),initial,count+1)
squareSpiralHelper(20,20,0)
squareSpiral(30)
|
25e98cf7b22e96811bfe666ab25db99a7c1465d3 | Rajeshdraksharapu/Leetcode-Prblems | /candyCrushRepeat.py | 1,622 | 3.8125 | 4 | def CandyCrush(candies):
#First Cheack the rows
for col in range(len(candies[0])):
for row in range(len(candies)-2):
num1=abs(candies[row][col])
num2=abs(candies[row+1][col])
num3=abs(candies[row+2][col])
if num1==num2 and num2==num3 and num1!=0:
candies[row][col]=-num1
candies[row+1][col]=-num2
candies[row+2][col]=-num3
for row in range(len(candies)):# Checking column if 3 consequtive elements are same then we put -num to it
for col in range(len(candies[0])-2):
num1=abs(candies[row][col])
num2=abs(candies[row][col+1])
num3=abs(candies[row][col+2])
if num1==num2 and num2==num3 and num1!=0:
candies[row][col]=-num1
candies[row][col+1]=-num2
candies[row][col+2]=-num3
#print(candies)
crush=False
for column in range(len(candies[0])):
swap=len(candies)-1
for row in range(len(candies)-1,-1,-1):
if candies[row][column]>0:
candies[swap][column]=candies[row][column]
swap-=1
for swapable in range(swap,-1,-1):
candies[swapable][column]=0
print(candies)
board =[
[110,5,112,113,114],
[210,211,5,213,214],
[310,311,3,313,314],
[410,411,412,5,414],
[5,1,512,3,3],
[610,4,1,613,614],
[710,1,2,713,714],
[810,1,2,1,1],
[1,1,2,2,2],
[4,1,4,4,1014]
]
CandyCrush(board)
|
d0fa360e0d87c9e15f353f66de059299cd35bdb4 | adamdrucker/python-guizero-test | /gui_test.py | 1,174 | 3.9375 | 4 | from guizero import App, Text, TextBox, PushButton, Slider, Picture
''' Func takes the value from "my_name", which is a text box
accepting input, and updates the "welcome_message" variable,
which is what's displayed in the window '''
def say_my_name():
welcome_message.value = first_name.value, last_name.value
# Update the button message
update_text.text = "You made a change!"
''' Func takes a value passed to it and then adjusts the message size
based on that value '''
def change_text_size(slider_value):
welcome_message.size = slider_value
# Creates the GUI app, with title
app = App("Hello, World!")
# Displays message in body of app window
welcome_message = Text(app, text="Welcome to my app!", size=30, font="Sans serif", color="blue")
# Displays text box in body
first_name = TextBox(app, width=20)
last_name = TextBox(app, width=20)
# Displays a button in the body
# The "command" argument allows for a function to be called on button push
update_text = PushButton(app, command=say_my_name, text="Display my name")
# Text size for slider
text_size = Slider(app, command=change_text_size, start=30, end=70)
app.display()
|
38e2143b83a77cbf1740af9e69d9d260b9767c1f | Draster51/Py_basics | /funciones2.py | 1,103 | 3.84375 | 4 | def multiplicar_por_dos (n): ##una funcion normal
return n*2
def sumar_dos (n): ##una funcion normal
return n+2
def aplicar_operacion (f,numeros): ##Esta funcion recibe 2 parametros: que funcion a usar y el arreglo de numeros
resultado = [] ##Aqui defino que la funcion va a usar un array
for numero in numeros: ##defino que un ciclo para recorrer el arreglo
resultado = f(numero) ##defino que el resultaod va a ser una funcion ya declarada
resultado.append(resultado) ##
sumar = lambda x, y: x + y ##Aqui uso la funcion lamnda como definicion de la variable sumar
def aplicar_operaciones(num):
operaciones = [abs, float] ##Utilizo la funcion abs dentro de un arreglo que utilizara una funcion
resultado = [] ##defino que la funcion va a usar un array
for operacion in operaciones: ##defino un ciclo
resultado.append(operacion(num)) ##defino lo que el ciclo hara, llama la misma funcion en la cual esta encapsulado
return resultado |
4406d653e5205cb91bc389df70164ab254adda96 | henrylu518/LeetCode | /Insert Interval.py | 1,314 | 4 | 4 | """
Author: Henry, henrylu518@gmail.com
Date: May 8, 2015
Problem: Insert Interval
Difficulty: Medium
Source: https://oj.leetcode.com/problems/insert-interval/
Notes:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
"""
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def insert(self, intervals, newInterval):
return self.merge(intervals + [newInterval])
def merge(self, intervals):
if intervals == []: return []
intervals = sorted(intervals, key = lambda m : m.start)
result = [intervals[0]]
for i in xrange(1, len(intervals)):
if result[-1].end >= intervals[i].start:
result[-1].end = max(result[-1].end, intervals[i].end)
else:
result.append(intervals[i])
return result |
d732bfc4c9ecf3121a0bdf897eddf0b3cd414638 | mlbudda/Checkio | /elementary/first_word_simplified.py | 256 | 3.96875 | 4 | # First Word (simplified)
def first_word(text):
""" Splits and returns first word """
return text.rsplit()[0]
# Running some tests...
print(first_word("Hello world") == "Hello")
print(first_word("a word") == "a")
print(first_word("hi") == "hi") |
25fedf3055705e2aad19806ab3d1836563f42136 | jamesfulford/misc-software | /game-simulation/7 Wonders/engine/city.py | 1,296 | 3.640625 | 4 | # city.py
# by James Fulford
import json
cities = json.load(open("cities.json"))
resources = [
"wood",
"ore",
"stone",
"brick",
"cloth",
"glass",
"paper"
]
class City():
played_cards = [] # make sure no None shows up here
# to avoid free card exploits for cards without prebuilds
hand = []
resources = {}
coins = 0
def __init__(self, name, side, start_coins=3):
self.coins = start_coins
self.get_benefits(cities[name][side]["resources"])
def get_benefits(self, benefits):
for bene in benefits.keys():
if bene in resources:
try:
self.resources[bene] += benefits[bene]
except KeyError:
self.resources[bene] = benefits[bene]
def can_play(self, card):
"""
Returns whether given card can be played by this city.
Cannot play cards you have already built.
Can build cards you have prebuild for
Cannot build cards if insufficient resources
"""
played_cards = map(lambda x: str(x).lower(), self.played_cards)
if str(card).lower() in played_cards:
return False
if card.prebuild in played_cards:
return True
for res in card.cost
|
ad9023de91e638ffbc6da9cd817fb6304283ec67 | 8439941788/Repo-1 | /jj.py | 1,469 | 3.84375 | 4 | import random
list=["s","w","g"]
print("NUMBER OF ATTEMPTS=10")
print("Snake as s,Water as w,Gun as g")
print("lets the game begin")
print("your score represented by 'z',comp score represented by 'y'")
name=input("Enter your name")
for i in range(10):
v = random.choice(list)
x = input("enter your choice")
if x=='s':
if x=='s'and v=='s':
print("you choose",x)
print("comp choose",v)
print("Draw")
elif x=='s'and v=='w':
print("you choose",x)
print("comp choose",v)
print("you won")
elif x=='s'and v=='g':
print("you choose",x)
print("comp choose",v)
print("comp won")
elif x=='w':
if x=='w'and v=='s':
print("you choose",x)
print("comp choose",v)
print("comp won")
elif x=='w'and v=='w':
print("you choose",x)
print("comp choose",v)
print("draw")
elif x=='w'and v=='g':
print("you choose",x)
print("comp choose",v)
print("you won")
elif x=='g':
if x=='g'and v=='s':
print("you choose",x)
print("comp choose",v)
print("you won")
elif x=='g'and v=='w':
print("you choose",x)
print("comp choose",v)
print("comp won")
elif x=='g'and v=='g':
print("you choose",x)
print("comp choose",v)
print("draw")
print("no of attempt left",10-(i+1))
|
946ca8b9b39fd1c509f035fdb5e2bfbce7a33efe | XTmingyue/Algorithm | /Tree/145_postorderTraversal.py | 688 | 3.625 | 4 | #!/usr/bin python
# -*- coding: utf-8 -*-
# @Time : 2020/8/16 11:29 下午
# @Author : xiongtao
# @File : 145_postorderTraversal.py
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class PostorderTraversal():
# 返回以root为根结点的后序遍历
def postorderTraversal(self, root:TreeNode):
if root==None:
return None
elif root.left==None and root.right==None:
return [root.val]
else:
nums = self.postorderTraversal(root.left)
nums.extend(self.postorderTraversal(root.right))
nums.append(root.val)
return nums |
5873802db5dbb61e0445e55f05013453af330f55 | jakegoodman01/LinearAlgebraTools | /api/vector-header.py | 2,110 | 3.546875 | 4 |
"""
This file contains the documentation for vector.py
"""
# conj(z) produces the conjugate of z
# modulus(z) produces the modulus of z
# format_complex(z) produces the string representation of z
# Vector(*args):
# A Vector object represents the vector with the given coordinates in args
# Vector = (args[0], args[1], ..., args[n])^T
# :param args: the coordinates of the Vector
#
# FIELDS:
# * components: the list of the components of the vector
# * field: the field of the vector
# * dim: the dimension of the vector
#
# METHODS:
# * zero_vector() produces the zero_vector in the same dimension as self
# * is_zero() produces true if self is the zero vector
# * copy() produces a copy of self
# * sub(n) produces the nth component of self
#
# is_equal(v, w) produces true if v equals w
# add(v, w, *args) produces the sum of v, w and args
# requires: v and w are in the same dimension
# negate(v) produces -v
# subtract(v, w) produces the difference v - w
# requires: v and w are in the same dimension
# scalar_multiply(v, s) produces the product of v and s
# requires: v and s are in the same field
# is_scalar_multiple(v, w) produces true if v and w are scalar multiples of each other
# requires: v and w are in the same dimension
# dot_product(v, w) produces the dot product of v and w
# requires: v and w are in the same dimension
# norm(v) produces the length (or norm) of v
# normalize(v) produces v normalized
# is_orthogonal(v, w) produces true of v and w are orthogonal
# angle(v, w) produces the angle, in radians [0, pi], between v and w
# proj(v, w) produces the projection of v along w
# component(v, w) produces the component of v along w
# requires: w != 0
# perp(v, w) produces the remainder of v along w, a.k.a. perp
# requires: w != 0
# vector_conj(v) produces the conjugate of vector v
# inner_product(w, z) produces the standard inner product <w, z>
# cross_product(u, v) produces the cross product of u and v
# requires: u and v are vectors in R^3
# extend_zeros(v, n) adds n zeros of "padding" onto the tail of v, modifies v
|
5cf379af971e08befdf1b8fc428a71fc00335055 | aleontiev-sf/Homework3 | /PyPoll/main.py | 3,180 | 4.03125 | 4 | # This python script reads an input file, in a subdirectory called Resrouces,
# containing voting results.
# After processing all the input data, it prints the total number of votes, the percentage
# of votes and total votes for each candidate, as well as the overall winner.
# Data in the input file are in csv format and comprised of three columns (all strings):
# voter ID, county and candidate.
# Input data (rows) are assumed to be unique (no duplicates) and contiguous (no gaps).
# To process a different file, change the input file name in line 18.
# Results are also saved in an output file in the Resources subdirectory.
# NOTE: the output file is overwritten; if its contents are needed, either
# save its contents to another file OR change the name of the output file.
#
# Dependencies
import os
import csv
candidates = {} # Declare a dictionary called candidates
# index candidate name, value vote count
election_csv = os.path.join("Resources", "election_data_2.csv")
with open(election_csv, newline="") as csvfile:
csvreader = csv.reader (csvfile, delimiter=",")
next (csvreader) # Skip over the first line (the header)
for row in csvreader: # For every row in the input file check to see:
if row[2] in candidates: # If the current candidate exists in the candidates dict
candidates[row[2]] += 1 # if so, increment her/his vote count
else: # otherwise
candidates[row[2]] = 1 # initialize her/his vote to 1
total_votes = csvreader.line_num - 1 # Total number of votes is the number of lines
# in input file minus 1 (header line)
print ("Election Resuls\n")
print ("--------------------------\n")
print ("Total Votes: " + str(total_votes))
print ("\n--------------------------\n")
for key, value in candidates.items(): # This loop prints voting results for each candidate
# key is candidate name, value is the vote count
print (key + ": " + "{0:.1f}%".format(value/total_votes * 100) +
" (" + str(value) + ")")
print ("\n--------------------------\n")
print ("Winner: " + max(candidates, key=candidates.get) ) # determine the winner using
print ("\n--------------------------") # max method
# Now output same results to the output file
# NOTE: the output file is overwritten; if its contents are needed, either
# save its contents to another file OR change the name of the output file below
output_path = os.path.join('Resources', 'Election_results_2.txt')
with open(output_path, 'w') as f:
f.write ("Election Resuls\n")
f.write ("--------------------------\n")
f.write("Total Votes: " + str(total_votes) + '\n')
f.write ("\n--------------------------\n")
for key, value in candidates.items():
f.write(key + ": " + "{0:.1f}%".format(value/total_votes * 100) +
" (" + str(value) + ")\n")
f.write ("\n--------------------------\n")
f.write("Winner: " + max(candidates, key=candidates.get) + '\n')
f.write ("\n--------------------------") |
d27f831503867712df6bed4389c6019788975487 | puneet4840/Data-Structure-and-Algorithms | /Dynamic Programming/1.1 - Normal Fibonacci without DP.py | 284 | 3.921875 | 4 | # Fibonacci Series without Dynamic Programming.
print()
from time import time
def Fib(n):
if n<=1:
return n
else:
return Fib(n-2)+Fib(n-1)
n=int(input('Enter the nth term: '))
t1=time()
result=Fib(n)
t2=time()
print(result)
print(f'{round(t2-t1,2)} sec') |
8b452520bc41b9b02b9a17e0b0874e07dadfec40 | imaaduddin/Everything-Python | /WhileLoop.py | 201 | 4.21875 | 4 | # while loop = a statement that will execute it's block of code as long as it's condition remain true
name = ""
while len(name) == 0:
name = input("Enter your name!")
print("Hello " + name + "!") |
a40e41f6a4b42512fdc1b53dae024347c8b6a787 | Nicoleyuan/Why-do-not-you-study-from-now-on | /Algorithm/Experiment/1 Sorting Algorithm/MergeSort.py | 1,020 | 3.734375 | 4 | #coding: utf-8
#!/usr/bin/python
import time
from random100 import get_andomNumber
'''
#随机生成0~100之间的数值
def get_andomNumber(num):
lists=[]
i=0
while i<num:
lists.append(random.randint(0, 100))
i+=1
return lists
'''
start =time.clock()
#归并排序
def merge_sort(lists):
if len(lists) <= 1:
return lists
mid = int(len(lists) / 2)
left = merge_sort(lists[:mid])
right = merge_sort(lists[mid:])
return merge(left, right)
def merge(left,right):
result=[]
i,j=0,0
while i<len(left) and j<len(right):
if left[i]<=right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
result+=left[i:]
result+=right[j:]
return result
a = get_andomNumber(100000)
'''print("排序之前:%s" %a)
b = merge_sort(a)
print("排序之后:%s" %b)
'''
end = time.clock()
print('Merge_Sort Running time: %s s'%((end-start)*60))
|
7839bce01e42483d5987a7f19de738a6d79f72b2 | MateuszMazurkiewicz/CodeTrain | /InterviewPro/2019.11.12/task.py | 1,068 | 4.28125 | 4 | '''
You are given a hash table where the key is a course code, and the value is a list of all the course codes that are prerequisites for the key. Return a valid ordering in which we can complete the courses. If no such ordering exists, return NULL.
Example:
{
'CSC300': ['CSC100', 'CSC200'],
'CSC200': ['CSC100'],
'CSC100': []
}
This input should return the order that we need to take these courses:
['CSC100', 'CSC200', 'CSCS300']
Here's your starting point:
'''
def courses_to_take(course_to_prereqs):
queue = []
order = []
for node in courses:
if len(courses[node]) == 0:
queue.insert(0, node)
while len(queue) > 0:
node = queue.pop()
if node not in order:
order.append(node)
for n in courses.keys():
if set(courses[n]) <= set(order) and n not in order:
queue.insert(0, n)
return order
courses = {
'CSC300': ['CSC100', 'CSC200'],
'CSC200': ['CSC100'],
'CSC100': []
}
print(courses_to_take(courses))
# ['CSC100', 'CSC200', 'CSC300'] |
f121fa3555531d76e4732bc0c57a9be98192a65e | rosieyzh/comp321 | /assignment3/virus.py | 414 | 3.578125 | 4 | str1 = input()
str2 = input()
#pinpoint differing substring by comparing the two lines
start = 0
end1 = len(str1)-1
end2 = len(str2)-1
minlength = min(len(str1), len(str2))
#find index at first different char
while start < minlength and str1[start] == str2[start]:
start+=1
#find index of last different char
while min(end1, end2) >= start and str1[end1] == str2[end2]:
end1-=1
end2-=1
print(end2-start+1)
|
a3cd9c5806de522999befb35fd1d727e8f8ef90f | xiangyu-zhang-95/Learn-Python-The-Hard-Way | /Exercise-42/ex42.py | 666 | 3.890625 | 4 | class Animal(object):
def __init__(self):
return
def sound(self):
print("animal sound")
class Dog(Animal):
def __init__(self):
return
def sound(self):
print("dog sound")
class Human(Animal):
def __init__(self, name):
self.name = name
def sound(self):
print(f"human sound: I am {self.name}")
class Student(Human):
def __init__(self, name, school):
super(Student, self).__init__(name)
self.school = school
def sound(self):
print(f"student sound: I am {self.name} at {self.school}")
animal = Animal()
animal.sound()
dog = Dog()
dog.sound()
human = Human("xz")
human.sound()
student = Student("xz", "cornell")
student.sound()
|
ec3d030db3a3c7d9e311f4adc6527268b10a0ae0 | tapumar/Competitive-Programming | /Uri_Online_Judge/2203.py | 383 | 3.53125 | 4 | import math
while(True):
try:
jogo = input().split()
jogo = [int(x) for x in jogo]
d1 = math.sqrt( math.pow( jogo[0]-jogo[2], 2 ) + math.pow( jogo[1]-jogo[3], 2) ) + ( jogo[4]*1.5 );
d2 = jogo[5] + jogo[6];
if( d2 >= d1 ):
print("Y")
else:
print("N")
except EOFError:
break
|
a48599501e497c08ab99cdf4668bdc034fddd74a | betolabrada/10DaysOfStatistics | /day5_poisson1.py | 276 | 3.875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def fact(n):
return 1 if n <= 0 else n * fact(n-1)
def p(k, l):
return (l**k * math.exp(-l)) / fact(k)
mean = float(input())
val = int(input())
print("{:.3f}".format(p(val, mean)))
|
8c69aff61955897165e228c39da0f55aa508763a | SaiVK/Leetcode-Archive | /code/Simplified-Fractions.py | 631 | 3.609375 | 4 | class Solution(object):
def simplifiedFractions(self, n):
def solve_as_string(top, bottom):
r = (float(top) / float(bottom))
return str(r)
if (n == 1):
return []
allVals = []
vals = set()
tVals = []
while (n >= 2):
for i in range(1, n):
tVals.append([i, n])
n = (n - 1)
tVals.sort()
for (i, n) in tVals:
r = solve_as_string(i, n)
if (r not in vals):
vals.add(r)
allVals.append('{}/{}'.format(i, n))
return sorted(allVals) |
0f515db013195ca9a99b55741e2733f467f8847a | d3m41k/MyFirstQA | /3.py | 636 | 3.921875 | 4 | class Human:
def __init__(self, name, last_name):
self.name = name
self.last_name = last_name
def full_name(self):
return self.name + " " + self.last_name
class Student(Human):
def __init__(self, name, last_name, score):
self.name = name
self.last_name = last_name
self.score = score
def full_name(self):
return "Student: " + self.name + " " + self.last_name
def say_hello(self):
print("Hello, " + self.name)
human1 = Human("Dima", "Last Name")
student_dima = Student("Dima", "Student", 34)
print(student_dima.full_name()) |
669bdb089aa591b899d6a726864929812e26c47c | vivekpapnai/Python-DSA-Questions | /Recursion/printMinimumArray.py | 226 | 3.5 | 4 | import sys
def minArray(arr, mini):
if len(arr) == 0:
print(mini)
return
mini = min(mini, arr[0])
minArray(arr[1:], mini)
array = [5, 7, 11, -32, 9, 4]
minArray(array, sys.maxsize)
|
f032d73bc8368ad529a15084f67fd2b6f63ee25c | juan7914/prueba1 | /ejercicios clase tres 3/HolaMundoab.py | 229 | 3.96875 | 4 | print("si el primer numero es mayor al segundo imprime HOLA MUNDO")
a = float(input("ingresa el primer numero "))
b = float(input("ingresa el segundo numero "))
if a > b :
print("HOLA MUNDO")
else:
print("ADIOS MUNDO CRUEL")
|
f3cb317b0fcdeac4fae1444fd758f373b9bcec40 | HaroldAgnote/CECS-229 | /LabAssignments/Chapter 2/Lab5.py | 857 | 3.765625 | 4 | from plotting import plot
#1a
def addVectorsAndScale(a, v, w):
x = list(((v[i] + w[i]) for i in range(len(v))))
y = list(a*x[i] for i in range(len(v)))
return y
v = [1,2,3]
w = [1,0,-1]
a = 2
print(addVectorsAndScale(a,v,w))
#1b
def computeDotProduct(v, w):
sum = 0
for x in range((len(v))):
sum += v[x]*w[x]
return sum
def computeDotProductLine(v,w):
return sum(v[i]*w[i] for i in range(len(v)))
print(computeDotProductLine(v,w))
#2
pt1 = [3.5, 3]
pt2 = [.5, 1]
#Procedure multiplies the vector v by the scalar a
def scalar_vector_mult(a, v):
return [a*v[i] for i in range(len(v))]
#Procedure computes the sum of two vectors
def addVectors(v, w):
return [v[i] + w[i] for i in range(len(v))]
#plot([scalar_vector_mult(i/100, v) for i in range(101)], 5)
plot([addVectors(scalar_vector_mult(i/100, pt1), pt2) for i in range(101)], 4) |
16608f3505ca507b942e7352ed1d3256358e9eb8 | vithiyasivasamy/python-programming | /pos.py | 100 | 3.90625 | 4 | nu=int(input())
if(nu>0):
print("Positive")
elif(nu<0):
print("Negative")
else:
print("Zero")
|
24bf4ffe314e622f0a13e5615bdc02f6ba44435a | guojch/Python-learning-record | /study/cycle.py | 193 | 3.765625 | 4 |
# 循环
# for
a = range(10)
b = list(a)
print(a, b)
total = 0
for x in range(101):
total += x
print(total)
# while
total = 0
n = 99
while n > 0:
total += n
n -= 2
print(total)
|
8aa16a3f2880bae01986dfdcf43b625cca447279 | Sandeepyedla0/competitive_coding | /reverse_integer.py | 294 | 3.59375 | 4 | def revint(nums):
rev_num=0
m=nums
if nums<0:
nums=nums*-1
while(nums>0):
remainder=nums%10
rev_num=(rev_num*10)+remainder
nums=nums//10
if(m<0):
rev_num*=-1
print(rev_num)
if __name__=="__main__":
nums=-456
revint(nums) |
e00fe1b68f80fd090dea080a9d79d281a56414ba | jamiejamiebobamie/CTI-IPS-2020 | /main 19.py | 272 | 3.734375 | 4 | def find_pivot_index(input_list):
# List is sorted, but then rotated.
# Find the minimum element in less than linear time
# return it's index
min_i = 0
for i in range(len(input_list)):
if input_list[i] < input_list[min_i]:
min_i = i
return min_i
|
9364734d4cb56b1c0f804afa579c73fd4705ec28 | wmillar/ProjectEuler | /085.py | 1,280 | 3.703125 | 4 | '''
By counting carefully it can be seen that a rectangular grid measuring 3 by 2
contains eighteen rectangles.
Although there exists no rectangular grid that contains exactly two million
rectangles, find the area of the grid with the nearest solution.
'''
def countRectangles(x, y):
x, y = x+1, y+1
totalCombos = 0
for cX in xrange(1, x):
for cY in xrange(1, y):
totalCombos += (x-cX)*(y-cY)
return totalCombos
target = 2000000
difference = target
diffX, diffY = -1, -1
for x in xrange(1,100):
y = x
if countRectangles(x,x) > target:
break
while True:
combos = countRectangles(x, y)
if combos < target:
prevCombos = combos
prevCombosY = y
else:
break
y += 1
difference1 = combos-target
difference2 = target-prevCombos
if difference1 < difference2:
if difference1 < difference:
difference = difference1
diffX, diffY = x, y
else:
if difference2 < difference:
difference = difference2
diffX, diffY = x, prevCombosY
print diffX*diffY
|
bb13b18d2942e87ed1c998ec5a096eda8b6759d4 | SnehaThakkallapally/Assignment3 | /merge_sort.py | 644 | 4.0625 | 4 | def mergesort(list1):
if len(list1)>1:
mid = len(list1)//2
left_list= list1[:mid]
right_list = list1[mid:]
mergesort(left_list)
mergesort(right_list)
i=0
j=0
k=0
while i<len(left_list) and j< len(right_list):
if left_list[i] < right_list[j]:
list1[k] = left_list[i]
i=i+1
k=k+1
else:
list1[k] = right_list[j]
j=j+1
k=k+1
while i < len(left_list):
list1[k]= left_list[i]
i=i+1
k=k+1
while j < len(right_list):
list1[k]= right_list[j]
j=j+1
k=k+1
num= int(input("How many elements you want in the list"))
list1=[int(input()) for x in range(num)]
mergesort(list1)
print(list1) |
163583fb80eaf163892e3374fedf612a7c5816a8 | albert-yakubov/py-practice | /LRUCache.py | 856 | 3.765625 | 4 | from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
def get(self, key : int):
"""return the value of the key
and move the accessed key to the front"""
if key in self.cache:
self.cache.move_to_end(key)
return self.cache[key]
return -1
def put(self, key: int, value: int) -> None:
"""keep track of capacity
if full evict something"""
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(False)
def run(self):
lru = LRUCache(3)
lru.put(1, 2)
lru.put('a', 'b')
print(lru)
lru = LRUCache(3)
lru.put(1,2)
lru.put('a','b')
print(LRUCache.run(lru)) |
3c8a4490c7dc8d2327b723e018443a623a88f06b | sjdeak/interview-practice | /contest/interview/microsoft/#1.py | 504 | 3.546875 | 4 | def dfs(now, step):
print('now, step, X', now, step, X)
if step > X: return
currentAt = now[-1]
if now not in ignoredups:
ignoredups.add(now)
else:
return
if currentAt == P and 0 < step:
ans.add(now)
for n in range(1, N + 1):
if n == currentAt: continue
if (currentAt % n == 0) or (n % currentAt == 0):
dfs(tuple(list(now) + [n]), step + 1)
N = input1
P = input2
X = input3
ans = set()
ignoredups = set()
dfs(tuple([P]), 0)
print('ans', ans)
return len(ans)
|
ffbb445fc1a31ad3402e5db6596b61df2f6a8b26 | KhanChan18/this-algo | /algo-py/pzy/prioqueue.py | 541 | 3.71875 | 4 | class PriorityQueueBase:
class _Item:
def __init__(self, k, v):
self.key = k
self.value = v
def __lt__(self, other):
return self.key < other.key
def is_empty(self):
return len(self) == 0
class UnsortedPriorityQueue(PriorityQueueBase):
def _find_min(self):
if self.is_empty():
raise ValueError('Priority queue is empty')
small = self.data.first()
walk = self.data.after(small)
while walk is not None:
if walk.
|
b346a8a6033697684c9a2fbcd85dc4f4482b8e2b | ryan-way-leetcode/python | /23_MergeKSortedLists/testsolution.py | 969 | 3.609375 | 4 | import unittest
from solution import Solution, ListNode
class TestSolution(unittest.TestCase):
def setUp(self):
self.s = Solution()
def test_example1(self):
test = [
ListNode(1, ListNode(4, ListNode(5))),
ListNode(1, ListNode(3, ListNode(4))),
ListNode(2, ListNode(6)),
]
exp = ListNode(1,
ListNode(1,
ListNode(2,
ListNode(3,
ListNode(4,
ListNode(4,
ListNode(5,
ListNode(6))))))))
act = self.s.mergeKLists(test)
while act is not None and exp is not None:
self.assertEqual(exp.val, act.val)
exp, act = exp.next, act.next
if act is None and exp is None:
return
else:
self.assertTrue(False)
|
4bb486cc7ce3348f2d5e161e349b82683865b65a | Jokky6/algorithm011-class01 | /Week_03/homework/lowest-common-ancestor-of-a-binary-tree.py | 2,268 | 3.65625 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : lowest-common-ancestor-of-a-binary-tree.py
@Contact : 13801489449@163.com
@License : (C)Copyright 2019-2020,林间有风
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2020/7/10 1:27 下午 Jokky 1.0 None
'''
"""
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
"""
class TreeNode(object):
def __init__(self,x):
self.val = x
self.left = None
self.right = None
# class Solution:
# def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# if not root:return root
# if root.val == p.val or root.val == q.val:return root
# left = self.lowestCommonAncestor(root.left,p,q)
# right = self.lowestCommonAncestor(root.right,p,q)
# if left and right:return root
# if left:return left
# if right:return right
class Solution:
def lowestCommonAncestor(self,root:'TreeNode',p:'TreeNode',q: 'TreeNode') -> 'TreeNode':
# If looking for me, return myself
if root == p or root == q:
return root
left = right = None
# else look in left and right child
if root.left:
left = self.lowestCommonAncestor(root.left, p, q)
if root.right:
right = self.lowestCommonAncestor(root.right, p, q)
# if both children returned a node, means
# both p and q found so parent is LCA
if left and right:
return root
else:
# either one of the chidren returned a node, meaning either p or q found on left or right branch.
# Example: assuming 'p' found in left child, right child returned 'None'. This means 'q' is
# somewhere below node where 'p' was found we dont need to search all the way,
# because in such scenarios, node where 'p' found is LCA
return left or right
|
4647dfb44f2f00354720408c7f708250e9bc7a98 | Greenwicher/Competitive-Programming | /LeetCode/349.py | 1,583 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 2 20:54:41 2017
@author: liuweizhi
"""
#%% Version 1 - binary search
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1, nums2 = list(map(sorted, [nums1, nums2]))
if len(nums1) > len(nums2): nums1, nums2 = nums2, nums1
common = set()
for i in nums1:
if self.binary_search(i, nums2):
common.add(i)
return list(common)
def binary_search(self, x, nums):
l, r = 0, len(nums)
while(l < r):
m = (l + r) // 2
if x < nums[m]:
r = m - 1
elif x > nums[m]:
l = m + 1
else:
return True
if x == nums[l]:
return True
else:
return False
#%% Version 2 - two pointers
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1, nums2 = list(map(sorted, [nums1, nums2]))
common = set()
i, j = [0] * 2
while(i < len(nums1) and j < len(nums2)):
if nums1[i] == nums2[j]:
common.add(nums1[i])
i += 1
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
j += 1
return list(common) |
af3715f9df24fcf6ad3beef6ffbc4a11664c9b3c | newfull5/CodeSignal | /validTime.py | 182 | 3.546875 | 4 | def validTime(time):
if int(time[0:2]) < 24 and int(time[3:5]) < 60:
if time == '24:00':
return False
return True
else:
return False
|
5199a6c36a17f5057ea4ebe4473c24e2c188f26a | dennismarks/Daily-Coding-Problem | /Python/#004-first-missing-positive-int.py | 1,249 | 4.0625 | 4 | def first_missing_pos_int(array):
"""
Given an array of integers, find the first missing positive integer in
linear time and constant space. In other words, find the lowest positive
integer that does not exist in the array. The array can contain duplicates
and negative numbers as well.
You can modify the input array in-place.
"""
n = max(array)
if n < 1:
return 1
if len(array) == 1:
return 2 if array[0] == 1 else 1
my_array = [0] * n
# set value at index i to 1 if such value exists in array
for i in range(len(array)):
if array[i] > 0:
my_array[array[i] - 1] = 1
j = 0
# return first occurence of zero
for j in range(len(my_array)):
if my_array[j] == 0:
return j + 1
return j + 2
def first_missing_pos_int_using_set(array):
my_set = set(array)
for i in range(1, len(array)):
if (i in my_set) and (i + 1 not in my_set):
return i + 1
if __name__ == '__main__':
assert first_missing_pos_int([3, 4, -1, 1]) == 2
assert first_missing_pos_int([1, 2, 0]) == 3
assert first_missing_pos_int_using_set([3, 4, -1, 1]) == 2
assert first_missing_pos_int_using_set([1, 2, 0]) == 3
|
9b21e91e602f566a8ba8f78f319326fd9ecdaab1 | Vishwaja-Matikonda/Python-practice-problems | /whole_file.py | 166 | 3.765625 | 4 | #reading whole data of a file into a string
str=open("hello.txt")
s=str.read()
print(len(s))
print(s[:12])
if 'BYE' in s:
print("yes")
else:
print("no") |
e05bc6b4781e1a7a7a1c739816c4fa3b22d7f16c | zl0bster/BubblesProject | /fractal_tree_draw.py | 1,080 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#
# draws fractal tree on screen
#
#
# pip install simple_draw
#
import simple_draw as sd
def draw_branch(point,
angle,
length,
color):
branch = sd.get_vector(start_point=point, angle=angle, length=length, )
branch.draw(color=color)
return branch.end_point
def draw_fork(point,
angle,
tilt,
length,
color):
angle1 = angle + tilt
angle2 = angle - tilt
vertex1 = draw_branch(point, angle1, length, color)
vertex2 = draw_branch(point, angle2, length, color)
return ([vertex1, angle1], [vertex2, angle2])
def fractal_tree(point,
length=100,
direction=90,
tilt=30,
scale=0.6,
color=sd.COLOR_DARK_GREEN):
vertexes = draw_fork(point, direction, tilt, length, color)
while length > 10:
length *= scale
for points in vertexes:
fractal_tree(points[0], length, points[1], tilt, scale, color)
return
|
449c477a7b3ce0043882ab44735b99e45c9c6b27 | Luciekimotho/datastructures-and-algorithms | /MSFT/dictionary2.py | 993 | 3.890625 | 4 |
#Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them.
#If there is no possible reconstruction, then return null.
#For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox'].
##Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond'].
def split_sent(s, dict_words):
words = set(dict_words)
llist = list()
for i in range(len(s)):
if s[0:i + 1] in words:
llist.append(s[0:i + 1])
words.remove(s[0:i + 1])
llist += split_sent(s[i+1: ], words)
return llist
dict_words = ['quick', 'brown', 'the', 'fox']
sentence = "thequickbrownfox"
print (split_sent(sentence, dict_words))
|
60d3471784f3f8136dfb5e76bebc676ceb143dd8 | Luizcarlosqueiroz/PythonExercises | /03_EstruturaDeRepeticao/32.py | 240 | 4.0625 | 4 | numb = int(input("Digite um número: "))
fatorial = numb
print(f"O fatorial de {numb}")
print(f"{numb}! = {numb}", end="")
for i in reversed(range(1, numb)):
print(f".{i}", end="")
fatorial = fatorial * i
print(f" = {fatorial}")
|
96c3031d188575eebf869595d2ca9adb0b2941a7 | vishalkumar9dec/demopython | /sortingList.py | 339 | 4.0625 | 4 | '''raw_input = input('Enter the CSV : ')
str_list = [x for x in raw_input.split(",")]
str_list.sort()
#print(str_list)
print (','.join(str_list))'''
lines = []
print('Enter the input in multi lines : ')
while True:
test = input()
if test:
lines.append(test)
else:
break
print('\n'.join(lines).upper())
|
88510aec5802703dab4868bba7ab2de7983b17f8 | chriswolfdesign/MIT600EDX | /week2/Lecture3/Exercises/6_guess_my_number/guess_my_number.py | 678 | 4.0625 | 4 | high = 100
low = 0
guess = 50
print("Please think of a new between 0 and 100!")
while high > low:
print("Is your secret number {}?".format(guess))
feedback = input("Enter 'h' to indicate the guess is too high. " + \
"Enter 'l' to indicate the guess is too low. " + \
"Enter 'c' to indicate I guessed correctly. ")
if feedback == 'l':
low = guess
guess = (low + high) // 2
elif feedback == 'h':
high = guess
guess = (low + high) // 2
elif feedback == 'c':
break
else:
print("Sorry, I did not understand your input.")
print ("Game over. Your secret number was: {}".format(guess))
|
0660958338dc0fd67564fd24cd75cf6a91c32f9f | Jashwanth-k/Data-Structures-and-Algorithms | /1.Recorsions - 1/First index of a list using Slicing.py | 344 | 3.578125 | 4 | def firstIndex(a,x):
l = len(a)
if l == 0:
return -1
if a[0] == x:
return 0
smallerList = a[1:]
smallerListOutput = firstIndex(smallerList,x)
if smallerListOutput == -1:
return -1
else:
return smallerListOutput + 1
a = [1,2,7,3,4,5,6,7,8,9,7]
print(firstIndex(a,7)) |
12d1c5e3c74f318a7f914a95bb631cc16cf2ae4d | perkPerkins/480Calculator | /CalculatorGUI.py | 3,338 | 3.953125 | 4 | from tkinter import *
import Calculator
root = Tk()
root.title("480 Calculator")
calc = Calculator.Calculator()
calculation_entry = Entry(root, width=25, borderwidth=5)
calculation_entry.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
def button_click(operand_or_operator):
current = calculation_entry.get()
calculation_entry.delete(0, END)
calculation_entry.insert(0, current + operand_or_operator)
return
def clear_entry_box():
calculation_entry.delete(0, END)
def equals_button():
expression = calculation_entry.get()
value = calc.API(str(expression))
calculation_entry.delete(0, END)
if value == "Invalid Expression":
calculation_entry.delete(0, END)
calculation_entry.insert(0, value)
else:
calculation_entry.insert(0, value)
# Define buttons
button_1 = Button(root, text="1", padx=40, pady=20, command=lambda: button_click("1"))
button_2 = Button(root, text="2", padx=40, pady=20, command=lambda: button_click("2"))
button_3 = Button(root, text="3", padx=40, pady=20, command=lambda: button_click("3"))
button_4 = Button(root, text="4", padx=40, pady=20, command=lambda: button_click("4"))
button_5 = Button(root, text="5", padx=40, pady=20, command=lambda: button_click("5"))
button_6 = Button(root, text="6", padx=40, pady=20, command=lambda: button_click("6"))
button_7 = Button(root, text="7", padx=40, pady=20, command=lambda: button_click("7"))
button_8 = Button(root, text="8", padx=40, pady=20, command=lambda: button_click("8"))
button_9 = Button(root, text="9", padx=40, pady=20, command=lambda: button_click("9"))
button_0 = Button(root, text="0", padx=40, pady=20, command=lambda: button_click("0"))
button_plus = Button(root, text="+", padx=40, pady=20, command=lambda: button_click("+"))
button_minus = Button(root, text="-", padx=40, pady=20, command=lambda: button_click("-"))
button_mult = Button(root, text="*", padx=40, pady=20, command=lambda: button_click("*"))
button_div = Button(root, text="/", padx=40, pady=20, command=lambda: button_click("/"))
button_exponent = Button(root, text="^", padx=40, pady=20, command=lambda: button_click("^"))
button_equal = Button(root, text="=", padx=40, pady=20, command=equals_button)
button_clear = Button(root, text="AC", padx=35, pady=20, command=clear_entry_box)
button_negative = Button(root, text="Negative", padx=15, pady=20, command=lambda: button_click("n"))
button_left_parenth = Button(root, text="(", padx=40, pady=20, command=lambda: button_click("("))
button_right_parenth = Button(root, text=")", padx=40, pady=20, command=lambda: button_click(")"))
# Put buttons on screen
button_clear.grid(row=1, column=0)
button_left_parenth.grid(row=1, column=1)
button_right_parenth.grid(row=1, column=2)
button_div.grid(row=1, column=3)
button_7.grid(row=2, column=0)
button_8.grid(row=2, column=1)
button_9.grid(row=2, column=2)
button_mult.grid(row=2, column=3)
button_4.grid(row=3, column=0)
button_5.grid(row=3, column=1)
button_6.grid(row=3, column=2)
button_minus.grid(row=3, column=3)
button_1.grid(row=4, column=0)
button_2.grid(row=4, column=1)
button_3.grid(row=4, column=2)
button_plus.grid(row=4, column=3)
button_0.grid(row=5, column=0)
button_equal.grid(row=5, column=1)
button_exponent.grid(row=5, column=2)
button_negative.grid(row=5, column=3)
root.mainloop()
|
53d638096990ff5f9e718f860def5f6df2b13325 | VRamazing/cracking-coding-interview | /ArraysList/zeroAtMatrix.py | 581 | 3.90625 | 4 | def zeroAtMatrix(A_copy):
A=A_copy
rows = len(A)
cols = len(A[0])
stop = False
zeroList = []
#searching position for element with value zero
for row in range(rows):
for col in range(cols):
if(A[row][col]==0):
stop = True
zeroList.append((row, col))
#zeroing on element value
for pos in zeroList:
i=0
j=0
while(j<cols):
A[pos[0]][j]=0
j+=1
while(i<rows):
A[i][pos[1]]=0
i+=1
print(A_copy)
multiList = [[1,2,3],[2,0,5],[5,6,0]]
newList = multiList.copy()
# print(multiList)
zeroAtMatrix(newList)
print(multiList)
#Time complexity n2 |
2145472996bb6d056e52012a2bc0dd8a6e7337dd | ArtyomKolosov2/Programming-languages-labs | /lab23/task6.py | 1,654 | 4.15625 | 4 | # Программа вычесляет элементы фибоначи
#
# Version: 1.0
# Group: 10701219
# Author: Колосов Артём Александрович
# Date: 16.3.2020
def get_input(msg):
return input(msg)
def fibonachi_rec(n):
if n <= 0:
return 0
if n == 1:
return 1
return fibonachi_rec(n - 1) + fibonachi_rec(n - 2)
def fibonachi_elem(n):
a = 0
b = 1
i = 0
while i < n:
c = a
a = b
b += c
i += 1
return c
def output_to_user(msg="", s="", e="\n"):
print(msg, sep=s, end=e)
def all_fib(n, k=1):
for i in range(k, n + 1):
output_to_user(fibonachi_elem(i), e=" ")
output_to_user()
def build_to_int(var):
if not (isinstance(var, str) and var.isdigit()):
return None
return int(var)
def main():
while True:
task = get_input("Input command\n"
"1 - Output one element recursion\n"
"2 - Output to the specified element\n"
"3 - Output part of sequence\n"
"4 - Exit\n")
if task == "1":
n = build_to_int(get_input("Input number of element: "))
if n:
print(fibonachi_rec(n-1))
elif task == "2":
n = build_to_int(get_input("Input number of element: "))
if n:
all_fib(n)
elif task == "3":
k = build_to_int(get_input("Input Start: "))
n = build_to_int(get_input("Input End: "))
if n and k:
all_fib(n, k)
elif task == "4":
break
if __name__ == "__main__":
main()
|
172d65fa5b3e048b896650cf7361ea1398c0dd6a | tek-life/algorithm-practice | /29_Divide_Two_Integers.py | 808 | 3.59375 | 4 | ass Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if divisor ==0 or divisor==-1 and dividend==-2**31:
return 2**31-1
flag=0
p=abs(dividend)
if p!=dividend:
flag^=1
q=abs(divisor)
temp=q
if q!=divisor:
flag^=1
if p < q: return 0
m=1
res=0
if q==1:
res=p
else:
while p>=q:
m=1
while (q<<1)<=p:
q<<=1
m<<=1
res+=m
p-=q
q=temp
if flag:
return 0-res
else:
return res
|
a2f01336436fa9976ae1b50fb67d6bc8d5218c20 | chanvy-iami/Python3-Road | /14-数据结构.py | 494 | 3.953125 | 4 | # 列表
'''
列表可变,且存在多种方法
'''
# 将列表当作队列使用
# 列表推导式
'''
列表推导式提供从序列创建列表的途径
'''
a = [2, 3, 1]
b = [3*i for i in a]
print(b)
# 嵌套列表
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
trasmatrix = [[row[i] for row in matrix] for i in range(4)]
print(trasmatrix)
# del语句
'''
del语句通过列表索引来删除其中值
'''
# 元组和序列
# 集合
# 字典
# 遍历
|
894812ec812dcdbaadff64fd937c3c5aff2c908f | nptit/python-snippets | /genPrimes.py | 725 | 4.09375 | 4 | def genPrimes():
x = 1
while True:
x += 1
if isPrime(x):
yield x
def isPrime(x):
if x == 1:
return False
return False if any(x % i == 0 for i in range(2, x // 2 + 1)) else True
g = getPrimes()
print g.next()
print g.next()
print g.next()
# Note that our solution makes use of the for/else clause, which
# you can read more about here:
# http://docs.python.org/release/1.5/tut/node23.html
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
|
2a56bcac725f33cf930647a1b840ba49617b71f7 | SebasBaquero/taller1-algoritmo | /taller estructuras de control selectivas/punto10.py | 562 | 3.703125 | 4 | """
Entradas
Categoría-->int-->a
SalarioBruto-->int-->sb
Salidas
salarioAumento-->str-->c
"""
a=int(input("Escriba la categoría: "))
sb=int(input("Escriba el salario bruto: $"))
if (a==1):
c=("El salario bruto es de: $"+str(sb+(sb*0.1)))
elif (a==2):
c= ("El salario bruto es de: $"+str(sb+(sb*0.15)))
elif (a==3):
c= ("El salario bruto es de: $"+str(sb+(sb*0.2)))
elif (a==4):
c= ("El salario bruto es de: $"+str(sb+(sb*0.40)))
elif (a==5):
c= ("El salario bruto es de: $"+str(sb+(sb*0.6)))
else:
c=("Categoria inexistente")
print(c)
|
919d321cb5428de9f203d88a1a62fee6208b5ae5 | YunsongZhang/lintcode-python | /Twitter OA/University Career Fair.py | 616 | 3.65625 | 4 | def merge(intervals):
intervals = sorted(intervals, key=lambda x: x[0])
result = []
count = 0
for interval in intervals:
if len(result) == 0 or result[-1][1] <= interval[0]:
count += 1
result.append(interval)
else:
result[-1][1] = max(result[-1][1], interval[1])
return count
def arrange(arrival, duration):
intervals = []
for i in range(len(arrival)):
intervals.append([arrival[i], arrival[i] + duration[i]])
return merge(intervals)
arrival = [1, 3, 3, 5, 7]
duration = [2, 2, 1, 2, 1]
print(arrange(arrival, duration)) |
2ccc81b8076698f5b04d8e64dc59bad6629ed270 | jxhangithub/lintcode | /Interviews/goldmansachs/1375.Substring With At Least K Distinct Characters/Solution.py | 624 | 3.515625 | 4 | class Solution:
"""
@param s: a string
@param k: an integer
@return: the number of substrings there are that contain at least k distinct characters
"""
def kDistinctCharacters(self, s, k):
# Write your code here
res = 0
if not s or len(s) < k:
return res
for left in range(len(s)):
right = left
counter = set([])
while right < len(s) and len(counter) < k:
counter.add(s[right])
right += 1
if len(counter) == k:
res += len(s) - right + 1
return res
|
219d5fcd99a9ebc89e134f54a7c308c85a54402f | bahostetterlewis/Python-Idioms | /sum_of_digits.py | 220 | 3.90625 | 4 | def digit_sum(num):
return sum(int(x) for x in str(num))
def digit_sum_alt(num):
def digits(number):
while number:
yield number % 10
number /= 10
return sum(digits(num))
|
ea4bf804014224fd21c80200e70381d10c906c7c | Aravindh-S/Assignments | /python/assignments/heap.py | 4,207 | 4.34375 | 4 |
"""
This progrom calculates the min heap and max
heap of a given data also performing operations like
(i) Insertion
(ii) Deletion of max from max heap
(iii) Deletion of min from min heap
"""
MAXI = True
class Heap:
"""
This is the class that contains all the heap functions
"""
heap = [0]
def insert(self, inp):
"""
takes in the input as single element and appends in heap
"""
self.heap.append(inp)
if MAXI is False:
self.min_the_heap(len(self.heap) - 1)
else:
self.max_the_heap(len(self.heap) - 1)
# self.max_the_heap()
def max_the_heap(self, index):
"""
This computes the max heap using recurssion
"""
parent = index // 2
if index <= 1:
return self.heap
elif self.heap[index] > self.heap[parent]:
self.swap(index, parent)
self.max_the_heap(parent)
else:
self.max_the_heap(parent)
def min_the_heap(self, index):
"""
This computes the max heap using recurssion
"""
parent = index // 2
if index <= 1:
return self.heap
elif self.heap[index] < self.heap[parent]:
self.swap(index, parent)
self.min_the_heap(parent)
else:
self.min_the_heap(parent)
def delmax(self):
"""
This deletes the max element from the max heap
"""
self.swap(1, (len(self.heap) - 1))
self.heap.pop()
self.place_down()
def delmin(self):
"""
This deletes the min element from the min heap
"""
self.swap(1, (len(self.heap) - 1))
self.heap.pop()
print(self.heap)
self.place_down_min()
def place_down_min(self, index=1):
"""
This pushes down the top most element making sure that
the heap stucture is maintained in case of min heap
"""
left = index * 2
right = index * 2 + 1
smallest = index
if len(self.heap) > left and self.heap[smallest] > self.heap[left]:
smallest = left
if len(self.heap) > right and self.heap[smallest] > self.heap[right]:
smallest = right
if smallest != index:
self.swap(index, smallest)
self.place_down_min(smallest)
def place_down(self, index=1):
"""
This pushes down the top most element making sure that
the heap stucture is maintained in case of max heap
"""
left = index * 2
right = index * 2 + 1
largest = index
if len(self.heap) > left and self.heap[largest] < self.heap[left]:
largest = left
if len(self.heap) > right and self.heap[largest] < self.heap[right]:
largest = right
if largest != index:
self.swap(index, largest)
self.place_down(largest)
def swap(self, ind, par):
"""
swaps the given two argument
"""
self.heap[ind], self.heap[par] = self.heap[par], self.heap[ind]
def show_tree(self):
"""
prints the tree
"""
print(self.heap[1:])
if __name__ == '__main__':
CLASS_VAR = Heap()
# instatiating class variable
print("Min heap(0) or Max Heap(1)")
MAXI = input()
CHOICE = 0
while CHOICE != 5:
print("Choice :'\t'1.insert'\t'2.Print heap'\t'3.Delete min'\t'4.Delete max'\t'5.Break")
CHOICE = int(input())
if CHOICE == 1:
LIST_INPUT = input("Enter the element in the form of list: ")
for b in LIST_INPUT:
CLASS_VAR.insert(b)
elif CHOICE == 2:
CLASS_VAR.show_tree()
elif CHOICE == 3:
if MAXI is False:
CLASS_VAR.delmin()
CLASS_VAR.show_tree()
else:
print("This is Max heap...Cannot delete Min")
elif CHOICE == 4:
CLASS_VAR.delmax()
if MAXI is True:
CLASS_VAR.show_tree()
else:
print("This is Min heap...Cannot delete Max")
else:
break
|
6d113df57f0bbf0f1dc18316443ed92d34e95495 | ShubhamKulkarni1495/List_python | /List/string2.py | 186 | 3.53125 | 4 | mainStr = "the quick brown fox jumped over the lazy dog. the dog slept over the verandah."
subStr =[ "over" ]
for i in subStr:
mainStr=mainStr.replace(' '+ i +' ',' ')
print(mainStr) |
77cc21e494a0e726725f9697d9d9cdff31a67926 | rubythonode/Python-Challanges | /21.py | 411 | 3.828125 | 4 |
from math import sqrt
totalX=0
totalY=0
while(True):
n=input()
if n:
l = n.split(' ')
if(l[0]=="UP"):
totalY+=int(l[1])
if(l[0]=="DOWN"):
totalY-=int(l[1])
if (l[0] == "LEFT"):
totalX -= int(l[1])
if (l[0] == "RIGHT"):
totalX += int(l[1])
else:
break
print(int(sqrt(totalX*totalX+totalY*totalY))) |
5ebf9275d98284a87986ce23861e7ca42812cad8 | daaimah123/LearningPython | /whileLoop.py | 363 | 4.09375 | 4 | # user_response = None
# while user_response != 'please':
# user_response = input('What is the magic word? ')
# msg = input('what\'s the secret password? ')
# while msg != 'bananas':
# print('WRONG!')
# # break statement
# msg = input('what\'s the secret password? ')
# print('CORRECT!')
num = 0
while num < 11:
num+=2
print(num) |
52172c007b4110179ff7e5e00eb42094f9e3eb44 | dehvCurtis/NSA_Py3_COMP3321 | /Lesson_02/lesson02_sec3_ex4.py | 297 | 4.15625 | 4 |
grocery_list = ['apples','bread','milk','juice']
def in_grocery_list():
item_check = input('Which item would you like to check for? ')
if item_check in grocery_list:
print('ok')
elif item_check not in grocery_list:
print(f'{item_check} Not Found!')
in_grocery_list() |
05731c8236e29d2823c0f9723fd77fd9d2b77d81 | judyliou/LeetCode | /python/257. Binary Tree Paths.py | 1,279 | 3.765625 | 4 | # Both O(n) DFS
# Recursion
class Solution(object):
def binaryTreePaths(self, root):
curPath = ""
allPath = []
return self.findPath(root, curPath, allPath)
def findPath(self, root, curPath, allPath):
if root == None:
return allPath
if root.left == None and root.right == None:
path = curPath + str(root.val)
allPath.append(path)
return allPath
curPath += str(root.val) + "->"
allPath = self.findPath(root.left, curPath, allPath)
allPath = self.findPath(root.right, curPath, allPath)
return allPath
# Iteration
class Solution(object):
def binaryTreePaths(self, root):
if not root:
return []
allPath = []
stack = [(root, '')]
while stack:
node, path = stack.pop()
if node.left == None and node.right == None:
path += str(node.val)
allPath.append(path)
else:
path += str(node.val) + '->'
if node.left:
stack.append((node.left, path))
if node.right:
stack.append((node.right, path))
return allPath
|
0dab5ef1e0c39fd1a96f3e5031321f2626d4ecbe | Renzhihan/machine_learning | /Part 1 - Data Preprocessing/Section 2 -------------------- Part 1 - Data Preprocessing --------------------/Data_Preprocessing/data_preprocessing.py | 1,290 | 3.53125 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#importing the dataset
dataset=pd.read_csv('Data.csv')
X=dataset.iloc[:,:-1].values
#取所有行数 除去最后一列
y=dataset.iloc[:,3].values
#taking care of missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(add_indicator=False,copy=True,missing_values=np.nan,strategy='mean',verbose=0) #均值
X[:,1:3]=imputer.fit_transform(X[:,1:3])
#encoding categorical data
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
labelencoder_X=LabelEncoder()
X[:,0]=labelencoder_X.fit_transform(X[:,0])
#dummy encoding 虚拟编码
onehotencoder=OneHotEncoder()
X_t=onehotencoder.fit_transform(X[:,0].reshape(-1, 1)).toarray()
X=np.concatenate((X_t,X[:,1:3]),axis=1)
labelencoder_y=LabelEncoder()
y=labelencoder_y.fit_transform(y)
#spliting the dataset into the training and test set
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X, y,train_size=0.8,random_state=0)
#random_state=0时,每次得到完全一样的训练集和测试集
#feature scaling
from sklearn.preprocessing import StandardScaler
sc_X=StandardScaler()
X_train=sc_X.fit_transform(X_train)
X_test=sc_X.transform(X_test)
|
b063cd500d9fad1b434de38a447d24c3594d463f | chirumist/Python-Practice | /python-files/oops.py | 1,713 | 3.625 | 4 | class Student:
no_of_projects = 1
def __init__(self, name, age, role):
self.name = name
self.age = age
self.role = role
def detail(self):
return f"Name is {self.name}. Age is {self.age}. Role is {self.role}"
@classmethod
def changeProjects(cls, projects):
cls.no_of_projects = projects
@classmethod
def from_string_by_pip_dash(cls, str):
return cls(*str.split("-||-"))
@classmethod
def from_string_by_colon(cls,str):
return cls(*str.split(":"))
@classmethod
def from_string_by_coma(cls, str):
return cls(*str.split(","))
pass
# chirag = Student()
# chirag.name = "Chirag"
# chirag.age = 22
# chirag.role = "Developer"
# print(chirag.__dict__)
# print(Student.__dict__)
# chirag.no_of_projects = 11
# print(chirag.__dict__)
"""
Class with prop and mathod and constructor or __init__
"""
# chirag = Student("Chirag", 22, "Developer")
# friends = Student("FCOMPANY", 34, "CEO")
# print(friends.no_of_projects, "Default Value")
# friends.no_of_projects = 11
# print(friends.no_of_projects, "Change Value")
# # For Class variable value change
# print(Student.no_of_projects, "Class")
# chirag.changeProjects(12)
# print(Student.no_of_projects, "Class")
# print(chirag.no_of_projects, "Instance")
# print(chirag.detail())
"""
Class with alternative constructor
"""
friends = Student.from_string_by_pip_dash("FCOMPANY-||-34-||-CEO")
print(friends.__dict__)
newfriends = Student.from_string_by_colon("NCOMPANY:35:GTA-CEO")
print(newfriends.__dict__)
chirag = Student.from_string_by_coma("Chirag,22,Developer")
print(chirag.__dict__) |
a507cdf090de45983cafbe666a5a2b56588c55b8 | maayansharon10/intro_to_cs_python | /ex12/ex12/player.py | 1,619 | 3.8125 | 4 | from .ai import *
class Player:
INSERT_MOVE = "Please insert the column you would like to place your " \
"next disk at."
INVALID_MOVE = "your move is not valid, please try again"
def __init__(self, game, name):
"""constractor of instant of type Player.
:param color - represent color of his disks.
:param type can be h - human or m - machine."""
self.player_name = name
self.game = game
# list of tuples (row, col) of all disks player has on board
self.list_of_disks = []
def get_player_name(self):
return self.player_name
class HumanPlayer(Player):
def __init__(self, game, name):
Player.__init__(self, game, name)
self.player_type = "h"
def get_player_type(self):
return self.player_type
def choose_move(self):
"""player decides on his next move.
:return move (int represent num of column)"""
next_move = input(self.INSERT_MOVE)
next_move = int(next_move)
return next_move
class AiPlayer(Player):
def __init__(self, game, name):
Player.__init__(self, game, name)
self.player_type = "m"
# create player's brain
self.brain = AI(self.game, self.player_name)
def get_player_type(self):
return self.player_type
def choose_move(self):
"""player decides on his next move.
:return move (int represent num of column)"""
next_move = self.brain.find_legal_move()
return next_move |
e07956efe1b8b8dbe31acfc90c75af9608900d15 | bar2104y/Abramyan_1000_tasks | /Results/Python/Minmax/1.py | 150 | 3.578125 | 4 | n = int(input('N: '))
x = int(input())
ma, mi = x,x
for i in range(n-1):
x = int(input())
ma = max(ma,x)
mi = min(mi,x)
print(mi, ma)
|
164882edea72677bfdba593bd90525c829235e39 | Vivekagent47/HackerRank | /Problem Solving/76.py | 977 | 3.8125 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countApplesAndOranges function below.
def countApplesAndOranges(s, t, a, b, apples, oranges):
apple_fall = 0
orange_fall = 0
home_len = t - s
apple_dist = s - a
orange_dist = t - b
for ele in apples:
if ele >= apple_dist and ele <= (apple_dist + home_len):
apple_fall = 1 + apple_fall
print(apple_fall)
for ele in oranges:
if ele <= orange_dist and ele >= (orange_dist - home_len):
orange_fall = 1 + orange_fall
print(orange_fall)
if __name__ == '__main__':
st = input().split()
s = int(st[0])
t = int(st[1])
ab = input().split()
a = int(ab[0])
b = int(ab[1])
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
|
1078a00341d42159aafff83ad7582b23281ccca5 | lifesailor/data-structure-and-algorithm | /chapter2/heap_sort/heap_sort.py | 1,555 | 3.75 | 4 | """
Priority Queue는 가장 높은 우선순위
Priority Queue API
- MaxPQ(): 우선순위 큐 생성
- MaxPQ(int max): 최대 크기를 지정해서 우선순위 큐 생성
- MaxPQ(Key[] a); a[]의 키를 이용해 우선순위 큐 생성
- void insert(Key v): 우선순위 큐에 키 추가
- Key max(): 가장 큰 키 리턴
- Key delMax(): 가장 큰 키를 리턴하고 삭제
- boolean is_empty(): 우선순위 큐가 비어있는가.
- int size(): 우선순위 큐에 저장된 키의 개수
"""
class HeapSort:
@classmethod
def less(cls, ary, i, j):
return ary[i] < ary[j]
@classmethod
def exch(cls, ary, i, j):
temp = ary[i]
ary[i] = ary[j]
ary[j] = temp
@classmethod
def is_sorted(cls, ary):
for i in range(1, len(ary)):
if cls.less(ary, i+1, i):
return False
return True
@classmethod
def show(cls, ary):
for i in range(1, len(ary)):
print(ary[i], end=' ')
@classmethod
def sort(cls, ary):
N = len(ary)
ary.insert(0, None)
for k in range(N//2, 0, -1):
cls.sink(ary, k, N)
while N > 1:
cls.exch(ary, 1, N)
N = N - 1
cls.sink(ary, 1, N)
@classmethod
def sink(cls, ary, k, N):
while 2 * k <= N:
j = 2 * k
if j < N and cls.less(ary, j, j+1):
j += 1
if not cls.less(ary, k, j):
break
cls.exch(ary, k, j)
k = j
|
ef94c721f08a9a80fbcba357c9190b0af884e290 | ajmarin/coding | /leetcode/00028_implement_strstr.py | 276 | 3.53125 | 4 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not needle:
return 0
for start in range(len(haystack) - len(needle) + 1):
if haystack[start:].startswith(needle):
return start
return -1 |
996f065415023dfb4fdcd4db21391176e0eb0eb8 | miguelmartinez0/MISCourseWork | /MIS 304/DictionariesOct20.py | 2,605 | 4.34375 | 4 | #Creates three different sets with the same three elements
letter_set = set(['a', 'b', 'c'])
string_set = set ('abc')
another_string_set = set('aabbbccc')
new_set = set (['abc']) #Set with just one element of abc
word_set = set (['one', 'two', 'three'])
print (word_set)
print ()
#set_variable.add (element) #Add element into a set
#set_variable.update (element_list) #Add a bunch of elements into a set
letter_set.add ('def') #Add one element of "def", does not pull them apart
print (letter_set)
print ()
set1 = set([12, 24, 36])
set2 = set(['one', 'two', 'three'])
set1.update(set2) #Adds the three elements from set2 into set 1
print(set1)
print()
#set_variable.remove (element) #Removes an element, but causes an error if element doesn't exist
#set_variable.discard (element) #Removes an element, does not cauase an error if element isn't there
letter_set = set(['a', 'b', 'c'])
letter_set.remove('c') #Removes c from the set
print(letter_set)
print()
set1 = set([12, 24, 36])
set1.discard(12) #Gets rid of the 12 element in the set
#set1.remove(12) #Causes an error message since 12 is not in the set
print(set1)
print()
name_set = set(['Clint', 'Katie', 'Caryn'])
for name in name_set: #For every element in the set
print(name) #Prints each name in the set on a separate line
print()
#set1_variable.union(set2_variable) #Gets all unique elements from both of the sets, not duplicates
#set1_variable | set2_variable #Alternative method
set1 = set(['a', 'b', 'c'])
set2 = set(['c', 'd', 'e'])
set3 = set1.union(set2) #Combines both sets into a new set with 5 different elements
print(set3)
print()
#set1_variable.intersection(set2_variable) #Finds the elements that are shared in both sets
#set1_variable & set2_variable #Alternative method
set1 = set(['a', 'b', 'c'])
set2 = set(['c', 'd', 'e'])
set3 = set1.intersection(set2) #Creates a new set with only the c element
print(set3)
print ()
#set1_variable.difference(set2_variable) #Finds the unique elements in the first set
#set1_variable - set2_variable #Alternative method
set1 = set(['a', 'b', 'c'])
set2 = set(['c', 'd', 'e'])
set3 = set1.difference(set2) #Creates a new set with only a and b elements, unique to set 1
set4 = set2.difference(set1) #Creates a new set with only d and e elements, unique to set 2
#set1_variable.symmetric_difference(set2_variable) #Unique elements of both set, ignore overlaps
#set1_variable ^ set2_variable #Alternative method
set1 = set(['a', 'b', 'c'])
set2 = set(['c', 'd', 'e'])
set3 = set1.symmetric_difference(set2) #Creates a new set with 4 unique elements, ignoring c
print(set3)
|
9a7a8aaca0dd77778fad8362f790da6bf48dff94 | patruk91/pokemons | /chained_pokemons.py | 1,710 | 3.625 | 4 | import os
import time
def get_pokemon_list():
pokemons_list = []
with open("pokemons.csv") as file_object:
for line in file_object:
pokemons_list.append(line.rstrip().lower())
return pokemons_list
def user_name():
user = input("Your name: ")
return user
def get_pokemon_name(user):
pokemon = input(
"{} say name of your pokemon: ".format(user.title())).lower()
return pokemon
def main():
os.system('clear')
pokemons_list = get_pokemon_list()
first_user = user_name()
second_user = user_name()
while True:
while True:
os.system('clear')
pokemons_popped = []
first_pokemon = get_pokemon_name(first_user)
if first_pokemon in pokemons_list:
pokemons_popped.append(first_pokemon)
pokemons_list.remove(first_pokemon)
second_pokemon = get_pokemon_name(second_user)
if second_pokemon in pokemons_list and second_pokemon[0] == first_pokemon[-1]:
pokemons_popped.append(second_pokemon)
pokemons_list.remove(second_pokemon)
print("\nGOOD ANSWER!")
time.sleep(3)
continue
else:
print("\n{} you lose!" .format(second_user.title()))
break
else:
print("\n{} you lose!".format(first_user.title()))
break
repeat_game = input("\nDo you want to play again (y/n)? ")
if repeat_game == 'y':
print()
continue
else:
break
if __name__ == "__main__":
main()
|
e8861f2c442a98a0056ef87c4bace4a24e666268 | AdrianVides56/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 163 | 3.90625 | 4 | #!/usr/bin/python3
def no_c(my_string):
new = ""
for a in my_string:
if a == 'c' or a == 'C':
continue
new += a
return new
|
6d913c96f57de466f1ae308dfc7f3356ce6f2a8f | O-Seok/python_basic | /online/section05-1.py | 1,874 | 4.40625 | 4 | # Section05-1
# python 흐름제어(제어문)
# 조건문 실습
# boolean
print(type(True), type(False))
print('boolean')
# example 1
if True:
print('Yes')
# example 2
if False:
print('No')
# example 3
if False:
print('No')
else:
print('Yes')
# 관계연산자
# >, >=, <, <=, ==, !=
print()
print('관계연산자')
a = 10
b = 0
print(a == b)
print(a != b)
print(a > b)
print( a >= b)
print(a < b)
print( a<= b)
# 참 거짓 종류(True, False)
# 참 : "내용", [내용], (내용), {내용}, 1, True
# 거짓 : "", [], (), {}, 0, False
print()
print('참 거짓 종류별 출력')
city = ""
if city:
print("True")
else:
print("False")
# 논리 연산자
# and or not
print()
print('논리연산자')
a = 100
b = 60
c = 15
print('and : ', a > b and b > 3)
print('or : ', a > b or c > b)
print('not : ', not a > b)
print(not False)
print(not True)
# 산술, 관계, 논리 연산자
# 우선순위 : 산술 > 관계 > 논리 순서로 적용
print()
print('산술,관계,논리 연산자 순서')
print('ex1 : ', 5 + 10 > 0 and not 7 + 3 == 10)
score1 = 90
score2 = 'A'
if score1 >= 90 and score2 == 'A':
print('합격 하셨습니다.')
else:
print('죄송합니다. 불합격입니다.')
# 다중조건문
# if 다음의 또 다른 조건들이 필요하다면 elif를 통해서 여러가지 조건문을 주어서 흐름문을 이용할 수 있다.
print()
print('다중 조건문')
num = 70
if num >= 90:
print('num 등급 A', num)
elif num >= 80:
print('num 등급 B', num)
elif num >= 70:
print('num 등급 C', num)
else:
print('꽝')
# 중첩 조건문
print()
print('충접조건문')
age = 27
height = 175
if age >= 20:
if height >= 170:
print('A지망 지원 가능')
elif height >= 160:
print('B지망 지원 가능')
else:
print('지원 불가')
else:
print('20세 이상 지원 가능')
|
9a423cbbf9d5508b7f700e4aa99a8d20e249c49c | dpk3d/HackerRank | /missingElement.py | 984 | 3.984375 | 4 | """
Given an array of size N-1 such that it can only contain distinct integers in the range of 1 to N.
Find the missing element.
"""
# 1. Via Natural Sum n * (n + 1 ) // 2
def find_missing_element(arr):
last_element = arr[-1]
print("Last Number in Array is ===> ", last_element)
total_sum = last_element * (last_element + 1) // 2
arr_sum = sum(arr)
missing_element = total_sum - arr_sum
print("Missing Element in the Array is ====>", missing_element)
array = [1, 2, 3, 4, 5, 7, 8, 9, 10]
find_missing_element(array)
"""
Result :
Last Number in Array is ===> 10
Missing Element in the Array is ====> 6
"""
# 2. Via XOR Approach
def find_missing_element_xor(arr):
size = len(arr)
xor1 = arr[0]
for i in range(1, size):
xor1 = xor1 ^ arr[i]
xor2 = 0
for i in range(1, size + 2):
xor2 = xor2 ^ i
print("Missing Element ===> ", xor1 ^ xor2)
find_missing_element_xor(array)
"""
Result :
Missing Element ===> 6
"""
|
bfc7c8d36a89768c496b1d3f1e2798ffff5437e3 | shellslau/interview_questions | /square_interview_round2.py | 1,834 | 3.890625 | 4 | # aba
# lol
# "ab" "a"
# "hell" "eh"
# "lleh" "hell"
def is_palindrome_pair(a, b):
s = a + b
for i in range(1, (len(s)/2) + 1):
if (s[i-1] != s[-i]):
return False
return True
# print is_palindrome_pair('ab', 'a')
# print is_palindrome_pair('hell', 'eh')
# print is_palindrome_pair('lleh', 'hell')
# print is_palindrome_pair('lle', 'hell')
# ["a", "ba", "hello", "olleh", "eeh"]
# ["aab", "a", ""]
def check_palindromes(strings):
for i in range(len(strings)):
aString = strings[i]
for j in range(len(strings)):
bString = strings[j]
if (is_palindrome_pair(aString, bString) and j != i):
return True
return False
# print check_palindromes(["a", "ba", "hello", "olleh", "eeh"])
# # [("a", "ba"), ("hello", "olleh"), ... ]
# print check_palindromes(["aab", "ab", ""])
def find_palindromes(strings):
palindromes = []
for i in range(len(strings)):
aString = strings[i]
for j in range(len(strings)):
bString = strings[j]
if (j != i and is_palindrome_pair(aString, bString)):
palindromes.append((aString, bString))
return palindromes
# print find_palindromes(["a", "ba", "hello", "olleh", "eeh"])
# print find_palindromes(["aab", "ab", ""])
# print find_palindromes(["a", "a", "ba", "hello", "olleh", "eeh", "hellol", "eh", "leh"])
def reverse(s):
return s[::-1]
def make_palindrome_strings(s):
l = []
for i in range(1, len(s) + 1):
l.append(reverse(s[-i:]))
return l
# "hello" -> "olleh", "lleh"
print make_palindrome_strings('hello')
# "hellol" -> "leh"
# "hel" "lol" -> "leh"
# "olle" "hello" => "ollehello"
# "" "hello" => "olleh"
# "h" "ello" => "olle"
# ======================
# "he" "llo" => "oll"
# "hel" "lo" => "ol"
|
02df27a3073314d7b4b998d5b149e3ca8aa26932 | thiagoprocaci/pythonAlgorithmLib | /src/TrainsProblem.py | 5,764 | 3.90625 | 4 | from Graph import *
import math
def main():
text = 'AB5;BC4;CD8;DC8;DE6;AD5;CE2;EB3;AE7'
graph = GraphSupport.buildGraph(text)
#1. The distance of the route A-B-C.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['C']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode, 2)
found = False
for path in pathList:
if path == ['A', 'B', 'C']:
found = True
print '1. The distance of the route A-B-C:', graph.getPathCost(path)
if not found:
print '1. The distance of the route A-B-C', 'NO SUCH ROUTE'
#2. The distance of the route A-D.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['D']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode, 1)
found = False
for path in pathList:
if path == ['A', 'D']:
found = True
print '2. The distance of the route A-D:', graph.getPathCost(path)
if not found:
print '2. The distance of the route A-D:', 'NO SUCH ROUTE'
#3. The distance of the route A-D-C.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['C']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode, 2)
found = False
for path in pathList:
if path == ['A', 'D', 'C']:
found = True
print '3. The distance of the route A-D-C:', graph.getPathCost(path)
if not found:
print '3. The distance of the route A-D-C:', 'NO SUCH ROUTE'
#4. The distance of the route A-E-B-C-D.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['D']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode, 4)
found = False
for path in pathList:
if path == ['A', 'E', 'B', 'C', 'D']:
found = True
print '4. The distance of the route A-E-B-C-D:', graph.getPathCost(path)
if not found:
print '4. The distance of the route A-E-B-C-D:', 'NO SUCH ROUTE'
#5. The distance of the route A-E-D.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['D']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode, 4)
found = False
for path in pathList:
if path == ['A', 'E','D']:
found = True
print '5. The distance of the route A-E-D:', graph.getPathCost(path)
if not found:
print '5. The distance of the route A-E-D:', 'NO SUCH ROUTE'
#6. The number of trips starting at C and ending at C with a maximum of 3 stops.
#In the sample data below, there are two such trips: C-D-C (2 #stops). and C-E-B-C (3 stops).
originNode = graph.nodeDict['C']
pathList2Stops = BreadthFirstSearch.findAllPathWithNoGoal(graph, originNode, 2)
pathList3Stops = BreadthFirstSearch.findAllPathWithNoGoal(graph, originNode, 3)
sumPath = 0
for path in pathList2Stops:
if path[-1] == 'C':
sumPath = sumPath + 1
for path in pathList3Stops:
if path[-1] == 'C':
sumPath = sumPath + 1
print '6. The number of trips starting at C and ending at C with a max 3 stops:', sumPath
#7. The number of trips starting at A and ending at C with exactly 4 stops.
#In the sample data below, there are three such trips: A to C (via #B,C,D); A to C (via D,C,D); and A to C (via D,E,B).
originNode = graph.nodeDict['A']
pathList4Stops = BreadthFirstSearch.findAllPathWithNoGoal(graph, originNode, 4)
sumPath = 0
for path in pathList4Stops:
if path[-1] == 'C':
sumPath = sumPath + 1
print '7. The number of trips starting at A and ending at C with exactly 4 stops:', sumPath
#8. The length of the shortest route (in terms of distance to travel) from A to C.
originNode = graph.nodeDict['A']
goalNode = graph.nodeDict['C']
pathList = BreadthFirstSearch.findAllPath(graph, originNode, goalNode)
found = False
shortestLength = None
shortestPath = None
for path in pathList:
lengthRoute = graph.getPathCost(path)
if shortestLength is None:
shortestLength = lengthRoute
shortestPath = path
elif lengthRoute < shortestLength:
shortestLength = lengthRoute
shortestPath = path
found = True
if not found:
print '8. The length of the shortest route (in terms of distance to travel) from A to C.', 'NO SUCH ROUTE'
else:
print '8. The length of the shortest route (in terms of distance to travel) from A to C.', shortestLength, shortestPath
#9. The length of the shortest route (in terms of distance to travel) from B to B.
originNode = graph.nodeDict['B']
i = 1
shortestLength = None
shortestPath = None
while i <= len(graph.nodeDict):
pathList = BreadthFirstSearch.findAllPathWithNoGoal(graph, originNode, i)
i = i + 1
for path in pathList:
if path[-1] != 'B':
continue
lengthRoute = graph.getPathCost(path)
if shortestLength is None:
shortestLength = lengthRoute
shortestPath = path
elif lengthRoute < shortestLength:
shortestLength = lengthRoute
shortestPath = path
found = True
if not found:
print '9. The length of the shortest route (in terms of distance to travel) from B to B.', 'NO SUCH ROUTE'
else:
print '9. The length of the shortest route (in terms of distance to travel) from B to B.', shortestLength, shortestPath
#10.The number of different routes from C to C with a distance of less than 30. In the sample data, the trips are: CDC, CEBC, CEBCDC, CDCEBC, #CDEBC, CEBCEBC, CEBCEBCEBC.
originNode = graph.nodeDict['C']
i = 1
numberDiffRoute = 0
finished = False
while True:
if finished:
break
pathList = BreadthFirstSearch.findAllPathWithNoGoal(graph, originNode, i)
i = i + 1
if len(pathList) == 0:
break
finished = True
for path in pathList:
cost = graph.getPathCost(path)
if (path[-1] == 'C') and cost < 30:
numberDiffRoute = numberDiffRoute + 1
if cost < 30:
finished = False
print '10.The number of different routes from C to C with a distance of less than 30.', numberDiffRoute
if __name__ == '__main__':
main()
|
7df4d19551a42feb71dbbfb9a9afea4f777c3c8b | KoliosterNikolayIliev/Softuni_education | /Fundamentals2020/Lists Advanced - Lab/02. Todo List.py | 289 | 3.734375 | 4 | command = input()
notes = []
while command != 'End':
tokens = command.split('-')
priority = int(tokens[0])
note = tokens[1]
notes[priority - 1] = note
command = input()
result = []
for element in notes:
if element != 0:
result.append(element)
print(result)
|
34618d06b2d4955bb31100ca7936a75e7e3fefe7 | Microsongs/Algorithm_Note | /Sort/bubble.py | 468 | 3.953125 | 4 | # bubble sort
def bubble(arr):
# 0 ~ len-1까지 반복
for i in range(len(arr)-1, 0, -1):
# 0~i까지 반복
for j in range(0, i):
# 앞 수가 뒷 수보다 클 경우 swap
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
#main
data = [int(x) for x in input("여러개 숫자 입력 : ").strip().split()]
print("원본 데이터 : ",data)
bubble(data)
print("정렬 후 데이터 : ",data)
|
1826f9d6db67e2d11ac6b2ab440df6f2afdbad54 | rodbv/advent-of-code-2020 | /day-03/solution.py | 686 | 4.1875 | 4 | # Problem spec: https://adventofcode.com/2020/day/3
with open("input.txt", "r") as input_file:
input = [line.strip() for line in input_file.readlines()]
TREE = "#"
repeat_width = len(input[0])
def traverse(steps_right, steps_down):
trees_found = 0
x_position = 0
for line in input[::steps_down]:
tree_or_space_pos = x_position % repeat_width
tree_or_space = line[tree_or_space_pos]
if tree_or_space == TREE:
trees_found += 1
x_position += steps_right
return trees_found
print("Part 1:", traverse(3, 1))
print(
"Part 2:",
traverse(1, 1) * traverse(3, 1) * traverse(5, 1) * traverse(7, 1) * traverse(1, 2),
)
|
95baea1369b7cf7f29a040b9ca200afffa6c76f0 | mariane-sm/python_scripts | /hanoi.py | 655 | 4.03125 | 4 | class Peg:
def __init__(self,values,name):
self.v = values
self.name = name
pegA = Peg([3,2,1,0], "pegA") #disco 3 eh o de maior raio
pegB = Peg([], "pegB")
pegC = Peg([], "pegC")
def hanoi(n, src, dst, tmp):
if (n > 0):
hanoi(n-1, src, tmp, dst) # move to middle all (n-1)
move(n, src, dst)
print "move disc %d from %s to %s" %(n, src.name, dst.name)
hanoi(n-1, tmp, dst, src)
else: # n == 0
print "move disc %d from %s to %s" %(n, src.name, dst.name)
move(n, src, dst)
def move(n, src, dst):
src.v.remove(n)
dst.v.append(n)
print pegA.v
print pegB.v
print pegC.v
hanoi(3, pegA, pegC, pegB)
print pegA.v
print pegB.v
print pegC.v |
474b95817f65feea09309e162b8adc1bba63d139 | ruianpan/sp18-mp | /frontier.py | 1,978 | 3.6875 | 4 | """
A priority queue class optimized for searching frontier management
"""
__author__ = 'Zhengdai Hu'
from heapq import heappush, heappop
import itertools
class Frontier:
def __init__(self) -> None:
super().__init__()
self.priority_queue = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping of node to entries
self.REMOVED = '<removed-task>' # placeholder for a removed task
self.counter = itertools.count() # unique sequence count
def __contains__(self, node):
return node in self.entry_finder
def __bool__(self):
return bool(self.entry_finder)
def __remove(self, node):
"""Mark an existing node as REMOVED. Raise KeyError if not found."""
entry = self.entry_finder.pop(node)
entry[-1] = self.REMOVED
def add(self, node, priority):
"""Add a new node or update the priority of an existing node"""
if node in self.entry_finder:
self.__remove(node)
count = next(self.counter)
entry = [priority, count, node]
self.entry_finder[node] = entry
heappush(self.priority_queue, entry)
@property
def nearest(self):
"""Remove and return the lowest priority node and its priority. Raise KeyError if empty."""
while self.priority_queue:
priority, count, node = self.priority_queue[0]
if node is not self.REMOVED:
return node, priority
else:
heappop(self.priority_queue)
raise KeyError('frontier is empty')
def pop_nearest(self):
"""Remove and return the lowest priority node and its priority. Raise KeyError if empty."""
while self.priority_queue:
priority, count, node = heappop(self.priority_queue)
if node is not self.REMOVED:
del self.entry_finder[node]
return node, priority
raise KeyError('frontier is empty')
|
6b889b2ca0dd976a105be51a616422eb1f34b20a | ShankulShukla/Approaches-to-Sentiment-Analysis | /MultinomialNB_Training.py | 12,648 | 3.5 | 4 | # Classifier based on Bayes theorem
# Using TF-IDF to tokenize documents, learn the vocabulary and inverse document frequency weightings as vectorised classifier input
# Extensive english language analysis to develop pre-processing for the classifier
# Unigram and Bigram approach
import pandas as pd
import numpy as np
import re
import os
from sklearn.feature_extraction.text import TfidfVectorizer
# Pre-processing the review text before tokenizing using TF-IDF
# Removing html, hyperlinks
# Removing symbols
# Extracting emoticons and appending at the end of review, as emoticons in my analysis carry special meaning so not removing it
def preprocessing(text):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, ' ', text)
newtext = re.sub(r'http\S+', ' ', cleantext)
emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', newtext)
text = re.sub('[\W]+', ' ', newtext.lower()) + ' '.join(emoticons).replace('-', '')
return text
# Using TF-IDF to convert data into a numerical vector format where each word is represented by a matrix (word vectors).
# Using ngram approach, example for text "great movie", bigram "great movie" make lot much sense than unigrams "great" and "movie"
def vectorizer_ngram(data, unigram=True):
if unigram:
tfidf = TfidfVectorizer()
else:
tfidf = TfidfVectorizer(ngram_range=(2, 2))
tfidf.fit(data)
return tfidf
# Importing the dataset of 50000 IMDB reviews.
df = pd.read_csv(os.getcwd()+r'\data\IMDB_Dataset.csv')
# Expanding contractions before pre-processing review text
# Focusing mainly on word "not" as I have used it to create reverse associations among phrases, explained further
contraction_mapping = {"ain't": "is not", "aren't": "are not", "can't": "cannot", "'cause": "because",
"could've": "could have", "couldn't": "could not",
"didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not",
"hasn't": "has not", "haven't": "have not",
"he'd": "he would", "he'll": "he will", "he's": "he is", "how'd": "how did",
"how'd'y": "how do you", "how'll": "how will", "how's": "how is",
"I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have",
"I'm": "I am", "I've": "I have", "i'd": "i would",
"i'd've": "i would have", "i'll": "i will", "i'll've": "i will have", "i'm": "i am",
"i've": "i have", "isn't": "is not", "it'd": "it would",
"it'd've": "it would have", "it'll": "it will", "it'll've": "it will have", "it's": "it is",
"let's": "let us", "ma'am": "madam",
"mayn't": "may not", "might've": "might have", "mightn't": "might not",
"mightn't've": "might not have", "must've": "must have",
"mustn't": "must not", "mustn't've": "must not have", "needn't": "need not",
"needn't've": "need not have", "o'clock": "of the clock",
"oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not",
"sha'n't": "shall not", "shan't've": "shall not have",
"she'd": "she would", "she'd've": "she would have", "she'll": "she will",
"she'll've": "she will have", "she's": "she is",
"should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have",
"so've": "so have", "so's": "so as",
"this's": "this is", "that'd": "that would", "that'd've": "that would have", "that's": "that is",
"there'd": "there would",
"there'd've": "there would have", "there's": "there is", "here's": "here is",
"they'd": "they would", "they'd've": "they would have",
"they'll": "they will", "they'll've": "they will have", "they're": "they are",
"they've": "they have", "to've": "to have",
"wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will",
"we'll've": "we will have", "we're": "we are",
"we've": "we have", "weren't": "were not", "what'll": "what will",
"what'll've": "what will have", "what're": "what are",
"what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have",
"where'd": "where did", "where's": "where is",
"where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is",
"who've": "who have",
"why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not",
"won't've": "will not have",
"would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would", "y'all'd've": "you all would have", "y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would", "you'd've": "you would have", "you'll": "you will",
"you'll've": "you will have",
"you're": "you are", "you've": "you have"}
# List to identify negation words in review
negation = ['no', 'not', 'none', 'never', 'hardly', 'scarcely', 'barely', 'donot']
# stop_words for identifying stop words and removing it from review
# As stop words generally do not pertains any special meaning not considering in this implementation
stop_words = ["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself",
"yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",
"they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those",
"am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did",
"doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "of", "at", "by", "for", "with",
"between", "into", "during", "before", "after", "above", "below", "to", "from",
"up", "down", "in", "out", "on", "off", "over", "under", "again", "once", "here", "there",
"when", "where", "why", "how", "all", "any", "both", "each", "other", "such", "own", "same", "too",
"very", "s", "t", "can", "will", "just", "don", "should", "now"]
# Removing stop word from review text
def remove_stop_words(text):
text = ' '.join(word for word in text.split()
if word.lower() not in stop_words)
return text
# Pre-processing the review using above defined contraction mapping dictionary
def contractionmap(text):
for n in contraction_mapping.keys():
text = text.replace(n, contraction_mapping[n])
return text
# In this function, I will prepend the prefix "not" to every word after a token of logical negation(negation list above) until the next punctuation mark.
# EX- "I did not like this movie", in this example classifier will interpret "like" as a different feature(positive feature) ignoring its association with negation "not"
# After adding negation prefix, "like" becomes "notlike" will thus occur more often in negative document and act as cues for negative sentiment
# Similarly, words like "notbad" will acquire positive associations with positive sentiment
# Returning pre-processed review text
def negationprefix(text):
text = remove_stop_words(text)
token = text.split()
negationFlag = False
processedtoken = []
# Punctuation to stop
punctuation = re.compile(r'[.,!?;]')
for i in token:
if i in negation:
negationFlag = True
processedtoken.append(i)
else:
if negationFlag:
processedtoken.append("not" + i)
else:
processedtoken.append(i)
if punctuation.search(i):
negationFlag = False
newText = ' '.join(processedtoken)
return preprocessing(newText)
# Using sklearn's multinomial naive bayes algorithm as classifier to fit the sentiment model
# Using partial fit only to allow incremental learning, so at end I can use the remaining test data (not used for training) to further train the model for web app deployment
def fitting(x, y):
from sklearn.naive_bayes import MultinomialNB
clf = MultinomialNB()
clf.partial_fit(x, y, classes=np.array([0, 1]))
return clf
# for calculating the model metrics: specificity, sensitivity and balanced accuracy
def confusion_matrix(y_pred, y_test, pos_label):
true_positive = 0
false_negative = 0
false_positive = 0
true_negative = 0
for (pred, true) in zip(y_pred, y_test):
if pred == pos_label and true == pos_label:
true_positive += 1
elif pred == pos_label:
false_positive += 1
elif true == pos_label:
false_negative += 1
else:
true_negative += 1
sensi = true_positive / (true_positive + false_negative)
spec = true_negative / (true_negative + false_positive)
return sensi, spec
# Mapping target labels to its numeric value for training
df.sentiment = [1 if each == "positive" else 0 for each in df.sentiment]
# Applying contraction mapping on the reviews
df['review'] = df['review'].apply(contractionmap)
# Adding negation prefix on the reviews where ever found in the review based on condition defined
df['review'] = df['review'].apply(negationprefix)
# Changing pandas dataframes to numpy arrays
x, y = df['review'].values, df['sentiment'].values
# Splitting the dataset into 80% training and 20% testing
# Not shuffling the dataset as the reviews in the csv file are added in a random manner only, thus shuffling make not much difference
split = int(x.size * .8) # 80% - 20%
x_train, x_test, y_train, y_test = x[:split], x[split:], y[:split], y[split:]
# Using unigram feature from TF-IDF to train the model
# Fit the TF-IDF vectorizer on training data
vect_unigram = vectorizer_ngram(x_train)
# Transform the training data
train_transform = vect_unigram.transform(x_train)
# Fitting the classifier
clf_unigram = fitting(train_transform, y_train)
# For testing, tranforming the test data on the vectorizer fitted on the training data
test_transform = vect_unigram.transform(x_test)
# Predict
pred = clf_unigram.predict(test_transform)
acc_unigram = (pred == y_test).sum() / len(y_test)
# output model metrics obtained after training model
print("Accuracy on test dataset using unigram features - ", acc_unigram*100)
sensi, spec = confusion_matrix(pred, y_test, 1)
print("Specificity of Multinomial naive bayes(unigram) is-",spec)
print("Sensitivity of Multinomial naive bayes(unigram) is-",sensi)
print("Balanced accuracy of Multinomial naive bayes(unigram) is-",(spec+sensi)/2)
# Using bigram feature from TF-IDF to train the model
# Fit the TF-IDF vectorizer on training data
vect_bigram = vectorizer_ngram(x_train, unigram=False)
# Transform the training data
train_transform = vect_bigram.transform(x_train)
# Fitting the classifier
clf_bigram = fitting(train_transform, y_train)
# For testing, tranforming the test data on the vectorizer fitted on the training data
test_transform = vect_bigram.transform(x_test)
# Predict
pred = clf_bigram.predict(test_transform)
acc_bigram = (pred == y_test).sum() / len(y_test)
# output model metrics obtained after training model
print("Accuracy on test dataset using bigram features - ", acc_bigram*100)
sensi, spec = confusion_matrix(pred, y_test, 1)
print("Specificity of Multinomial naive bayes(bigram) is-",spec)
print("Sensitivity of Multinomial naive bayes(bigram) is-",sensi)
print("Balanced accuracy of Multinomial naive bayes(bigram) is-",(spec+sensi)/2)
# Exporting the classifier, unigram tf-idf and bigram tf-idf map for deployment/testing
import pickle
pickle.dump(clf_unigram,open('models/NBclassifier_unigram.pkl','wb'),protocol=4)
pickle.dump(clf_bigram,open('models/NBclassifier_bigram.pkl','wb'),protocol=4)
pickle.dump(vect_unigram,open('models/tfidf_unigram.pkl','wb'),protocol = 4)
pickle.dump(vect_bigram,open('models/tfidf_bigram.pkl','wb'),protocol = 4)
|
0202928df806f81765bfdf899074118673cc8b2a | Narengowda/algos | /v3/heap_sort.py | 1,390 | 3.546875 | 4 | import operator
import math
class Heap(object):
def __init__(self, values, op):
self.values = values if values else []
self.op = op
def insert(self, value):
self.values.append(value)
self._heapify()
def _heapify(self, index=0):
c_one, c_two = self.children(index)
if c_one:
self._heapify(c_one)
if self.op(self.values[c_one], self.values[index]):
self.values[index], self.values[c_one] = self.values[c_one], self.values[index]
if c_two:
self._heapify(c_two)
if self.op(self.values[c_two], self.values[index]):
self.values[index], self.values[c_two] = self.values[c_two], self.values[index]
def children(self, parent_index):
one, two = parent_index * 2 + 0, parent_index * 2 + 1
if one >= len(self.values):
one = None
if two >= len(self.values):
two = None
return one, two
def parent(self, children_index):
return math.ceil(children_index / 2)
def pop(self):
max_ele = self.values[0]
del self.values[0]
self._heapify()
return max_ele
def sort(self):
for i in range(len(self.values) + 1000):
self._heapify()
heap = Heap([6,3,2,8,4,2,65,22,2,224,7,9], operator.gt)
heap.sort()
print heap.values
|
dbaeaf9bc0a64e284a9e345c6d3bba2f7137b74f | Why-Not-Sky/my-experiments | /test_unicode_file.py | 345 | 3.734375 | 4 | # -*- coding: utf-8 -*-
import io
foo = u'Δ, Й, ק, م, ๗, あ, 叶, 葉, and 말.'
filename = 'text.txt'
# process Unicode text
with io.open(filename,'w',encoding='utf8') as f:
f.write(foo) # foo.encode('utf8'))
f.close()
with io.open(filename,'r',encoding='utf8') as f:
text = f.read()
f.close()
print (text)
|
44478422c58ee0db8686a69b6c5518576e8a52ff | ArthurBomfimNeto/exercicios_python- | /exe27.py | 205 | 4 | 4 | nome = input('Digite o nome:')
nm = nome
nome = nome.split()
print('muito prazer {}'.format(nm))
print('Seu primeiro nome é {} '.format(nome[0]))
print('Seu segundo nome é {} '.format(nome[len(nome)-1])) |
68341266f65f634b8561a9ac5e753fc7dab5a92d | rafaelperazzo/programacao-web | /moodledata/vpl_data/39/usersdata/103/15472/submittedfiles/dec2bin.py | 172 | 3.59375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n=int(imput('Digite um valor:'))
e=0
soma=0
while n>=1:
soma=soma+(n%2)*(10**e)
e=e+1
n=n//2
print(soma) |
ee963106968d923c89114a6e3a25bdb90acd7088 | lesoame/Python_Mundo_1 | /ex016.py | 438 | 4.3125 | 4 | # Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira
# Ex: Digite um número: 6.127, o nº 6.127 tem a parte inteira 6.
from math import trunc
num = float(input('Digite um valor qualquer: '))
print('A parte inteira de {} é igual a {}'.format(num, trunc(num)))
num1 = float(input('Digite um número: '))
print('A parte inteira do número {} é igual a {}'.format(num1, int(num1)))
|
03e76b3f1b41667ab7604693e9f5be046a58bc19 | sarospa/project-euler-python | /euler-113.py | 998 | 3.515625 | 4 | # Solution to https://projecteuler.net/problem=113
import math
import utilities
LENGTH = 10
cache = dict()
def count_nonbouncy(base, length, increase, decrease):
if len(base) > 0 and (len(base), base[-1], increase, decrease) in cache:
return cache[(len(base), base[-1], increase, decrease)]
if increase and decrease:
return 0
if len(base) == length:
return 1
if len(base) == 0:
total = 0
digits = range(1, 10)
else:
total = 1
digits = range(0, 10)
for i in digits:
if len(base) > 0 and i > int(base[-1]):
total += count_nonbouncy(base + str(i), length, True, decrease)
elif len(base) > 0 and i < int(base[-1]):
total += count_nonbouncy(base + str(i), length, increase, True)
else:
total += count_nonbouncy(base + str(i), length, increase, decrease)
if len(base) > 0:
cache[(len(base), base[-1], increase, decrease)] = total
return total
def main():
return count_nonbouncy("", 100, False, False)
if __name__ == "__main__":
utilities.print_runtime(main) |
abcbb6f7a02de5de2d19df7a96a2fa018d2d1985 | nithin-kumar/urban-waffle | /InterviewCake/max_product_3.py | 699 | 4.125 | 4 | import math
def highest_product_of_3(list_of_ints):
# Calculate the highest product of three numbers
if len(list_of_ints) < 3:
raise Exception
return
window = [list_of_ints[0], list_of_ints[1], list_of_ints[2]]
min_number = min(window)
min_index = window.index(min_number)
prod = reduce(lambda x, y: x*y, window)
for i in range(3, len(list_of_ints)):
if list_of_ints[i] > min_number:
window[min_index] = list_of_ints[i]
min_number = min(window)
min_index = window.index(min_number)
prod = max(prod, reduce(lambda x, y: x*y, window))
return prod
print highest_product_of_3([-10, 1, 3, 2, -10]) |
981c51260bed9e8c0ec88d796c00f6f988dc2d0e | ashi1994/PythonPractice | /Basic/AccessModifier_Public_Private_Protected.py | 307 | 3.765625 | 4 | '''
Created on May 31, 2018
@author: aranjan
'''
class parent1:
name='ashiwani'#This is public
__age=21 #This is private
_sex='male' # This is protected
class child(parent1):
def show(self):
print(self.name)
#print(self.__age)
print(self._sex)
obj=child()
obj.show() |
bcac660fc7838744976c5607436c951bc7ae65aa | djulls/tools | /date2timestamp.py | 436 | 3.78125 | 4 | #/usr/bin/env python
import time
import datetime
import argparse
def date_to_timestamp(date):
return time.mktime(datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S").timetuple())
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="")
parser.add_argument('date',help='Datetime to be converted (format: yyyy-mm-ddThh:mm:ss)')
args = parser.parse_args()
print date_to_timestamp(args.date)
|
72abd457463cd0baa3f03beb2fcf52e221b6c5f6 | FIRESTROM/Leetcode | /Python/229__Majority_Element_II.py | 1,689 | 3.625 | 4 | # Boyer-Moore Majority Vote Algorithm
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return nums
check = len(nums) / 3
val1, val2 = nums[0], nums[1]
count1, count2 = 0, 0
for n in nums:
if n == val1:
count1 += 1
continue
if n == val2:
count2 += 1
continue
if count1 == 0:
val1 = n
count1 = 1
continue
if count2 == 0:
val2 = n
count2 = 1
continue
count1 -= 1
count2 -= 1
count1, count2 = 0, 0
for n in nums:
if n == val1:
count1 += 1
if n == val2:
count2 += 1
result = []
if count1 > check:
result.append(val1)
if count2 > check and val2 != val1:
result.append(val2)
return result
# Another normal solution, not O(1) space complexity
from collections import defaultdict
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
dic = defaultdict(int)
check = len(nums) / 3
for i in nums:
if i not in dic:
dic[i] = nums.count(i)
for val, times in dic.items():
if times > check:
result.append(val)
return result
|
87162e8efafb5bd119e0b26ab7ccb23aaecd63a8 | crazyguy106/cfclinux | /steven/python/personal_workshop/containers/variables/variable_types.py | 313 | 3.921875 | 4 | #!/usr/bin/python3
# String
my_string = 'Hello World'
another_string = "Another World"
print(type(my_string), my_string)
print(type(another_string), another_string)
# integer
my_int = 10
# float
my_float = 10.5
# list
ls = []
ls = [1, 2, 3]
ls = [1, 'a']
# dictionary
dictionary = {'my_key': 10}
# Boolean
|
e05c34c728045a1fb62c3df5fdd6c9b2c87f2b83 | queensland1990/HuyenNguyen-Fundamental-C4E17 | /SS01/Homework/ss1/session2/oneton.py | 125 | 3.546875 | 4 | #1. n cac so chan tuw 0 toi 10
#2. Tong quat lon 0-> # N
n=int(input("enter a number:"))
for i in range(0,n,2):
print(i)
|
dfef6765ec23c93d3aab8a104bea588d49f6b4d8 | sharmak/python | /ds/sorted_permuatation.py | 770 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 29 06:01:26 2014
@author: kishor
"""
# Sorted Permuataion problem
def is_perm_solution(n, k):
return n == k
def generate_perm_candidates(n, k, a, data):
candidates = list()
for ele in data:
if ele not in a:
candidates.append(ele)
return sorted(candidates)
def print_perm_solution(a, data):
print a
def permutations(a, n, k, data):
if is_perm_solution(n, k):
print_perm_solution(a, data)
else:
k = k + 1
candidates = generate_perm_candidates(n, k, a, data)
for c in candidates:
a[k-1] = c
permutations(a, n, k, data)
a[k-1] = -1
data = [1, 2, 3]
a = [-1, -1, -1]
permutations(sorted(a), 3, 0, data) |
8a8e7901cd1facd0025def90df7222cd6c2d73b0 | kenjo138/DOCFULLY | /test_homework.py | 1,227 | 3.75 | 4 |
# Use the list: [2,3,4,5,8,4,6,3,4,6,8,9,7,5,3,5,7,4,3,2,2,1,4,6,8,6,8,9,3]
data = [2,3,4,5,8,4,6,3,4,6,8,9,7,5,3,5,7,4,3,2,2,1,4,6,8,6,8,9,3]
# Section 4 : Q3
print(50*'-')
print("Section 4 : Q3")
print(50*'-')
#mean_function
def mean_fn(data):
try:
return sum(data)/len(data)
except:
print("Divide by 0!")
return 0
#mode_function
def mode_fn(data):
#Initialize variables
most_freq=0
count=0
#Return zero if empty list
if len(data)==0:
return 0
#Find the unique number in the list
data1=set(data)
#Count the frequency of the unique number
#Determine the most freq
for i in data1:
if count<data.count(i):
most_freq=i
count=data.count(i)
return most_freq
#median_function
def median_fn(data):
#Return zero if empty list
if len(data)==0:
return 0
data.sort()
#the data length is odd
if len(data)%2 != 0:
median_val=data[int(len(data)/2.0+0.5)]
else:
median_val=0.5*(data[int(len(data)/2-1)]+data[int(len(data)/2)])
return median_val
#main function
print(mode_fn(data))
|
eb9ff602f79351afbd08351a3c78fa7e5f346ae4 | CiroIgnacio/Python_Curso | /Ahorcado/ahorcado.py | 1,818 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 23:22:16 2020
@author: ciro
"""
#%%
import random
import unicodedata
def elimina_tildes(cadena):
s = ''.join((c for c in unicodedata.normalize('NFD',cadena) if unicodedata.category(c) != 'Mn'))
return s
Word_file = "/home/ciro/Desktop/Ciro/Programacion/Python/Python_Curso/dict/Untitled Document 1"
WORDS = open(Word_file).read().splitlines()
play = 'Y'
computer = 0
player = 0
while play == 'Y':
word = random.choice(WORDS).lower()
word = elimina_tildes(word)
word1 = word
user_inp = ''
c = 0
letters = []
for i in range(len(word)):
if word[i] == ' ':
user_inp += ' '
else:
user_inp += '*'
print(user_inp)
while user_inp != word:
letter = input()
user_inp = list(user_inp)
word1 = list(word1)
if letter in word1:
for i in word1:
if i == letter:
index = word1.index(letter)
word1[index] = '*'
user_inp[index] = letter
user_inp = "".join(user_inp)
print(user_inp)
else:
c += 1
user_inp = "".join(user_inp)
print(user_inp)
# Info user
letters.append(letter)
print("Letras usadas:", end = " ")
for i in letters:
print(i, end = "-")
print(f"\nVidas restantes: {5-c}")
if c > 4:
computer += 1
print("Perdiste")
break
if user_inp == word:
player += 1
print("Ganaste")
print(f"La palabra era: {word}")
print(f"SCORE\nComputer: {computer}\nPlayer: {player}")
play = input('Do you want to play again? (Y/N): ').upper()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.