blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
599b56585ac98d54c80362bfc8a974ad57fc784c | troywsmith/pygo | /arrays/idk.py | 752 | 3.84375 | 4 | """
Given an array of sorted integers,
return a string array that contains the ranges of consecutive integers
"""
def create_range(lower, upper):
s = str(lower) + '-' + str(upper)
return s
def hi(arr):
rangeString = ''
isRange = False
for i in range(0, len(arr)):
while (i < len(arr) - 1 and arr[i] + 1 == arr[i + 1]):
if not isRange:
rangeString += str(arr[i])
isRange = True
i += 1
if isRange:
rangeString += '-'
isRange = False
rangeString += str(arr[i])
return rangeString
if __name__ == "__main__":
arr = [-2, 0, 1, 2, 3, 4, 5, 8, 9, 11, 13, 15, 18, 22, 25, 28, 29, 30]
print(hi(arr))
|
034e159b3ce979fb1de98e24a0fb66528863e672 | JulyKikuAkita/PythonPrac | /cs15211/DailyTemperatures.py | 3,426 | 4.09375 | 4 | __source__ = 'https://leetcode.com/problems/daily-temperatures/'
# Time: O(N)
# Space: O(W) The size of the stack is bounded as it represents strictly increasing temperatures.
#
# Description: Leetcode # 739. Daily Temperatures
#
# Given a list of daily temperatures T, return a list such that,
# for each day in the input, tells you how many days you would have to wait until a warmer temperature.
# If there is no future day for which this is possible, put 0 instead.
#
# For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73],
# your output should be [1, 1, 4, 2, 1, 1, 0, 0].
#
# Note: The length of temperatures will be in the range [1, 30000].
# Each temperature will be an integer in the range [30, 100].
#
import unittest
# 308ms 97.44%
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
if not T:
return []
stk = []
res = [0] * len(T)
for i in range(len(T)):
while stk and T[stk[-1]] < T[i]:
t = stk.pop()
res[t] = i - t
stk.append(i) # top is the current min
return res
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought: https://leetcode.com/problems/daily-temperatures/solution/
# Approach #1: Next Array [Accepted]
# Complexity Analysis
# Time Complexity: O(NW), where N is the length of T and W is the number of allowed values for T[i].
Since W=71, we can consider this complexity O(N).
# Space Complexity: O(N + W), the size of the answer and the next array.
# 92.71% 11ms
class Solution {
public int[] dailyTemperatures(int[] T) {
int[] ans = new int[T.length];
int[] next = new int[101];
Arrays.fill(next, Integer.MAX_VALUE);
for (int i = T.length - 1; i >= 0; i--) {
int warmer_index = Integer.MAX_VALUE;
for (int t = T[i] + 1; t <= 100; ++t) {
if (next[t] < warmer_index) warmer_index = next[t];
}
if (warmer_index < Integer.MAX_VALUE) ans[i] = warmer_index - i;
next[T[i]] = i;
}
return ans;
}
}
Approach #2: Stack [Accepted]
#66ms 52.63%
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
//Start from backward, mainin a increasing order in stack
for (int i = temperatures.length -1; i >= 0; i--) {
while(!stack.isEmpty() && temperatures[stack.peek()] <= temperatures[i]) {
stack.pop();
}
if (!stack.isEmpty()) res[i] = stack.peek() - i;
stack.push(i);
}
return res;
}
}
#58ms 64.22%
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
//Start from index 0, maintaining a decreasing order in stack
for (int i = 0; i < temperatures.length; ++i) {
while(!stack.isEmpty() && temperatures[stack.peek()] < temperatures[i]) {
res[stack.peek()] = i - stack.pop();
}
stack.push(i);
}
return res;
}
}
''' |
81d4660e546ddb900ccdcfcc56dcfdc8734a3524 | softpaper95/algorithm | /3.연습장.py | 120 | 3.953125 | 4 | list = [[2, 5, 3], [4, 4, 1], [1, 7, 3]]
for i in list:
n, m = i
print(n, m)
# print('n:',n,'m:',m, "h:", h) |
f044be8bb559e253609ffe680137d2dca2bcd1e5 | isi-vista/vistautils | /vistautils/scripts/tar_gz_to_zip.py | 3,219 | 3.875 | 4 | import argparse
import os
import tarfile
from zipfile import ZipFile
USAGE = """
Converts a (un)compressed tar file to .zip
This is useful because .zip allows random access, but the LDC often distributes things as .tgz.
zip version will be input name with .tar/.tar.gz/.tgz stripped (if present), .zip added
"""
def getargs():
"""Get command-line arguments."""
parser = argparse.ArgumentParser(usage=USAGE)
arg = parser.add_argument
arg("tar_file_name", help="The input .tar/.tar.gz/.tgz file to be converted")
arg(
"--dont-stream",
action="store_true",
help="Should the tar contents be added to the zip file by unpacking "
"them to disk first, rather than streaming them?",
)
arg(
"--omit-large-files",
action="store_true",
help="Should large files (larger than LARGE_FILE_CUTOFF) not be "
"transferred from the tar file to the zip file?",
)
arg(
"--large-file-cutoff",
type=float,
default=2,
help="Files larger than this cutoff (in gigabytes) will not be added"
"to the zip file. The default is 2 gigabytes.",
)
return parser.parse_args()
def main():
args = getargs()
tar_file = args.tar_file_name
output_zip_name = _output_name(tar_file)
dont_stream = args.dont_stream
omit_large_files = args.omit_large_files
large_file_cutoff = args.large_file_cutoff * 1e9
print(f"Copying tarball {tar_file} to {output_zip_name}")
print(
"WARNING: This will throw away all metadata. It also might not work "
"if you have files with /s in the name or other odd things. "
"Please sanity check your output"
)
if os.path.exists(output_zip_name):
print(f"WARNING: Removing existing file at {output_zip_name}")
os.remove(output_zip_name)
with ZipFile(output_zip_name, "x") as out:
with tarfile.open(tar_file) as inp:
if dont_stream:
inp.extractall()
for member in inp:
if member.isfile():
out.write(member.name)
os.remove(member.name)
else:
for member in inp:
if member.isfile():
if omit_large_files and member.size > large_file_cutoff:
print(
f"WARNING: Omitting {member.name} as "
f"its size {member.size / 1e9:.2f} GB "
f"exceeds {args.large_file_cutoff:.2f} GB"
)
else:
print(f"Copying {member.name}")
with inp.extractfile(member) as data:
out.writestr(member.name, data.read())
def _output_name(filename: str) -> str:
valid_extensions = [".tar", ".tgz", "tar.gz"]
for valid_extension in valid_extensions:
if filename.endswith(valid_extension):
filename = filename[: len(filename) - len(valid_extension)]
break
return filename + ".zip"
if __name__ == "__main__":
main()
|
ef64195b69ba7216b18eb12dc8ae686f302c51fd | addkap92/Python-Crash-Course | /5-3 Alien Colors #1.py | 234 | 4.03125 | 4 | alien_color = ['green', 'yellow', 'red']
color = input("An alien was just shot down! What color was it?\n")
if color in alien_color:
print("You got 5 points!")
else:
print("You didn't get any points, try for the green ones!")
|
3acfc01fa9bee4a622f248823bc59837d04d486f | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/5fcf51ad35524c0f917bc7ecceb49e0d.py | 581 | 3.546875 | 4 | import re
class Bob:
def hey(self, statement):
if self.silence(statement):
return 'Fine. Be that way!'
elif self.yelling(statement):
return 'Woah, chill out!'
elif self.question(statement):
return 'Sure.'
else:
return 'Whatever.'
def yelling(self, statement):
return statement == statement.upper() and re.search(r'[a-zA-Z]', statement)
def question(self, statement):
return statement[-1] == '?'
def silence(self, statement):
return statement.strip() == ''
|
0f64ad2a86c8bbe6329296e94bd8b8ac563b95f9 | 156076769/spark-exam | /pyspark-s3-parquet-example/pyspark-scripts/nations-parquet-sql-local.py | 2,169 | 3.53125 | 4 | """
File name: nations-parquet-local.py
Author: Jonathan Dawson
Date Created: 6/8/2016
Date Modified: 6/8/2016
Python Version: 2.7
PySpark Version: 1.6.1
Example of loading .parquet formatted files into a in-memory SQLContext table and running SQL queries against it.
This script is configured to run against a local instance of Spark and pulls the .parquet file from the local
file store.
"""
import sys
import os
LINE_LENGTH = 200
def print_horizontal():
"""
Simple method to print horizontal line
:return: None
"""
for i in range(LINE_LENGTH):
sys.stdout.write('-')
print("")
try:
from pyspark import SparkContext
from pyspark import SparkConf
from pyspark import SQLContext
print ("Successfully imported Spark Modules -- `SparkContext, SQLContext`")
print_horizontal()
except ImportError as e:
print ("Can not import Spark Modules", e)
sys.exit(1)
conf = (SparkConf()
.setAppName("Jon's Nation Cool App")
.set("spark.executor.memory", "1g"))
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sparkContext=sc)
# Loads parquet file located in local file system into RDD Data Frame
parquetFile = sqlContext.read.parquet('../test-data/nation.plain.parquet')
# Stores the DataFrame into an "in-memory temporary table"
parquetFile.registerTempTable("parquetFile")
# Run standard SQL queries against temporary table
nations_all_sql = sqlContext.sql("SELECT * FROM parquetFile")
# Print the result set
nations_all = nations_all_sql.rdd.map(lambda p: "Country: {0:15} Ipsum Comment: {1}".format(p.name, p.comment_col))
print("All Nations and Comments -- `SELECT * FROM parquetFile`")
print_horizontal()
for nation in nations_all.collect():
print(nation)
# Use standard SQL to filter
nations_filtered_sql = sqlContext.sql("SELECT name FROM parquetFile WHERE name LIKE '%UNITED%'")
# Print the result set
nations_filtered = nations_filtered_sql.rdd.map(lambda p: "Country: {0:20}".format(p.name))
print_horizontal()
print("Nations Filtered -- `SELECT name FROM parquetFile WHERE name LIKE '%UNITED%'`")
print_horizontal()
for nation in nations_filtered.collect():
print(nation)
|
e200a5924596e1f13298af034dce4e75fd63042f | Thiagolivramento/linguagem_II | /CRUD/contoles.py | 3,714 | 3.703125 | 4 |
# Criando a tabela se necessário
class CreateTable:
def createTable(con):
with con:
cur = con.cursor()
cur.execute("Drop se a tabela Musica existir")
cur.execute(
"CREATE TABLE Musica(Id SERIAL PRIMARY KEY, Nome VARCHAR(25), Autor VARCHAR(25), Gênero VARCHAR(25));")
print ('Tabela música criada!')
# Inserir valores
class InsertData:
def insertTable(con):
with con:
try:
cur = con.cursor()
with warnings.catch_warnings():
warnings.simplefilter('ignore')
cur.execute(
"CREATE TABLE IF NOT EXISTS Musica(Id SERIAL PRIMARY KEY, Nome VARCHAR(25), Autor VARCHAR(25), Genero VARCHAR(25));")
print ('Tabela música criada!')
warnings.filterwarnings('ignore', 'tabela desconhecida!')
name = raw_input("Nome da música: ")
autoria = raw_input("Autoria: ")
gender = raw_input("Gênero: ")
cur.execute("INSERT INTO Emp (Nome, Autor, Genero) VALUES(%s, %s, %s)",
(name, autoria, gender))
print ("Dados Inseridos")
con.commit()
except Exception as e:
print (e)
class ReadData:
# Ler registros da tabela
def retrieveTable(con):
with con:
cur = con.cursor(cursor_factory=pdb.extras.DictCursor)
cur.execute("SELECT * FROM Musica")
rows = cur.fetchall()
for row in rows:
if rows == None:
print ('Tabela vazia!')
break
else:
print('ID: {0} Nome: {1} Autor: {2} Gênero: {3}'.format(
row[0], row[1], row[2], row[3]))
class UpdateData:
# UPDATE registro
def updateRow(con):
with con:
try:
cur = con.cursor()
cur = con.cursor(cursor_factory=pdb.extras.DictCursor)
cur.execute("SELECT * FROM Musica")
rows = cur.fetchall()
for row in rows:
print('ID: {0} Nome: {1} Autor: {2} Gênero: {3}'.format(
row[0], row[1], row[2], row[3]))
e_id = input("Digite o Id que deseja")
name = raw_input("Digite o nome que você quer atualizar")
autoria = raw_input("Digite a autoria que você quer atualizar")
gender = raw_input("Digite o gênero que você quer atualizar")
cur.execute("UPDATE Musica SET Nome =%s, Autor = %s, Gênero = %s, WHERE Id = %s",
(name, autoria, gender, e_id))
print ("Número de linhas atualizadas: ", cur.rowcount)
if cur.rowcount == 0:
print ('Registro não atualizado!')
except TypeError as e:
print ('ID não existe!')
class DelData:
# # Deletar
def deleteRow(con):
with con:
try:
cur = con.cursor()
cur = con.cursor(cursor_factory=pdb.extras.DictCursor)
cur.execute("SELECT * FROM Musica")
rows = cur.fetchall()
for row in rows:
print('ID: {0} Nome: {1} Autor: {2} Gênero: {3}'.format(
row[0], row[1], row[2], row[3]))
id = raw_input("Qual é o ID que será deletado?")
cur.execute("DELETE FROM Musica WHERE Id = %s", id)
print ("Número de linhas deletadas: ", cur.rowcount)
except TypeError as e:
print ('ID não existe!')
|
b225b5c6cfc3df7a0dbefce4b35cb4beca8841c2 | esethuraman/Problems | /graphs/GraphAdjacencyList.py | 1,109 | 3.8125 | 4 | class Graph:
def __init__(self, vertices_count):
self.vertices_count = vertices_count
self.adj_list = [None] * vertices_count
def add_edge(self, frm, to):
if None == self.adj_list[frm]:
self.adj_list[frm] = []
if None == self.adj_list[to]:
self.adj_list[to] = []
self.adj_list[frm].append(to)
self.adj_list[to].append(frm)
def get_edges(self):
for i in range(self.vertices_count):
if self.adj_list[i] is not None:
for j in range(len(self.adj_list[i])):
print(i, ' -> ', self.adj_list[i][j])
def get_graph(self):
return self.adj_list
def build_graph(self):
graph = Graph(6)
graph.add_edge(0, 1)
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
print("Edges of Graph")
graph.get_edges()
print("Adjacency List of Graph")
print(graph.get_graph())
g = Graph(6)
g.build_graph()
|
cb45393c9f6891233c61940941825c7bb7615e16 | mine1984/Advent-of-code | /2015/day03/day03a.py | 830 | 3.8125 | 4 | # Santa is delivering presents to an infinite two-dimensional grid of houses.
# Moves are always exactly one house to the north (^), south (v), east (>), or west (<).
#
# Santa ends up visiting some houses more than once. How many houses receive at least one present?
class player:
def __init__(self):
self.x = 0
self.y = 0
def move(self,direct):
if direct == '^':
self.y += 1
if direct == 'v':
self.y += -1
if direct == '>':
self.x += 1
if direct == '<':
self.x += -1
santa = player()
directions = input()
houses = [(santa.x,santa.y)]
counter = 1
for direct in directions:
santa.move(direct)
x = santa.x
y = santa.y
if (x,y) not in houses:
houses.append((x,y))
counter += 1
print(counter)
|
259c33a5ad1e751f688bc58aed2d22dc2fae0d75 | LukeBrazil/fun_fair_danger | /room3.py | 3,661 | 4.03125 | 4 | # ROOM3 ROTTEN TOMATOES: Go ahead , pick your poison, a bucket full of rotten tomatoes at your disposal.
import random
from pip._vendor.colorama import Fore, Back, Style
def Tomato():
rotten_tomatoes = 3 # get 3 chances for a hit (accumalator)
game_running = True
play_again = "y"
ogre_conquered = False
sarcasm_list=["\n-Well, aren't we just a ray of frigging sunshine.","\n-How many times do I have to flush before you go away?","\n-Well, this day was a total waste of makeup.","\n-Back off! You’re standing in my aura.","\n-Whatever kind of look you were going for, you missed", "\n-Sarcasm is just one more service we offer.","\n-Aw, did I step on your poor little bitty ego?"]
print("""
Welcome to Room 3:
Yes, I know, an Ogre blocking the doorway.
He won't move an inch, as if the Queen of England's Beefeaters.
Try him, sneeze, laugh, have a pretend heart attacked!
Please be advised, don't touch him, as Ogres can be very Cranky!
Well, what are you waiting for?
""")
question_one = input("\nApproach the Ogre? yes (y) or no (n) ")
if question_one == "y":
print("\nOK, you asked for it!")
elif question_one == "n":
print("\nOgre approaching you! No limits set!")
else:
print("""
Sorry! Only a small challenge!
And Bummer! No choice actually!
Ogre still approaching!
\n\nGrab a bucket Bimbo!
""")
while game_running and play_again == "y":
value = random.randint(0, len(sarcasm_list) -1) # shuffle sarcastic remarks with hit
hit = random.randint(0,3)
if rotten_tomatoes == 3:
input("\n\nHit enter, go for a rotten tomato strike!")
if hit == 1:
print("\nBINGO!")
ogre_conquered = True
break #game over
else:
print(sarcasm_list[value])
play_again = input("\n\nWould you like another chance? yes (y) or no (n) ")
if rotten_tomatoes == 1:
input("\nGet on with it! Hit enter! Any strikes this time?")
if hit == 1:
print("\nDITTO!")
ogre_conquered = True
break #game over
else:
print(sarcasm_list[value])
play_again = input("\n\nWould you like another chance? yes (y) or no (n) ")
if rotten_tomatoes == 1:
input("\nGO ON..., and hit enter again!")
if hit == 1:
print("\nDAMMIT, was the last one?")
ogre_conquered = True
break #game over
else:
print(sarcasm_list[value])
print("""
\nYou're all out of tomatoes!
""")
rotten_tomatoes -= 1 # game change here
if rotten_tomatoes == 0:
play_again = ("\nyes (y) or no (n)")
if play_again == "y":
rotten_tomatoes = 3
print("""
With a healthy smile, muscles, bones and liver,
You're - Off to the next maize-ing thither,
Hopefully, not craving any liquor!
Escaped the Dragons and muscle engraving!
Only to remember the goldentomato key-winger!
You've been gifted a golden tomato, you will need this in the future!""")
print("Your passcode to enter the next room is: " + Fore.YELLOW + "goldentomato" + Fore.WHITE)
room3entrance = input("\nEnter key from Axe Room: ")
room3_passcode = room3entrance
if room3_passcode == "goldenaxe".lower():
Tomato()
|
43e7260f6c00190aec82c4161269046ad6f96508 | hjqjk/python_learn | /Learning_base/main/multiprocessing/mp_multiprocess1.py | 420 | 3.5625 | 4 | #!/usr/bin/env python
#_*_ coding:utf-8 _*_
#利用Pool的map,起多进程
from multiprocessing import Pool
import time
def f(x):
time.sleep(0.5)
return x*x
if __name__ == '__main__':
#print map(f,[1,2,3,4,5,6,7]) #串型处理,花费时间长
p = Pool(10) #设定进程池,最多只能起5个进程
print p.map(f,[1,2,3,4,5,6,7]) #并行处理,效率提高 |
a1f120204d8c4baa3066322ee1041141cce50db9 | mattecora/dbscout | /utils/sample_ds.py | 517 | 3.734375 | 4 | """
sample_ds.py
Extract a random sample from a dataset.
Arguments:
- The dataset to be sampled
- The output dataset
- The fraction to be sampled
"""
from sys import argv
from pyspark import SparkContext
# Create the Spark context
sc = SparkContext(appName="sample_ds")
# Read the input file
inFile = sc.textFile(argv[1])
# Sample the input lines
sampledFile = inFile.sample(False, float(argv[3]), 0)
# Save output
sampledFile.saveAsTextFile(argv[2])
# Close the Spark context
sc.stop() |
b053c98cd247402e21fb4a5c9840e980372fe5f5 | hyang012/leetcode-algorithms-questions | /053. Maximum Subarray/Maximum_Subarray.py | 540 | 4.03125 | 4 | """
Leetcode 53. Maximum Subarray
Given an integer array nums, find the contiguous subarray
(containing at least one number) which has the largest sum and
return its sum.
"""
def maxSubArray(nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums is not None and len(nums) != 0:
cur_max, cur_sum = nums[0], nums[0]
for i in range(1, len(nums)):
cur_sum = max(cur_sum + nums[i], nums[i])
cur_max = max(cur_sum, cur_max)
return cur_max
|
3b5eedc47e5c52ab44ae8db20accb62c6882a7f0 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/TinaB/lesson02/generators.py | 799 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Last week we looked at Spotify’s top tracks from 2017.
We used comprehensions and perhaps a lambda to find tracks we might like.
Having recovered from last week’s adventure in pop music we’re ready to venture back.
Write a generator to find and print all of your favorite artist’s
tracks from the data set. Your favorite artist isn’t represented in that set?
In that case, find Ed Sheeran’s tracks.
Load the data set following the instructions from last week.
Submit your generator expression and the titles of your or Ed’s tracks.
"""
import pandas as pd
music = pd.read_csv("featuresdf.csv")
tracks = (x for x in zip(music.artists, music.name)
if x[0] == 'Ed Sheeran')
for track in tracks:
print(f'Artist: {track[0]} -- Track: {track[1]}')
|
6d3b2fce5fe9344b82e54042fe7f9a4b9c49dd75 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_74/175.py | 7,974 | 4.15625 | 4 | #!/usr/bin/env python
"""Problem
Blue and Orange are friendly robots. An evil computer mastermind has locked
them up in separate hallways to test them, and then possibly give them cake.
Each hallway contains 100 buttons labeled with the positive integers {1, 2,
..., 100}. Button k is always k meters from the start of the hallway, and the
robots both begin at button 1. Over the period of one second, a robot can walk
one meter in either direction, or it can press the button at its position once,
or it can stay at its position and not press the button. To complete the test,
the robots need to push a certain sequence of buttons in a certain order. Both
robots know the full sequence in advance. How fast can they complete it?
For example, let's consider the following button sequence:
O 2, B 1, B 2, O 4
Here, O 2 means button 2 in Orange's hallway, B 1 means button 1 in Blue's
hallway, and so on. The robots can push this sequence of buttons in 6 seconds
using the strategy shown below:
Time | Orange | Blue
-----+------------------+-----------------
1 | Move to button 2 | Stay at button 1
2 | Push button 2 | Stay at button 1
3 | Move to button 3 | Push button 1
4 | Move to button 4 | Move to button 2
5 | Stay at button 4 | Push button 2
6 | Push button 4 | Stay at button 2
Note that Blue has to wait until Orange has completely finished pushing O 2
before it can start pushing B 1. Input
The first line of the input gives the number of test cases, T. T test cases
follow.
Each test case consists of a single line beginning with a positive integer N,
representing the number of buttons that need to be pressed. This is followed by
N terms of the form "Ri Pi" where Ri is a robot color (always 'O' or 'B'), and
Pi is a button position. Output
For each test case, output one line containing "Case #x: y", where x is the
case number (starting from 1) and y is the minimum number of seconds required
for the robots to push the given buttons, in order. Limits
1 < Pi < 100 for all i.
Small dataset
1 < T < 20.
1 < N < 10.
Large dataset
1 < T < 100.
1 < N < 100.
Sample
Input
3
4 O 2 B 1 B 2 O 4
3 O 5 O 8 B 100
2 B 2 B 1
Output
Case #1: 6
Case #2: 100
Case #3: 4
"""
from __future__ import division, print_function
from optparse import OptionParser
import sys
import functools
import logging
from collections import defaultdict
def configure_log(log_file=None):
"Configure the log output"
log_formatter = logging.Formatter("%(asctime)s - %(funcName)s:%(lineno)d - "
"%(levelname)s - %(message)s")
if log_file:
handler = logging.FileHandler(filename=log_file)
else:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(log_formatter)
LOG.addHandler(handler)
LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
LOG = logging.getLogger('template')
configure_log()
class memoized(object):
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
def process(moves, N):
"Process the input moves and return the total time"
time = 0
pos = {'O': 1, 'B': 1}
index = {'O': 0, 'B': 0}
length = {'O': len(moves['O']), 'B': len(moves['B'])}
button_pressed = 0
while button_pressed < N:
press_only_once = True
to_remove = []
for robot in moves:
if index[robot] < length[robot]:
position, order = moves[robot][index[robot]]
if pos[robot] == position:
LOG.debug('robot %s in position to press with order %d'
% (robot, pos[robot]))
if order == button_pressed and press_only_once:
LOG.debug('robot %s press button' % robot)
button_pressed += 1
press_only_once = False
index[robot] += 1
elif pos[robot] > position:
pos[robot] -= 1
LOG.debug('robot %s move back to pos: %d'
% (robot, pos[robot]))
elif pos[robot] < position:
pos[robot] += 1
LOG.debug('robot %s move forward to pos: %d'
% (robot, pos[robot]))
else:
LOG.error('incorrect position')
else:
LOG.info('no more move for robot %s' % robot)
to_remove.append(robot)
for robot in to_remove:
moves.pop(robot)
time += 1
return time
def do_job(in_file, out_file):
"Do the work"
LOG.debug("Start working with files: %s and %s"
% (in_file.name, out_file.name))
# first line is number of test cases
T = int(in_file.readline())
for testcase in xrange(T):
# for integer input
# values = map(int, in_file.readline().split())
# for other inputs
values = in_file.readline().rstrip('\n').split()
N = int(values.pop(0))
moves = defaultdict(list)
for order in xrange(N):
robot = values.pop(0)
position = int(values.pop(0))
moves[robot].append((position, order))
LOG.debug(moves)
result = process(moves, N)
print_output(out_file, testcase, result)
def print_output(out_file, testcase, result):
"Formats and print result"
print("Case #%d:" % (testcase + 1), end=' ', file=out_file)
print(result, file=out_file)
def main(argv=None):
"Program wrapper."
if argv is None:
argv = sys.argv[1:]
usage = "%prog [-v] [-w out_file] [-t] in_file"
parser = OptionParser(usage=usage)
parser.add_option("-t", dest="template", action="store_true", default=False,
help=("template name for construct"
"out file name as in_file.out (default False)"))
parser.add_option("-w", dest="out_file",
help=("output file or stdout if FILE is - (default case)"
"or TEMPLATE.out (default if template is given)"))
parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help = "run as verbose mode")
(options, args) = parser.parse_args(argv)
if not args:
parser.error('no input file given')
if options.verbose:
LOG.setLevel(logging.DEBUG)
if args[0] == '-':
in_file = sys.stdin
else:
try:
in_file = open(args[0], 'r')
except IOError:
parser.error("File, %s, does not exist." % args[0])
if options.template and not options.out_file:
options.out_file = ''.join((args[0], '.out'))
if not options.out_file or options.out_file == '-':
out_file = sys.stdout
else:
try:
out_file = open(options.out_file, 'w')
except IOError:
parser.error("Problem opening file: %s" % options.out_file)
sys.setrecursionlimit(2**31-1)
do_job(in_file, out_file)
return 0
if __name__ == '__main__':
sys.exit(main())
|
8fb96fcd8cc90e472107db6303a18508090bcc8c | Maelibe/Pythons-tasks | /EDX/Task2 Bisection search.py | 900 | 4.125 | 4 | print("Please think of a number between 0 and 100!")
print("Is your secret number 50 ?")
left = 0
right = 100
guess = abs(left - right)/2
while True:
print("Enter", "'h'", " to indicate the guess is too high.", end=" ")
print("Enter", "'l'", " to indicate the guess is too low.", end=" ")
inp = str(input(" "))
if inp == "l":
left = guess
guess = int(abs(left - right) / 2)
guess += int(left)
print("Is your secret number ", guess, "?")
if inp == "h":
right = guess
guess = abs(left - right) / 2
guess = int(right - guess)
print("Is your secret number ", guess, "?")
if inp != "c" and inp != "h" and inp != "l":
print("Sorry, I did not understand your input.")
print("Is your secret number ", guess, "?")
if inp == "c":
print("Game over.Your secret number was:", guess)
break
|
dd1170d995d68b47d212083975bf21569c7c236f | dojojon/SpookyHouse | /step08/game.py | 4,545 | 3.515625 | 4 | import pygame
from random import randint
def render_sky():
"Draw the sky"
screen.blit(sky_image, (0, 0))
return
def render_windows():
"Draw the window back grounds"
screen.blit(windows_image, (0, 0))
return
def render_house():
"Draw the house"
screen.blit(house_image, (0, 0))
return
def render_title():
"Draw the title of the game in the center of the screen"
# draw title text to a surface
surface = large_font.render("Spooky House", True, (255, 255, 255))
# calculate the x postion to center text
screen_x = (screen_width - surface.get_width()) / 2
# draw to screen
screen.blit(surface, (screen_x, 0))
return
def read_ghost_data(asset_path):
"Read the positions of the ghosts"
result = []
# open up the file for reading
windows_file = open(asset_path + "ghost_data.txt", "r")
# read the contents
window_lines = windows_file.readlines()
# process each line to a list
for line in window_lines:
line = line.rstrip("\n")
line = line.split(",")
# create a dictionary for each line
line = {
"x1": int(line[0]),
"y1": int(line[1]),
"x2": int(line[2]),
"y2": int(line[3]),
"visible": False
}
# add to a list
result.append(line)
# close the file
windows_file.close()
return result
def render_ghost(ghost):
"Draw a ghost"
# Calculate width and height of Window
ghost_width = ghost["x2"] - ghost["x1"]
ghost_height = ghost["y2"] - ghost["y1"]
# Resize the ghost image to the window
ghost_scaled = pygame.transform.scale(
ghost_image, (ghost_width, ghost_height))
# Draw ghost
screen.blit(ghost_scaled, (ghost["x1"], ghost["y1"]))
return
def render_ghosts():
# Draw some ghosts
for ghost in ghosts:
if ghost["visible"]:
render_ghost(ghost)
def update_ghosts():
global hide_ghost_at, show_ghost_at
"Update the ghost states"
# if the hide time is in the past, hide the ghosts
if hide_ghost_at < pygame.time.get_ticks():
for ghost in ghosts:
if ghost["visible"] == True:
ghost["visible"] = False
show_ghost_at = randomShowTime()
# check to see if all ghosts are hidden
if(all(ghost["visible"] == False for ghost in ghosts)):
# if show_ghost_at is in the past, show a ghost
if show_ghost_at < pygame.time.get_ticks():
ghost_to_turn_on = randint(0, len(ghosts) - 1)
ghosts[ghost_to_turn_on]["visible"] = True
hide_ghost_at = randomHideTime()
return
def randomHideTime():
"Return when to hide the ghost in ticks"
now = pygame.time.get_ticks()
now = now + randint(1000, 2000)
return now
def randomShowTime():
"Return when to show the next ghost in ticks"
now = pygame.time.get_ticks()
now = now + randint(1000, 3000)
return now
# Define variables
screen_width = 800
screen_height = 600
# set up pygame
pygame.init()
# set up a screen
screen = pygame.display.set_mode((screen_width, screen_height))
# set up the clock
clock = pygame.time.Clock()
# folder containing the game assets
asset_path = "../assets/"
# Loading game assets
house_image = pygame.image.load(asset_path + "house.png")
sky_image = pygame.image.load(asset_path + "sky.png")
windows_image = pygame.image.load(asset_path + "windows.png")
ghost_image = pygame.image.load(asset_path + "ghost.png")
skull_image = pygame.image.load(asset_path + "skull.png")
# set up font support
pygame.font.init()
large_font = pygame.font.Font(asset_path + "StartlingFont.ttf", 50)
# Ghost Positions
ghosts = read_ghost_data(asset_path)
# keep the game running while true
running = True
# Hide and shot times
hide_ghost_at = 0
show_ghost_at = 0
while running:
# handle every event since the last frame.
for event in pygame.event.get():
# if quit (esc) exit the game
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
# fill the screen with a solid black colour
screen.fill((0, 0, 0))
# Update ghosts
update_ghosts()
# draw sky
render_sky()
# draw windows
render_windows()
# draw ghosts
render_ghosts()
# draw house
render_house()
# draw title
render_title()
# update the screen
pygame.display.update()
# limit the game to 60 frames per second
clock.tick(60)
|
4e32036ea75cd097b2840ac7c1f593a57ae0482d | GrishaAdamyan/All_Exercises | /if3.py | 211 | 3.890625 | 4 | print('Duq hashvel giteq?')
x = input()
print('Duq giteq te qani taric e baxkacac hayoc aybuben@?')
y = input()
if x == 'yes' or x == 'no' and y == 'yes' or y == 'no':
print('RIGHT')
else:
print('WRONG') |
37ab77ef07786bf8d5f12328e87fdc5fdffaba14 | Guillermocala/Py_stuff | /Diseño_microelectronico_digital/clase2/Ejercicio5.py | 531 | 3.953125 | 4 | # Escrita un programa que de cómo resultado un archivo de texto con
# una matriz que muestre todas las combinaciones de multiplicación de
# los número 1 hasta 10.
def main():
print("\t\tTablas de multiplicar")
res = ""
for x in range(1, 10):
for y in range(10):
res += str(x) + " x " + str(y) + " = " + str(x * y) + "\n"
res += "\n"
with open('tablas_multiplicar.txt', 'w') as f:
f.write(res)
print("txt generado exitosamente!")
if __name__ == "__main__":
main() |
44444bb0aa1dd061da161bfffdaee160270b6e50 | bamboodew/jackfrued_Python-100-Days | /src/Day001_FirstPython/test_if.py | 299 | 3.671875 | 4 | from random import randint
print(2 ** 10)
i = randint(0, 1000)
s = input("请输入:")
num = int(s)
# print(i)
while num != i:
if num > i:
print("大了\n")
elif num < i:
print("小了\n")
s = input("请再输入:")
num = int(s)
print("\n猜对了")
|
dd168e740e7d91cf6ad292401019e06d0052e8c5 | nilay0512/Nilay_test | /Task-2-Assignment/Program7.py | 75 | 3.6875 | 4 | x=range(7)
for i in x:
if i==3 or i==6 :
continue
print(i)
|
168da40a1d580813f63274c4eaf00cea31fae2f4 | bigsaigon333/BaekjunOnlineJudge | /2667.py | 1,903 | 3.640625 | 4 | # Date: 2020-08-31 Mon 21:47
# 1st try: 1h 8m 31s
# Comment: 언어에 대한 확신이 없으니까, 사소한 문법이 틀린게 아닌지 계속 찾게 된다
# runtime-error가 발생하였는데, 이는 group 개수가 N개가 넘을때를 고려하지 않고 배열을 선언하여서이다.
# intput, output을 잘 확인하자. 이번 문제에서는 각 그룹에 번호를 부여할 필요가 전혀 없었다. 그냥 갯수만 세면 되는 문제였다
# 필요한 것만 구현하자
import sys
from collections import deque
def print_table(nums):
for _ in range(N):
print(nums[_])
print()
N = int(sys.stdin.readline())
board = [[0 for _ in range(N)] for _ in range(N)]
vis = [[False for _ in range(N)] for _ in range(N)]
group = []
q = deque()
for i in range(N):
board[i] = list(map(int, (c for c in sys.stdin.readline().strip())))
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
count = 0
for i in range(N):
for j in range(N):
if board[i][j] == 1 and not vis[i][j]:
q.append((i, j))
# print(f"{i} {j} is added")
vis[i][j] = True
count = 1
while(q):
x, y = q.popleft()
# print(f"{x} {y}")
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
# print(f"nx: {nx} ny: {ny}")
if nx < 0 or nx >= N or ny < 0 or ny >= N:
continue
if vis[nx][ny] or board[nx][ny] == 0:
continue
vis[nx][ny] = True
q.append((nx, ny))
count += 1
# print(f"{nx} {ny} is added")
# print(q)
# print_table(group)
group.append(count)
# print(num_group)
print(len(group))
print(*sorted(group), sep="\n")
|
9ddcbc4ed0bf4ac34d242ecf62763a27f1e7f502 | Bhuvanjeet/Food-Recommendation-Engine | /food_recommendation.py | 2,292 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""food_recommendation.ipynb
@author: Bhuvanjeet
**Food Recommendation Engine**
To recommend food items based on similarity in 'brand' and 'ingredients'.
**Project Overview:**
**1-Exploratory Data Analysis - EDA**
**2-Vectorization**
**3-Cosine Similarity**
**4-Input and Output**
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df=pd.read_csv('food_items.txt')
df.drop('index',axis=1,inplace=True)
df.drop(df.iloc[:,5:],axis=1,inplace=True)
df.head()
"""or you could simply have done:
df = df [ ['brand','categories','ingredients','manufacturer','title'] ]
this will automatically drop other columns
"""
#data cleaning
#removing duplicates from df
df.drop_duplicates(inplace=True)
#filling null places with ''
df=df.fillna(value='')
"""We want to predict 'title' of food item. So from the dataframe, we can see that it depends basically on two features: 'brand' and 'ingredients'.So, we will combine these two columns into 1 column."""
df['prepared_data'] = df['brand'] + " " + df['ingredients']
"""**Vectorization**"""
from sklearn.feature_extraction.text import CountVectorizer
#converts a collection of text documents to a matrix of token counts
#bow - bag-of-words model
bow_transformer = CountVectorizer()
vector_matrix = bow_transformer.fit_transform(df['prepared_data'])
"""**Cosine Similarity**"""
from sklearn.metrics.pairwise import cosine_similarity
cos_similar = cosine_similarity(vector_matrix)
"""**Input**"""
food_item = input('Enter the title of the food : ')
def search_index(title):
return df[df['title'] == title].index
index_item=search_index(food_item)
#making a list of similar items to the item entered by the user
similar_items = list(enumerate(cos_similar[int(index_item[0])]))
#sorting in descending order
sorted_similar_items=sorted(similar_items,key=lambda x:x[1],reverse=True)
sorted_similar_items[:10] #to display first 10 elements of the sorted list
"""**Output**"""
def search_title(index):
return df['title'][index]
i=0
for item in sorted_similar_items:
print(search_title(item[0]))
i=i+1
if(i>50): #printing top 50 similar food items
break
"""So, we have successfully built a food recommendation engine."""
|
7dc8043b3fdaa189dfd6d657d9bfa06e18706780 | queeniekwan/mis3640 | /session06/ex_06.py | 1,679 | 4.25 | 4 | def factorial(n):
"""
return the factorial number for integer n
"""
if isinstance(n, int):
if n == 0:
return 1
else:
return n * factorial(n-1)
else:
return 'Please enter an integer'
def fibonacci(n):
"""
return the nth fibonacci number
"""
if n ==1 or n ==2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
def gcd(x1, x2):
"""
returns the greatest common divisor of two positive integers x1 and x2
"""
if isinstance(x1, int) and isinstance(x2, int) and x1 > 0 and x2 > 0:
a = max(x1, x2)
b = min(x1, x2)
r = a % b
if r == 0:
return b
else:
return gcd(b, r)
else:
return 'Please enter two positive integers'
def move(n, source, bridge, destination):
if n == 3:
return (f'{source} --> {destination}\n'
f'{source} --> {bridge}\n'
f'{destination} --> {bridge}\n'
f'{source} --> {destination}\n'
f'{bridge} --> {source}\n'
f'{bridge} --> {destination}\n'
f'{source} --> {destination}\n')
else:
return (move(n-1, source, destination, bridge) +
f'{source} --> {destination}\n' +
move(n-1, bridge, source, destination))
def main():
# print(factorial(0))
# print(factorial('6'))
# print(factorial(6))
# print(fibonacci(4))
# print(gcd(1071, 462))
# print(gcd(12, 6))
# print(gcd(12, 9))
# print(gcd(-4, '5'))
# print(move(3, 'a', 'b', 'c'))
print(move(4, 'a', 'b', 'c'))
if __name__ == "__main__":
main() |
cbb786472b417f3a39a899d58e1d93444af1224c | Blossomyyh/leetcode | /lastSubString.py | 1,476 | 3.5625 | 4 | """
My idea is simple, it is kind of DP or linear search or whatever ...
One observation is that the answer should reach the end of string s.
Otherwise, you can always extend the hypothetical answer to the end of string s
which will be lexicographically larger than the hypothetical answer.
Next, let's assume the current dp answer is stored in a variable pre.
The idea is that when moving one letter backward,
pre either stays the same or it would be the current index.
And when we compare current index substring against pre substring,
we only need to compare upto index pre,
because we already know the comparison results beyond pre,
and we know it will be lexicographically smaller
(because pre is the currently lexicographically largest substring index).
The runtime complexity will be O(n), since we compare each letter once in the worst case.
Space complexity is apprarently O(1)
Note that I have put a naive string comparison in comment section
which will be much slower (should be O(n^2) runtime),
so replacing it with the comparison upto pre gives much faster runtime.
"""
class Solution:
def lastSubstring(self, s: str) -> str:
i ,j , k =0 ,1 ,0
n=len(s)
while j+k<n:
if s[i+k]==s[j + k] :
k+=1
continue
elif s[i+k]>s[j+ k ]:
j=j+k+1
else:
i=max(j,i + k+1)
j=i+1
k=0
return s[i:] |
77747b46d1b04ba4289250e88a5b6722f39ec9a0 | harshjoshi02/Hacktoberfest2020 | /Python/Tasks/count_of_students_in_class.py | 489 | 3.890625 | 4 | #Write a Python program to count the number of students of individual class
from collections import Counter
classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)
#we will need a dictionary to store the repeated students of a sections' tally
classdict = {}
for c in classes:
if not str(c[0]) in classdict:
classdict[str(c[0])] = c[1]
else:
classdict[str(c[0])] += c[1]
students = Counter(classdict)
print(students)
|
6c511b63f8a6d213cc1e91f1e17663d2419e8b29 | sunnycol/warmup | /hw5.py | 2,905 | 3.71875 | 4 | #!/usr/bin/python
__author__ = "Stephen Li"
__email__ = "stephen.liziyun at gmail dot com"
import sys
class AdjacencyListGraph(object):
"""Adjacency list implementation of undirected weighted graph. """
def __init__(self):
self.nodes = []
self.edges = {}
def add_edge(self, u, v, weight):
"""Add nodes and edges."""
if u not in self.edges:
self.edges[u] = {}
self.nodes.append(u)
if v not in self.edges:
self.edges[v] = {}
self.nodes.append(v)
# undirected weighted edge, no duplicated
if (u not in self.edges[v].keys()) and (v not in self.edges[u].keys()):
self.edges[u][v] = weight
self.edges[v][u] = weight
def Dijkstra(graph, start):
# Initialization
n = len(graph.nodes)
dist_vector = n * [1000000]
intree = n * [False]
parent = n * [-1]
dist_min = 1000000
# Starting from given vertex (tranform to 0-based)
dist_vector[start-1] = 0
u = start
while intree[u-1] == False:
intree[u-1] = True
edges_u = graph.edges[u]
for v in edges_u.keys():
if dist_vector[v-1] > dist_vector[u-1] + graph.edges[u][v]:
dist_vector[v-1] = dist_vector[u-1] + graph.edges[u][v]
parent[v-1] = u-1
u = start
dist_min = 1000000
for x in graph.nodes:
if intree[x-1] == False and dist_min > dist_vector[x-1]:
dist_min = dist_vector[x-1]
u = x
# print dist_vector
return dist_vector
def main():
args = sys.argv[1:]
if not args:
print 'usage: inputfile'
sys.exit(1)
graph = AdjacencyListGraph()
with open(args[0]) as fileobject:
for line in fileobject:
line = line.strip().split()
start = line[0]
for x in xrange(1, len(line)):
edge = tuple(line[x].split(','))
# print int(start), int(edge[0]), int(edge[-1])
graph.add_edge(int(start), int(edge[0]), int(edge[-1]))
# Test output
# print graph.nodes
# for u in graph.edges.keys():
# for v, weight in graph.edges[u].items():
# print u, v, weight
dist_dict = Dijkstra(graph, 1)
# Print result
# print '7', dist_dict[7-1]
# print '37', dist_dict[37-1]
# print '59', dist_dict[59-1]
# print '82', dist_dict[82-1]
# print '99', dist_dict[99-1]
# print '115', dist_dict[115-1]
# print '133', dist_dict[133-1]
# print '165', dist_dict[165-1]
# print '188', dist_dict[188-1]
# print '197', dist_dict[197-1]
# print dist_dict[7-1],',',dist_dict[37-1],',',dist_dict[59-1],',',dist_dict[82-1],',',dist_dict[99-1],',',dist_dict[115-1],',',dist_dict[133-1],',',dist_dict[165-1],',',dist_dict[188-1],',',dist_dict[197-1]
if __name__ == '__main__':
main() |
0c6ccfd2691b91957241b03b95db39706371af7a | liwzhi/Zillow-house-prediction | /Desktop/machineLearning-master/combination.py | 1,559 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 11:19:58 2015
@author: weizhi
"""
class Solution:
# @return a list of lists of integers
def combine(self, n, k):
result = []
self.combineRecu(n, result, 0, [], k)
return result
def combineRecu(self, n, result, start, intermediate, k):
if k == 0:
result.append(intermediate[:])
for i in xrange(start, n):
intermediate.append(i + 1)
self.combineRecu(n, result, i + 1, intermediate, k - 1)
intermediate.pop()
class Solution2:
def combine(self,n,k):
result = []
self.helper(n,result,0,[],k)
return result
def helper(self,n,result,start,intermediate,k):
if k==0:
result.append(intermediate[:])
for i in range(start,n):
intermediate.append(i+1)
self.helper(n,result,i+1,intermediate,k-1)
intermediate.pop()
class Solution4:
def combine(self,nums):
result = []
self.helper(nums,result,0,[])
return result
def helper(self,nums,result,start,intermediate):
result.append(intermediate)
for i in range(start,len(nums)):
intermediate.append(nums[i])
self.helper(nums,result,i+1,intermediate)
intermediate.pop()
if __name__ == "__main__":
result = Solution2().combine(4, 2)
print result
result = Solution4().combine([2,3,4,5])
print result
|
d9342615a47041d97ca0ae0da06260fc8a6f991e | jennyChing/leetCode | /264_nthUglyNumber2.py | 1,650 | 4.21875 | 4 | '''
264. Ugly Number II
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
Hint:
1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
'''
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
N = {1:1}
p2 = p3= p5 = 1 # use p2/3/5 to record the accumalated times of the number so far
for i in range(2, n + 1):
# find the next smallest ugly number:
while N[p2] * 2 <= N[i - 1]: # if can multiple more one 2 and stay less then the last number
p2 += 1
while N[p3] * 3 <= N[i - 1]: # if can multiple more one 2 and stay less then the last number
p3 += 1
while N[p5] * 5 <= N[i - 1]: # if can multiple more one 2 and stay less then the last number
p5 += 1
N[i] = min(N[p3] * 3, min(N[p2] * 2, N[p5] * 5))
return N[n]
if __name__ == '__main__':
res = Solution().nthUglyNumber(13)
print(res)
|
62e47f6d7ad7af4c7c12e39a1f15fc1604453b7a | Zia-/Mathematical-Code-Solutions | /src/12.wave-array.py | 786 | 4.3125 | 4 | """
author: Dr. Mohammed Zia
https://www.linkedin.com/in/zia33
Problem Statement:
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
more: https://practice.geeksforgeeks.org/problems/wave-array-1587115621/1
"""
def wave_arr(n):
"""
Generate wave array
"""
try:
mid_idx = len(n) // 2
for i in range(mid_idx):
if (n[2*i] < n[2*i+1]):
n[2*i], n[2*i+1] = n[2*i+1], n[2*i]
return n
except Exception as e:
print(e)
if __name__ == '__main__':
# n = [1,2,3,4,5]
n = [2,4,7,8,9,10]
print(wave_arr(n)) |
a1bde9fbe11c689f7af590139e646629e0346982 | 666graham666/- | /ex11.py | 184 | 3.640625 | 4 | import turtle
turtle.shape('turtle')
turtle.left(90)
n = 50
def but(n):
turtle.circle(n)
turtle.circle(-n)
x = 1
while x <=20:
but(n)
n += 5
x += 1
input()
|
ab62c974d019074eb8cae38a24f25e1570111ed5 | raduvieru/turtle | /turtle9.py | 766 | 3.9375 | 4 | import turtle
from math import pi, sin
screen = turtle.Screen()
def poligon(n, r):
if n < 3:
exit()
turtle.penup()
alpha = (n - 2) * 180 / n #marimea ungiului intern din poligon
#turtle.reset()
turtle.goto(0, 0)
turtle.forward(r)
turtle.left(180 - alpha/2)
# turtle.left(-alpha / 2)
turtle.pendown()
i = 0
while i < n:
turtle.forward(2 * r * sin(pi / n))
turtle.left(180 - alpha)
i += 1
plg_num = int(turtle.numinput("Numar poligoane", "Numar poligoane", 3, minval=3, maxval=20))
raza = int(turtle.numinput("Numar poligoane", "Numar poligoane", 40, minval=3, maxval=100))
j = 3
while j <= plg_num+3:
poligon(j, raza)
raza += 20
# plg_num += 1
j += 1
screen.exitonclick()
|
d890399e968d766a92352106caea8a6b7d9c195b | bayysp/PythonTutorial | /SplitFunction.py | 271 | 4.09375 | 4 | #split function is using for split a string with parameter
#for example
print("Bayu:Ai:Yola".split(":"))
#it will put a 'Bayu' 'Ai' and 'Yola' into array
#it also can be access by an index
print("My Name is "+"Bayu:Ai:Yola".split(":")[1])
#it will show 'My Name is Ai' |
3e205542c2f403e4ff5caaf408b53590f347cfee | tzm25/Self-Taught-Programmer | /For loop.py | 814 | 3.765625 | 4 | blog_post=["","The 10 coolest math functions in Python","", "How to make HTTP requests in Python", "A tutorial about data types in python"]
for post in blog_post:
if post == "":
continue
else:
print(post)
myString="This is a string"
for char in myString:
print(char)
for x in range(0,20):
print(x)
my_info={"Name":"TZM", "Age":"22", "Gender":"Male"}
for key in my_info:
print(key, ":", my_info[key])
blog_post={"Python":["The 10 coolest math functions in Python", "How to make HTTP requests in Python", "A tutorial about data types in python"], "Javascript":["Namespaces in Javascript","New functions available in ES6"]}
for category in blog_post:
print("Posts about", category)
for post in blog_post[category]:
print(post)
|
6e9700312c738043ac64245558d3454395910f3a | kamalkoushik24/zap | /pset6/readability/readability.py | 971 | 3.890625 | 4 | from cs50 import get_string # importing the cs50 library
letter = 0
sentence = 0 # initializing all the variables
word = 1
text = get_string("Text: ") # getting the text from the user
n = len(text) # getting the length of the text
for i in range(n):
if ((text[i] >= 'A' and text[i] <= 'Z') or (text[i] >= 'a' and text[i] <= 'z')): # counting the number of letters
letter += 1
for i in range(n):
if text[i] == ' ': # counting the number of words
word += 1
for i in range(n):
if text[i] == "?" or text[i] == "." or text[i] == "!": # counting the number of sentences
sentence += 1
l = (letter / word) * 100 # getting the value of L
s = (sentence / word) * 100 # getting the value of S
grade = round(0.0588 * l - 0.296 * s - 15.8) # calculating the grade
if grade < 0:
print("Before Grade 1\n")
elif grade >= 16:
print("Grade 16+\n") # printing the text according to the grade
else:
print(f"Grade {grade}\n")
|
4526cc38e3a8b1de8aa92c99281bdd8126c1411c | junyechen/Basic-level | /1046 划拳.py | 1,444 | 3.75 | 4 | """
划拳是古老中国酒文化的一个有趣的组成部分。酒桌上两人划拳的方法为:每人口中喊出一个数字,同时用手比划出一个数字。如果谁比划出的数字正好等于两人喊出的数字之和,谁就赢了,输家罚一杯酒。两人同赢或两人同输则继续下一轮,直到唯一的赢家出现。
下面给出甲、乙两人的划拳记录,请你统计他们最后分别喝了多少杯酒。
输入格式:
输入第一行先给出一个正整数 N(≤100),随后 N 行,每行给出一轮划拳的记录,格式为:
甲喊 甲划 乙喊 乙划
其中喊是喊出的数字,划是划出的数字,均为不超过 100 的正整数(两只手一起划)。
输出格式:
在一行中先后输出甲、乙两人喝酒的杯数,其间以一个空格分隔。
输入样例:
5
8 10 9 12
5 10 5 10
3 8 5 12
12 18 1 13
4 16 12 15
输出样例:
1 2
"""
#####################################################################################
#非常简单 一次通过
#####################################################################################
N = int(input())
Adrink, Bdrink = 0, 0
for i in range(N):
result = [int(i) for i in input().split()]
temp = result[0] + result[2]
if temp == result[1] == result[3]:
pass
elif result[1] == temp:
Bdrink += 1
elif result[3] == temp:
Adrink += 1
print(Adrink,Bdrink)
|
0dbec13ea22b6b03e0ed526e03dcb011eacc9a71 | tobigrimm/adventofcode2020 | /day03/day03.py | 775 | 3.953125 | 4 | #!/usr/bin/env python3
import sys
from typing import List
def navigate_slope(map: List[str], x_inc: int = 1, y_inc: int = 3) -> int:
h = len(map)
w = len(map[0])
x, y = 0, 0
trees = 0
while x < h:
if map[x][y] == "#":
trees += 1
x += x_inc
# simulate the endless repeat to the right
y = (y + y_inc) % w
return trees
if __name__ == "__main__":
with open(sys.argv[1], "r") as infile:
map = [line.strip() for line in infile]
part1 = navigate_slope(map)
print(f"part 1: {part1} trees hit")
result = 1
# calculate the possible results
for x, y in [(1, 1), (1, 3), (1, 5), (1, 7), (2, 1)]:
result *= navigate_slope(map, x, y)
print(f"part 2: {result} trees hit")
|
2a5effb1eafc11da5c0c5ad8a606ee5701bdea3a | Tanuki157/Chapter-2 | /Chapter 2.py | 5,265 | 3.921875 | 4 | def personal_info(): #program that shows first and last name, address, phone number
#and, what college major this person wants
print("Taylor")
print("Short")
print("74 W. Shady St. Rossville, GA 307041")
print("706-858-4395")
print("Film editing")
def total_purchase():
first = float(input("Please enter a price for your fisrt item: "))
second = float(input("Please enter a price for your second item: "))
third = float(input("Please enter a price for your third item: "))
fourth = float(input("Please enter a price for your fourth item: "))
fifth = float(input("Please enter a price for your fifth item: "))
print("")
subtotal = (first + second + third + fourth + fifth)
print("Subtotal: $", subtotal)
tax = (.07 * subtotal)
print("Tax: $", tax)
total = (tax + subtotal)
print("Total: $", total)
def distance_traveled():
speed = int(input("How fast are you driving? "))
six = speed * 6
print("At", speed, "miles per hour you will travel", six, "miles in 6 hours.")
ten = speed * 10
print("At", speed, "miles per hour you will travel", ten, "miles in 10 hours.")
fifthteen = speed * 15
print("At", speed, "miles per hour you will travel", fifthteen, "miles in 15 hours.")
def sales_tax():
sale_amount = float(input("Enter the sale amount: "))
state_tax = .05 * sale_amount
county_tax = .025 * sale_amount
total_tax = county_tax + state_tax
total_sale = sale_amount + total_tax
print("Your purchase price was: \t$", format(total_sale, '7.2f'))
print("Your state tax amount is: \t$", format(state_tax, '7.2f'))
print("Your county tax amount is: \t$", format(county_tax, '7.2f'))
print("Your total tax is: \t\t$", format(total_tax, '7.2f'))
print("Your total sale is: \t\t$", format(total_sale, '7.2f'))
def tip_tax_total():
sale_amount = float(input("Please enter the sale amount: "))
print("The sale was: \t\t\t$", format(sale_amount, '7.2f'))
tip_amount = .18 * sale_amount
sales_tax = .07 * sale_amount
total_bill = (sales_tax + tip_amount + sale_amount)
print("The tip amount is: \t\t$", format(tip_amount, '7.2f'))
print("The sales_tax amount is: \t$", format(sales_tax, '7.2f'))
print("The total bill is: \t\t$", format(total_bill, '7.2f'))
def temp_converter():
degrees = int(input("Please enter the degrees Celsius: "))
fahrenheit = (9/5) * degrees +32
print(degrees, "degrees celsius is", fahrenheit, "degrees fahrenheit")
def cookie_monster():
cookies = int(input("How many cookies do you want to make? "))
print("For", cookies,"cookies you will need:")
sugar_X = 1.5 / 24
butter_X = 1 / 24
flour_X = 2.75 / 24
sugar_cups = (cookies * sugar_X) // 1
butter_cups = (cookies * butter_X) // 1
flour_cups = (cookies * flour_X) // 1
sugar_oz = ((cookies * sugar_X) %1)*8
butter_oz = ((cookies * butter_X) %1)*8
flour_oz = ((cookies * flour_X) %1)*8
print(sugar_cups, "cup(s)", sugar_oz, "ounces of sugar.")
print(butter_cups, "cup(s)", butter_oz, "ounces of butter.")
print(flour_cups, "cup(s)", flour_oz, "ounces of butter.")
def class_demographics():
females = float(input("Enter the number of females: "))
males = float(input("Enter the number of males: "))
students = females + males
con_f = females / students
con_m = males / students
print("The class consists of", format(con_f, '.0%'), "females and", format(con_m, '.0%'), "males.")
def tortuga_1():
import turtle
turtle.pensize(5)
turtle.forward(155)
turtle.write("E",font=(35))
turtle.goto(0,0)
turtle.left(90)
turtle.forward(150)
turtle.write("N",font=(35))
turtle.goto(0,0)
turtle.left(90)
turtle.forward(155)
turtle.write("W",font=(35))
turtle.goto(0,0)
turtle.left(90)
turtle.forward(150)
turtle.penup()
turtle.forward(20)
turtle.write("S", font=(35))
turtle.pendown()
turtle.pensize(3)
turtle.penup()
turtle.goto(0,0)
turtle.pendown()
turtle.left(45)
turtle.forward(125)
turtle.goto(0,0)
turtle.left(90)
turtle.forward(125)
turtle.goto(0,0)
turtle.left(90)
turtle.forward(125)
turtle.goto(0,0)
turtle.left(90)
turtle.forward(125)
def tortuga_2():
import turtle
turtle.setup(800,600)
turtle.penup()
turtle.left(180)
turtle.forward(160)
turtle.right(90)
turtle.forward(120)
turtle.pendown()
turtle.pensize(9)
turtle.pencolor("light blue")
turtle.circle(100)
turtle.left(90)
turtle.pencolor("yellow")
turtle.circle(100)
turtle.right(180)
turtle.penup()
turtle.forward(215)
turtle.left(90)
turtle.pendown()
turtle.pencolor("black")
turtle.circle(100)
turtle.left(90)
turtle.pencolor("green")
turtle.circle(100)
turtle.right(180)
turtle.penup()
turtle.forward(215)
turtle.left(90)
turtle.pendown()
turtle.pencolor("red")
turtle.circle(100)
|
216811689504a8e5d57bcc840ae4fbe978565984 | RaymondZano/MBAN-Python-Course | /1 Dishes_Duties.py | 4,428 | 4.09375 | 4 |
"""
Dean Luis and Dean Amber have both been assigned to wash the dishes
after the Winter Ball. They are trying to divide the work evenly, and
Dean Luis gets the great idea that one person should wash the cups,
plates, and silverware, while the other washes the pots and pans.
* It takes 15 seconds to wash one cup, and there are 500 cups.
* It takes 10 seconds to wash one plate, and there are 500 plates.
* It takes 10 seconds to wash one piece of silverware, but they can be
washed three at a time. There are 1200 pieces of silverware
* It takes 80 seconds to wash one pot and there are 25 pots
* It takes 60 seconds to wash one pot and there are 75 pans
He asks Dean Amber which she prefers. Which should Amber choose?
a) the cups, plates, and silverware
b) the pots and pans
"""
# Washing Time Breakdown:
cup_time = 15
plate_time = 10
silverware_time = 10
pots_time = 80
pans_time = 60
# Quantity of Dishes:
cup_qty = 500
plate_qty = 500
silverware_qty = 1200/3
pots_qty = 25
pans_qty = 75
# Plates, Cups, and Silverware
cup_wash = (cup_time * cup_qty)
plate_wash = (plate_time * plate_qty)
silver_wash = (silverware_time * silverware_qty)
cps_wash = cup_wash + plate_wash + silver_wash
print(cps_wash)
# Pots and Pans
pot_wash = (pots_time * pots_qty)
pan_wash = (pans_time * pans_qty)
pp_wash = pot_wash + pan_wash
print(pp_wash)
# Testing for Equality
print(cps_wash == pp_wash)
"""
Dean Amber runs an analysis in Python and realizes that the duties
aren't even close to equal. She drafts Dean Luis an email informing
him of the situation.
"""
print(f"""
Dear Luis,
It has come to my attention that with our current quantities of:
{cup_qty} cups, {plate_qty} plates, {silverware_qty} pieces of
silverware, {pots_qty} pots, and {pans_qty} pans, our duties
would not even be close to equal if we were to split them in the
way that you have recommended.
I will begin working on a solution where our duties are split
more equally. And reply to you via SMS message.
Sincerely,
Dean Amber
""")
# We have just used an f string above, which is a way to dynamically
# call variables and other objects into a print script.
###################
# Calculations in f strings
###################
# We can make calculations in f strings as follows.
print(f"""
Dear Luis,
To give more details on my previous email, one of us would be
working for {int(cps_wash / 3600)} hours and {int((cps_wash % 3600) / 60)}
minutes, while the other would be working {int(pp_wash / 3600)}
hours and {int((pp_wash % 3600) / 60)} minutes.
I will begin working on a solution where our duties are split
more equally.
Sincerely,
Dean Amber
""")
# See Footnote 1 for these calculations step-by-step
###############################################################################
## Part 2: Making the Calculation Balance
###############################################################################
"""
Prof. Chase:
Use this template to help balance the workload between Dean Luis
and Dean Amber.
"""
# Current Variables
print(cup_wash)
print(plate_wash)
print(silver_wash)
print(pot_wash)
print(pan_wash)
# Change the duties below to balance the workload
luis = plate_wash+pan_wash+pot_wash
amber = cup_wash+silver_wash
print(luis)
print(amber)
# Testing for Equality
print(luis == amber)
###############################################################################
## Part 3: Reply to Dean Luis with your new duties
###############################################################################
print(f"""
Dear Dean Luis,
Sincerely,
Dean Amber
""")
###############################################################################
## Footnotes
###############################################################################
"""
Footnotes
Footnote 1: f string calculations
{int( # int() can be used similar to =ROUNDDOWN() in Excel
cps_wash / 3600) # dividing cps_wash by 3600 so that it is in hours, not seconds
} # closing the f string
(int( # int() can be used similar to =ROUNDDOWN() in Excel
cps_wash % 3600) # taking the remainder of cps_wash using %
/ 60)} # dividing by 60 so the remainder is in minutes, not seconds
""" |
c47d08e4a3cac57bc8adee6a853ce03fd20c1f19 | manthanmtg/zero-to-hero-in-python-in-30-days | /day7/break.py | 105 | 3.53125 | 4 | for i in range(1, 30):
if(i == 12):
break
print(i, end = " ")
print("Loop completed") |
3fe488913d5fd6d60d06c0f4239cbff947b8fed8 | RapAPI/Server | /rearrange.py | 6,699 | 3.9375 | 4 | import re
import pronouncing
from random import shuffle
def parse_cmu(cmufh):
"""Parses an incoming file handle as a CMU pronouncing dictionary file.
Returns a list of 2-tuples pairing a word with its phones (as a string)"""
pronunciations = list()
for line in cmufh:
line = line.strip()
if line.startswith(';'): continue
word, phones = line.split(" ")
word = re.sub(r'\(\d\)$', '', word.lower())
phones_list = phones.split(" ")
pronunciations.append((word.lower(), phones))
return pronunciations
pronunciations = parse_cmu(open('cmudict-0.7b'))
def syllable_count(phones):
return sum([phones.count(i) for i in '012'])
def phones_for_word(find):
"""Searches a list of 2-tuples (as returned from parse_cmu) for the given
word. Returns a list of phone strings that correspond to that word."""
matches = list()
for word, phones in pronunciations:
if word == find:
matches.append(phones)
return matches
def rhyming_part(phones):
"""Returns the "rhyming part" of a string with phones. "Rhyming part" here
means everything from the vowel in the stressed syllable nearest the end
of the word up to the end of the word."""
idx = 0
phones_list = phones.split()
for i in reversed(range(0, len(phones_list))):
if phones_list[i][-1] in ('1', '2'):
idx = i
break
return ' '.join(phones_list[idx:])
def search(pattern):
"""Searches a list of 2-tuples (as returned from parse_cmu) for
pronunciations matching a given regular expression. (Word boundary anchors
are automatically added before and after the pattern.) Returns a list of
matching words."""
matches = list()
for word, phones in pronunciations:
if re.search(r"\b" + pattern + r"\b", phones):
matches.append(word)
return matches
def rhymes(word):
"""Searches a list of 2-tuples (as returned from parse_cmu) for words that
rhyme with the given word. Returns a list of such words."""
all_rhymes = list()
all_phones = phones_for_word(word)
for phones_str in all_phones:
part = rhyming_part(phones_str)
rhymes = search(part + "$")
all_rhymes.extend(rhymes)
return [r for r in all_rhymes if r != word]
def wordsRhyme(strWordA, strWordB):
rhymes_A = pronouncing.rhymes(strWordA)
for rhyming_word in rhymes_A:
if rhyming_word == strWordB:
return True
return False
def groupingAlgorithm(arrstrVerses):
arrtupVerses = []
arrUnmatchedVerses = []
arrstrFinalLyrics = []
i = 0
while (i < len(arrstrVerses)):
if (i + 1) < len(arrstrVerses):
wordA = arrstrVerses[i].split()[-1]
wordB = arrstrVerses[i + 1].split()[-1]
if wordsRhyme(wordA, wordB):
t = arrstrVerses[i], arrstrVerses[i + 1]
arrtupVerses.append(t)
i = i + 2
else:
arrUnmatchedVerses.append(arrstrVerses[i])
i = i + 1
else:
arrUnmatchedVerses.append(arrstrVerses[i])
i = i + 1
shuffle(arrtupVerses)
for pair in arrtupVerses:
arrstrFinalLyrics.append(pair[0])
arrstrFinalLyrics.append(pair[1])
for verse in arrUnmatchedVerses:
arrstrFinalLyrics.append(verse)
return arrstrFinalLyrics
def rearrange_text(arg):
import sys, operator, random;
word_group = list()
line_lengths = list()
arg_list = list(str(arg).split('\n'))
#print(arg_list)
for line in arg_list:
line = line.strip()
words = line.split()
word_group.append(words)
line_lengths.append(len(words))
#print(words)
median_line_length = sorted(line_lengths)[int(len(sorted(line_lengths))/2)]
#print("Median Line Lenght", median_line_length)
#print("Pre-split line count", len(word_group))
w = 0
while w < len(word_group):
words = word_group[w]
if len(words) > 5/3 * median_line_length:
new_line_first = list(words[:int(len(words)/2)])
new_line_second = list(words[int(len(words)/2):])
word_group[w] = new_line_first
#w -= 1
if(w == len(word_group)):
word_group.append(new_line_second)
continue
word_group.insert(w+1, new_line_second)
continue
w+=1
#print("post-split line number", len(word_group))
rhymes_list = dict()
line_num = 0
text = list()
rubbish = list()
for words in word_group:
if (len(words) < 1 or len(phones_for_word(words[-1])) < 1):
continue
#print(phones_for_word(words[-1]))
#raw_text = raw_text_file.readlines()
ph = phones_for_word(words[-1])[0]
phones_list = rhyming_part(ph).split(' ')
if(rhymes_list.get(''.join(list(reversed(phones_list)))) == None):
rhymes_list[''.join(list(reversed(phones_list)))] = list()
rhymes_list[''.join(list(reversed(phones_list)))].append(line_num)
#print(line_num, ' '.join(words))
line_num += 1
punctuation_num = random.randrange(0,10)
if(set(range(0,4)).issuperset(set([punctuation_num]))):
punctuation = '.'
elif(set(range(4,6)).issuperset(set([punctuation_num]))):
punctuation = ','
elif(punctuation_num == 6):
punctuation = '!'
elif(punctuation_num == 7):
punctuation = '?'
elif(punctuation_num == 8):
punctuation = ';'
else:
punctuation = '!'
text.append(' '.join(words) + punctuation)
#print (list(reversed(phones_list)))
#helper = [(key, len(rhymes_list[key])) for key in rhymes_list.keys()]
#helper.sort(key=lambda x: x[1])
#print(rhymes_list[helper[0][0]])
#print(sorted((rhymes_list), key=operator.itemgetter(1, 2, 3, 4)))
#print(sorted((rhymes_list)))
#print(list(sorted((rhymes_list))))
values = list(sorted((rhymes_list)))
line_order = list()
for v in values:
for r in rhymes_list[v]:
line_order.append(r)
#print(line_order)
#print(len(line_order))
output_text = list()
for l in line_order:
output_text.append(text[l])
#print(output_text)
output_text += rubbish
#print('\n'.join(output_text))
#print('\n')
output_text = [s for s in output_text if len(s) > 0]
output_text = groupingAlgorithm(output_text)
#print('\n'.join(output_text))
return '\n'.join(output_text)
|
3a407255d23d6ef331b509ef6f4a0fe91437c342 | Molly-l/vbn | /day03/recursion.py | 286 | 4.0625 | 4 | """
就一个数n的阶乘
"""
# def recursion(n):
# resule = 1
# for i in range(1,n+1):
# resule *= i
# return resule
# 递归函数
def recursion(n):
# 递归的终止条件
if n <= 1:
return 1
return n * recursion(n - 1)
print(recursion(3)) |
bc5d5dd0dad669c59ebf7b97e8ff3cbab772e813 | rockerishFox/AI_Lab5 | /utils.py | 1,598 | 3.5 | 4 | from math import sqrt
def read_graph_from_file(filename):
routes = []
with open(filename, 'r') as file:
cities_no = int(file.readline())
for i in range(cities_no):
city_routes_string = file.readline().strip().split(',')
city_routes = [float(route) for route in city_routes_string]
routes.append(city_routes)
return routes
def read_graph_from_file_with_coordinates(filename):
routes = []
coordinates = []
with open(filename, 'r') as file:
cities_no = get_nodes_from_file(file)
for i in range(cities_no):
line = file.readline().strip().split(' ')
coordinates.append([float(line[1]), float(line[2])])
routes.append([])
for city1 in range(cities_no):
for city2 in range(cities_no):
routes[city1].append(get_euclidian_distance(coordinates[city1], coordinates[city2]))
return routes
def get_euclidian_distance(a, b):
return sqrt((b[0]-a[0])*(b[0]-a[0])+(b[1]-a[1])*(b[1]-a[1]))
def get_nodes_from_file(filename):
nr = 0
line = filename.readline().strip().split(':')
while line[0].strip(' ') != 'DIMENSION':
line = filename.readline().strip().split(':')
nr = int(line[1])
filename.readline()
filename.readline()
return nr
def result_to_file(access_mode, output_file, no_of_cities, cities_order, total_cost):
with open(output_file, access_mode) as output:
output.write(str(no_of_cities) + '\n')
output.write(str(cities_order) + '\n')
output.write(str(total_cost) + '\n')
|
e4171c75fa8c3eadae239181dd5da3c3f9c41c5a | thehanemperor/LeetCode | /LeetCode/Math/Basic/69. Sqrt(x).py | 437 | 3.640625 | 4 | class Solution:
def mySqrt(self, x: int) -> int:
if x< 2:
return x
left,right = 2, x//2
while left <= right:
mid = left + (right -left)//2
num = mid ** 2
print(mid,num)
if num > x:
right = mid - 1
elif num < x:
left = mid + 1
else:
return mid
return right |
25cfd89c01a46439b18ec47b495b3a7171c16943 | dmendelsohn/project_euler | /solutions/problem_067.py | 703 | 3.6875 | 4 | import utils
# Just compute the continuous path from top of triangle to bottom with highest sum (same as Problem #18)
def compute(verbose=False):
MEMO = {}
def best_to_point(grid, i, j):
if (i,j) in MEMO:
return MEMO[(i,j)]
elif (j > i) or (i < 0) or (j < 0):
return 0
else:
a = best_to_point(grid, i-1, j)
b = best_to_point(grid, i-1, j-1)
answer = grid[i][j] + max(a,b)
MEMO[(i,j)] = answer
return answer
grid = utils.load_grid(utils.INPUT_PATH + "p067_triangle.txt", ' ')
answer = max(best_to_point(grid,len(grid)-1,j) for j in range(len(grid)))
return answer, "Maximum sum through triangle"
|
53fd549fd499b72e7e9159565fa6e048b77bc7d9 | karanpradhan/Real-Estate-Price-Estimation | /original_data/dictionary.py | 7,720 | 3.640625 | 4 | #!/usr/bin/python2
#----------------------------------
# dictionary.py
#----------------------------------
#
# builds a dictionary to translate between ints and words
# simplest usage:
# my_dict = dictionary(['testfile.txt']) # build word -> int mapping
# print my_dict.translate_file('testfile.txt') # translate same file
import os, sys, counter, pickle, time, glob
# WARNING: assumes input is tokenized (depending on option);
# does not lowercase
class dictionary:
''' main class of dictionaries'''
def __init__(self, doc_list=[], n_vocab=100,zero_based_index = True,tokenize_method="simple",include_OOV=True,file_name="dict.pkl"):
# TODO: add in options for chinese and for non-zero-base indexing)
self.n_vocab = n_vocab # vocabulary size
self.dict = {} # mapping from word to unique integer
self.inverse_dictionary = {} # mapping from integer to word
self.name = file_name
self.zero_based_index = zero_based_index
self.tokenize_method = tokenize_method
self.include_OOV = include_OOV
self.dict = build_dictionary(doc_list, self.n_vocab, self.zero_based_index,self.tokenize_method,self.include_OOV)
for word in self.dict.keys():
self.inverse_dictionary[self.dict[word]] = word
def write(self, filename = "dict.pkl"):
''' dump dictionary to a pickle'''
output = open(filename, 'wb')
pickle.dump(self.dict, output)
return filename
def read(self, filename = "dict.pkl"):
pkl_file = open(filename, 'rb')
self.dict = pickle.load(pkl_file)
return self.dict
def contains_word(self, word):
return word in self.keys()
def translate_file(self, filename,tokenize_method="simple",include_OOV=True):
''' translate words in a file to integers'''
infile = open(filename)
words = []
words_inter = []
words_final = []
self.include_OOV = include_OOV
'''
for line in infile:
#print words #DEBUG
if(tokenize_method=="simple"):
for word in line.split():
word = word.lower()
words.append(word)
# else: #commented before
# words.append(tokenize.tokenize(line)) #commented before
'''
if(tokenize_method == "simple"):
for line in infile:
for word in line.split():
# word = word.lower()
words.append(word)
else:
for line in infile:
words_inter.append(tokenize_string(line))
words = [item for sublist in words_inter for item in sublist]
for word in words:
if word <> '</S>':
words_final.append(word)
int_list = translate_words_to_integers(words_final, self.dict,self.zero_based_index,self.include_OOV)
return int_list
def translate_directory(self, dirname, outfilename='ints.txt'):
''' translate words in files in a directory to ints'''
outfile = open(outfilename,'w')
files = glob.glob(dirname + "/*")
for file in files:
int_list = self.translate_file(file)
for item in int_list:
outfile.write(str(item) +'\n')
outfile.close()
def print_dictionary(self, print_ints=False):
''' print out the words in the dictionary, with or without the ints'''
if print_ints:
words = self.dict.items()
for pair in words:
print pair[1], pair[0]
else:
words = self.dict.keys()
words.sort()
print words
def print_dictionary_to_file(self, filename, print_ints=False):
''' print out the words in the dictionary, with or without the ints'''
file_ptr = open(filename,'w')
if print_ints:
# TODO: should sort these based on the integer
words = self.dict.items()
for pair in words:
file_ptr.write(str(pair[1]) + ' ' + pair[0] + '\n')
else:
words = self.dict.keys()
words.sort()
for word in words:
file_ptr.write(word)
def make_dictionary(token_list):
''' input: a list of tokens'''
c = counter.Counter()
for word in token_list:
c.add(word)
word_int_dict = {}
for i,word in enumerate(c.words()):
word_int_dict[word] = i
return word_int_dict # words -> int
def build_dictionary(document_list, n_vocab=100,zero_based_index = True,tokenize_method="simple",include_OOV=True, src_directory=""):
''' input: a list of documents '''
c = counter.Counter()
words = []
words_mid = []
words_inter = []
for document_name in document_list:
print document_name
file = open(document_name)
if(tokenize_method == "simple"):
for line in file:
for word in line.strip().split():
# word = word.lower()
c.add(word)
else:
print "tokenizing"
words_inter = []
for line in file:
words_inter.append(tokenize_string(line))
words_mid = [item for sublist in words_inter for item in sublist]
for word in words_mid:
if word <> '</S>':
c.add(word)
words = c.top_n_words(n_vocab).keys()
#print len(words)
word_int_dict = {}
if include_OOV:
if zero_based_index:
word_int_dict['<OOV>'] = 0
for i,word in enumerate(words):
word_int_dict[word] = i+1
else:
word_int_dict['<OOV>'] = 1
for i,word in enumerate(words):
word_int_dict[word] = i+2
else:
for i,word in enumerate(words):
word_int_dict[word] = i
return word_int_dict # words -> int
# TODO: move into the object?
def translate_words_to_integers(word_list, dictionary, zero_based_index = True,keep_OOV=True):
'''translates the document to a list of integers'''
# missing word is tagged as '0'
int_list = []
for word in word_list:
if word in dictionary:
int_list.append(dictionary[word])
else:
if(keep_OOV):
if zero_based_index:
int_list.append(0)
else:
int_list.append(1)
return int_list
# TODO: move into the object?
def translate_integers_to_words(int_list, dictionary):
'''inverse of translate_words_to_integers'''
# build reverse dictionary
reverse_dict = {}
reverse_dict[0] = '-' # 0 maps to "-" for now
for (word, int) in dictionary.items():
reverse_dict[int] = word
# now map the int_list to corresponding words
word_doc = []
for int in int_list:
if int in reverse_dict:
word_doc.append(reverse_dict[int])
else:
word_doc.append('<OOV>') # out of vocabulary - should be rare
return word_doc
if __name__ == '__main__':
my_dict = make_dictionary(['a', 'list', 'of', 'a', 'word'])
print my_dict
my_dict = dictionary(['testfile.txt'])
my_dict.print_dictionary() # defaults without the ints
my_dict.write()
my_dict.read()
my_dict.print_dictionary(True) # with the ints as well as words
print "translating file"
print my_dict.translate_file('testfile.txt')
print "test one-based indexing"
my_dict = dictionary(['testfile.txt'], 100, False,"tokenize")
my_dict.write()
my_dict.print_dictionary(True) # with the ints as well as words
print my_dict.translate_file('testfile.txt')
|
cd4657440add50b7598df9bab42ee4e4c9c3163b | nicholas-lau/G16OutputAnalyser | /MiscellaneousFunctions.py | 204 | 3.71875 | 4 | def jobChoice(user_operations):
print("\n==================== Job Choice ====================\n")
for count, operation in enumerate(user_operations):
print(count+1, operation)
return 1 |
8a279d2f585a3cb655252fb5e379a89c6feb0a66 | Silentsoul04/FTSP_2020 | /W3_2020_School/Python_Try_Except_Finally_Blocks.py | 4,091 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 25 11:17:16 2020
@author: Rajesh
"""
'''
Python Try Except Finally :-
-----------------------------
'''
NOTE :- There are we have mainly 3 blocks like listed below.
1) try block
2) except block
3) finally block
1) try block :-
----------------
It is used to test the errors which is available into written codes.
2) except block :-
----------------
It is used to handle the errors.
3) finally block :-
-------------------
It will be always executed irrespective of try and except blocks and whether the exception
raised or not.
'''
Exception Handling :-
-----------------------
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
These exceptions can be handled using the try statement.
'''
Ex :- The try block will generate an exception, because x is not defined.
try:
print(x)
except:
print('An Exception Occured')
----------- Result ---------
An Exception Occured
NOTE :- Since the try block raises an error, the except block will be executed.
NOTE :- Without the try block, the program will crash and raise an error.
Ex :- This statement will raise an error, because x is not defined.
print(x) # NameError: name 'x' is not defined
'''
Many Exceptions :-
---------------------
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
'''
Ex :- Print one message if the try block raises a NameError and another for other errors.
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
----------- Result ---------
Variable x is not defined
Ex :-
try:
print(20/0)
except:
print('There is some error into codes')
----------- Result ---------
There is some error into codes
Ex :-
try:
print(10/0)
except NameError:
print("Variable x is not defined")
except FileNotFoundError:
print('File is not found error')
except ZeroDivisionError:
print('division by zero')
----------- Result ---------
division by zero
'''
Else :-
-------------
You can use the else keyword to define a block of code to be executed if no errors
were raised.
'''
Example
In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
----------- Result ---------
Hello
Nothing went wrong
'''
Finally :-
------------
The finally block, if specified, will be executed regardless if the try block raises
an error or not.
'''
Ex :-
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
----------- Result ---------
Something went wrong
The 'try except' is finished
NOTE :- This can be useful to close objects and clean up resources.
Ex :- Try to open and write to a file that is not writable:
try:
f = open("E:\W3_2020_School\demofile.txt")
f.write("FORSK CODING SCHOOL , JAIPURA. This is Rajesh sharma from Sikar,Rajasthan.")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
'''
Raise an exception :-
-----------------------
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
'''
Ex :- Raise an error and stop the program if x is lower than 0.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
------- Result --------
Exception: Sorry, no numbers below zero
x = 125
if x < 250:
raise Exception('Is it X value is greather than given value.')
------- Result --------
Exception: Is it X value is greather than given value.
NOTE :- The raise keyword is used to raise an exception.
NOTE :- You can define what kind of error to raise, and the text to print to the user.
Ex :- Raise a TypeError if x is not an integer.
x = "hello"
#x = 120
if not type(x) is int:
raise TypeError("Only integers are allowed")
------- Result --------
TypeError: Only integers are allowed
|
e8093d1a48765300a829ab40f053a1ba3c881025 | Huikie/Rush-Hour | /Code/Algorithms/breadthfirst.py | 3,294 | 4 | 4 | from Code.Classes.board import Board
import copy as copy
import time
import queue
class Breadthfirst:
def __init__(self):
self.breathfirst = []
self.board = Board()
self.boards = []
self.archive = {}
self.queue = queue.Queue()
def breadthFirst(self, size):
"""Function that runs the breadthfirst algorithm and stops as soon
as it has found a solution.
"""
self.start_time = time.time()
self.first_board = copy.deepcopy(self.board.board)
self.queue.put(self.board)
# Iterates over all the boards.
while not self.queue.empty():
board = self.queue.get()
# Selects each move.
for move in range(-(size - 1), (size - 1)):
# Makes deepcopy of board for move.
self.board_temp = copy.deepcopy(board)
self.board_temp2 = copy.deepcopy(board)
# select each car.
for car in self.board.cars.keys():
# Checks if move is possible.
if self.board_temp.move(car, move) == True:
# Checks if board is already in archive.
if str([self.board_temp.board]) not in self.archive:
# Saves board.
self.queue.put(copy.deepcopy(self.board_temp))
self.archive[str([self.board_temp.board])] = str([self.board_temp2.board])
# Checks if won.
if self.board_temp.won(size) == True:
self.won_info()
return True
# Moves car back.
self.board_temp.move(car, -move)
def won_info(self):
"""Function that displays information about the results of the breadthfirst algorithm.
"""
counter = 2
# Prints winning board.
self.printBoard(str([self.board_temp.board]))
# Selects parent and prints it.
self.printBoard(self.archive[str([self.board_temp.board])])
# Selects parent of parent and prints it.
parent = self.archive[str([self.board_temp.board])]
self.printBoard(self.archive[parent])
# Prints parent board until the first board is reached.
while self.archive[parent] != str([self.first_board]):
counter += 1
# Selects parent of child and prints it.
parent = self.archive[parent]
self.printBoard(self.archive[parent])
# Prints extra info.
elapsed_time = time.time() - self.start_time
print("\nPlease read the solution from bottom to top!")
print("\nThe algorithm took", round(elapsed_time, 2), "seconds to solve the board!")
print("Minimum amount of moves required to win the game:", counter)
def printBoard(self, board):
"""Function that creates a better representation of the
board (making it easier to read) and prints it.
"""
board = board.replace("[","")
board = board.replace(",","")
board = board.replace("'","")
board = board.replace("]","\n")
board = " " + board
print(board)
|
c13fe4c8a3aafa2b9e427a78385900d33470e611 | laszlobalint/python-playground | /loops.py | 513 | 3.78125 | 4 | warriors = ['Superman', 'Batman', 'Flash', 'Donatello']
# Whole loop
for warrior in warriors:
print(warrior)
# Partial loop
for warrior in warriors[1:3]:
print(warrior)
# Searching loop
for warrior in warriors:
if warrior == 'Flash':
print(f'{warrior} - fast and powerful')
break
else:
print(warrior)
# While loop
age = 25
num = 0
while num < age:
if num == 0:
num += 1
continue
if num % 2 == 0:
print(num)
if num > 10:
break
num += 1 |
b9564579442a6b50cc3c79aea47c571d857dfed4 | cyndyishida/MergeLinkedLists | /Grading/LinkedList.py | 1,409 | 3.9375 | 4 | class LinkedListNode:
def __init__(self, val = None):
"""
:param val of node
:return None
Constructor for Linked List Node, initialize next to None object
"""
self.val = val
self.next = None
def __le__(self, other):
'''
:param other: Linked list node
:return: boolean value of less than equal to other
'''
if isinstance(other, LinkedListNode):
return self.val <= other.val
class LinkedList:
def __init__(self):
"""
:param None
:return None
Constructor for Singly Linked List, initialize head to None object
"""
self.head = None
def __repr__(self):
'''
:param: none
:return: string representation of linked list
'''
result = []
current = self.head
while current:
result.append(str(current.val))
current = current.next
return " -> ".join(result)
__str__ = __repr__
def push_back(self, data):
'''
:param data: val for new node to be added to Linked list
:return: None
'''
node = LinkedListNode(data)
if self.head:
last = self.head
while last.next:
last = last.next
last.next = node
else:
self.head = node
|
97104d4277a4a88ec6ac9ebe45552ddfa29a3509 | Aleti-Prabhas/geekforgeeks | /binary_to_decimal.py | 471 | 3.9375 | 4 | #User function Template for python3
class Solution:
def binary_to_decimal(self, str):
sum=0
i=0
while(str!=0):
dec=str%10
no=no+dec.pow(2,i)
str=str//10
i=i+1
# Code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
T=int(input())
for i in range(T):
str = input()
ob = Solution()
ans = ob.binary_to_decimal(str)
print(ans)
# } Driver Code Ends |
f67575beee6e12b97af73b76b74f07e22966b074 | welsny/solutions | /414.Third_Maximum_Number.py | 285 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = heapq.nlargest(3, set(nums))
return res[-1] if len(res) >= 3 else res[0]
|
8964adcf965c4cb8b34026d36a81d332ec89b6aa | gmt710/leetcode_python | /hot/48_rotate.py | 548 | 3.671875 | 4 | class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
if len(matrix) == 0 or len(matrix[0]) == 0: return []
r = len(matrix)
c = len(matrix[0])
for i in range(r):
for j in range(i+1,c):
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
for i in range(r):
matrix[i] = matrix[i][::-1]
|
16a758055c853ef5d5a893467da190bb2f59cdfa | adixie/bank-account | /bank.py | 1,253 | 3.8125 | 4 | class BankAccount:
def __init__(self, name, email, account_balance, interest_rate):
self.name = name
self.email = email
self.account_balance = 0
self.interest_rate = 0.05
def deposit(self, amount):
self.account_balance += amount
return self
def withdraw(self, amount):
if (self.balance - amount) > 0:
self.account_balance -= amount
else:
print("Insufficient Funds")
return self
def display_account_info(self):
print(self.account_balance)
def yield_interest(self):
interest_yield = 0
interest_yield += self.account_balance * self.interest_rate + self.account_balance
print(interest_yield)
SarahAccount = BankAccount("SarahAccount", "sarah@fake.email", 100, 0.05)
MikeAccount = BankAccount("MikeAccount", "mike@fake.email", 100, 0.05)
SarahAccount.deposit(100).deposit(100).deposit(100).withdraw(50).yield_interest()
MikeAccount.deposit(200).deposit(600).withdraw(37).withdraw(50).withdraw(10).withdraw(15).yield_interest()
|
a52c8f556aba5e6537ac8022ec118d7c1c10fe37 | TonyPeng2003/final_exam | /final_exam/27.py | 276 | 3.59375 | 4 | Tony = {'age':'15','most_famous_book':'Angel',,'country':'US'}
Livia = {'age':'14','most_famous_book':'Get OUt',,'country':'China'}
Mike = {'age':'17','most_famous_book':'Miao Cat','country':'UK'}
persons = [Tony,Mike,Livia]
for introduction in persons:
print(introduction)
|
d9cab76dec27f4e73acd545e204f5a75f6ab243e | zp89n11/pythonproject | /py_practical_1/Hero.py | 841 | 3.6875 | 4 | # -*- encoding: utf-8 -*-
# @ModuleName: House,英雄类。是所有之类英雄的父类,
# @Function:
# @Author: 张鹏
# @Time: 2021/3/28 0:12
class Hero:
# 血量
hp = 0
# 攻击力
power = 0
# 台词
speakLines = ""
'''英雄的名'''
name = ""
def speak_lines(self):
print(f"{self.speakLines}")
def fight(self, enemy_power, enemy_hp):
# 英雄的名言
self.speak_lines()
# 我的血量减去敌人的攻击力获取剩余血量
my_hp = self.hp - enemy_power
# 敌人的血量是多少
enemy_final_hp = enemy_hp - self.power
if my_hp > enemy_final_hp:
print(f"{self.name}赢了!!!")
elif enemy_final_hp > my_hp:
print("敌人赢了!!!")
else:
print("平手")
|
5e778ba91617ebb0b4c3df2b9449223706ad62f3 | HigorSenna/python-study | /guppe/lambdas_e_funcoes_integradas/len_abs_sum_round.py | 879 | 3.96875 | 4 | """
Len. Abs, Sum, Round
len() -> retona o tamanho de um iteravel
abs() -> Retorna o valor absoluta de um número inteiro ou real
sum() -> Recebe como parâmetro um iteravel, podendo receber um iteravel, retorna a soma total dos elementos,
incluindo o valor inicial
OBS: O valor inicial default é 0
round() -> retorna um numero arredondado para n digito de precisao após a casa decimal. Se a precisao nao for informada
retorna o inteiro mais próximo da entrada.
"""
print(len('Teste'))
# Ao utilizar a funcao len(), por baixo dos panos, o python faz:
# Dunder __len()__
'Teste'.__len__()
print(abs(-5))
print(abs(3.14))
print(abs(-3.14))
print(sum([1, 2, 3, 4, 5]))
print(sum([1, 2, 3, 4, 5], 10))
print(sum({'a': 1, 'b': 2, 'c': 3}.values()))
print(round(10.2))
print(round(10.5))
print(round(10.6))
print(round(1.2121212121, 2))
print(round(1.219999999, 2))
|
515b089b3b116a0c9a23a5ae075fa06e92d70f43 | shoichiaizawa/edX_MITx_6.00.1x | /lecture05/l5_problem02.py | 681 | 3.984375 | 4 | def recurPower(base, exp):
'''
base: int or float.
exp: int >= 0
returns: int or float, base^exp
'''
# Your code here
if exp == 0:
return 1
elif exp == 1:
return base
else:
return base * recurPower(base, exp-1)
# ----------
# Test cases
# ----------
print recurPower(-9.01, 0) # ==> 1.0000
print recurPower(6.48, 9) # ==> 20145360.9346
print recurPower(0.56, 3) # ==> 0.1756
print recurPower(-9.6, 3) # ==> -884.7360
print recurPower(-8.37, 1) # ==> -8.3700
print recurPower(6.89, 7) # ==> 737113.8193
print recurPower(0.64, 10) # ==> 0.0115
print recurPower(-1.07, 10) # ==> 1.9672
|
b5d56c6db7e27374d62672b20e60b723f96cc4ce | bdavs/Piratebot | /json_helper.py | 1,578 | 3.59375 | 4 | import json
"""reading the ship file to add all the users ships to the dataspace"""
def to_dict(self):
"""creates a dict from ship params"""
return {
'captain': self.captain,
'cannons': self.cannons,
'crew': self.crew,
'armor': self.armor,
'sails': self.sails,
'gold': self.gold,
'win': self.win,
'loss': self.loss,
'x': self.x,
'y': self.y
}
def from_dict(self, json_data=None):
"""creates a ship based on a dict"""
if json_data is None:
return None
self.captain = json_data['captain']
self.cannons = json_data['cannons']
self.crew = json_data['crew']
self.armor = json_data['armor']
self.sails = json_data['sails']
self.gold = json_data['gold']
self.win = json_data['win']
self.loss = json_data['loss']
self.x = json_data['x']
self.y = json_data['y']
# should this be here?
self.position = json_data['position']
return True
def write_ships(ship):
ships[ship.position] = ship
with open("ship_file.json", "r") as read_file:
first = read_file.read(1)
global ships
ships = []
if first:
read_file.seek(0)
json_data = json.load(read_file)
for s in json_data:
ships.append(s)
index = 0
for ship in ships:
ship["ship_name"] = ship["captain"] + "\'s ship"
ship["win"] = 0
ship["loss"] = 0
ship["x"] = 0
ship["y"] = 0
ships[index] = ship
index += 1
with open("ship_file.json", "w") as write_file:
json.dump(ships, write_file)
|
61b650e7f4fb367c3dd3a403f6fa186e15d790b3 | Trotuga/CYPIrvinBM | /libroo/problemas_resueltos/problema2_10.py | 664 | 3.953125 | 4 | A = int(input("Escribe un numero: "))
B = int(input("Escribe otro numero: "))
C = int(input("Escribe otro numero: "))
if A > B:
if A > C:
print(f"El numero {A} es el mayor. ")
elif A == C:
print(f"El numero {A} y {C} Son iguales y son los mayores. ")
else:
print(f"El numero {C} es el mayor. ")
elif A == B:
if A > C:
print(f"{A} y {B} son iguales y son los mayores. ")
elif A == C:
print(f"Los tres numeros {A} son iguales. ")
else:
print(f"El numero {C} es el mayor. ")
elif B > C:
print(f" El numero {B} es el mayor. ")
else:
print(f"El numero {C} es el mayor. ")
print("Fin. ")
|
7ccf210029ea1b73bb94a5f033e68a455aaebe72 | ARORACHAITANYA/hackerrank | /Strings/#4 Find a string.py | 145 | 3.65625 | 4 | import re
def count_substring(string, sub_string):
s = [m.start() for m in re.finditer(f'(?={sub_string})', f'{string}')]
return len(s)
|
95cf67d35d6815db7285909e6bcb3fe31869377e | igorkoury/cev-phyton-exercicios-parte-2 | /Aula18 - Listas (Parte 2)/ex084 – Lista composta e análise de dados.py | 1,129 | 4.1875 | 4 | '''Exercício Python 084: Faça um programa que leia nome e peso de várias pessoas,
guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.'''
dados = []
pessoas = []
mai = men = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso [kg] : ')))
if len(pessoas) == 0:
mai = men = dados[1]
else:
if dados[1] > mai:
mai = dados[1]
if dados[1] < men:
men = dados[1]
pessoas.append(dados[:])
dados.clear()
resp = ' '
while resp not in 'SN':
resp = str(input('Deseja continuar? ')).upper().strip()[0]
if resp == 'N':
break
print(f'Os dados cadastrados foram {pessoas}')
print(f'Você cadastrou {len(pessoas)} pessoas')
print(f'O maior peso foi de {mai}kg: ', end=' ')
for p in pessoas:
if p[1] == mai:
print(f'{p[0]}', end=' ')
print(f'\nO menor peso foi de {men}kg: ', end=' ')
for p in pessoas:
if p[1] == men:
print(f'{p[0]}')
|
dd7866aef9c2da91ab6cfc7b50533056a788e451 | gjcraig/TrafficDataProject | /venv/graph.py | 1,977 | 3.640625 | 4 | from functions import *
import matplotlib.pyplot as plt
import math
from random import gauss
data = df("Road_Safety_Data.csv")
# # Bar chart
x = ['Fatal', 'Serious', 'Slight']
counts = [header_count('Accident_Severity', 1), header_count('Accident_Severity', 2), header_count('Accident_Severity', 3)]
x_pos = [i for i, _ in enumerate(x)]
plt.bar(x_pos, counts, color='green')
plt.title("Number of Accidents at each Severity Level")
plt.xticks(x_pos, x)
plt.show()
#######################################################################################
print('------------t-test example------------')
day_of_week = [row[9] for row in data]
casualties = [row[7] for row in data]
# combind into a 2d list
tData = [list(a) for a in zip(day_of_week, casualties)]
weekDaystr = [row[1] for row in tData if row[0]!='1' and row[0]!='7']
weekEndstr = [row[1] for row in tData if row[0]=='1' or row[0]=='7']
weekDay = [int(s) for s in weekDaystr]
weekEnd = [int(s) for s in weekEndstr]
print('Weekday mean casualties is', mean(weekDay))
print('Weekend mean casualties is', mean(weekEnd))
student_two(weekEnd, weekDay)
print('This large t value shows that the difference in these means is statistically significant')
# extract the data for each variable
speedLimits = [row[13] for row in data]
casualties = [row[7] for row in data]
#######################################################################################
print('------------ANOVA example------------')
# combind into a 2d list
anovaData = [list(a) for a in zip(speedLimits, casualties)]
# group the data. In this example we group by speed limit.
speed20str = [row[1] for row in anovaData if row[0]=='20']
speed30str = [row[1] for row in anovaData if row[0]=='30']
speed40str = [row[1] for row in anovaData if row[0]=='40']
speed20 = [int(s) for s in speed20str]
speed30 = [int(s) for s in speed30str]
speed40 = [int(s) for s in speed40str]
anova_one(speed20, speed30, speed40)
# F(2,33808) = 2.9957 for alpha = 0.05
|
dfd291d7abb06c1fd6a1564a17bf5e1a716d6877 | mosman94109/primes | /product_of_primes.py | 1,427 | 4.59375 | 5 | #!/usr/bin/env python
"""
From number theory:
Product of primes less than n is less than or equal to e ** n as n grows.
This script computes the sum of the logarithms of all the primes from 2 to some number n
(identfied as LARGE_NUM in this script), and prints out the sum of the logs
of the primes, the number n, and the ratio of these two quantities.
"""
import math as m
LARGE_NUM = 2 ** 20
def get_primes(max_num):
primes = (2, 3)
def check_if_prime(num):
for prime in primes[1: ]: # Skip 2; we're only evaulating odd integers
num_is_prime = True
if prime > m.sqrt(max_num): # https://en.wikipedia.org/wiki/Prime_number says you can stop at sqrt of n
break
elif num % prime == 0:
num_is_prime = False
break
return num_is_prime
num_to_check = 5
while num_to_check <= max_num:
num_is_prime = check_if_prime(num_to_check)
if num_is_prime:
primes += (num_to_check,)
num_to_check += 2
return primes
def get_sum_of_logs_of_primes(primes):
sum_of_logs = 0
for prime in primes:
sum_of_logs += m.log(prime)
return sum_of_logs
primes = get_primes(LARGE_NUM)
sum_of_logs_of_primes = get_sum_of_logs_of_primes(primes)
print "Sum of logs: {}, n: {}, ratio: {}".format(sum_of_logs_of_primes,
LARGE_NUM, sum_of_logs_of_primes / LARGE_NUM)
|
43b97f9c198e7e45918642fb13bfb39df55527fa | irfankhan309/DS-AL | /Py_Codes/my_practice/python_series/test.py | 3,426 | 4.125 | 4 | import time
def hotel():
'''this hotel function is for booking the table with defined numbers as per requirement and taking input of from consumer
what he exactly requires\nwe have table numbers starts with 100 to 200 i.e..,\nwe have large space to book table as it containing 100 tables
starts with 100 and ends with 200
\nthanks for your interest'''
print("welcome to BlueRose Hotel")
table=int(input("enter your booked table to get your order now:"))
if table==100:
print("your family details:\n1.john\n2.alaska\n3.julie\n4.sam\n5.jonsen")
print("plese wait we check what you ordered!")
time.sleep(5)
print("hello sir, your table no is 100,\nyour order is roasted chicken,\nthanks")
elif table==101:
print("hai your selected table number is 101, your oreder will server with in 20 min as others also waiting!")
else:
print("sorry you have attempted wrong table number!")
def take_away():
print("please place an order:\npress the digits to order")
print("*"*50)
print("1.grilled chicken\n2.mutton chops\n3.manchuria\n4.noodles\n5.biryani\n6.mutton biryani")
print("*"*50)
order=int(input("select your dish:"))
if order==1:
order1=int(input("how many:"))
gc=200
time.sleep(5)
print("you have ordered grilled chicken:")
print("please pay the bill:",order1*gc)
print("thanks,visit again Blue Rose hotel!")
if order==2:
order2=int(input("enter how many plates of chops:"))
mc=150
time.sleep(5)
print("your orders is, mutton chops:")
print("please pay the bill:",order2*mc)
print("thanks,visit again Blue Rose hotel!")
if order==3:
order3=int(input("how many plates:"))
mnc=80
time.sleep(5)
print("your order is manchuria:")
print("please pay the bill:",order3*mnc)
print("thanks,visit again Blue Rose hotel!")
if order==4:
order4=int(input("how many plates noodles:"))
nd=70
time.sleep(5)
print("your oder is noodles:")
print("please pay at counter:",order4*nd)
print("thanks,visit again Blue Rose hotel!")
if order==5:
order4=int(input("how many plates biryani you want to order:"))
bi=180
print("your order is biryani,(",order4,")plates you have ordered:")
time.sleep(5)
print("please pay the bill:",order4*bi)
print("thanks,visit again Blue Rose hotel!")
if order==6:
order6=int(input("how many plates of mutton biryani:"))
mbi=280
print("you have ordered mutton biryani(",order6,")plates")
time.sleep(5)
print("please pay the bill:",order6*mbi)
print("thanks,visit again Blue Rose hotel!")
|
103ec4738bc045f7f76db1681173005058243904 | blackrain15/Machine_Learning_Basics | /Linear Regression_Gradient Descent/Linear Regression_Sample Implementation.py | 3,074 | 4.0625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Import the training dataset into a pandas dataframe. The training data has 2 variables x = Distance in KMs driven by a driver, y = Profit in $
mydata = pd.read_csv("ex1data1.txt", header = None)
#Plot the training data in a 2D graph to visualize the data spread
fig, axes = plt.subplots(nrows=2, ncols =1, figsize = (8,4))
axes[0].scatter(mydata.iloc[:,0], mydata.iloc[:,1])
axes[0].set_xlabel("Distance in KMs")
axes[0].set_ylabel("Profit in $")
axes[0].set_title("Distance vs. Actual Profit")
plt.tight_layout()
#Initial the values of co-efficients theta0 = intercept and theta1 = x1 co-efficient
thetas = np.random.rand(2)
#thetas.reshape(1,2)
#Initialize the hyper-parameter learning rate alpha with 0.01. Please fine tune the learning rate for optimal performance againsta different training set
alpha = 0.01
cost_series = []
counter = 0
#Iteratively find out the optimal values of x co-efficients until the cost function convergers
while(True):
counter = counter+1
#Cost = MSE = Mean of squared errors for the training set
cost = 0
for i in range(len(mydata)):
cost = cost + pow(((thetas[0]*mydata.iloc[i,0]+thetas[1])-mydata.iloc[i,1]),2) #Predicted value of Y = theta0+theta1*x1. The difference w.r.t. to the actual value of Y is squared (to avoid negative values pulling down the costs)
#Mean of Squared error is cost
cost = cost/len(mydata)
#Keeps track of cost valyes in each iteration
cost_series.append(cost)
#Using Gradient-descent principle, value of del_theta1 is calculated
del_theta1 = 0
for i in range(len(mydata)):
del_theta1 = del_theta1 + (((thetas[0]*mydata.iloc[i,0]+thetas[1])-mydata.iloc[i,1]))
del_theta1 = del_theta1*(2/len(mydata))
#Using Gradient-descent principle, value of del_theta0 is calculated
del_theta0 = 0
for i in range(len(mydata)):
del_theta0 = del_theta0 + (((thetas[0]*mydata.iloc[i,0]+thetas[1])-mydata.iloc[i,1])*mydata.iloc[i,0])
del_theta0 = del_theta0 * (2/len(mydata))
#theta values are update in line with G.D. formula
thetas[0] = thetas[0] - alpha * del_theta0
thetas[1] = thetas[1] - alpha * del_theta1
#Iteration stops when the change in cost functional is <0.001 i.e. the cost function has converged
if(counter>=2):
if(abs(cost_series[counter-2] - cost_series[counter-1])<0.0001): #The value 0.0001 can be changed based on implementation needs
break
#Plot how the cost values have changed over different iterations. This is important to analyze how the cost function has converged
axes[1].plot(cost_series)
axes[1].set_xlabel("# of iterations")
axes[1].set_ylabel("Cost")
axes[1].set_title("Cost vs. Iterations")
plt.tight_layout()
#Calculate the predicted valyes of as (w0 + w1*x1)
predict_y =[]
for i in range(len(mydata)):
predict_y.append(thetas[0]*mydata.iloc[i,0]+thetas[1])
#Plot the linear prediction line in the first graph
axes[0].plot(mydata.iloc[:,0], predict_y)
|
25f0502b6cb2a66dcfa3bfc7fc2aef9bf2404ab9 | adliaulia/Basic-Python-B4-C | /Pertemuan-4/dictionary.py | 231 | 4.21875 | 4 | #dictionary data tdk terurut, dapat diubah, dan memiliki index
dict = {"brand":"Ford","model":"Mustang","year":1964}
print(dict)
for x in dict:
print(x)
#change value
dict["year"] = 2021
print(dict)
x = dict["year"]
print(x) |
605658e533374eb2b3ad57dc932747dd711c0b48 | Aasthaengg/IBMdataset | /Python_codes/p02880/s442407760.py | 162 | 3.6875 | 4 | a = int(input())
f = False
for i in range(1,10):
for j in range(1,10):
if i*j == a:
f = True
if f:
print("Yes")
else:
print("No")
|
b7898ba2627d58b1c0925b535390676118f7db06 | romeorizzi/temi_prog_public | /2018.12.05.provetta/all-CMS-submissions-2018-12-05/2018-12-05.11:51:15.087870.VR437289.conta_inversioni.py | 627 | 3.53125 | 4 | """
* user: VR437289
* fname: ALVIANO
* lname: MASENELLI
* task: conta_inversioni
* score: 100.0
* date: 2018-12-05 11:51:15.087870
"""
# -*- coding: utf-8 -*-
# Template per la soluzione del problema conta_inversioni
from __future__ import print_function
import sys
if sys.version_info < (3, 0):
input = raw_input # in python2, l'equivalente di input è raw_input
def numero_di_inversioni(p):
w=0
for i in range (0,len(p)):
for j in range (i+1,len(p)):
if (p[i]>p[j]):
w=w+1
return w
p = list(map(int, input().strip().split()))
print(numero_di_inversioni(p))
|
1b55d13658a614199c02f8d8adce229bf3ef1ed1 | lmycd/leetcode | /leetcode/Find the Difference.py | 954 | 3.625 | 4 | """
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
"""
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
letters={}
for c in s:
letters[c]= letters[c]+1 if c in letters else 1
for c in t:
if c not in letters:
return c
else:
letters[c]-=1
if letters[c]<0:
return c
"""
算法思路:利用dict s的字母存入dict并且计数,然后遍历t的字母,出现一次相同的字母,value-1,value为负数即difference,没出现的字母就肯定是difference
或者对于s的每个字母在t中找返回的是下标,删掉找到的。留下的就是difference
""" |
43a2fcf1d49f1044cf9a146e4d9186aa86ac9676 | xpandi-top/ML-THUAUS | /a_overall_data.py | 1,715 | 3.859375 | 4 | """
数据的类型: 类别, 日期, 数值,ID
数据的分布:每个特征下的数据分布
数据之间的关系:correlation数据的类型: 类别, 日期, 数值,ID
数据的分布:每个特征下的数据分布
数据之间的关系:correlation
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
def general_describe(df):
"""
general describe about the data
:param df: data frame type
:return:
"""
df.head()
features = df.columns.tolist()
print('the number of features is ', len(features))
print('the features are \n', np.array(features))
print(df.dtypes)
def plot_hist(df, name=''):
"""
visualize the dataset hist data, if want to dip into the specific data ,use df['feature'].hist()
:param df:
:return:
"""
df.hist(xlabelsize=7, ylabelsize=7, figsize=(12, 10))
plt.savefig('./pic/'+name+'hist.png')
plt.show()
def correlation_map(df, name =''):
"""
correlation map for total data
notice: the df can only be number no text. so some unique type of values should be transformed first
:param df: data frame data
:return:
"""
colormap = plt.cm.RdBu
plt.figure(figsize=(14, 12))
plt.title('Pearson Correlation of Features', y=1.05, size=15)
sns.heatmap(df.astype(float).corr(), linewidths=0.1, vmax=1.0,
square=True, cmap=colormap, linecolor='white', annot=True)
plt.savefig('./pic/' + name + 'correlation_map.png')
plt.show()
if __name__ == '__main__':
filename = './data/under_sample_data.csv'
df = pd.read_csv(filename)
general_describe(df)
plot_hist(df)
correlation_map(df)
|
20edec4365350ab8c1c536acd84b6759325ac220 | samyhkim/algorithms | /121 - best time to buy and sell stock.py | 352 | 3.53125 | 4 | def maxProfit(prices):
if not prices:
return 0
min_price = prices[0]
max_profit = 0
for i in range(1, len(prices)):
min_price = min(min_price, prices[i])
max_profit = max(max_profit, prices[i] - max_profit)
return max_profit
print(maxProfit([7, 1, 5, 3, 6, 4]) == 5)
print(maxProfit([7, 6, 4, 3, 1]) == 0)
|
9d7e4ca0821bc374cccf5962fe051afd1f18b5e9 | flexgp/novelty-prog-sys | /src/PonyGE2/src/utilities/representation/python_filter.py | 739 | 3.8125 | 4 | def python_filter(txt):
""" Create correct python syntax.
We use {: and :} as special open and close brackets, because
it's not possible to specify indentation correctly in a BNF
grammar without this type of scheme."""
indent_level = 0
tmp = txt[:]
i = 0
while i < len(tmp):
tok = tmp[i:i+2]
if tok == "{:":
indent_level += 1
elif tok == ":}":
indent_level -= 1
tabstr = "\n" + " " * indent_level
if tok == "{:" or tok == ":}":
tmp = tmp.replace(tok, tabstr, 1)
i += 1
# Strip superfluous blank lines.
txt = "\n".join([line for line in tmp.split("\n")
if line.strip() != ""])
return txt
|
b56aadf481681d4ca69854217a239e241ba6b474 | nitinaggarwal1986/learnpythonthehardway | /ex16c.py | 1,206 | 4.75 | 5 | # To use the argv command to take the filename as the argument.
from sys import argv
# Taking filename as a parameter passed to the python script.
script, filename = argv
# To check with user if they want to overwrite the file mentioned.
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
# Wait to let the user hit CTRL-C if they do not wish to overwrite.
raw_input("?")
# To open the file mentioned by the filename.
print "Opening the file..."
target = open(filename, 'w')
# Truncating the file by deleting all its contents.
print "Truncating the file. Goodbye!"
target.truncate()
# Asking user to input the three lines that will go into the file.
print "Now I'm going to ask you for three lines."
# Getting the lines from the user one by one.
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
# Writing the lines into the file followed by the return.
print "I'm going to write these to the file."
input = "%r \n %r \n %r \n" % (
line1, line2, line3)
target.write(input)
# Closing the file after the writing job is done.
print "And finally, we close it."
target.close() |
05a6f105cbe24dec3a85aff65327b220eb70ecb2 | MAPLE-Robot-Subgoaling/IPT | /data/HW3/hw3_401.py | 716 | 4.15625 | 4 | def main():
temp = float(input("Please enter the temperature: "))
tempMeasure = input("Please enter 'C' for Celcius, or 'K' for Kelvin: ")
if tempMeasure=="C":
if temp<=0:
print("At this temperature, water is a (frozen) solid.")
elif temp>0 and temp<100:
print("At this temperature, water is a liquid.")
else:
print("At this temperature, water is a gas. ")
else:
if temp<=273.16:
print("At this temperature, water is a (frozen) solid.")
elif temp>273.16 and temp<373.16:
print("At this temperature, water is a liquid.")
else:
print("At this temperature, water is a gas.")
main()
|
8a6765506aa60bbab1bd60051ed7975848e1e811 | 1BM18CS114/ADA_LAB | /ass1.py | 1,265 | 3.53125 | 4 | ##Tower of hanoi
def toh(a, c, b, n):
if n == 1:
print("Move Block from {} to {}".format(a,b))
else:
toh(a, b, c, n - 1)
toh(a, c, b, 1)
toh(b, c, a, n - 1)
#toh("a", "b", "c", 3)
##GCD using recursion
def gcd(m, n):
if m == n:
print(m)
return
if m > n:
gcd(m - n, n)
else:
gcd(m, n - m)
#gcd(10, 2)
##Binary search
a = [1, 2, 3, 3, 3, 4, 5, 6]
length = 8
def search(key, a, length):
start1 = 0
end1 = length - 1
#while flag1 == 0 or flag2 == 0:
#if flag1 == 0:
#mid1 = (start + end) // 2
#if a[mid1] == key:
#if a[mid1] - a[mid1 - 1] != 0:
#print("First occrance is {}".format(mid1))
#flag = 1
#else:
#end1 = mid1 - 1
#elif a[mid1] > key:
#end1 = mid1 - 1
#else:
#start1 = mid1 + 1
while start1 < end1:
mid1 = (start1 + end1) // 2
if a[mid1] == key:
pos = mid1
elif a[mid1] > key:
end1 = mid1 - 1
elif a[mid1] < key:
start1 = mid1 + 1
start1 = end1 = pos
while key - a[start1] == 0 or key - a[end1] == 0:
if key - a[start1] == 0:
start1 -= 1
if key - a[end1] == 0:
end1 += 1
print("First pos is {}".format(start1))
print("End pos is {}".format(end1))
print("Count is {}".format(end1 - start1))
search(3, a, 8)
|
af08a3c0f75f20781de7e5b22f20af1592cd5b09 | Davitkhachikyan/HTI-1-Practical-Group-2-Davit-Khachikyan | /homework_5/is_palindrome.py | 270 | 4.21875 | 4 | def is_palindrome(word):
while len(word) != 0:
if word[0] == word[-1]:
word = word[1:-1]
is_palindrome(word)
else:
return "No"
return "Yes"
user_input = input("Enter a text")
print(is_palindrome(user_input))
|
89a6ee402450f535c585e82f964fd85294fd86ef | miaopei/MachineLearning | /LeetCode/github_leetcode/Python/escape-the-ghosts.py | 1,764 | 4.0625 | 4 | # Time: O(n)
# Space: O(1)
# You are playing a simplified Pacman game.
# You start at the point (0, 0), and your destination is (target[0], target[1]).
# There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]).
#
# Each turn, you and all ghosts simultaneously *may* move
# in one of 4 cardinal directions: north, east, west, or south,
# going from the previous point to a new point 1 unit of distance away.
#
# You escape if and only if you can reach the target before any ghost
# reaches you (for any given moves the ghosts may take.)
# If you reach any square (including the target) at the same time as a ghost,
# it doesn't count as an escape.
#
# Return True if and only if it is possible to escape.
#
# Example 1:
# Input:
# ghosts = [[1, 0], [0, 3]]
# target = [0, 1]
# Output: true
# Explanation:
# You can directly reach the destination (0, 1) at time 1,
# while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you.
#
# Example 2:
# Input:
# ghosts = [[1, 0]]
# target = [2, 0]
# Output: false
# Explanation:
# You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
# Example 3:
# Input:
# ghosts = [[2, 0]]
# target = [1, 0]
# Output: false
# Explanation:
# The ghost can reach the target at the same time as you.
#
# Note:
# - All points have coordinates with absolute value <= 10000.
# - The number of ghosts will not exceed 100.
class Solution(object):
def escapeGhosts(self, ghosts, target):
"""
:type ghosts: List[List[int]]
:type target: List[int]
:rtype: bool
"""
total = abs(target[0])+abs(target[1])
return all(total < abs(target[0]-i)+abs(target[1]-j) for i, j in ghosts)
|
348da7bf6f2fe6f5f49c5deddecb8bff389a35b6 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/421ec0af42d04ad4ad2c6d283b03ae26.py | 208 | 4.09375 | 4 | def word_count(phrase):
'''Returns dict with word counts for a given phrase.'''
count = {}
for word in phrase.split():
count.setdefault(word, 0)
count[word] += 1
return count
|
c0b0dc4cb349c9bfbdd5a4ab59fc3414ab370da5 | adheepshetty/leetcode-problems | /String/String to Integer.py | 1,809 | 3.953125 | 4 | #author: Adheep
import unittest
class Solution:
'''
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible,
and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect
on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either
str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
'''
def myAtoi(self, str):
str = str.strip()
if len(str) == 0: return 0
tmp = "0"
result = 0
i = 0
if str[0] in "+-":
tmp = str[0]
i = 1
MAX_INT = 2147483647
MIN_INT = -2147483648
for i in range(i, len(str)):
if str[i].isdigit():
tmp += str[i]
else:
break
if len(tmp) > 1:
result = int(tmp)
if result > MAX_INT > 0:
return MAX_INT
elif result < MIN_INT < 0:
return MIN_INT
else:
return result
class Test(unittest.TestCase):
def test_myAtoi(self):
s = "42 words 42"
expected = 42
sol = Solution()
self.assertEqual(sol.myAtoi(s),expected)
if __name__ == "__main__":
print(Solution.__doc__)
unittest.main() |
70fb879c448d9043713eb0a2945b790db0284f4e | lhf860/leetcode_python | /dynamic_programming_03/爬楼梯.py | 974 | 4.1875 | 4 | # coding:utf-8
"""
是一维动态规划的应用题
问题描述:
假设你正在爬楼梯,需要n阶才能到达楼顶,每次你可以爬1个或者2个台阶,你有多少种不同的方法可以爬到楼顶
思路:
若想爬到楼顶n处,只有两种可能:1)从n-1层楼顶向上爬一层, 这种只需要计算到达n-1层的方法数
2) 从n-2层向上爬2层,这种方法只需要计算爬n-2层的方法数,之后将二者相加即可。
计算到达n层的方法数=到达n-1层的方法数 + 到达n-2层的方法数;
计算n-1层的方法数=到达n-2层方法数 + 到达n-3层的方法数
......
包含重叠子问题,大的问题的解由小问题的解构成
"""
def climb_stairs(n):
count = [0, 1, 2]
for i in range(3, n+1):
count.append(count[i-1] + count[i-2])
return count[n]
n = 10 # 代表楼梯的层数
print(climb_stairs(n))
|
9b39a8a8288b323cfa818d7927c339ccf1ed2680 | akshit113/HackerRank-Practice-Problems | /love letter.py | 799 | 3.734375 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the theLoveLetterMystery function below.
def theLoveLetterMystery(s):
orig = s
if s == s[::-1]:
return 0
s = list(s)
left = ord(s[0])
right = ord(s[-1])
count = 0
cnt = 1
while right > left:
cnt += 1
right = right - 1
s[-1] = (chr(right))
print(s)
if s[::-1] == s:
break
while left > right:
cnt += 1
left = left - 1
s[-1] = (chr(left))
print(s)
if s[::-1] == s:
break
return cnt
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
result = theLoveLetterMystery(s)
print(str(result) + '\n')
|
b6bdd33d0758144123403146b43305d619d805cf | shun8800/CondigTestStudy | /PythonFunction/Sorting/sort_selection.py | 588 | 3.671875 | 4 | # 정렬 : 데이터를 특정한 기준에 따라 순서대로 나열하는 것
# 문제 상황에 따라서 적절한 정렬 알고리즘이 공식처럼 사용 됨
# 선택 정렬 : 처리되지 않은 데이터 중 가장 작은 데이터를 선택해 맨 앞의 데이터와 바꾸는 것
# 선택 정렬 : O(N^2)
array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]
for i in range(len(array)):
min_index = i
for j in range(i+1, len(array)):
if array[min_index] > array[j]:
min_index = j
array[i], array[min_index] = array[min_index], array[i]
print(array)
|
9c8a3729328aec5135afa1f713a930801745c79d | xiyiwang/leetcode-challenge-solutions | /2021-04/2021-04-28-uniquePathsWithObstacles.py | 1,042 | 3.921875 | 4 | """
LeetCode Challenge: Unique Paths II (2021-04-28)
A robot is located at the top-left corner of a m x n grid.
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid.
Now consider if some obstacles are added to the grids. How many
unique paths would there be?
An obstacle and space is marked as 1 and 0 respectively in the grid.
Constraints:
- m == obstacleGrid.length
- n == obstacleGrid[i].length
- 1 <= m, n <= 100
- obstacleGrid[i][j] is 0 or 1.
"""
from itertools import product
class Solution:
# runtime: O(mn)
def uniquePathsWithObstacles(self, obstacleGrid: list) -> int:
m, n = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
dp[0][0] = int(obstacleGrid[0][0] == 0)
for i, j in product(range(m), range(n)):
if obstacleGrid[i][j] == 1: continue
if i > 0: dp[i][j] += dp[i-1][j]
if j > 0: dp[i][j] += dp[i][j-1]
return dp[-1][-1]
|
e7615c060f5978bab50367d49a0fcee3db2e8033 | limianscfox/Python_learn | /Python_Crash_Cours_2rd/7/7.1/test_7_3.py | 153 | 4.28125 | 4 | num = input("please enter a number:")
if int(num) % 10 == 0:
print(f"{num} is Multiples of 10 !")
else:
print(f"{num} is not Multiples of 10 !")
|
16bab867ad7dcd837e4a3f051238a127dce3d1fa | IgnacioLoria1995/cursoPythonTest | /ejercicio2.py | 793 | 3.90625 | 4 | #programa de prueba II
clientes = int(input('Ingrese numero de clientes entre 1 y 120: '))
while clientes < 1 or clientes > 120:
print('por favor ingrese un numero entre 1 y 120')
clientes = int(input('Ingrese numero de clientes entre 1 y 120: '))
else:
for i in range(clientes):
print('cliente numero: '+str(i+1))
nombre = input('Ingrese nombre: ')
apellido = input('Ingrese apellido: ')
edad = int(input('Ingrese edad: '))
if edad <18:
condicion_edad = 'menor'
elif edad <65:
condicion_edad = 'mayor'
elif edad <120:
condicion_edad = 'jubiliado'
else:
condicion_edad = 'cadaver'
print('Su nombre es: '+nombre+' '+apellido+' '+'Y usted es '+condicion_edad)
|
55dd9013223f0678f63f4cc14e04cb817e857bac | danilobellini/wta2015 | /code/54_metaclass.py | 610 | 3.640625 | 4 | import sys
class Metaclass(type):
def __init__(cls, name, bases, namespace):
print("Initializing class {}\n"
"bases: {}\n"
"namespace: {}"
.format(name, bases, namespace))
if sys.version_info.major == 2: # Python 2
exec("""class M1(object): __metaclass__ = Metaclass""")
else: # Python 3
exec("""class M1(object, metaclass=Metaclass): pass""")
# Initializing class M1
# bases: (<class 'object'>,)
# namespace: {'__module__': '__main__', ...}
# Similar: M1 = Metaclass("M1", (object,), {})
# (mas o namespace resultante nem '__module__' possui)
|
035f30c36350af1644a9e69a834650148cdbca17 | AdamBures/ALGHORITHMS-PYTHON | /selection_sort.py | 310 | 3.890625 | 4 | def selectionSort(arr):
for i in range(len(arr)):
minimum = i
for j in range(i+1,len(arr)):
if arr[j] < arr[minimum]:
minimum = j
arr[minimum],arr[i] = arr[i], arr[minimum]
return arr
arr = [5,1,3,4,6,7]
print(selectionSort(arr))
|
7577861b457a184044a9daa6b3e6e6b2c80c6307 | patchgi/mitsuboshi | /app.py | 242 | 3.828125 | 4 | #coding:utf-8
import random
if __name__=="__main__":
result="000"
while result!="012":
rand=random.randint(0,2)
result=result[1:]+str(rand)
print(("燃やせ","友情","パッションは")[rand])
print ("ミツボシ☆☆★")
|
949b0d67dc7bdc024bb6c9d31ddf3954da858d58 | murphylan/python | /Parent.py | 766 | 3.96875 | 4 | class Parent: # 定义父类
parentAttr = 100
def __init__(self):
print ("调用父类的初始化方法")
def parentMethod(self):
print ('调用父类的方法')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print ("父类属性 :", Parent.parentAttr)
class Child(Parent): # 定义子类
def __init__(self):
print ("调用子类的初始化方法")
def childMethod(self):
print ('调用子类的方法')
c = Child() # 子类实例
c.childMethod() # 调用子类的方法
c.parentMethod() # 调用父类的方法
c.setAttr(200) # 通过基类的方法设置属性值
c.getAttr() # 通过基类的方法获取属性值
|
adc353e3b5ec35710c2f1824546e9ad77cc791b5 | raffg/supermarket_optimization | /supermarket_optimization.py | 3,768 | 3.875 | 4 | # This script identifies association rules based on existing records of
# buyer’s transactions at a supermarket. The input is a whitespace
# delimited data file, where each row records the SKU numbers of items
# in a single transaction. The script finds the most common items sold
# together. The set size for the common items is defined in the variable
# item_set_size, and a parameter 'sigma' defines the minimum number of
# occurances of each set to return. Default values are 3 for item_set_size
# and 4 for sigma.
import csv
import sys
from itertools import combinations
from collections import Counter
# model parameters
try:
filename = sys.argv[1]
except IndexError:
filename = 'retail_25k.dat'
try:
item_set_size = int(sys.argv[2])
except IndexError:
item_set_size = 3
try:
sigma = int(sys.argv[3])
except IndexError:
sigma = 4
def main():
# Run through the data pipeline
print('Opening file...')
with open(filename, 'r') as f:
data = [line.rstrip().split() for line in f]
print('Finding all sets... ')
sets = find_combos(data, item_set_size)
print('Counting all unique combinations...')
counter = count_combos(sets)
print('Formatting output...')
output = format_output(counter, item_set_size, sigma)
print('Saving file...')
with open("output.csv", "w") as f:
writer = csv.writer(f)
writer.writerows(output)
print('Complete')
def find_combos(data, item_set_size=3):
'''
Takes a list-of-lists and a set size parameter; for each sublist finds all
combinations of elements of length item_set_size, and returns a list of
the lists of combinations.
Input: [[1, 2, 3], [1, 2, 4]], 2
Output: [[(1, 2), (1, 3), (2, 3)], [(1, 2), (2, 4), (1, 4)]]
'''
sets = []
for line in data:
sets.append(list(set(combinations(line, item_set_size))))
return sets
def count_combos(sets):
'''
Takes a list-of-lists of combination sets, flattens the lists, and
returns a list of tuples of all combinations and frequencies,
sorted in order of frequency.
Input: [[(1, 2), (1, 3), (2, 3)], [(1, 2), (2, 4), (1, 4)]]
Output: [((1, 2), 2), ((1, 3), 1), ((2, 3), 1), ((2, 4), 1), ((1, 4), 1)]
'''
flattened = [elem for sublist in sets for elem in sublist]
return Counter(flattened).most_common()
def format_output(counter, item_set_size, sigma):
'''
Takes a flattened list of tuples of combinations and frequencies,
the item_set_size (corresponding to the length of the combinations),
and a sigma parameter defining the minimum frequency to return.
Adds a header row and formats the data into a list-of-lists where each
row takes the form:
<item set size (N)>, <co-occurrence frequency>,
<item 1 id >, <item 2 id>, …. <item N id>
Input: [((1, 2), 2), ((1, 3), 1), ((2, 3), 1), ((2, 4), 1), ((1, 4), 1)],
3,
1
Output (excluding header): [[3, 2, 1, 2],
[3, 1, 1, 3],
[3, 1, 2, 3],
[3, 1, 2, 4],
[3, 1, 1, 4]]
'''
# define header
output = [['item set size (N)', 'co-occurrence frequency']]
output[0].extend(['item {} id'.format(N + 1)
for N in range(item_set_size)])
# format and append each row
for item_set in counter:
if item_set[1] >= sigma:
row = [item_set_size, item_set[1]]
row.extend(item_set[0])
output.append(row)
else:
# function takes sorted input so we can stop once sigma is reached
return output
return output
if __name__ == "__main__":
main()
|
9c060bf97546ed6ca73ab89befe16b642ebdf7ef | candido00/Python | /Python Exercicios/lerParImpar.py | 336 | 3.96875 | 4 | num = int
numeros = []
count1 = 0
count2 = 0
while(num != -1):
num = int(input("INFORME UM NUMERO OU( -1 ) PARA ENCERRAR: "))
numeros.append(num)
for x in(numeros):
if(x % 2 == 0 and x != 0):
count1 += 1
elif(x % 2 !=0 and x != -1):
count2 += 1
print("PARES: ",count1)
print("IMPARES: ",count2)
|
4f52f88a3c45582df6693400b93596fddc1ef965 | anthony-frion/Flow-shop-heuristics | /heuristics.py | 10,826 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 3 16:56:13 2020
@author: Anthony
"""
import random
import ordonnancement as o
import flowshop as f
import numpy as np
# schedules jobs according to a sequence and returns the corresponding length
def evaluate(sequence, nb_machines) :
ordo = o.Ordonnancement(nb_machines)
ordo.ordonnancer_liste_job(sequence)
return ordo.duree()
# creates a random scheduling and prints its information
"""def random_scheduling(F) :
sequence = []
while F.l_job != [] :
sequence.append(F.l_job.pop(random.randint(0, len(F.l_job) - 1)))
ordo = o.Ordonnancement(F.nb_machines)
ordo.ordonnancer_liste_job(sequence)
ordo.afficher()
print("The length of this scheduling is {}".format(evaluate(sequence, F.nb_machines)))"""
# Simple test of the 'evaluate' and 'random_scheduling' functions
"""F = f.Flowshop()
F.definir_par("jeu2.txt")
random_scheduling(F)"""
#####################################################"
# Useful auxilary functions
def fst(couple):
a, b = couple
return a
def snd(couple):
a, b = couple
return b
# schedules jobs according to a sequence and returns the corresponding length
def evaluate(sequence, nb_machines):
ordo = o.Ordonnancement(nb_machines)
ordo.ordonnancer_liste_job(sequence)
time = ordo.duree()
return time
# creates a random sequences from the jobs given in the flowshop F
def random_sequence(F):
sequence = []
jobs = [J for J in F.l_job]
while jobs != []:
sequence.append(jobs.pop(random.randint(0, len(jobs) - 1)))
return sequence
# creates a random scheduling and prints its information
def random_scheduling(F):
sequence = random_sequence(F)
ordo = o.Ordonnancement(F.nb_machines)
ordo.ordonnancer_liste_job(sequence)
ordo.afficher()
print("The length of this scheduling is {}".format(evaluate(sequence, F.nb_machines)))
return sequence
# Swaps the two elements at the given indexes
def swap(sequence, index1, index2):
copy = [J for J in sequence]
copy[index1], copy[index2] = sequence[index2], sequence[index1]
return copy
# Inserts the element index2 at the position index1
def insert(sequence, index1, index2):
copy = [J for J in sequence]
if index1 > index2:
index1, index2 = index2, index1
copy[index1] = sequence[index2]
for k in range(index1 + 1, index2 + 1):
copy[k] = sequence[k - 1]
return copy
# Gets a random neighbour with the swap and insertion operators
def random_neighbour(sequence):
index1, index2 = random.randint(0, len(sequence) - 1), random.randint(0, len(sequence) - 1)
while index2 == index1:
index2 = random.randint(0, len(sequence) - 1)
if random.randint(0, 1) == 0:
return swap(sequence, index1, index2)
else:
return insert(sequence, index1, index2)
# Computes the simulated annealing and returns a sequence of jobs and the associated time
# For each iteration the temperature is multiplied by the 'temperature_multiplier' parameter
# Once the temperature is under the 'final_temperature' parameter, the algorithm stops
def recuit(F, initial_temperature, temperature_multiplier, final_temperature) :
sequence = random_sequence(F)
time = evaluate(sequence, F.nb_machines)
temperature = initial_temperature
while temperature >= final_temperature :
nei_seq = random_neighbour(sequence)
nei_time = evaluate(nei_seq, F.nb_machines)
if nei_time <= time or random.random() <= np.exp((time - nei_time) / temperature):
sequence = nei_seq
time = nei_time
temperature *= temperature_multiplier
return sequence, time
# Auxilary function for the 'one cut point' reproduction from the left
def LeftAuxReproduction1(seq1, seq2, cut_point, F):
n = len(seq1)
first_part = seq1[:cut_point]
child_seq = first_part
for k in range(cut_point, n):
if seq2[k] not in first_part:
child_seq.append(seq2[k])
for i in range(cut_point):
if seq2[i] not in child_seq:
child_seq.append(seq2[i])
time = evaluate(child_seq, F.nb_machines)
return child_seq, time
# Auxilary function for the 'one cut point' reproduction from the right
def RightAuxReproduction1(seq1, seq2, cut_point, F):
n = len(seq1)
child_seq = [J for J in seq2]
first_part = seq1[cut_point:]
ind=cut_point
for k in range(cut_point):
if seq1[k] not in first_part:
ind-=1
child_seq[ind]=seq1[k]
child_seq1=child_seq[ind:]
for i in range(cut_point,n):
if seq1[i] not in child_seq1:
ind-=1
child_seq[ind]=seq1[i]
time = evaluate(child_seq, F.nb_machines)
return child_seq, time
# Random reproduction of two sequences with one cut point
def Leftreproduction1(seq1, seq2, F):
cut_point = random.randint(0, len(seq1) - 1)
return LeftAuxReproduction1(seq1, seq2, cut_point, F)
# Best possible reproduction of two sequences with one cut point
def bestReproduction1(seq1, seq2, F):
best_child = seq1
best_time = 100000
for cut_point in range(len(seq1)):
child_seq, time = LeftAuxReproduction1(seq1, seq2, cut_point, F)
if time < best_time:
best_time = time
best_child = child_seq
child_seq, time = RightAuxReproduction1(seq1, seq2, cut_point, F)
if time < best_time:
best_time = time
best_child = child_seq
return best_child, best_time
# Auxilary function for the 'two cut points' reproduction
def auxReproduction2(seq1, seq2, cut_point1, cut_point2, F):
first_part = seq1[:cut_point1]
last_part = seq1[cut_point2:]
mid_part = []
for J in seq2[cut_point1: cut_point2]:
if J not in first_part and J not in last_part:
mid_part.append(J)
for J in seq1[cut_point1: cut_point2]:
if J not in mid_part:
mid_part.append(J)
child_seq = first_part + mid_part + last_part
time = evaluate(child_seq, F.nb_machines)
return child_seq, time
# Random reproduction of two sequences with two cut points
def reproduction2(seq1, seq2, F):
cut_point1, cut_point2 = 0, 0
while cut_point1 >= cut_point2:
cut_point1, cut_point2 = random.randint(0, len(seq1) - 1), random.randint(0, len(seq1) - 1)
return auxReproduction2(seq1, seq2, cut_point1, cut_point2, F)
# Best possible reproduction of two sequences with two cut points
def bestReproduction2(seq1, seq2, F):
best_child = seq1
best_time = 100000
for cut_point1 in range(1, len(seq1) - 1):
for cut_point2 in range(cut_point1 + 1, len(seq1) - 1):
child_seq, time = auxReproduction2(seq1, seq2, cut_point1, cut_point2, F)
if time < best_time:
best_time = time
best_child = child_seq
return best_child, best_time
# Tries n random reproductions with two cut points (n being the number of jobs)
# This is much faster than trying all the possibilities with two cut points as there are about n**2 possibilities
def bestOfNReproduction2(seq1, seq2, F) :
best_child = seq1
best_time = 100000
cut_point1, cut_point2 = 0, 0
for k in range(len(seq1)) :
while cut_point1 >= cut_point2 :
cut_point1, cut_point2 = random.randint(0, len(seq1) - 1), random.randint(0, len(seq1) - 1)
child_seq, time = auxReproduction2(seq1, seq2, cut_point1, cut_point2, F)
if time < best_time :
best_time = time
best_child = child_seq
return best_child, best_time
# Generates an initial population of solutions with the simulated annealing,
# Then makes them reproduce themselves following a 'binary tree' structure :
# Each generation is half the size of the previous one
def binaryTreeReproductions(initialPopulation, reproductionAlgorithm):
recuits = []
for k in range(initialPopulation):
sequence, time = recuit(F, 5, 0.99, .1)
recuits.append((sequence, time))
print([snd(x) for x in recuits], min([snd(x) for x in recuits]))
population = recuits
while len(population) > 1:
new_population = []
for k in range(len(population) // 2):
new_population.append(reproductionAlgorithm(fst(population[2 * k]), fst(population[2 * k + 1]), F))
population = new_population
print(population[0])
# Creates an initial population through annealing, then reduces it to one solution
# At each step it seeks a good possible reproduction between the first element of the population and the others
# Then it kills the parents and adds the new found solution to the population
# The goal is to reduce the time, so it always looks for reproductions which the child is better than both the parents
def seekBestReproductions(initialPopulation, reproductionAlgorithm):
recuits = []
for k in range(initialPopulation):
sequence, time = recuit(F, 5, 0.99, .1)
recuits.append((sequence, time))
print([snd(x) for x in recuits], min([snd(x) for x in recuits]))
population = recuits
print(population)
while len(population) > 1:
best_child, best_time = population[0]
best_parent = 1
for k in range(1, len(population)):
child, time = reproductionAlgorithm(fst(population[0]), fst(population[k]), F)
if time < best_time and time < snd(population[k]) and time < snd(population[0]):
best_time = time
best_child = child
best_parent = k
print("Obtaining time {} from parents of times {} and {}".format(best_time, snd(population[0]),
snd(population[best_parent])))
if best_parent != 1 :
population.pop(best_parent)
population.pop(0)
elif len(population) > 2 :
population.pop(0)
to_remove = 0
for k in range(len(population)) :
if snd(population[k]) > snd(population[to_remove]) :
to_remove = k
population.pop(to_remove)
else :
if snd(population[0]) <= snd(population[1]) :
population.clear()
else :
population.pop(0)
population.append((best_child, best_time))
print(population[0])
# Tests
F = f.Flowshop()
F.definir_par("jeu3.txt")
seekBestReproductions(200, bestReproduction1)
#Test Timo
|
150734135781073166497c06bb3a981f620d576a | coderFH/python | /stage-01/13-python文件操作/14-python文件练习.py | 2,119 | 3.59375 | 4 | # #实现文件的复制操作
# sourceFile = open("a.txt","r",encoding="utf-8")
# desFile = open("a_dat.txt","a",encoding="utf-8")
#
# while True:
# content = sourceFile.read(1024)
# if len(content) == 0:
# break
# desFile.write(content)
#
# sourceFile.close()
# desFile.close()
#
# print("==================================2.按文件名不同,划分到不同的文件夹====")
# #0, 获取所有的文件名称列表
# import os
# import shutil
#
# path = "files"
#
# if not os.path.exists(path):
# exit()
#
# os.chdir(path)
#
# file_list = os.listdir("./")
#
# # 1. 遍历所有的文件(名称)
# for file_name in file_list:
# # print(file_name)
# # 2. 分解文件的后缀名
# # 2.1 获取最后一个.的索引位置 xx.oo.txt
# index = file_name.rfind(".")
# if index == -1:
# continue
# # print(index)
# # 2.2 根据这个索引位置, 当做起始位置, 来截取后续的所有字符串内容
# extension = file_name[index + 1:]
# print(extension)
#
# # 3. 查看一下, 是否存在同名的目录
# # 4. 如果不存在这样的目录 -> 直接创建一个这样名称的目录
# if not os.path.exists(extension):
# os.mkdir(extension)
#
# shutil.move(file_name, extension)
print("====================================3.生成txt格式的文件清单====")
import os
# 通过给定的文件夹, 列举出这个文件夹当中, 所有的文件,以及文件夹, 子文件夹当中的所有文件
def listFilesToTxt(dir, file):
# 1. 列举出, 当前给定的文件夹, 下的所有子文件夹, 以及子文件
file_list = os.listdir(dir)
# 2. 针对于, 列举的列表, 进行遍历
for file_name in file_list:
new_fileName = dir + "/" + file_name #files/avi
# 判定, 是否是目录, listFiles
if os.path.isdir(new_fileName): #是目录
file.write(new_fileName + "\n")
listFilesToTxt(new_fileName, file)
else:
file.write("\t" + file_name + "\n")
file.write("\n")
f = open("list.txt", "a")
listFilesToTxt("files", f)
|
32e3a62408e671df28a234f828c51aba2ed1421e | erknuepp/CIS2348 | /Homework2/HW2Zy910.py | 407 | 3.8125 | 4 | # Lauren Holley
# 1861058
import csv
frequency = {}
file = input()
with open(file, 'r') as csvfile:
word_reader = csv.reader(csvfile, delimiter=',')
for row in word_reader:
for word in row:
if word not in frequency.keys():
frequency[word] = 1
else:
frequency[word] +=1
for word in frequency:
print(word, frequency[word]) |
782a1671833d187c6e169815d68240d60d80c933 | amarasm/KidEd | /KidEdCat.py | 4,640 | 4.09375 | 4 | #User Story 1: As a user I can choose a category and based on what I’ve chosen I will be able to learn it.
import json
import random
def loadCateg():
with open('Categories.json') as data_file:
file = json.load(data_file)
categ = file["categories"]
return categ
def AskToChooseACateg(categ):
print ("\nDear user, please choose a category from", (", ").join(categ.keys()))
chosenCateg = input("Category:")
return chosenCateg
def randomCategKey(chosenCateg, categ):
with open('Categories.json') as data_file:
file = json.load(data_file)
while True:
if chosenCateg == "animals":
print("\nHow many animals do you want to learn today?Your maximum is 25")
while True:
number = input("Number of animals you want to learn today:")
if number.isnumeric():
number = int(number)
if number < 26:
break
else:
print("oops!You have to type a number from 1 to 25!Now try again!")
else:
print("Please insert numbers only:)")
numberlist = []
for keys in file["categories"]["animals"].keys():
numberlist.append(keys)
yourchoices = random.choices(numberlist, k=number)
for number in yourchoices:
print("Its name is", number, ", its sound is", file["categories"]["animals"][number]["sound"],"and it's a type of", file["categories"]["animals"][number]["kind"], ".")
break
elif chosenCateg == "colors":
print("\nHow many colors do you want to learn today?Your maximum is 10")
while True:
number = input("Number of colors you want to learn today:")
if number.isnumeric():
number = int(number)
if number < 11:
break
else:
print("oops!You have to type a number from 1 to 10!Now try again!")
else:
print("Please insert numbers only:)")
numberlist = []
for keys in file["categories"]["colors"].keys():
numberlist.append(keys)
yourchoices = random.choices(numberlist, k=number)
for number in yourchoices:
print(number)
break
elif chosenCateg == "alphabet":
print("\nHow many letters do you want to learn today?Your maximum is 26")
while True:
number = input("Number of letters you want to learn today:")
if number.isnumeric():
number = int(number)
if number < 27:
break
else:
print("oops!You have to type a number from 1 to 26!Now try again!")
else:
print("Please insert numbers only:)")
numberlist = []
for keys in file["categories"]["alphabet"].keys():
numberlist.append(keys)
yourchoices = random.choices(numberlist, k=number)
for number in yourchoices:
print("the lowercase is",number, "the uppercase is", file["categories"]["alphabet"][number]["upperCase"], ". For example:", file["categories"]["alphabet"][number]["example"])
break
elif chosenCateg == "numbers":
print("\nHow many numbers do you want to learn today?Your maximum is 10")
while True:
number = input("Number of numbers you want to learn today:")
if number.isnumeric():
number = int(number)
if number < 11:
break
else:
print("oops!You have to type a number from 1 to 10!Now try again!")
else:
print("Please insert numbers only")
numberlist = []
for key in file["categories"]["numbers"].keys():
numberlist.append(key)
yourchoices = random.choices(numberlist, k=number)
for number in yourchoices:
print(number, " - ", file["categories"]["numbers"][number]["name"])
break
else:
print("Oh wait you chose wrong!")
chosenCateg = AskToChooseACateg(categ)
def main():
categorySetup = loadCateg()
chosenCategory = AskToChooseACateg(categorySetup)
randomCategKey(chosenCategory, categorySetup)
main()
|
e581f4e834f21985baf4413b4172b6ad1b179220 | GRE-EXAMINATION/UCTB | /UCTB/utils/multi_threads.py | 2,657 | 3.703125 | 4 | import os
from multiprocessing import Pool, Manager
from functools import reduce
# (my_rank, n_jobs, dataList, resultHandleFunction, parameterList)
def multiple_process(distribute_list, partition_func, task_func, n_jobs, reduce_func, parameters):
"""
Args:
distribute_list(list): The "data" list to be partitioned, such as a list of files which will be
distributed among different tasks and each task process a part of the files.
partition_func(function): Partition function will be used to cut the distribute_list, it should accept
three inputs: distribute_list, i, n_job, where i is the index of jobs (i.e. integer from 0 to n_jobs-1),
n_jos is the number of threads; partition function should return a data_list for the job_i
task_func(function): Task function, where the inputs are share_queue, locker, data, parameters, no return.
pls refer to the DiDi-Data processing codes for more information.
n_jobs(int): Number of threads
reduce_func(function): Reduce function which combine the outputs from all the threads into one final output.
parameters(list): parameters send to the task function
"""
if callable(partition_func) and callable(task_func) and callable(reduce_func):
print('Parent process %s.' % os.getpid())
manager = Manager()
share_queue = manager.Queue()
locker = manager.Lock()
p = Pool()
for i in range(n_jobs):
p.apply_async(task_func, args=(share_queue, locker, partition_func(distribute_list, i, n_jobs),
[i] + parameters,))
print('Waiting for all sub_processes done...')
p.close()
p.join()
print('All sub_processes done.')
result_list = []
while not share_queue.empty():
result_list.append(share_queue.get_nowait())
return reduce(reduce_func, result_list)
else:
print('Parameter error')
"""
# Example
def task(share_queue, locker, data, parameters):
print('Child process %s with pid %s' % (parameters[0], os.getpid()))
result = sum(data)
locker.acquire()
share_queue.put(result)
locker.release()
if __name__ == "__main__":
data = [e for e in range(1000000)]
n_job = 4
sum_result = \
multiple_process(distribute_list=data,
partition_func=lambda data, i, n_job: [data[e] for e in range(len(data)) if e % n_job == i],
task_func=task, n_jobs=n_job, reduce_func=lambda x, y: x + y, parameters=[])
print('Result', sum_result)
""" |
970910d5ea6cb2fb4acdbe100cd5f2b4defe9c77 | VPoint/PythonExperiments | /D3-Lists/d3q1.py | 955 | 4.09375 | 4 | # Cette programme affiche le nombre des valeurs positives ( alors, strictement plus grande
# que zero) dans un liste donné par l'utilisateur.
def positive(l):
''' paramètres (un liste) et retourne un entier
Cet fonction utilise un boucle pour parcourir la liste donnée et compter le nombre
des valeurs positives.'''
num = 0
for x in l:
# Cet boucle parcours le liste et compare chaque élément
# avec zéro pour verifier si l'élément est positive
if float(x) > 0:
# Si l'élément est plus grande que zéro, le compteur ajoute un.
num += 1
return num
# Ici, la program demande l'utilisateur pour une liste et convertit la chaîne des
# charactères retournée par 'input' dans une liste
liste = list(eval(input("Veuillez entrer une liste des valeurs separees par virgules: ")))
# La programme affiche le nombre des entiers positives dans la liste.
print(positive(liste))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.