blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
80fad3452e898af975946fa677e820eafe3ef850 | AlexAntartico/python-random-quote | /get-quote.py | 753 | 3.71875 | 4 | import random
file="quotes.txt"
def quote_generator():
f = open(file)
quotes = f.readlines()
f.close()
first_random_item, second_random_item = random.sample(quotes, 2)
print (first_random_item, second_random_item,sep="",end="")
def add_quote():
user_quote=input("Write your quote and hit enter:\n")
a... |
274d3a851e3868539fdf142a54c5d86464a4001a | seligman/aoc | /2020/Helpers/day_13.py | 1,968 | 3.53125 | 4 | #!/usr/bin/env python3
DAY_NUM = 13
DAY_DESC = 'Day 13: Shuttle Search'
def chinese_remainder(values):
prod = 1
for _, n in values:
prod *= n
total = 0
for val, n in values:
b = prod // n
total += val * b * pow(b, n - 2, n)
total %= prod
return total
def calc(log, ... |
143732899d1245aa322be55268a66a2755ab20d4 | seligman/aoc | /2015/Helpers/day_14.py | 2,312 | 3.671875 | 4 | #!/usr/bin/env python3
import re
DAY_NUM = 14
DAY_DESC = 'Day 14: Reindeer Olympics'
class Deer:
def __init__(self, name, speed, limit, rest):
self.name = name
self.speed = int(speed)
self.limit = int(limit)
self.rest = int(rest)
self.state = "fly"
self.left = sel... |
5af299de7486e589dcd420eb4d8bbfe21ddd2e68 | seligman/aoc | /2022/Helpers/parsers.py | 766 | 3.671875 | 4 | #!/usr/bin/env python3
def get_ints(line):
ret = [""]
for x in line:
if len(ret[-1]) == 0 and x == "-":
ret[-1] = "-"
elif "0" <= x <= "9":
ret[-1] += x
else:
if len(ret[-1]) > 0:
ret.append("")
if len(ret[-1]) == 0:
ret.po... |
0659c8d86de90ac4a7b306e440347fbc79d6b8f8 | Zeeshan17CO50/human_menudriven_software | /human_software.py | 5,787 | 3.625 | 4 | import pyttsx3
import os
pyttsx3.speak("Welcome to my tools:")
# software_list = ["notepad", "firefox", "calc", "chrome", "exit"]
# firefox,ping,calc,exit
# creating software lists txt files
with open('software_lists.txt', 'w+') as f:
isEmpty = f.read().strip()
if isEmpty == "":
previous = "chrome,fir... |
80ae3af9862adc319777f36138db546b21f0ba4c | anh-duc-nguyen/CS480-AI | /project2/myothello.py | 2,401 | 3.734375 | 4 |
from othello import *
class AnhPlayer(othello_player):
'''
This is a Othello player AI with heuristic implemented
This AI using a matrix to calculate the piority and
calculate the friendly mobilty of each piece on the board.
@Author: Anh Nguyen
@Version: Oct -16
'''
def initialize(sel... |
25598a057964615ad5adb85172be91934ec61de1 | shlomo-hadar/LibraryProject | /helloWorld/Proj/book.py | 824 | 3.796875 | 4 | ##################
class Book:
def __init__(self, title="", author="", publication_year=0, comic=0,
dramatic=0, educational=0, hosting_library="", current_holder=""):
self.title = title
self.author = author
self.publication_year = publication_year
self.comic = comic
... |
b44bbdf00878a876e6ca4e3342993c8e7ab7a01b | balage77/AOC2018 | /Day 01/day-01.py | 667 | 3.96875 | 4 | # Read the puzzle file
freq_changes = tuple(open("day-01.txt", 'r'))
result_freq = 0;
# First part of the day
for freq_change in freq_changes:
result_freq += int(freq_change)
print("Result frequency: ", result_freq)
# Second part of the day
freq_set = {0}
actual_freq = 0
searching = True
while searching:
... |
491a83599e3facf18c005f5d11f1dca5f750c0f5 | lxr17/study | /net/lanxingren/study/lesson7.py | 5,170 | 3.984375 | 4 | # s1 = "hello, world"
# s2 = 'hello, world'
# s3 = '''
# hello
# world
# '''
# print(s1, s2, s3, sep="_", end="")
# s1 = '\'hello, world!\''
# s2 = '\n\\hello, world!\\\n'
# print(s1, s2, end='')
# s1 = '\141\142\143\x61\x62\x63'
# s2 = '\u4f55\u91d1\u534e'
# print(s1, s2)
# s1 = "hello" * 3
# print(s1)
# s2 = "worl... |
794eca2f33cdee46eaf817c0b061b1d92ff77bd7 | mikaylab12/fibonacci_task | /main.py | 495 | 4.4375 | 4 | # defining a Fibonacci variable
def fibonacci(x):
if x <= 1:
return x
else:
return (fibonacci(x-2)) + fibonacci(x-1)
# number of terms
terms=20
# Fibonacci function in order to receive the first 20 terms and their values
if terms <= 0:
print("Please enter a positive integer") # Fibonacci seq... |
041814210485288241b03d96c626a8f491473bfd | arunk38/learn-to-code-in-python | /Python/automatetheboringstuff/src/1_baiscs/2-guess-the-number.py | 527 | 4.125 | 4 | import random
secretNumber = random.randint(1, 20)
print("Guess a number between 1 and 20...")
# the game starts now
for guessTaken in range(1, 76):
print("Take a guess:")
num = int(input())
if num < secretNumber:
print("Guess higher...")
elif num > secretNumber:
print("Guess lower..... |
9f3b8f2668269ac3c30ecb4e79fa2b4792cf2048 | arunk38/learn-to-code-in-python | /Python/pythonSpot/src/2_intermediate/4_finite_state_machine/__init__.py | 933 | 3.953125 | 4 | """
A finite state machine (FSM) is a mathematical model of computation with states, transitions, inputs and outputs.
This machine is always in a one state at the time and can move to other states using transitions. A transition
changes the state of the machine to another state.
A large number of probl... |
11c8373e7564bfbe227acdb43d82c7a6134a4c53 | arunk38/learn-to-code-in-python | /Python/pythonSpot/src/2_intermediate/1_sets/__init__.py | 614 | 4.03125 | 4 | """
A set in python is a collection of objects, different from lists and tuples.
Modeled after set in mathematics
"""
# Multiple occurrences of same item are removed
x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)
# remove elements
x.remove("Radio")
print(x)
# add elements
x.add("Telephone")
... |
78fb94234343625144577ff5d5de1390ed1c8fdf | arunk38/learn-to-code-in-python | /Python/pythonSpot/src/1_basic/1_strings/modifyStrings.py | 246 | 4.46875 | 4 | s = "Hello Python"
print(s + ' ' + s) # print concatenated string.
print(s.replace('Hello','Thanks')) # print a string with a replaced word
# convert string to uppercase
s = s.upper()
print(s)
# convert to lowercase
s = s.lower()
print(s)
|
a963ca774f1caaf01de5e36be58a5514451efdca | aarush3002/usaco | /beads.py | 1,893 | 3.859375 | 4 | """
ID: aarush31
LANG: PYTHON3
TASK: beads
"""
with open('beads.in','r') as filein:
N = int(filein.readline()) # Number of beads
beads = filein.readline()[:-1] # Necklace
def canCollect(s):
return not ('r' in s and 'b' in s) # If r and b are not in the same str,
# th... |
97b1ca02efa5c0396228640b8b1a338a5f1829f8 | FGG100y/myleetcode | /hwtt/filter_repeat_chars.py | 268 | 3.9375 | 4 | #!/usr/bin/env python
# filter repeated characters
def filter_chars(s):
# return unique characters string
res = ''
for c in s:
if c not in res:
res += c
return res
if __name__ == "__main__":
print(filter_chars('bacaadcae'))
|
6495ddc18f27fe4847e602864f4db031f3f02b10 | FGG100y/myleetcode | /hwtt/subway_shortest_path.py | 6,171 | 4.09375 | 4 | #!/usr/bin/env python
# encoding: utf-8
# shortest path: Depth-First-Search & Breadth-First-Search
# from optimization_graph import Digraph
from optimization_graph import Graph
from optimization_graph import Node
from optimization_graph import Edge
def print_path(path):
"""
:type path: list of Nodes
:... |
be591959b65deebd2994f5e839db6360dfe23dcd | FGG100y/myleetcode | /hwtt/common_lss.py | 233 | 3.84375 | 4 | #!/usr/bin/env python
# search for the longest common substring of two strings
def common_lss(s1, s2):
pass
if __name__ == "__main__":
s1 = 'abcdefghijklmnop'
s2 = 'abcsafjklmnopqrstuvw'
print(common_lss(s1, s2))
|
9b2e4b017ef9614b5620c385a7b7989a8cef2c93 | FGG100y/myleetcode | /hwtt/int_to_str.py | 554 | 3.984375 | 4 | #!/usr/bin/env python
# Big O | logarithmic complexity
def int2str(i):
"""returns a decimal string representation of an int
:type i: int
:rtype str
"""
digits = '0123456789'
if i == 0:
return '0'
result = ''
while i > 0:
result = digits[i%10] + result
i //= 10
... |
c835882b2438b96d4e69f2ef695270bba3843791 | connecttopawan/Learning_Python | /BinaryGap.py | 864 | 4.03125 | 4 | def BinaryGap(N):
"""
Determines the maximum 'binary gap' in an integer
:return: a count of the longest sequence of zeros in the binary representation of the integer
"""
# protect against crazy inputs
if not isinstance(N, int):
raise TypeError("Input must be an integer")
if N < 1:
... |
96f09239866afd1b1e5a386f96369599c4d14ecb | jayp0684/Find | /Find.py | 492 | 3.671875 | 4 | #str = "X-DSPAM-Confidence:0.8475"
#Use find and string slicing to extract the portion of the
#string after the colon character and then use the float function
#to convert the extracted string into a floating point number.
#results should include what index position the colon is
#in as well as the float val... |
64d998decbcf23a4acc0fc5828d49046d7bdf0b0 | danielmcarthur/covid-19-simulator | /f3_simulation_parameters_visualisation.py | 998 | 3.78125 | 4 | """
FIT9136 Algorithms and Programming Foundations in Python S1 2020: Assignment 2 v.1.5.1
student: Daniel John McArthur
student-id: 31421393
student-email: dmca0006@student.monash.edu
date-last-modified: 8 June 2020
The following was made using the provided template from the subject Moodle.
This program utili... |
224d4cccf0b5acfe65d097691c4538aa1bea12f9 | CodeAT007/ARSTAR | /arstar_itr2.py | 2,807 | 4.15625 | 4 | import random
def merge(left, right):
"""
merge 2 list as a sorted list with mergesort algorithm
"""
## if the list is empty
if not len(left) or not len(right):
return left or right
## merge the list in sorted manner
result = []
i, j = 0, 0
while (len(result) < len(left) +... |
47baaab0c8c1e52fb15b8bd6b1891f326d480cfa | jleyva82/Resources | /newfile_creation.py | 715 | 4.03125 | 4 | '''
Author = Jesus Leyva
Last Update: 01/28/2019
Purpose: Sample of how to use python to create a new file
sample resources as described via stack skills python lessons
'''
import json
import os
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size != 0:
old_file = open("./ages.json", "r+... |
0e566730c5d716870aa3cef47bb459b1742b07f4 | dazz22/udacity-coursework | /Algorithms_intro_to/l1ps10_mysol.py | 1,621 | 3.875 | 4 | # Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible Eulerian tour would be [1, 2, 3, 1]
def find_eulerian_tour(graph):
a = 0
graph2 = ... |
fda225370f1e6b5e9cbb005e6855ec2034f7633c | Programmer-X31/PythonProjects | /hackerterm/hackerterm.py | 802 | 3.984375 | 4 | import random
import os
def factorial(n):
try:
"""Finds the factorial of a number"""
if (n == 1):
return 1
return n * factorial(n - 1)
except RecursionError:
for i in range(n, 1, -1):
return n * i
while True:
try:
for i in r... |
d42a0dcad11a17459b4ea31e1e4839d8d4c2649d | Programmer-X31/PythonProjects | /Project Sudoku Solver/efficient_main.py | 1,862 | 3.8125 | 4 | from tkinter import *
grid = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9,... |
c4760b2f150f1f240eab12d362214f227a1b5eaf | SundaresanN/raspberrypi_iot_workshop | /python/classes.py | 129 | 3.578125 | 4 | class calc: #note here no parentheis
def add(x,y):
z=x+y
return(z)
def mul(x,y):
z=x*y
return(z)
print(calc.add(2,3))
|
e4af326ab2af04dacc2d3b9b70fd23b9b1e460e9 | yaleliyu/leetcode | /kth-ancestor-of-a-tree-node.py | 1,336 | 3.78125 | 4 | # https://leetcode.com/problems/kth-ancestor-of-a-tree-node/
class TreeAncestor:
class TreeNode:
def __init__(self, val: int, subNodes):
self.val = val
self.subNodes = subNodes
def __init__(self, n: int, parent):
self.parentDict = {'0':[0]}
self.buildT... |
497e54d00f4f7a6cc253d0dd41b32ef6db8db969 | Marcio-Santos7/uri-online-judge-python | /problemas-iniciante/o-maior-1013.py | 516 | 4.09375 | 4 | """
Faça um programa que leia três valores e apresente o maior dos três valores lidos seguido da mensagem “eh o maior”.
Entrada
O arquivo de entrada contém três valores inteiros.
Saída
Imprima o maior dos três valores seguido por um espaço e a mensagem "eh o maior".
"""
import math
a, b, c = input().split()
a = i... |
399aea654de3c89efdcdc3c569d101906770abfe | Marcio-Santos7/uri-online-judge-python | /problemas-iniciante/area-do-circulo-1002.py | 760 | 4 | 4 | """
A fórmula para calcular a área de uma circunferência é: área = pi.raio². Considerando para este problema que
pi = 3.14159:
- Efetue o cálculo da área, elevando o valor de raio ao quadrado e multiplicando por pi.
Entrada:
A entrada contém um valor de ponto flutuante (dupla precisão), no caso, a variável raio.
... |
25cb6955225c2681c3611a9af5c824cafb26bd8e | baumy1/Talking-Bin | /final.py | 1,138 | 3.75 | 4 | # Import dependecies, gpiozero for button, os to run commands in the terminal and random for obvious reasons
from gpiozero import Button
import os
import random
# Define the button using GPIO 2 (Pin 3)
button = Button(2)
# This variable requires the flap to be closed again before a sound can play again
hasPlayed = Fal... |
4325a2be1b3ddfbd6dd487dfee2df94d330d7d73 | brookeaddison/cssi_stuffs | /random_python_stuff/fizzbuzz.py | 276 | 3.734375 | 4 | """ My implementation of fizzbuzz. """
def fizzbuzz(number):
if number % 3 == 0 and number % 5 == 0:
print ('fizzbuzz')
elif number % 3 == 0:
print ('fizz')
elif number % 5 != 0:
print ('buzz')
if __name__ == '__main__':
fizzbuzz(15)
|
4282f0f546c6084e8aedbc9c9330b222716f288a | GavinHacker/Robomaster-AI-Challenge-2019 | /Ken/DJI/action.py | 4,215 | 3.8125 | 4 |
from Objects import *
from utils import *
"""
An Action is a command to the robot
It changes the state of the robot upon resolve
"""
class Action:
def frozenOk():
return False
# Returns True if the Action is successfully resolved
# Returns False if it didn't have any effect
def resolve(self... |
4d8986f7be083d2e4c8c819a45cedf509b8c79f1 | ceccacci1841630/Bioinformatics | /[PCS2] Homework 4/RabbitsAndRecurrenceRelations.py | 236 | 3.515625 | 4 | def rabbit_fib(n,k):
rabbits_alive = [1, 1+k]
for _ in range(n-2):
offspring = k * rabbits_alive[-2]
rabbits_alive.append(offspring + rabbits_alive [-1])
return rabbits_alive
print(rabbit_fib(33, 5)[-2]) |
9580dd91f5079136d3cfeb2b929cee385e5ce3ac | ceccacci1841630/Bioinformatics | /[PCS2] Homework 4/Utilities_fasta.py | 517 | 3.6875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 10:58:12 2019
@author: carlottaceccacci
"""
import os
def file_reader(file_name, fasta=False):
to_split_at = "\n"
if fasta:
to_split_at = ">"
path = os.path.expanduser("~/desktop/" + file_name)
with open(path, "r") as fi... |
f852898801c8d9e7a182dc5fbe4cbcadf4b72dc1 | Shafin-Thiyam/Python_prac | /Scrabble_cheater.py | 1,016 | 3.890625 | 4 | import sys
import Scrabble as scr
def valid_word(word,rack):
#Make a copy of rack for every new word so we can Manipulate without changing orginal rack
available_letters=rack[:]#['a','b','c','d','e','f','g']
for l in word:#l =dace
if l not in available_letters:
return False
... |
aa7abb2aa4217bd958676444dd64dddaf6df0353 | BoHyeonPark/BI_test | /bioinformatics_2_5.py | 158 | 3.890625 | 4 | #!/usr/bin/python
s1 = raw_input("Enter s1: ")
s2 = raw_input("Enter s2: ")
if len(s1) % 2 != 0 and len(s1) < len(s2):
print s1+s2
else:
print s2+s1
|
136a0abfa8ba0cd3f602117480c2be938f2db4d7 | lifeoflemons/Python_Practice | /Part_1/cars.py | 276 | 3.953125 | 4 | cars = ['bmw','audi','toyota','subaru']
print("here is the original list: ")
print(cars)
print("\nHere is the sorted list: ")
print(sorted(cars, reverse=True))
print("\nHere is the original list again:")
print(cars)
print("\n\n")
cars.reverse()
print(cars)
print(len(cars))
|
89d1483520100e0786947b72cbeae0fa33b8b303 | MuhammadAdnanKhalid/Problem-Solving-using-Bipartite-Graph | /Bipartite_Graph.py | 4,670 | 3.65625 | 4 | import pandas as pd
# Python program to find
# maximal Bipartite matching.
class GFG:
def __init__(self, graph):
# residual graph
self.graph = graph
self.ppl = len(graph)
self.jobs = len(graph[0])
# A DFS based recursive function
# that returns true if... |
5fa6884b11f9481ee914f6f186cabeb319f48453 | landalex/FinalProject | /pythonShineTest.py | 422 | 3.828125 | 4 | newList = []
for i in range(len(listOrig)):
newList.append(listOrig[i])
counter = 0
for i in range(len(listOrig) - 1):
counter += 1
if listOrig[i] > listOrig[i+1]:
newList[i+1] = newList[i]
newList[i] = listOrig[i+1]
elif listOrig[i] <= listOrig[i+1]:
newList[i+1] = listOrig[i+1]
if counter == ((len(listOr... |
038d0c9ef8854f6494c5dd0292ce3d967741fbca | klprabu/myprojects | /Python/HackerRank/PolarCordinatesComplexnumbers.py | 625 | 4.28125 | 4 | # Task
# You are given a complex . Your task is to convert it to polar coordinates.
#
# Input Format
#
# A single line containing the complex number . Note: complex() function can be used in python to convert the input as a complex number.
#
# Constraints
#
# Given number is a valid complex number
#
# Output... |
f98b7f22206c21c946fa2b418f6e335e428a68a4 | klprabu/myprojects | /Python/Self/HankerRankTest.py | 1,244 | 3.65625 | 4 | if __name__ == '__main__':
v_name = []
v_score = []
for cnt in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
v_name.append(name)
v_score.append(score)
# print(cnt+1)
n = cnt + 1
# print(v_score)
uni = []
uv = 0
... |
78366c08e2fe6ffac99dde10fdab254a7715df64 | klprabu/myprojects | /Python/HackerRank/Split_Join_String.py | 298 | 4.0625 | 4 | #This program will split the string and then join with the delimiter
def split_and_join(line):
# write your code here
line = line.split()
line = "-".join(line)
return line
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result) |
527bcbf66d546156ca449a91de977ad6826ce8f0 | klprabu/myprojects | /Python/Self/CodeIntrospection.py | 624 | 3.703125 | 4 | # Use the help function to see what each function does.
# Delete this when you are done.
help(dir)
help(hasattr)
help(id)
# Define the Vehicle class.
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
desc_str = "%s is a %s %s worth $%.2f." %... |
e596c8a0caa0ef023f4c6ea94b08cbf57d5b6d87 | klprabu/myprojects | /Python/HackerRank/StringFormattingHexBinOctDec.py | 978 | 3.875 | 4 | #To print the Decimal , octal, binary, hexa values with regular space inbetween
def print_formatted(number):
# your code goes here
len_bin = len(bin(number)) - 2
# print(len_bin)
space_padding = ' ' * (len_bin)
v = ''
if 1 <= number <= 99:
for i in range(1, number + 1):
... |
0af702316500299f4f8348bd9acaa3e30594f9da | keerthikeiths3/Projects | /Python/toss_2_player (1).py | 4,359 | 3.578125 | 4 | __author__ = 'Keerthi'
import _random
import sys
import os
from array import *
import ctypes
from random import randint
import random
def Roll_Dice_Player1():
global red_count1
global yellow_count1
global green_count1
global dice_num1
global player1_score
red_count1=0
yellow_count1=0
... |
e5b73ab72bd1d1ca614711f6f06a278027fb133f | 6324hiphop-man/python- | /spyder-study/4.py | 376 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 24 21:17:35 2019
@author: George~
"""
'''x =eval( input('x='))
y =eval( input('y='))
z = eval(" x+y")
#print('z=',"%d=%d+%d"%(z,x,y))
print('z=', x,'+',y,'=',z)
'''
x = float (input('x='))
y = float (input... |
a3a65e9f3b05b8430a78dabe84a6420e3d4c4806 | 6324hiphop-man/python- | /spyder-study/7.py | 598 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 14 15:33:53 2020
@author: George~
"""
#定义判断闰年函数
#函数参数:year————被判断年份
#函数值:是闰年返回True,不是闰年返回False
def isleap(year):
if year%4==0 and year%100!=0 or year%400==0: #“能整除4的但不能整除100” 或 “能整除400” 算法1
return True
else:
return False
... |
f2ac47b887bdaae94cc48928c795a7ec541f7566 | kiennd13/NguyenDucKien-Fundamentals-C4E30 | /Session 4/Homework/dict_excercise_4.py | 285 | 3.765625 | 4 | print("Answer the following algebra question: ")
print("If x=8, then what is the value of 4(x+3)?")
quiz={
1: 35,
2: 36,
3: 40,
4: 44
}
for k,v in quiz.items():
print(str(k)+'.',v)
n = int(input("Your choice: "))
if n != 4:
print(":(")
else:
print("Bingo") |
003be16b26acf7c17a0b46624328885c451af6c0 | rsdarji/CEGEP-sem-2-Algorithm | /match.py | 308 | 4 | 4 | def match(str):
count = 0
for i in str:
if(count < 0):
break
if(i=="("):
count+=1
elif(i==")"):
count-=1
return count==0
print(match("(()"))
#https://stackoverflow.com/questions/538346/iterating-each-character-in-a-string-using-python |
54ca41194ddb9075dfc2df952c4cfee6dcf54afd | jeffrlynn/Codecademy-Python | /reverse.py | 157 | 4.15625 | 4 | #Returns the reverse of your input
def reverse(text):
word = ""
l = len(text) - 1
while l >= 0:
word = word + word[l]
l = l - 1
return word
|
781bb0fefeefe50ab5ed57a7265ce4c3ab95887c | lees28/AI-planning | /1.py | 1,045 | 3.609375 | 4 |
from graph import Graph
class Solve:
def __init__(self,graph,colors):
self.graph = graph
self.colors = colors
def solve(self):
assignment = []
graph = self.graph
colors = self.colors
for i in range(graph.getNumNodes()):
for j in range(i,graph.getN... |
3bc5464f7aa1454fa87fa8d466dbbaef8bd28ded | Zapel/python_lesson | /lesson7/factorial.py | 233 | 3.953125 | 4 | # -*- coding: utf-8 -*-
from __future__ import print_function
def f(n):
input(n)
assert n>=0, "Факториал отрицательного не определен"
if n == 0:
return 1
return f(n-1)*n
|
ece3a753815214dbdc936ec28bda371729b68bb5 | subhro101/Effective-touch-dynamics-feature | /information_gain.py | 1,113 | 3.890625 | 4 | # File for the information gain feature selection algorithm
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_selection import mutual_info_classif
# The function which will be called
def get_features(raw_data, raw_ids, debug, run):
"""
Calc... |
5f57e83ec1c5a17fd61af78e7023a21582c6ae27 | wonjaegang/FBD2021 | /Baskin31_GameTable.py | 4,140 | 3.546875 | 4 | import random
import os
import game_settings
import Jaewon_algorithm
import Kyeongmin_algorithm
import Kyungho_algorithm
import random_algorithm
import User_input
class Player:
def __init__(self, name, strategy):
self.name = name
self.strategy = strategy
self.previous_num = 0
self.... |
647301915a50679194d45e1481e9b33f333feb67 | absurd678/first_code | /main.py | 2,844 | 3.65625 | 4 | # Welcome to Move! game!
# In this game the player is allowed to choose one of two nearest locations and get the small task
# The forbidden location is the Ctulhu's grave - the R'lyeh
# Here the main attributes are dictionaries, in case of its usefulness for this game
# The class-composite is here(Game), the compon... |
576769ac1d781fc0eb3267d97d1e162d395d2755 | usamah13/Python-games- | /CMPUT 175/cmout175lab2q1.py | 1,955 | 3.859375 | 4 |
from random import randint
#ACCEPTED_INPUTS = [1,5,10,25]
#BREAK_LOOP = "ERROR"
def generate_target_value():
return (randint(1, 99))
def ingest_user_value(goalInt, var):
ACCEPTED_INPUTS = [1,5,10,25]
if var.isdigit() and int(var) in ACCEPTED_INPUTS:
inputValue = int(var)
goalInt -= inputValue
return (goalI... |
c6693e40322006365867feae7bc9432c415ea4d7 | usamah13/Python-games- | /CMPUT 175/lab5.py | 1,088 | 4.09375 | 4 | import string
def encrypt(word_to_encrypt,key):
allAlphabets = string.ascii_uppercase
#print(allAlphabets)
encryptedAlphabets = allAlphabets[key:] + allAlphabets[:key]
#print(encryptedAlphabets)
encryptedMappings = str.maketrans(allAlphabets, encryptedAlphabets)
print(encryptedMappings)
return word_to_encrypt.t... |
2fb340bdf8ecbd51dd58929895f6cfbafcfdf43c | usamah13/Python-games- | /All CMPUT 175 and CMPUT 174 code/Remember_v1.py | 1,069 | 4.40625 | 4 | # Remember the word Version 1
#
# Displays 4 words to users. User is prompted to recall one of
# those four words. This is the the first programming project
# in CMPUT174, Winter 2018.
import time
def main():
# display instructions
print('A sequence of words will be displayed.')
print('You will be asked wh... |
0825606ba3b5ee0abf670dce487276287c2b4dd0 | usamah13/Python-games- | /CMPUT 175/reversestack.py | 339 | 3.96875 | 4 | from Stack import Stack
# I will be using the Satck class as a black box -----> Abstarction
def reverse(aString):
aStack = Stack()
for char in aString:
aStack.push(char)
while not aStack.isEmpty():#Very Important
print(aStack.pop(),end = '')
def main():
word = input('Enter word >')
r... |
0f5fb7d5edddf5db55647e2e4dd0f09cfabf0a3f | usamah13/Python-games- | /CMPUT 175/lab10q4.py | 286 | 4.0625 | 4 | def reverseDisplay(number):
if (number < 10):
print(number, end = '')
return number
else:
print(number%10, end = '')
return reverseDisplay(int(number/10))
def main():
number= int(input('Enter a number :'))
reverseDisplay(number)
main() |
288e7d7e0aeca4886db8d067b821c430a0459160 | usamah13/Python-games- | /All CMPUT 175 and CMPUT 174 code/CMPIT 174/guess.py | 633 | 4.3125 | 4 | # Guess the number
#
# LAB 1
# A number between 1 and 10 randomly selected
# and user is asked to guess that number.
import random
def main ():
# select a random number between 1 and 10
number = random.randint(1,10)
print ('I am thinking of a number between 1 and 10.')
# prompt user to guess a ... |
d463905ca17de5c8a45bad7486afa4e90268f1a7 | TanyaMozoleva/python_practice | /Weeks/week4/w4t7.py | 421 | 3.6875 | 4 | '''
'''
def test_string(phrase):
first_symbol = phrase[0].lower()
last_symbol = phrase[-1].lower()
vowels = 'aeiou'
index1 = vowels.find(first_symbol)
index2 = vowels.find(last_symbol)
return (index1 != -1 or index2 != -1) and len(phrase) % 2 == 0
def main():
result = test_string(... |
893a4f0ee78caa71658281840fedcd087d90ccfb | TanyaMozoleva/python_practice | /Lectures/Lec4/p23.py | 179 | 3.578125 | 4 | '''
complete the output
'''
s = 'Dogs have masters. Cats have staff.'
print('1.', s[1: 6])
print('2.', s[:2] * 3)
print('3.', s[-3])
print('4.', s[4] + s[1])
print('5.', s[-4:])
|
27fd73163e1d8a24668089e95dc9dcef4d9c6353 | TanyaMozoleva/python_practice | /Lectures/Lec8/p23.py | 512 | 3.84375 | 4 | '''
Complete the get_discount() function which returns the discount
amount (a float rounded to 2 decimal places). The function is passed
two parameters, the amount and the discount rate (an integer %).
'''
def get_discount(amount, discount_rate):
discount = amount * discount_rate / 100
return round(discount, ... |
184e555c70fe8d1425705a0658352a2afcaa5cae | TanyaMozoleva/python_practice | /Lectures/Lec8/p24.py | 562 | 3.78125 | 4 | '''
Complete the get_discount_message() function which returns a string
made up of the rate of discount, the string "% Discount: $", and the
discount amount. The function has two parameters, the discount
amount and the rate of discount (a whole number).
'''
def get_discount_message(discount_amt, rate):
discount_in... |
245d2413466dc57e4d9f59e2e9d429515911714f | TanyaMozoleva/python_practice | /Lectures/Lec8/p25.py | 966 | 3.859375 | 4 | '''
Complete the print_docket() function which prints the sales docket
information (the format should be as shown in the example output
shown). The function is passed two arguments, the price and the
discount rate (an int %). Your function code MUST make a call to both
the functions: get_discount() and get_discount_mes... |
ba0ff6495d39f33bacb391d9d26c9521afc9dc8d | TanyaMozoleva/python_practice | /Lectures/Lec8/p26.py | 1,293 | 4.46875 | 4 | '''
The following program prompts the user for a number of items to be
packaged. Each box can hold 10 items. Any left over items require an
extra box. The first 6 boxes cost $8 each and any boxes above the first
6, cost $5 each. The program executes as shown in the example
outputs below. Design the functions needed to ... |
e58b4f46be65b23de50687ec94facedf86ddb557 | TanyaMozoleva/python_practice | /Lectures/Lec11/p7.py | 715 | 3.953125 | 4 | '''
Complete the add_bonus() function which prints "Good job!"
and returns 30000 plus the salary if the parameter is a value greater
than 150000. Otherwise it prints "Superb performance!" and returns
300 plus the salary.
'''
def add_bonus(salary):
if salary >= 150000:
print('Good job')
salary = sal... |
53d1adff63c844963b9b96ca76b2c98cb512139b | TanyaMozoleva/python_practice | /Weeks/week3/w3t5.py | 633 | 4.03125 | 4 | '''
the amount to be paid after the discount has been subtracted from the discount
'''
def display_ticket_price(tickets, price, discount):
tickets_price = price - discount
gst = get_gst_amount(tickets_price)
print(get_sign_line('*', 20))
print('Tickets: ', tickets, sep='')
print('Price: $', tickets... |
54938289ce57483e3b989cdf386e26453763100f | TimHillier/projEuler | /8/LargestProductInASeries.py | 458 | 3.5 | 4 | #https://projecteuler.net/problem=8
#put all the digits into an arrayi
with open("number.txt") as f:
content = f.read()
list(content).remove('\n')
number = list(content)
new = [s for s in number if s.isdigit()]
n = [int(s) for s in number if s.isdigit()]
new = n
biggest = 0
for a in range(0,len(new)-13):
... |
c28ae9832cce598608a307b28b2ce3f3a210e85c | ZR-Huang/AlgorithmsPractices | /source_code_of_Grokking_Algorithms/CP7_dijkstra.py | 1,958 | 3.75 | 4 | # 创建整个图的散列表
graph = {}
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a']['end'] = 1
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['end'] = 5
graph['end'] = {}
infinity = float('inf')
# 创建开销表
costs = {}
costs['a'] = 6
costs['b'] = 2
costs['end'] = infinity
# 创建存储父节点的散列表
p... |
e2ed1e39dd7888b09853a480c87d412e6ba371e7 | ZR-Huang/AlgorithmsPractices | /Leetcode/LLCI/17_16_The_Masseuse_LCCI.py | 1,172 | 3.546875 | 4 | '''
A popular masseuse receives a sequence of back-to-back appointment requests and
is debating which ones to accept. She needs a break between appointments and
therefore she cannot accept any adjacent requests. Given a sequence of back-to-back
appoint ment requests, find the optimal (highest total booked minutes) ... |
0f17409534d47ac3d45f308fc8d3eae635e36e57 | ZR-Huang/AlgorithmsPractices | /Leetcode/Coding Interviews/05_ReplaceSpace.py | 1,975 | 3.84375 | 4 | '''
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
'''
class Solution:
def replaceSpace(self, s: str) -> str:
"""
list(s) : O(N), the length of the string is donated as N.
iterate the string : O(N)
list assignment: O(1)
... |
9c7a933975b67d43260cbabd52519cf665689f44 | ZR-Huang/AlgorithmsPractices | /Leetcode/Basic/Dynamic_Programming/198_House_Robber.py | 1,168 | 3.671875 | 4 | '''
You are a professional robber planning to rob houses along a street.
Each house has a certain amount of money stashed, the only constraint
stopping you from robbing each of them is that adjacent houses
have security system connected and it will automatically contact
the police if two adjacent houses were broken... |
3ba6f87c1cb2a6f422e58c46f9794c18d76c5773 | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/March/1160_Find_Words_That_Can_Be_Formed_by_Characters.py | 1,317 | 3.9375 | 4 | '''
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The ... |
d598c5a9e7b7d3ffe01b7574a929850c925f37c7 | ZR-Huang/AlgorithmsPractices | /Leetcode/Intermediate/Sort and search/347_Top_K_Frequent_Elements.py | 672 | 4.0625 | 4 | '''
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than... |
4fcd98e69f7804ce294e2fa83cdfc43401b94d65 | ZR-Huang/AlgorithmsPractices | /Templates/Quick_Sort.py | 640 | 3.9375 | 4 | def _quicksort_(nums, left, right) -> None:
if left >= right:
return
pivot_index = partition(nums, left, right)
_quicksort_(nums, left, pivot_index-1)
_quicksort_(nums, pivot_index+1, right)
def partition(nums, start, end) -> int:
l = r = start
while r < end:
if nums[r] <=... |
cd66bbfe95cdf5bb793ff9aed3871adde5f7743c | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/March/914_X_of_a_Kind_in_a_Deck_of_Cards.py | 1,360 | 3.90625 | 4 | '''
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split
the entire deck into 1 or more groups of cards, where:
Each group has exactly X cards.
All the cards in each group have the same integer.
Example 1:
Input: deck =... |
404a5dc51e59de455362bcce4d27d7a5afce8000 | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/March/945_Minimum_Increment_to_Make_Array_Unique.py | 1,682 | 3.90625 | 4 | '''
Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.
Return the least number of moves to make every value in A unique.
Example 1:
Input: [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: [3,2,1,2,1,7]
Output: 6
Explanation: Afte... |
4bd05b30057bc447d0bdd8030d6b0d35edfd8dde | ZR-Huang/AlgorithmsPractices | /Leetcode/Basic/Others/20_Valid_Parentheses.py | 961 | 4.09375 | 4 | '''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
... |
0140f78da46f2879ae9a8d228e16cc6c26b026cf | ZR-Huang/AlgorithmsPractices | /Leetcode/Intermediate/Math/50_Pow_x_n.py | 1,938 | 3.859375 | 4 | '''
Implement pow(x, n), which calculates x raised to the power n(x^n).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2^(-2) = 1/(2^2) = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, wi... |
cb6b300fa7f570b1378413df02219cf3c558db36 | ZR-Huang/AlgorithmsPractices | /Leetcode/Basic/Math/204_Count_Primes.py | 1,165 | 4.03125 | 4 | '''
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
'''
class Solution:
def countPrimes(self, n: int) -> int:
if n < 3:
return 0
ans = 1 # 2 is prime
for... |
76ecc89b3ca6edfb4ae3e5416da87998d0070fd1 | ZR-Huang/AlgorithmsPractices | /Leetcode/Coding Interviews/06_traversal_linked_list_from_end.py | 607 | 3.953125 | 4 | '''
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
Example 1:
Input:head = [1,3,2]
Output:[2,3,1]
Constraints:
- 0 <= linkedList.length <= 10000
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reversePrint(self, hea... |
52a9cdb3bdd1e49bf347b9e9f9e8ce3c7c1a997f | ZR-Huang/AlgorithmsPractices | /Leetcode/Basic/String/38_Count_and_Say.py | 1,140 | 3.828125 | 4 | import unittest
class TestSolutionMethods(unittest.TestCase):
def test_countAndSay(self):
s = Solution()
self.assertEqual(s.countAndSay(1), '1')
self.assertEqual(s.countAndSay(2), '11')
self.assertEqual(s.countAndSay(3), '21')
self.assertEqual(s.countAndSay(4), '1211')
... |
da2fd88da66b90ab38af974e38e3aec8ea853247 | ZR-Huang/AlgorithmsPractices | /Leetcode/Basic/Array/48_Rotate_Image.py | 1,798 | 4.3125 | 4 | '''
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,... |
cb68199199f518639e8d7314347556e2be7fa244 | ZR-Huang/AlgorithmsPractices | /Leetcode/Intermediate/Array_and_string/334_Increasing_Triplet_Subsequence.py | 2,078 | 4.09375 | 4 | '''
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return true if there exists i, j, k
such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 else return false.
Note: Your algorithm should run in O(n) time complexity and O(... |
68927391f12f9843d9b5fdb2ac142cb07b096441 | ZR-Huang/AlgorithmsPractices | /Leetcode/每日打卡/April/887_Super_Egg_Drop.py | 2,095 | 3.921875 | 4 | '''
You are given K eggs, and you have access to a building with N floors from 1 to N.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor
higher than F will break, and any egg dropped at or below... |
2a9e9fc13b420d5bd050732f4d0308a3f32f81f7 | praneesh12/python_review | /argument_parsing/cylinder_volume.py | 558 | 3.796875 | 4 | #cylinder_volume.py
import math
import argparse
def cylinder_volume(rad,h):
return((math.pi)*(rad**2)*h)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("radius", help = "Enter radius of the cylinder",type = float)
parser.add_argument("height", help = "Enter height of the cylinder",type = floa... |
d5b6103bc8b85f896e683bab9cae1aa58fe5ee3a | praneesh12/python_review | /CS 600X MIT/functions.py | 322 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 13 15:26:06 2017
@author: Praneesh
"""
def f(x) :
x = x + 1
print("in f(x), x = " , x)
return x
z = f(3)
def g(x):
def h() :
x = 'abc'
x = x + 1
print('x in g(x) is ', x)
h()
x = 3
z = g(x)
print(z)... |
a9aff10aa9a634abf0fafa793872b7c206cbaa39 | praneesh12/python_review | /Collections_module/hackerank_OrderedDict.py | 370 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 6 14:28:06 2019
@author: praneeshkhanna
"""
from collections import OrderedDict
n = int(input())
d = OrderedDict()
for i in range(n):
item, price = (input().rsplit(None, 1))
if item not in d.keys():
d[item] = int(price)
else:
d[item]... |
c148d81b8fe9a1feba746da7f12b23172c45b784 | praneesh12/python_review | /edx/Loops and strings/Modularity.py | 3,329 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 17 01:12:56 2018
@author: praneeshkhanna
"""
''' Inductive Reasoning '''
def mult_iter(a,b):
result = 0
while b >0 :
result += a
b -= 1
return result
def mult_recur(a,b):
if b == 1:
return a
else :
... |
727b757212efceb189d7e453a9567135f54c71b0 | avasbr/projects | /pgmUtils.py | 1,437 | 3.53125 | 4 | import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
def idx_to_assgn(idx,card):
""" Converts factor assignments to indices
Parameters
----------
idx: int or numpy array
indices for which we wish to compute factor assignments
card: numpy array
cardinalities of variables in the sco... |
eacdb47ed29e8bda05e39028902b1900571545a0 | akhil-8607/ApacheSpark-Pyspark | /spark_sql.py | 1,474 | 3.546875 | 4 | from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
sc = spark.sparkContext
sc.setLogLevel("WARN")
df = (spark.read.format("csv")
.option("header", "true")
.option("inferSchema","true")
.option("nullValue", "") # Replace any null data field with quotes
.load("Fake_data.csv"))
#SQL
#1)
pr... |
7ac925e9ec2da8d79ab06b2bc7852c1817ec86ef | kanthmallampalli/python_assignmets | /Strings/what is string.py | 840 | 3.875 | 4 | '''
a string is list of char,index of string starts from 0
individuval characters from string can be retrived by using slicing function with the help of index
strings are immutable
isallnum() finds any special char
isalpha () finds contains only alpha or not
is digits() finds string contains oly digits or not
is lowe... |
e23bf7431ebf71be5a10b65da5f0571bbeccc888 | geeks-codes/codes | /arrays-1/missing-number-in-array/missing_number.py | 648 | 4.03125 | 4 | '''Given an array of size n-1 and given that there are numbers from 1 to n with one missing, the missing number is to be found.'''
def check_missing_number(array):
'''
Return True if no elements are missing
:param array: list of numbers
:return: boolean
'''
previous_element = array[0]
for ... |
2b3b13116b86a0878ada0a5c50f8328752259836 | plavka/Ninja | /Py-Lutrija/lottery2.py | 330 | 3.640625 | 4 | from random import randint as rand_number
def create_lottery_numbers(amount=7):
return [rand_number(1,49) for i in range(amount)]
def get_user_input(prompt="Please enter how many random numbers would you like to have: "):
return int(input(prompt))
a = get_user_input()
for i in range(a):
create_lottery_n... |
72872e9f3ca9248c68fcef5c44eb21813851ad8e | osy123/pythonexample | /02_dictionary.py | 3,481 | 3.625 | 4 | empty_dict = {} # 중괄호로 딕셔너리 생성
print(empty_dict) # 딕셔너리는 키와 값으로 생성한다
bierce = {
"day": "A period of twenty-four hours, mostly misspent", # day , positive , misfortune = 키 , 오른쪽의 내용들은 값
"positive": "Mistaken at the top of one's voice",
"misfortune": "The kind of fortune that never misses"}
print(bierce)
lo... |
92ef82f4d2fc79a2abc499d081ccbed1417c9dad | yellow77/pythonad | /3-2.py | 117 | 3.546875 | 4 | a = range(5)
b = range(10,15)
c = list(a) + list(b)
print("List a", a)
print("List b", b)
print("List a + List b", c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.