blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
2a70f3d9a30a8aa866f76e4f8b7918712546c4e4
dastous/HackerRank
/Problem Solving/Picking Numbers
795
3.734375
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'pickingNumbers' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def pickingNumbers(a): # Write your code here l= len(a) c=[] max_len = [] for i in range(l): c.append([]) for j in range(l): if a[i] == a[j] or a[i]+1== a[j]: c[i].append(a[j]) for i in range(l): max_len.append(len(c[i])) return max(max_len) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) a = list(map(int, input().rstrip().split())) result = pickingNumbers(a) fptr.write(str(result) + '\n') fptr.close()
7b0a0b129a5a3f766a6366b491aeb96a11697632
ZaderRox1111/Turtle-Trajectory
/lab1_improved.py
598
3.859375
4
import turtle from math import sin, cos, pi, radians def main(): #turtles ezekiel = turtle.Turtle() turtle.Screen().delay(0) turtle.setworldcoordinates(-100, -300, 600, 300) trajectory(ezekiel, 50, 60, 'red') turtle.exitonclick() def trajectory(turtle, launchVel, launchAngle, color): launchAngle = radians(launchAngle) G = 9.81 totalTimeSteps = 20 turtle.color(color) for t in range(0, totalTimeSteps): x = launchVel * t * cos(launchAngle) y = launchVel * t * sin(launchAngle) - 0.5 * G * t**2 turtle.goto(x, y) main()
e3d05dcc9ea2a7f98b1ca4116855cb9566e43b73
mari00008/Python_Study
/Python_study/8.モジュールによるPythonの機能の拡張/2.detetimeモジュール(日付と時刻を扱うクラス).py
2,773
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[3]: #モジュールをインポート import datetime #datetime.dateクラスのインスタンス作成 #2018年10月15日 x = datetime.date(2018,10,15) #xのデータを表示 print("日付:",x) #xのクラスを表示 print("クラス:",type(x)) #インスタンス変数を使って年月日を表示 print(x.year,"年",x.month,"月",x.day,"日") # In[4]: #datetimeモジュールをインポート import datetime #datetime.timeクラスのインスタンスを作成 #15時42分19秒 x = datetime.time(15,42,19) #xのもつデータを表示 print("時刻:",x) #xのクラスを表示 print("クラス:",type(x)) #インスタンス変数を使って時刻表示 print(x.hour,"時",x.minute,"分",x.second,"秒") # In[8]: import datetime #datetimeオブジェクトのnowメソッドでリアルタイムを取得 x = datetime.datetime.now() #xの持つデータを表示 print("日付と時刻:",x) #インスタンス変数を使って年月日 print(x.year,"年",x.month,"月",x.day,"日") #インスタンス変数を使って時刻表示 print(x.hour,"時",x.minute,"分",x.second,"秒") print(x.timetuple()) # In[9]: import datetime x = datetime.date(2018,11,21) y = datetime.date(2018,11,20) print(x-y) print(type(x-y)) # In[10]: import datetime x = datetime.date(2018,5,10) dx = datetime.timedelta(100) #100日後の日付を表示 print(x + dx) # In[11]: #weekdayは0が月曜日、6が日曜日 import datetime x = datetime.date(2020,3,22) #曜日番号の取得 print(x.weekday()) # In[12]: import datetime dt = datetime.timedelta(1) x = datetime.date(2020,3,22) for k in range(7): x += dt print(x,"曜日番号",x.weekday()) # In[13]: import datetime dweek =["月","火","水","木","金","土","日"] dt = datetime.timedelta(1) #起点日時 x = datetime.date(2020,3,22) #日付と曜日の表示 for k in range(7): x += dt print(x,dweek[x.weekday()]) # In[14]: import datetime #datetime.datetimeクラスのインスタンスを作成 #2018/5/8/17/2/9 x = datetime.datetime(2018,5,8,17,2,9) #西暦4桁、月2桁、日2桁 print("{:%Y/%m/%d}".format(x)) # 西暦を2桁、月を下2桁、日を下2桁で表示 print("{:%y/%m/%d}".format(x)) # 時を24時間表記、分を2桁、秒を2桁で表示 print("{:%H:%M:%S}".format(x)) # 時を12時間表記、分を2桁、秒を2桁で表示 print("{:%I:%M:%S}".format(x)) # AM,PMの表記、時を12時間表記、分を2桁、秒を2桁で表示 print("{:%p%I:%M:%S}".format(x)) # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]: # In[ ]:
2337edd74e767d8a1d7b821c32100258f0424390
razoowp/Numpy
/vector-matrix-creation.py
484
4.125
4
# A 1-dimensional array is refferred to as Vector and 2-dimensional array is # reffered to as matrix #Question/Instructions ''' - Create a vector from the list [10, 20, 30]. Assign the result to the variable vector. - Create a matrix from the list of lists [[5, 10, 15], [20, 25, 30], [35, 40, 45]]. Assign the result to the variable matrix. ''' import numpy as np vector = np.array([10, 20, 30]) matrix = np.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
748227c2e645a59c7853fe05dd91f384018158c1
sampletest2019/python_practice
/selenium/test_function.py
190
3.5
4
# def add_two_numbers(num1, num2): # return num1 + num2 # # print(add_two_numbers(50,14)) # lambda # anonymous function two_num = lambda num1, num2: num1 + num2 print(two_num(56, 10))
51f12bf91ab4c0b1cacfea38be1825b79d600a08
pmacking/yahtzee-cli
/yahtzee/fileio.py
12,221
3.671875
4
#!python3 """ This module controls file input/output of yahtzee score files. github.com/pmacking/fileio.py """ import os from pathlib import Path import docx def print_fileio_confirmation(file_dir_str, file_name): """ Prints confirmation message when file creation completed. :param file_dir_str: textfile directory as string :param file_name: textfile basename """ print(f"\nSaved file: '{file_dir_str}/{file_name}'") class FileWriter: """ Objects instantiated by :class: `FileWriter <FileWriter>` can be called as a factory to write file as output per file formats. """ # attributes specified for docx only to enable passing to pdf conversion def __init__(self): self.docxfile_dir_str = '' self.docx_filename = '' def __repr__(self): return f"{self.__class__.__name__}()" def write_file(self, datetime_today, game_counter, players_list, ranking_dict, file_formats): """ The write_file method creates instances of each file_format, including creating Path, filename, and writing or converting files. :param datetime_today: The datetime today as string. :param game_counter: The count of the game as int. :param players_list: The list of player instances. :param ranking_dict: The ranking dictionary for the current round. :param file_formats: The file formats to write as list. """ # create class and write file for each format in file_formats for file_format in file_formats: if file_format == 'txt': textfile = TextFile() # create textfile directory textfile.create_textfile_dir() # create textfile basename textfile.create_textfile_name(game_counter, datetime_today) # write textfile textfile.write_textfile(game_counter, players_list, ranking_dict) elif file_format == 'docx': docxfile = DocxFile() # create docx directory and set locally for pdf convert self.docxfile_dir_str = docxfile.create_docxfile_dir() # create docx basename and set locally for pdf convert self.docx_filename = docxfile.create_docx_filename( game_counter, datetime_today) # write docxfile docxfile.write_docxfile(game_counter, players_list, ranking_dict) # REMOVED: ISSUES WITH MSFT WORD and NOT SUPPORTED ON LINUX # elif file_format == 'pdf': # # PDF instance in fileio.py # pdffile = PdfFile() # # create pdf file directory # pdffile.create_pdffile_dir() # # create pdf file basename # pdffile.create_pdf_filename(game_counter, datetime_today) # # convert docx to pdf # pdffile.convertDocxToPdf(self.docxfile_dir_str, # self.docx_filename) class TextFile: """ Objects instantiated by the :class:`TextFile <Textfile>` can be called to create a textfile of players and scores. """ def __init__(self): self.relative_path = 'data/textfiles' self.textfile_dir_str = '' self.textfile_name = '' def __repr__(self): return (f"{self.__class__.__name__}(" f"{self.textfile_dir_str}, {self.textfile_name})") def create_textfile_dir(self): """ Create textfiles folder. """ os.makedirs(Path.cwd() / f'{self.relative_path}', exist_ok=True) self.textfile_dir_str = str(Path.cwd() / f'{self.relative_path}') def create_textfile_name(self, game_counter, datetime_today): """ Create textfile filename with datetime and game number. :param game_counter: integer count of games played. :param datetime_today: date str to standardize output file basename. """ self.textfile_name = f"{datetime_today}Game{game_counter + 1}.txt" def write_textfile(self, game_counter, players_list, ranking_dict): """ Writes players scores to textfile. :param game_counter: integer count of games played. :param players_list: list of Player class instances. :param ranking_dict: ranking of players and grand total scores. """ with open(f'{self.textfile_dir_str}/{self.textfile_name}', 'w') as f: f.write(f'YAHTZEE GAME {game_counter+1}'.center(21)) f.write('\n') f.write('FINAL RANKINGS'.center(21)) f.write('\n') # write ranking of all players to file f.write(f"{'-'*21}") f.write('\n') for k, v in enumerate(ranking_dict): f.write(f"{v[0]}:".ljust(18) + f"{v[1]}".rjust(3)) f.write('\n') # enumerate players and write scores to file for j, player in enumerate(players_list): f.write(f"\n{'-'*21}") f.write(f"\n{'-'*21}\n") f.write(f"{players_list[j].name.upper()} " f"FINAL SCORES".center(21)) f.write('\n\n') f.write(f"ROLL SCORES".rjust(19)) # write player's score dictionary to file output_score_dict = players_list[j].get_score_dict() for i, k in enumerate(output_score_dict): f.write(f"\n{k.rjust(15)}: {output_score_dict[k]}") # write top, total, and grand total scores to file f.write(f"\n{'-'*21}\n") f.write(f"{'TOP SCORE BONUS'.rjust(19)}\n") f.write(f"Top Score: {players_list[j].get_top_score()}" f"\n".rjust(20)) f.write(f"Top Bonus Score: " f"{players_list[j].get_top_bonus_score()}\n".rjust(20)) f.write(f"\n{'TOTAL SCORES'.rjust(19)}\n") f.write(f"Total Top: " f"{players_list[j].get_total_top_score()}\n".rjust(20)) f.write(f"Total Bottom: " f"{players_list[j].get_total_bottom_score()}" f"\n".rjust(20)) f.write(f"{'-'*21}\n") f.write(f"GRAND TOTAL: " f"{players_list[j].get_grand_total_score()}".rjust(19)) f.write('\n') # print file creation confirmation print_fileio_confirmation(self.textfile_dir_str, self.textfile_name) class DocxFile: """ Objects instantiated by the :class:`DocxFile <DocxFile>` can be called to create a docx file of players and scores. """ def __init__(self): self.relative_path = 'data/docxfiles' self.docxfile_dir_str = '' self.docx_filename = '' def __repr__(self): return (f"{self.__class__.__name__}(" f"{self.docxfile_dir_str}, {self.docx_filename})") def create_docxfile_dir(self): """ Create docxfiles folder. :rtype: string :return: The docx directory Path. """ os.makedirs(Path.cwd() / f'{self.relative_path}', exist_ok=True) self.docxfile_dir_str = str(Path.cwd() / f'{self.relative_path}') return self.docxfile_dir_str def create_docx_filename(self, game_counter, datetime_today): """ Create docx filename with datetime and game number. :param game_counter: integer count of games played. :param datetime_today: date str to standardize output file basename. :return: The docx filename as string. """ self.docx_filename = f"{datetime_today}Game{game_counter+1}.docx" return self.docx_filename def write_docxfile(self, game_counter, players_list, ranking_dict): """ Writes players scores to docx file. :param game_counter: integer count of games played. :param players_list: list of Player class instances. :param ranking_dict: ranking of players and grand total scores. """ # open blank Document object doc = docx.Document() doc.add_paragraph(f'YAHTZEE GAME {game_counter + 1}', 'Title') doc.paragraphs[0].runs[0].add_break() # add picture of yahtzee game to document doc.add_picture( str(Path.cwd() / 'yahtzee/resources/yahtzeePicture.jpg')) doc.add_heading('FINAL RANKINGS', 1) for k, v in enumerate(ranking_dict): doc.add_paragraph(f"{v[0]}: {v[1]}") # add page break after rankings para_obj_rankings = doc.add_paragraph(' ') para_obj_rankings.runs[0].add_break(docx.enum.text.WD_BREAK.PAGE) # write each player score dict and total scores to file doc.add_heading('PLAYER SCORES AND TOTALS', 1) for j, player in enumerate(players_list): # write player name as header doc.add_heading(f"{players_list[j].name.upper()}", 2) # write scores for each scoring option doc.add_heading('ROLL SCORES', 3) output_score_dict = players_list[j].get_score_dict() for i, k in enumerate(output_score_dict): doc.add_paragraph(f"{k}: {output_score_dict[k]}") # write top score and bonus doc.add_heading('TOP SCORE BONUS', 3) doc.add_paragraph(f"Top Score: {players_list[j].get_top_score()}") doc.add_paragraph(f"Top Bonus Score: " f"{players_list[j].get_top_bonus_score()}") # write total scores and grand total doc.add_heading('TOTAL SCORES', 3) doc.add_paragraph(f"Total Top: " f"{players_list[j].get_total_top_score()}") doc.add_paragraph(f"Total Bottom: " f"{players_list[j].get_total_bottom_score()}") para_obj_grand_total = doc.add_paragraph( f"GRAND TOTAL: " f"{players_list[j].get_grand_total_score()}") # add pagebreak before writing next player scores to docx if j != (len(players_list)-1): para_obj_grand_total.runs[0].add_break( docx.enum.text.WD_BREAK.PAGE) # save Document object as docx filename doc.save(f"{self.docxfile_dir_str}/{self.docx_filename}") # print file creation confirmation print_fileio_confirmation(self.docxfile_dir_str, self.docx_filename) # class PdfFile: # """ # Objects instantiated by the :class:`DocxFile <DocxFile>` can be called to # convert a docx file to a pdf file # """ # def __init__(self): # self.pdffile_dir_str = '' # self.pdf_filename = '' # def __repr__(self): # return (f"{self.__class__.__name__}(" # f"{self.pdffile_dir_str}, {self.pdf_filename})") # def create_pdffile_dir(self): # """ # Create PDF files folder. # """ # os.makedirs(Path.cwd() / 'data/pdf_files/', exist_ok=True) # self.pdffile_dir_str = str(Path.cwd() / 'data/pdf_files/') # def create_pdf_filename(self, game_counter, datetime_today): # """ # Create pdf filename with datetime and game number. # :param game_counter: integer count of games played. # :param datetime_today: date str to standardize output file basename. # """ # self.pdf_filename = f"{datetime_today}Game{game_counter + 1}.pdf" # def convertDocxToPdf(self, docxfile_dir_str, docx filename): # """ # Converts Docx file to Pdf file # """ # convert(f"{docxfile_dir_str}/{docx filename}", # f"{self.pdffile_dir_str}/{self.pdf_filename}") # # print file convert confirmation # print_fileio_confirmation(self.pdffile_dir_str, self.pdf_filename)
5592ff96df88600b3f3f177413fafbc251b325e2
Silver-cybersec/LeetCode
/657.py
578
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 657. Judge Route Circle ''' class Solution(object): def judgeCircle(self, moves): """ :type moves: str :rtype: bool """ pos = [0,0] for i in moves: if i == 'U': pos[0]+=1 if i == 'D': pos[0]-=1 if i == 'L': pos[1]-=1 if i == 'R': pos[1]+=1 if pos == [0,0]: return True else: return False print Solution().judgeCircle("UU")
d112d8e36e8580bdb564b97a68f1e79c132c66da
chand777/python
/ite.py
75
4
4
num =[1,2,3,4,5,6] it=iter(num) print(next(it)) for i in it: print(i)
3ba09e039ec098bc337b7455310d4cdc26251993
rsamit26/InterviewBit
/Python/Backtracking/Subsets/subset ii.py
804
3.875
4
""" Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. The subsets must be sorted lexicographically. Example : If S = [1,2,2], the solution is: [ [], [1], [1,2], [1,2,2], [2], [2, 2] ] """ class Solution: def subset(self, s): res = self.subset_helper([], sorted(s)) final = [] for i in res: if i not in final: final.append(i) final.sort() return final def subset_helper(self, curr, s): if s: return self.subset_helper(curr, s[1:]) + self.subset_helper(curr + [s[0]], s[1:]) return [curr] c = Solution() s = [2, 2] print(c.subset(s))
3fd4c8254aa036296bbbebda62998a8a3d3c90cb
ecastan960/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
248
3.90625
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): a = 0 new = my_list.copy() for i in my_list: if i == search: new[a] = replace a = a + 1 else: a = a + 1 return new
5641e8b2646b0466388a27fed2570cd151c95c38
megatroom/dojo-python
/magicball/magic_ball.py
264
3.921875
4
from random import choice, randint answers = ["sim", "não", "talvez", "claro", "com certeza", "quem sabe um dia"] input("Entre com sua pergunta: ") print(choice(answers)) index = randint(0, len(answers)) input("Entre com sua pergunta: ") print(answers[index])
048869df72e327aedfadbefebcc446288098a89a
rlongo02/Python-Book-Exercises
/Chapter_9/9-13_OrderedDict_Rewrite.py
1,203
3.84375
4
from collections import OrderedDict glossary = OrderedDict() glossary['loop'] = "a sequence of instruction s that is continually repeated until a certain condition is reached", glossary['function'] = "a named section of a program that performs a specific task", glossary['boolean'] = "a data type that has one of two possible values (usually denoted true and false), intended to represent the two truth values of logic and Boolean algebra", glossary['list'] = "a tool that can be used to store multiple pieces of information at once", glossary['string'] = "a data type used in programming used to represent text", glossary['debugging'] = "the process of finding and removing programming errors", glossary['dictionary'] = "a mutable associative array (or dictionary) of key and value pairs", glossary['if statement'] = "conditionally executes a block of code, along with else and elif", glossary['PEP 8'] = "a set of recommendations how to write Python code", glossary['variables'] = "placeholder for texts and numbers", for term, definition in glossary.items(): if term == 'PEP 8': print("\n" + term + ":") else: print("\n" + term.title() + ":") print(definition)
edabeb7309d9a081b8791349644615e2f0a3ffaf
Satyam058/Python-Programs
/charwithindex.py
106
3.96875
4
s = input("Enter some string:") i=0 for x in s: print("The character present at",i,"index is",x) i+=1
0cefc450c8ea46f3ebae8bdc184e9474d94dac00
mjiujiang/PythonDesignPattern
/Python设计模式-9-【外观模式】.py
2,282
4.40625
4
""" 外观(Facade)模式:为子系统中的一组接口提供一个一致的界面。 ——此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。 与其它模式的区别:与 “简单工厂模式+策略模式”的组合版 很类似,不过外观类的接口不是简单的调用功能类的相应接口, 而是封装成了新的接口。 使用场景:维护一个遗留的大型系统是,可能这个系统已经非常难以维护和扩展,但是它包含很重要的功能,新的开发必须依赖于它, 这样增加外观Facade类,为系统封装一个比较清晰简单的接口,让新系统与Facade对象交互,Facade与遗留代码交互所有复杂的工作 """ import time SLEEP = 0.5 # 复杂部分 class TC1: def run(self): print("###### 测试1 ######") time.sleep(SLEEP) print(" 设置...") time.sleep(SLEEP) print("运行测试...") time.sleep(SLEEP) print("拆除...") time.sleep(SLEEP) print("测试结束了\n") class TC2: def run(self): print("###### 测试2 ######") time.sleep(SLEEP) print("设置...") time.sleep(SLEEP) print("运行测试...") time.sleep(SLEEP) print("拆除...") time.sleep(SLEEP) print("测试结束了\n") class TC3: def run(self): print("###### 测试3 ######") time.sleep(SLEEP) print(" 设置...") time.sleep(SLEEP) print("运行测试...") time.sleep(SLEEP) print("拆除...") time.sleep(SLEEP) print("测试结束了\n") # 外观模式 class ExecuteRunner: def __init__(self): self.tc1 = TC1() self.tc2 = TC2() self.tc3 = TC3() """列表解析 在一个序列的值上应用一个任意表达式,将其结果收集到一个新的列表中并返回。 它的基本形式是一个方括号里面包含一个for语句对一个iterable对象迭代""" self.tests = [i for i in (self.tc1, self.tc2, self.tc3)] def runAll(self): [i.run() for i in self.tests] #主程序 if __name__ == '__main__': testrunner = ExecuteRunner() testrunner.runAll()
923fa648a0005b2c29c396a5b7da720c6e4bd8f8
jia-kai/wordbar
/scripts/maptxt2json.py
525
3.578125
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: maptxt2json.py # $Date: Mon Sep 23 14:56:55 2013 +0800 # $Author: jiakai <jia.kai66@gmail.com> import json import sys if __name__ == '__main__': if len(sys.argv) != 2: sys.exit('usage: {} <.txt word map file>'.format(sys.argv[0])) rst = list() with open(sys.argv[1]) as fin: for i in fin.readlines(): i = i.split() word = i[0] data = map(int, i[1:]) rst.append([word] + data) print json.dumps(rst)
11f1f132e4eee67d42403d6506b58828ef5de490
maiconcarlosp/python
/Aula6/digitos.py
186
3.578125
4
frase = 'Houveram 12345 visitantes ontem.' # somente números digitos = [f for f in frase if f.isdigit()] # somente letras # digitos = [f for f in frase if f.isalpha()] print(digitos)
90ff75c2fbcdcab46c45a96c920212fff5b89655
Kryukov-And/currency_bot
/test.py
2,692
3.5
4
import unittest from Parser import Parser class ParserTest(unittest.TestCase): parser = Parser() def test_parse_city_found(self): self.parser.parse_city("проверка на абакан распознание города в предложении.") self.assertEqual(self.parser.get_city_name(), "Абакан") self.parser.clear() def test_parse_city_not_found(self): self.parser.parse_city("проверка на не распознание города в предложении.") self.assertEqual(self.parser.get_city_name(), None) self.parser.clear() def test_parse_currency_found(self): self.parser.parse_currency("проверка на распознание фунты валюты в предложении.") self.assertEqual(self.parser.get_currency(), "gbp") self.parser.clear() def test_parse_currency_not_found(self): self.parser.parse_city("проверка на не распознание валюты в предложении.") self.assertEqual(self.parser.get_city_name(), None) self.parser.clear() def test_parse_date_found(self): self.parser.parse_date("проверка на 20.12.2009 распознание числа в предложении.") self.assertEqual(self.parser.get_date(), "20") self.parser.clear() def test_parse_date_not_found(self): self.parser.parse_date("проверка на не распознание числа в предложении.") self.assertEqual(self.parser.get_date(), None) self.parser.clear() def test_parse_month_found(self): self.parser.parse_month("проверка на 20.12.2009 распознание месяца в предложении.") self.assertEqual(self.parser.get_month(), "12") self.parser.clear() def test_parse_month_not_found(self): self.parser.parse_date("проверка на не распознание месяца в предложении.") self.assertEqual(self.parser.get_month(), None) self.parser.clear() def test_parse_year_found(self): self.parser.parse_year("проверка на 20.12.2009 распознание года в предложении.") self.assertEqual(self.parser.get_year(), "2009") self.parser.clear() def test_parse_year_not_found(self): self.parser.parse_year("проверка на не распознание года в предложении.") self.assertEqual(self.parser.get_year(), None) self.parser.clear() if __name__ == '__main__': unittest.main()
2f5ac442b6cfbe8d91189d00b90c2cbb2e220ed8
snehal288/python
/iteration1.py
275
3.640625
4
def startDynamic(no): iCnt=0 while iCnt<no: print("jay ganesh") iCnt=iCnt+1 def main(): print("ENTER NUMBER OF TIMES YOU WANT TO DISPLAY MSG ON SCREEN") value=int(input()) startDynamic(value) if __name__=="__main__": main()
1a2c54795a6840760bc40f6693767dfcf68f1a0c
peterzhi/Python_turtle
/Relative_of_circle_and_dot.py
1,255
4.15625
4
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: peterZhi time:2020/1/5 #输入圆心坐标与任意一点,判断其余圆的关系 import turtle import math r=100 x1,y1=eval(input("请输入圆心坐标:")) turtle.penup() turtle.goto(x1,y1) turtle.pendown() turtle.write("("+str(x1)+","+str(y1)+")") turtle.dot(5,"black") turtle.penup() turtle.goto(x1,y1-r) turtle.pendown() turtle.circle(r) turtle.penup() turtle.goto(x1,y1) turtle.pendown() x2,y2=eval(input("请输入顶点坐标:")) deg=math.degrees(math.atan( (y2-y1) / (x2-x1) )) turtle.goto(x2,y2) turtle.dot(10,"red") turtle.write("("+str(x2)+","+str(y2)+")") length=( (x1-x2)**2 + (y1-y2)**2 )**0.5 turtle.penup() turtle.goto(x1-100,y1-150) turtle.pendown() if length == r: turtle.write("点("+str(x2)+","+str(y2)+")在圆上", font=("华文彩云",30,"normal")) elif length > r: turtle.write("点(" + str(x2) + "," + str(y2) + ")在圆外", font=("华文彩云", 30, "normal")) else: turtle.write("点(" + str(x2) + "," + str(y2) + ")在圆内", font=("华文彩云", 30, "normal")) turtle.hideturtle() turtle.penup() turtle.goto(x2,y2) turtle.pendown() turtle.showturtle() turtle.circle(0,deg) turtle.done()
87e0db6e374ebd8a4cc5110a7ced36620b0f3dfd
kozinarov/HackBulgaria-101-Python-Code
/week01/Dive into Python/diveintopython.py
3,571
3.75
4
import copy def palindrome(obj): return str(obj) == str(obj)[::-1] def to_digits(n): return [int(x) for x in str(n)] def is_number_balanced(n): print(n) digits = to_digits(n) middle_len = len(digits) // 2 left_digits = digits[0:middle_len] if len(digits) % 2 == 0: right_digits = digits[middle_len:] else: right_digits = digits[middle_len + 1:] print(left_digits) print(right_digits) return sum(left_digits) == sum(right_digits) # number = input("Number: ") # print(is_number_balanced(number)) def is_increasing(seq): for i in range(0, len(seq) - 1): if seq[i] >= seq[i+1]: return False return True # print(is_increasing([1, 2, 3, 4, 5])) def is_decreasing(seq): for i in range(0, len(seq) - 1): if seq[i] <= seq[i + 1]: return False return True # print(is_decreasing([100, 50, 120])) def get_largest_palindrome(n): n -= 1 while n >= 0: if palindrome(n): break n -= 1 return n # print(get_largest_palindrom(994687)) def is_anagram(a, b): a = a.lower() b = b.lower() a = str(a) b = str(b) a = list(a) b = list(b) a.sort() b.sort() len_a = len(a) cnt = 0 for elem_a in a: for elem_b in b: if elem_a == elem_b: cnt += 1 return len_a == cnt # print(is_anagram("BRADE", "BeaRD")) def birthday_ranges(birthdays, ranges): result = [] for rang in ranges: counter = 0 for day in birthdays: if day >= rang[0] and day <= rang[1]: counter += 1 result.append(counter) return result # print(birthday_ranges([1, 2, 3, 4, 5], [(1, 2), (1, 3), (1, 4), (1, 5), (4, 6)])) def sum_matrix(m): num = 0 for i in m: for j in i: num = num + int(j) return num # print(sum_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) def prime_numbers(n): all_numbers = [x for x in range(2, n + 1)] for i in range(2, n + 1): not_prime = [x for x in range(i * 2, n + 1, i)] all_numbers = set(all_numbers) - set(not_prime) return sorted(list(all_numbers)) # number = input("Number: ") # print(prime_numbers(number)) # da napisha matrix bombing def is_transversal(transversal, family): for members in family: result = [] for person in members: if person in transversal: result.append(person) if len(result) == 0: return False return True #print(is_transversal([2, 3, 6], [[1, 2], [4, 5, 6], [3, 4]])) NEIGHBORS = [ (-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)] def is_in(m, coord): if coord[0] < 0 or coord[0] >= len(m): return False if coord[1] < 0 or coord[1] >= len(m[0]): return False return True def bomb(m, coord): if not is_in(m, coord): return m target_value = m[coord[0]][coord[1]] dx, dy = 0, 1 for position in NEIGHBORS: position = (coord[dx] + position[dx], coord[dy] + position[dy]) if is_in(m, position): position_value = m[position[dx]][position[dy]] m[position[dx]][position[dy]] -= min(target_value, position_value) return m def matrix_bombing_plan(m): result = {} for i in range(0, len(m)): for j in range(0, len(m[0])): bombed = bomb(copy.deepcopy(m), (i, j)) result[(i, j)] = sum_matrix(bombed) return result
86788e048959e1a5f849940d566e2fc1c0456fc1
SaiChandraCh/leetcode-py
/src/53.py
686
3.578125
4
class Solution(object): def maxSubArray(self, nums): temp = 0 sum = 0 count = 0 if len(nums) == 1: return nums[0] else: for num in nums: temp = temp + num if (temp < 0): temp = 0 count += 1 if (temp > sum): sum = temp if count == len(nums): temp = nums[0] for num in nums: if (temp < num): temp = num sum = temp return sum if __name__ == "__main__": obj = Solution() print obj.maxSubArray([-2,1,-3,4,-1,2,1,-5,4])
7f6f0610f1993984721de8b4f8acb520f34e103d
moshlwx/leetcode
/CODE/452. 用最少数量的箭引爆气球.py
2,163
3.578125
4
''' 452. 用最少数量的箭引爆气球 在二维空间中有许多球形的气球。对于每个气球,提供的输入是水平方向上,气球直径的开始和结束坐标。由于它是水平的,所以纵坐标并不重要,因此只要知道开始和结束的横坐标就足够了。开始坐标总是小于结束坐标。 一支弓箭可以沿着 x 轴从不同点完全垂直地射出。在坐标 x 处射出一支箭,若有一个气球的直径的开始和结束坐标为 xstart,xend, 且满足 xstart ≤ x ≤ xend,则该气球会被引爆。可以射出的弓箭的数量没有限制。 弓箭一旦被射出之后,可以无限地前进。我们想找到使得所有气球全部被引爆,所需的弓箭的最小数量。 给你一个数组 points ,其中 points [i] = [xstart,xend] ,返回引爆所有气球所必须射出的最小弓箭数。 示例 1: 输入:points = [[10,16],[2,8],[1,6],[7,12]] 输出:2 解释:对于该样例,x = 6 可以射爆 [2,8],[1,6] 两个气球,以及 x = 11 射爆另外两个气球 示例 2: 输入:points = [[1,2],[3,4],[5,6],[7,8]] 输出:4 示例 3: 输入:points = [[1,2],[2,3],[3,4],[4,5]] 输出:2 示例 4: 输入:points = [[1,2]] 输出:1 示例 5: 输入:points = [[2,3],[2,3]] 输出:1 提示: 0 <= points.length <= 104 points[i].length == 2 -231 <= xstart < xend <= 231 - 1 ''' class Solution: def findMinArrowShots(self, points) -> int: '''重叠区间问题,考虑贪心算法 ''' # 按照结束坐标排序子区间 points_sorted = sorted(points, key=(lambda x: x[1])) arrow = [] last_end = float('-inf') # 计算最多不重叠子区间个数,与标准最小重叠区间的区别在于边界接触算重叠 for i in points_sorted: # 开始坐标大于上一段区间的结束才认为不重叠,接触和小于都算重叠,排除 if i[0] > last_end: arrow.append(i) last_end = i[1] return len(arrow) points = [[1,2],[2,3],[3,4],[4,5]] print(Solution().findMinArrowShots(points))
c6c7cffe95f3ef7cabf1bdf522fb21afe39139ec
DHIVYASHREE5/list_methods
/list methods.py
923
4.46875
4
fruits = ['apple', 'banana', 'cherry'] fruits.append("orange") print(fruits) # get the index of 'banana' index = fruits.index('banana') print(index) # 'grapes' is inserted at index 3 (4th position) fruits.insert(3, 'grapes') print('List:', fruits) # remove the element at index 2 removed_element = fruits.pop(2) print('Removed Element:', removed_element) # reverse the order of list elements fruits.reverse() print('Reversed List:', fruits) # sort the list fruits.sort() print(fruits) # copying a list x = fruits.copy() print(fruits) #count x = fruits.count("apple") print(fruits) #extend fruits = ['apple', 'banana', 'cherry'] cars = ['Ford', 'BMW', 'Volvo'] fruits.extend(cars) print('List after extend():', cars) # remove banana from the list fruits = ['apple', 'banana', 'cherry'] fruits.remove("banana") print(fruits) #clear fruits.clear() print(fruits)
1c37a6b4f9edefad67ecd0b969d297a6f2a44105
stewSquared/project-euler
/p038.py
1,040
3.953125
4
"""Take the number 192 and multiply it by each of 1, 2, and 3: 192 x 1 = 192 192 x 2 = 384 192 x 3 = 576 By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? """ from itertools import count, dropwhile DIGITS = sorted("123456789") LIMIT = 10**4 def cps(base): """cps - Concatenated Product Series""" cp = str(base) for n in count(2): yield cp cp += str(base*n) def pandigital(n): return sorted(str(n)) == DIGITS def longEnough(base): return next(dropwhile(lambda n: len(n) < len(DIGITS), cps(base))) ans = max(filter(pandigital, (map(longEnough, range(1, LIMIT))))) print(ans)
a20e3260e4f42941fe0aec9c35cf9191b1e6168e
zzq5271137/learn_python
/12-模块和包/loop_reference_2/loop_a.py
797
3.828125
4
""" 循环引用 """ """ 这里就出现了循环引用的问题(因为这里导入的是模块里的具体方法); 还是跟sys.modules以及导入模块时执行的那3步有关(注意观察执行此处代码时的具体报错信息, 参照那3步, 自行分析) 注: 如果以后开发时发现, 你的导入路径都是对的, 但是就是无法导入, 可能就是发生了循环导入的问题; 如何解决这个问题呢? 这个问题并不是Python本身的问题, 归根结底这是你程序结构设计的问题, 应该尽量避免两个模块的相互引用, 或者尽量避免模块的导入链条形成一个环形, 这是从根本上解决问题; """ from loop_reference_2.loop_b import sayhello_b print("loop_a been referenced") def sayhello_a(): print("hello loop_a")
736d81cc478649614079c57dc8ac88cd445321eb
DamManc/workbook
/chapter_5/es116.py
809
3.609375
4
# Exercise 116: Perfect Numbers from es115 import calc_div def is_magic(x): if sum(calc_div(x)) == x: return True else: return False def calc_magic(x): str_res = [] for i in calc_div(x): str_res.append(str(i)) return str_res def main(): n = input('Enter a number: ') try: x = int(n) if x <= 10_000: if is_magic(x): print('Your number is Perfect!') print(f'{x} is equal to {"+".join(calc_magic(x))}') else: print('Your number is not Perfect, Sorry :( ') else: print('Your entered number is too big, sorry') main() except ValueError: print('Enter a valid number..') main() if __name__ == '__main__': main()
d7a6176d87bfb02c9e7b77759fc0d6fb1a65a5df
JiniousChoi/encyclopedia-in-code
/quizzes/euler_prime_quiz/prime.py
950
3.625
4
#!/usr/bin/env from math import sqrt fp = open('./euler.txt', 'r') euler = fp.readline().strip()[2:] #remove 2.7 def get_euler(fr, to): global euler if fr <= to <= len(euler): return euler[fr:to] #append if possible line = fp.readline() if(line): euler = euler + line.strip() return get_euler(fr, to) #doom! return None def test_get_euler(): for i in range(100): ee = get_euler(i, i+10) print(ee) def is_prime(n): for i in range(2, int(sqrt(n))+1): if(n%i==0): return False else: return True def main(): for i in range(0,500): x = get_euler(i, i+10) x = int(x) if(len(str(x))!=10): continue if( is_prime(x) ): print("") print("prime: ", x) else: print('.', sep="", end="") if __name__ == '__main__': main() #test_get_euler() #close always fp.close()
631e779fdce9b84da32c9a81851b8aff24428e52
showdowmaxi/machine_learning_mini_project
/outliers/outlier_cleaner.py
870
3.875
4
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ #get size of data s = len(predictions) errors = (net_worths - predictions) **2 ### store three type of data into tuple, and sorted tuple based on error which is tuple[2][0] and return first 81 cleaned_data = sorted([(age[0],net_worth[0],error[0]) for age,net_worth,error in zip(ages,net_worths,errors)],key = lambda tup: tup[2])[:int(s*0.9)] #cleaned_data.sort(key = lambda tup: tup[2]) #cleaned_data = cleaned_data[:int(s*0.9)] return cleaned_data
e5a59b897678ca51ddfcb349ca299d0c840a0d87
tinayzhao/jokebot
/csv_jokes.py
983
4.03125
4
'''Functions used for processing jokes from a CSV file.''' import csv import os from utils import deliver_error_message def get_csv_jokes(csv_file): '''Obtain CSV jokes file. Args: csv_file: String name of csv_file Returns: See 'Returns' of the read_csv function. ''' if csv_file.split(".")[-1] != "csv": deliver_error_message("Please reference a CSV file.") if not os.path.isfile(csv_file): deliver_error_message("Cannot find joke file in current directory.") return read_csv(csv_file) def read_csv(file_name): ''' Reads jokes from a CSV file. Args: file_name: String of CSV file name Returns: List of tuples containing the prompt and punchline. The first item is the prompt. The second item is the punchline. ''' try: with open(file_name) as csv_file: table = csv.reader(csv_file, delimiter=',') return [(row[0], row[1]) for row in table if len(row) == 2 and row[0] and row[1]] except: deliver_error_message("Unable to read CSV file")
4b92fd9ce3b906ec1f20f3b16c2ae9963be1cf97
ldnpydojo/3-letter-word
/team1/main.py
1,855
3.78125
4
import random class Game(object): def __init__(self, word): self.word = word.lower() def check(self, guess): if len(guess) != len(self.word): return (0, 0) guess = guess.lower() wrong = "" unused = "" right = 0 for index, char in enumerate(guess): if self.word[index] == char: right += 1 else: wrong += char unused += self.word[index] wrongpos = 0 for char in wrong: i = unused.find(char) if i >= 0: wrongpos += 1 unused = unused[:i] + unused[i + 1:] return (right, wrongpos) @staticmethod def choose_word(length=3): with open('/usr/share/dict/words') as dic: words = dic.read().splitlines() words = [word for word in words if len(word) == length and word.islower() and word.isalpha()] out = random.choice(words) return out def test(): g = Game('cat') assert g.check('hat') == (2, 0) assert g.check('abt') == (1, 1) assert g.check('Ccc') == (1, 0) assert g.check('aaa') == (1, 0) assert g.check('TCa') == (0, 3) for length in range(2, 10): word = Game.choose_word(length=length) assert len(word) == length assert word.islower() assert word.isalpha() def game_loop(): g = Game(Game.choose_word(length=3)) for i in range(10): guess = raw_input('Guess: ').strip() correct, misplaced = g.check(guess) if correct == len(g.word): print 'Win!' break print 'Correct:', correct, 'Misplaced', misplaced else: print 'You loose!', print 'Correct word is ', g.word if __name__ == '__main__': test() game_loop()
5c600bd89f643bbc0470a6efda0a2b2ec6184303
kevinmchu/bme547ci
/tachycardia.py
577
4.34375
4
''' is_tachycardic.py Author: Kevin Chu Last Modified: 2/4/19 DESCRIPTION: This program takes a string as an input and determines whether it contains the word "tachycardic". ''' import re def is_tachycardic(test_str): # Make all characters lowercase test_str = test_str.lower() # By default, isTachycardic is false # If string contains "tachycardic," then change to true isTachycardic = False # Check to see if now lowercase string contains tachycardic if test_str.find("tachycardic") != -1: isTachycardic = True return isTachycardic
b3af81067eda4f97107abfdf3151b07cf44207d8
mlukjanska/testing-cheatsheet
/Scripts/compareCSV.py
1,571
3.59375
4
# Script to compare list of csv files row by rown in given folders - the differences are printed into console import csv import os #List of csv files to compare in the respective folders csvFiles = [ 'file1.csv', 'file2.csv' ] folder1 = 'old_folder_name' folder2 = 'old_folder_name' for csvFile in csvFiles: oldCsv = 'full_path_to_folder' + folder1 + '/' + csvFile newCsv = 'full_path_to_folder' + folder2 + '/' + csvFile if os.stat(oldCsv).st_size == 0: print('\n-----------------------------------------') print('File is EMPTY: ' + oldCsv) continue if os.stat(newCsv).st_size == 0: print('\n-----------------------------------------\n') print('File is EMPTY: ' + newCsv) continue with open(oldCsv, 'r') as f1: reader = csv.reader(f1) f1header = next(reader) # gets the first (header) line f1row1 = next(reader) # gets the next line with open(newCsv, 'r') as f2: reader = csv.reader(f2) f2header = next(reader) f2row1 = next(reader) print('\n-----------------------------------------') if f1row1 != f2row1: print('\nDIFFERENCES FOUND in: ' + csvFile + '\n') for index, column in enumerate(f1row1, start=0): if f1row1[index] != f2row1[index]: print(f1header[index] + ' ' + ' Old value: .' + f1row1[index] + '. New value: .' + f2row1[index] + '. (' + f2header[index] + ')') print('\n') if f1row1 == f2row1: print('No differences found in: ' + csvFile)
140afc946e278dd455137cf8f8c7bdb19be29d03
biadar1/Praca-domowa
/Lab2/Lab2/Lab2.py
1,882
3.578125
4
import sys import math def zadanie1(): a=input("Podaj zdanie\n") print("Użyłeś/aś "+str(a.count(" "))+" Spacji") def zadanie2(): sys.stdout.writelines("Podaj pierwszą\n") a=float(sys.stdin.readline()) sys.stdout.writelines("Podaj drugą\n") b=float(sys.stdin.readline()) sys.stdout.write(str(a*b)+"\n") #zadanie 3 #odszukałem def zadanie4(): a=float(input("Podaj liczbę")) print(math.fabs(a)) #a bez biblioteki math będzie #if a<0: # print(a*-1) #else: # print(a) def zadanie5(): a=float(input("Podaj pierwszą liczbę\n")) b=float(input("Podaj drugą liczbę\n")) c=float(input("Podaj trzecią liczbę\n")) if a>0 and a<=10: if a>b or b>c: print("Warunek spełniony") else: print("Warunek niespełniony") def zadanie6(): for i in range(1,11): print(i*5) def zadanie7(): i=int(input("Podaj ile liczb chcesz potęgować\n")) indeks=0 while indeks<i: a=float(input("Podaj liczbę: ")) print("Kwadrat tej liczby to: "+str(a**2)) indeks+=1 def zadanie8(): a=int(input("Ile chcesz podać liczb: ")) b=[] i=0 while i<a: c=float(input("Podaj liczbę: ")) b.insert(i,c) i+=1 def zadanie9(): a=int(input("Podaj liczbę całkowitą wielocyfrową dodatnią\n")) suma=0 while a>0: suma+=a%10 a=int(a/10) print(suma) def zadanie10(): a=-1 b="A" while a<0 or a>10: a=int(input("Podaj liczbę od 0 do 10\n")) while a!=0: print(b) b=b+"A" a-=1 def zadanie11(): a=0 while a<=3 or a>=9: a=int(input("Podaj liczbę od 3 do 9\n")) for i in range(1,a): for j in range(1,a): if i==3 or j==3: zadanie11()
bb3e7418a4ce4b674db31b30cf06e93ad48a6082
ctramm/Python_Training
/Udemy/Section 15/FindByIDName.py
1,090
3.515625
4
""" Section 15: Find Element by ID and Name https://letskodeit.teachable.com/pages/practice """ from selenium import webdriver class FindbyIDName: def find_by_id(self): base_url = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.get(base_url) element_by_id = driver.find_element_by_id("name") if element_by_id is not None: print("We found an element by id") driver.close() def find_by_name(self): base_url = "https://letskodeit.teachable.com/pages/practice" driver = webdriver.Firefox() driver.get(base_url) element_by_name = driver.find_element_by_name("show-hide") if element_by_name is not None: print("We found an element by Name") driver.close() def yahoo_example(self): base_url = "https://www.yahoo.com" driver = webdriver.Firefox() driver.get(base_url) driver.find_element_by_id("uh-signin") ff = FindbyIDName() # ff.find_by_id() # ff.find_by_name() ff.yahoo_example()
b2dde1c0357c475cf7476cdc4fff1889c03ad077
kranti-experiments/session-12-assignment-kranti-experiments
/polygonseqtype.py
6,994
3.703125
4
from polygon import Polygon class PolygonSeqType: ''' PolygonSeqType is a class which takes max_edges, common_radius as inputs and supports iterating through \ list of polygons and also has max_efficient_polygon property which indicates the maximum efficient polygon in the list A valid polygon have edges as minimum as 3 and a non-zero, non-negative radius The Class supports getters and setters for max_edges, common_radius using @property annotation The Class also supports lazy computing of its properties and also the properties are not claculated more than once ''' def __init__(self, max_edges, common_radius): self.maxedges = max_edges self.commonradius = common_radius @property def maxedges(self): #Getter for maxedges return self._maxedges @maxedges.setter def maxedges(self, max_edges): #Validate input values if(max_edges <= 2 or not isinstance(max_edges, int)): raise AttributeError(f'Invalid Input values in object creation, Cross check: max_edges:{max_edges}') else: #Setter for maxedges self._maxedges = max_edges self._polygons = [] self._maxpolygon = None @property def commonradius(self): #Getter for CommonRadius return self._commonradius @commonradius.setter def commonradius(self, common_radius): #Validate Input Values if(common_radius <= 0 or not isinstance(common_radius, int)): raise AttributeError(f'Invalid Input values in object creation, Cross check: common_radius: {common_radius}') else: #Setter for CommonRadius self._commonradius = common_radius self._polygons = [] self._maxpolygon = None def __len__(self): return (self._maxedges-2) def __iter__(self): #Iterable returning an iterator return self.PolygonIterator(self) def __getitem__(self, p): #Required for Subscription if(isinstance(p, int)): if(p < 0): #To support reverse iteration l[-1], [-2]... p = p + self.__len__() if(p < 0 or p >= self.__len__()): raise IndexError(f'Index {p} is out of range, maximum length {self.__len__()}') else: #Checks if Polygon for the query index is already available, if so returns the same #If not, computes the Polygon and returns the computed value try: print('Using Cached Value of Polygon for the query index') polygon = self._polygons[p] except IndexError: print('Computing Polygon for the query index') polygon = self._create_polygon(p) self._polygons.append(polygon) return polygon else: #This is to support slicing start, stop, step = p.indices(self.__len__()) rng = range(start, stop, step) poly_slices = [] for index in rng: try: #Checks if Polygon for the query index is already available, if so returns the same #If not, computes the Polygon and returns the computed value print('Using Cached Value of Polygon for the query index') poly_slices.append(self._polygons[index]) except IndexError: print('Computing Polygon for the query index') self._polygons.append(self._create_polygon(p)) poly_slices.append(self._polygons[index]) return poly_slices def _create_polygon(self, index): ''' This is an internal function to create a new polygon Also resets the value of MaxPolygon as its value will be changed with addition of every new polygon ''' self._maxpolygon = None return Polygon(index+3, self._commonradius) @property def maxpolygon(self): ''' Computes maximum efficiency polygon Maximum Efficiency = Polygon with highest area to perimeter ratio ''' if self._maxpolygon is None: #Checks if MaxPolygon is already computed, if so returns the cached value #If not computes and returns the value print('Computing MaxPolygon') #Inorder to calculate MaxPolygon, the Polygon List has to be available #If it is not available, first create the polygon list and then compute MaxPolygon value poly_len = len(self._polygons) max_poly_len = self.__len__() if(poly_len != max_poly_len): for index in range(poly_len, max_poly_len): print('Computing Polygon for the query index') self._polygons.append(self._create_polygon(index)) sorted_polygons = sorted(self._polygons, key=lambda p: p.area/p.perimeter, reverse=True) self._maxpolygon = sorted_polygons[0] else: print('Using Cached Value for MaxPolygon') return self._maxpolygon def __repr__(self): return(f'PolygonSeqType(max_edges = {self._maxedges}, common_radius = {self._commonradius})') class PolygonIterator: ''' Iterator Class that allows looping through the collection ''' def __init__(self, polyobj): #Save PolygonSeqType object for access during iterations/next item fetch self._index = 0 self._polyobj = polyobj def __iter__(self): #Iterator returning self return self def __next__(self): ''' __next__() function to fetch elements one by one Since the Polygons list is not created in advance, every time a call is made to acces next element Only that time, the polygon is created and maintained in the list Once all the Polygons are computed the list is reused and won't be created again and again in subsequent iter calls This way the iterator supports lazy computation of Polygons Data ''' if self._index >= self._polyobj.__len__(): raise StopIteration else: try: print('Using Cached Value of Polygon for the query index') polygon = self._polyobj._polygons[self._index] except IndexError: print('Computing Polygon for the query index') polygon = self._polyobj._create_polygon(self._index) self._polyobj._polygons.append(polygon) self._index += 1 return polygon
e958209a3e64691c64c07077990a32f86fef75ab
odeakifumi/reversi
/reversi.py
1,989
3.9375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys from random import randint N = 8 SQUARE_TYPE=('.', 'O', 'X') #変更できないリスト # コメントを残そう def display_board(board): print ' a b c d e f g h' for i in xrange(N): print i+1, for j in xrange(N): print SQUARE_TYPE[board[i][j]], print print def think_choice(board, me, opp): choice, result = None, [] # for pos in xrange(64): for x in xrange(N): for y in xrange(N): if board[x][y] != 0: # 既に駒が存在 continue cand = [] # scan all directions for xx, yy in ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)): cand_tmp = [] distance = 1 while True: xt = x + xx * distance yt = y + yy * distance if xt >= N or xt < 0 or yt >= N or yt < 0: break if board[xt][yt] == opp: cand_tmp.append((xt, yt)) distance += 1 continue if board[xt][yt] == me and cand_tmp: cand.extend(cand_tmp) break break if not cand: continue # nearly random strategy :) if (x, y) in ((0, 0), (0, N - 1), (N - 1, 0), (N - 1, N - 1)): return (x, y), cand # sumikko! if len(cand) + randint(0, 1) > len(result): choice, result = (x, y), cand return choice, result def play_othello(): board = [[0 for i in xrange(N)] for j in xrange(N)] board[3][3], board[4][4] = 1, 1 board[4][3], board[3][4] = 2, 2 display_board(board) player1, player2 = 1, 2 r = [] while 1: choice, result = think_choice(board, me=player1, opp=player2) if result: board[choice[0]][choice[1]] = player1 for pos in result: board[pos[0]][pos[1]] = player1 if not (r or result): break r = result display_board(board) player1, player2 = player2, player1 sys.stdin.readline() #入力待ち エンターが押されると,次にいく print "%s %s" % ("O" * board.count(1), "X" * board.count(2)) def main(): play_othello() if __name__ == '__main__': main()
01e82f7406ad099c9e1b4c69716b244e1d3b9ef7
vladimirf7/leetcode
/easy/math/sqrtx.py
443
3.53125
4
"""solved with help, middle """ class Solution: def mySqrt(self, x): """ :type x: int :rtype: int """ result = x while result*result > x: result = int((result + x/result) / 2) return int(result) if __name__ == '__main__': assert Solution().mySqrt(4) == 2 assert Solution().mySqrt(5) == 2 assert Solution().mySqrt(8) == 2 assert Solution().mySqrt(9) == 3
57ae5a6e6adafd61b6414527a78adaa077f5d9e5
muitimon/atcoder
/bizreach/2.py
324
3.671875
4
import sys def main(argv): m = int(argv[-1]) dic = {} for i in argv[:-1]: num, word = i.split(":") num = int(num) if m % num == 0: dic[num] = word if dic: for key, value in sorted(dic.items()): print(value, end="") else: print(m) if __name__ == '__main__': main(sys.argv[1:])
4efd12e7fba5cbe992e2ea963c534677438ae07e
PikeyG25/Python-class
/Hangman.py
1,020
3.859375
4
#Hangman game #Parker Gowans #11/18 #The classic gmae of Hangman. The computer picks a random word #and the player wrong to guess it, one letter at a time. If the player #can't guess the word in time, the little stick figure gets hanged. #Imports import random import time #Constants HANGMAN = ( """ ________ | | | | | | | ( ) | + | | | | |________ """, """ ________ | | | | | | | ( ) | + | + | | |________ """, """ ________ | | | | | | | ( ) | +\ | + | | |________ """, """ ________ | | | | | | | ( ) | /+\ | + | | |________ """, """ ________ | | | | | | | ( ) | /+\ | + | / | |________ """, """ ________ | | | | | | | ( ) | /+\ | + | / \ | |________ """) MAX_WRONG=len(HANGMAN)-1 WORDS =() for i in range(len(HANGMAN)): print(HANGMAN[i]) time.sleep(5)
def4ec5d460520054e4b1548810f7854f5619ca2
minhdua/NTUCODER
/basic2/bai22.py
191
3.796875
4
# SaitamaCoder def Factorial(n): f = 1 for x in range(1,n+1): f *=x return f def Main(): n = int(input()) factor_n = Factorial(n) print(factor_n) if __name__=='__main__': Main()
5acd865413bc7b2b91f9da2248444e57b4e6392a
corewithkanish/Novice-Coding
/HackerRank/Simple Array Sum/2ndOct_AniDhumal.py
227
3.8125
4
def sum_of_arr(n): arr=[] i=0 sum=0 while(n): inp=int(input()) arr.append(inp) i=i+1 n=n-1 for a in arr: sum=sum+a print (sum) inp=int(input()) sum_of_arr(inp)
42abe1a444e25a896c9aa0b1ca1726cc6e9f81bc
psigen/bazel-mixed-binaries
/pybin/counter.py
466
3.65625
4
#!/usr/bin/env python """ Load the file specified in the arguments and print each line. """ from __future__ import print_function import sys import os def count(): """ Count the number of instances of some string. """ match = sys.argv[1] path = sys.argv[2] cnt = 0 with open(path, 'r') as f: for line in f.readlines(): if match in line: cnt = cnt + 1 print(cnt) if __name__ == '__main__': count()
222128cde31fac919c84a171d2acb8a9fa20df8c
arnabs542/Problems
/trees/post_order_traversal_no_rec.py
1,307
3.953125
4
''' PROBLEM STATEMENT: PostOrder traversal Write a function to traverse a Binary tree PostOrder, without using recursion. As you traverse, please print contents of the nodes. Custom Input Format: --------------------- First line contains single integer denoting total no of nodes in the tree. Seconds line contains pre-order traversal of tree (values are space separated). For example: ------------ 3 1 # # Denotes tree like: 1 / \ null null -------------------------------------- 7 1 2 3 # # # # Denotes tree like: 1 / \ 2 null / \ 3 null / \ null null Use the option "Show Input/Output Code " just above the code editor, to see, how input is read, tree is built, the function that you are going to complete is called and output is printed. Note: ----- https://www.youtube.com/watch?v=hv-mJUs5mvU https://leetcode.com/problems/binary-tree-postorder-traversal/ ''' def postorderTraversal(root): if not root: return res = [] stack = [root] while stack: node = stack.pop() res.append(str(node.val)) if node and node.left_ptr: stack.append(node.left_ptr) if node and node.right_ptr: stack.append(node.right_ptr) ans = ' '.join(res[::-1]) print(ans) return ans
32b93b753c54daa75f354ead6f75ed8b6fe2dfd2
docxed/codeEjust
/[Final 2018] ISBN.py
704
3.578125
4
"""main""" def converting(num): """convert str to int""" if num.isdigit(): return int(num) else: return 10 def product(fore, back): """product of number""" return fore * back def main(): """main docx""" isbn = list(map(converting, [i for i in "".join(input().split("-"))])) pos = 0 product_of_number = list() for i in range(10, 1, -1): result = product(i, isbn[pos]) product_of_number.append(result) pos += 1 sum_of_product = -(sum(product_of_number)) modu = sum_of_product % 11 if modu == isbn[-1]: print("Yes") else: modu = "X" if modu == 10 else modu print("No", modu) main()
18be70585951ba832a6d2bd5970b4da1f7bf7cfb
mjoehler94/adventOfCode
/2021/day4.py
2,837
3.609375
4
# get numbers first with open("data/day4.txt") as f: numbers = f.readline() boards = f.read() numbers = [int(x) for x in numbers.split(',')] print(numbers[:10]) # print(boards[:153]) # print(boards.split()) def make_boards(raw_boards): numbers = raw_boards.split() counter = 0 board_num = 0 board_dict = dict() step = 25 while counter < len(numbers): board_dict[board_num] = [int(num) for num in numbers[counter:counter + step]] counter += step board_num += 1 for board in board_dict.values(): assert len(board) == 25 return board_dict # write function to check if solved def score_board(numbers, board): # return false or score of board and final number board_score = 0 # check rows step = 5 position = 0 while(position < len(board)): row = board[position:position + step] if all([num in numbers for num in row]): board_score = numbers[-1] * sum([x for x in board if x not in numbers]) break else: position += step # check cols position = 0 while(not board_score and position < step): col = board[position::step] if all([num in numbers for num in col]): board_score = numbers[-1] * sum([x for x in board if x not in numbers]) break else: position += 1 # print(type(numbers[-1]), numbers[-1]) return board_score # solve part 1 print("Part 1") board_dict = make_boards(boards) # print(board_dict) def part1(numbers, board_dict): # for each number called check all boards for winners for i in range(1,len(numbers)): for bnum, board in board_dict.items(): score = score_board(numbers[:i],board) if score: print(bnum, i) print(score) return part1(numbers, board_dict) print("Done\n") # part 2 # which board will win last and what is it's score def part2(numbers, boards): # for each board print winning position, and score boards = list(boards.values()) score_of_last_board = 0 max_turns_to_win = 0 for i, b in enumerate(boards): for n in range(1,len(numbers)): score = 0 score = score_board(numbers[:n], b) # print(f"board: {i}, number_position: {n}, score: {score}") if score: if n > max_turns_to_win: # print(i, n) max_turns_to_win = n score_of_last_board = score break # print(b) # print(max_turns_to_win) # print(score_of_last_board) return score_of_last_board print("Part 2") # print(len(numbers)) # print(len(board_dict.values())) p2 = part2(numbers, board_dict) print(p2) print('Done')
1e387c820d485c8c4edf89b5e807425fbd9374c1
avpps/python_various
/reduction_sum.py
458
3.8125
4
''' What will be sum of n first natural numbers if we remove firstly every k element of this list, then every k-1 and etc. till k=2 inclusive? ''' def oszcz(n=1000000, k=100): suma = n * (n + 1) / 2 for i in range(k-1): c = 0 m = 0 while m < n: c += 1 m = k * c - i if m <= n: suma -= m print(int(suma)) return int(suma) if __name__ == '__main__': oszcz()
a7fe5e03e737c675e2b6bc6dacebcd3871a6dcdc
icebowl/python
/binaryconvert.py
485
3.9375
4
def bincon (decimal): print("BASE 10 DECIMAL: ",decimal) bin_str ="" for i in range(8): binary = str(decimal % 2); print (binary," ") decimal = decimal // 2; bin_str = str(bin_str) + binary; print(bin_str) #bin_str = "".join(reversed(bin_str)) print(bin_str[::-1] ) print() def main(): print ("Type a value less than 0 to exit.",end='') done = 0 while (done >= 0): dec = input("Input a base 10 number less than 256.") dec = int(dec) bincon(dec) main()
92d9f4fc94135b9db08af90ba17b9ca56645a32b
svworld01/group-coding
/day0003/3_Implement_strstr.py
1,173
3.65625
4
# created by KUMAR SHANU # 3. Implement strStr() # https://leetcode.com/problems/implement-strstr/ """ Approach : Two Pointers solution """ class Solution: def strStr(self, haystack: str, needle: str) -> int: # find length of both strings n = len(haystack) m = len(needle) # pointers i -> haystack # j -> needle i, j = 0, 0 if m == 0: return 0 # scan string until its lenght is greater than or # equal to lenght of the needle string while i < n and n - i + 1 >= m: if haystack[i] == needle[j]: k = i # move the pointers while j < m and i < n and haystack[i] == needle[j]: i += 1 j += 1 # if we found substring if j == m: return k # otherwise continue to scan and repoint # the pointer to the starting of needle string i = k + 1 j = 0 else: i += 1 # return -1 if we doesn't find substring in haystack return -1
efbc68fff097704acb9ed3d8178d99df24692181
JiqiuWu/CMEECourseWork
/Week2/Code/cfexercises2.py
1,793
4.40625
4
#!/usr/bin/env python3 """some examples to improve the understanding of if and while loops""" __author__ = 'Jiqiu Wu (j.wu18@imperial.ac.uk)' __version__ = '0.0.1' # What does each of fooXX do? import sys #import sys so that the test section can be conducted def foo_1(x = 4): """define a function that will calculate the square root""" return x ** 0.5 # obtain the square root of x def foo_2(x = 4, y = 7): """define a function that will return the bigger number""" if x > y: return x return y # obtain the larger one def foo_3(x = 1, y = 2, z = 3): """define a function that will order the three numbers from small one to big one""" if x > y: tmp = y y = x x = tmp if y > z: tmp = z z = y y = tmp return [x, y, z] #order from small one to big one, but i think there is a problem???let me think about def foo_4(x = 3): """define a function that will obtain the factorial of x""" result = 1 for i in range(1, x + 1): result = result * i return result # obtain the factorial of x def foo_5(x = 5): """define a function that will calculate the factorial of x""" if x == 1: return 1 return x * foo_5(x - 1) # a recursive function that calculates the factorial of x def foo_6(x=5): # Calculate the factorial of x in a different way """define a function that will calculate the factorial of x in a different way""" facto = 1 while x >= 1: facto = facto * x x = x - 1 return facto def main(argv): print(foo_1(4)) print(foo_2(4,7)) print(foo_3(1, 2, 3)) print(foo_4(3)) print(foo_5(5)) print(foo_6(5)) return 0 if (__name__ == "__main__"): status = main(sys.argv) sys.exit(status)
1225aff3b7a55b03238c58b1480208f535dce93e
haydenwhitney/portfolio
/Change Sorter/change_sorter.py
1,052
4.125
4
#Hayden Whitney #9/18 #Change Sorter def change(): total_change = int(input("How much change do you have? ")) quarters = total_change // 25 leftovers = total_change % 25 dimes = leftovers // 10 leftovers = leftovers % 10 nickels = leftovers // 5 leftovers = leftovers % 5 cents = leftovers // 1 leftovers = leftovers #3 display it back to the user print("Quarters: ", quarters, "\nDimes: ", dimes, "\nNickels: ", nickels, "\nCents: ", cents) change() def change2(total_change): total_change = total_change quarters = total_change // 25 leftovers = total_change % 25 dimes = leftovers // 10 leftovers = leftovers % 10 nickels = leftovers // 5 leftovers = leftovers % 5 cents = leftovers // 1 leftovers = leftovers return quarters, dimes, nickels, cents total_change = int(input("How much change do you have? ")) quarters, dimes, nickels, cents = change2(total_change) print("Quarters: ", quarters, "\nDimes: ", dimes, "\nNickels: ", nickels, "\nCents: ", cents)
4ce908fd8b364ceb66f33ab260ce2ca3367ae324
mikestrain/PythonGA
/CLASS11 - Packages and APIs/HOMEWORK/additional_exercise_sets_equal.py
324
3.5
4
import random import os os.system("clear") list1 = ["a",",b","c","d","e","f","g"] list2 = ["a",",b","c","d","e","f","g"] random.shuffle(list2) print(list1) print(list2) def lists_equal(L1,L2): S1 = set(L1) S2 = set(L2) if S1 == S2: return True else: return False print(lists_equal(list1,list2))
1d2717f5b9f9787fbc2d74d5a59fff5ac942ccf9
Philoso-Fish/CARLA
/carla/data/processing.py
508
3.84375
4
from sklearn import preprocessing def normalize(df, num_cols, scaler=None): """ Normalizes continous columns of the given dataframe :param df: Datafame to scale :param num_cols: Numerical columns to scale :param scaler: Prefitted Sklearn Scaler :return: Data """ df_scale = df.copy() if not scaler: scaler = preprocessing.MinMaxScaler() scaler.fit(df_scale[num_cols]) df_scale[num_cols] = scaler.transform(df_scale[num_cols]) return df_scale
138aae57862cb65a59f79d75b7ea06f488c025b1
sathish-csk/thinkpython
/exercise6.6.py
409
3.984375
4
def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_palindrome(string): new_string = str(string) if len(new_string) <= 1: return (True) elif first(new_string) == last(new_string): return is_palindrome(middle(new_string)) else: return (False) print(is_palindrome('worw')) print(is_palindrome('woow'))
88fa813189b5f79e08fd422d2360fbe1d7484395
stecat/pyTraining
/Day2/dictionary_3LevelMenus.py
3,317
3.640625
4
# Author:Steve # 打印3级菜单 data = { "北京": { "昌平": { "沙河-2": ["sh-3", "sh-3"], "a-2": ["a-3", "b-3"] }, "朝阳": { "cy-a2": ["cy-3", "cy-3"], "cy-b2": ["cy-3", "cy-3"] } }, "杭州": { "西湖": { "翠苑-2": ["翠苑-3", "翠苑-3"], "a-2": ["a-3", "b-3"] }, "上城": { "qj-a2": ["qj-3", "qj-3"], "qj-b2": ["qj-3", "qj-3"] } } } ''' while True: for i in data: print(i) choice = input("选择进入1>>:") if choice in data: while True: for i2 in data[choice]: print("\t", i2) choice2 = input("选择进入2>>:") if choice2 in data[choice]: while True: for i3 in data[choice][choice2]: print("\t\t", i3) choice3 = input("选择进入>>3:") if choice3 in data[choice][choice2]: for i4 in data[choice][choice2][choice3]: print("\t\t", i4) choice4 = input("最后一层,按b返回>>:") if choice4 == "b": pass # pass为占位符 if choice3 == "b": break if choice2 == "b": break ''' # 新方法,设置flag,每层内部输入q都能退出,思考优化 exit_flag = False # 打印第一层 while not exit_flag: for i in data: print(i) choice = input("选择进入1>>:") # 选择第一层,打印第二层 if choice in data: while not exit_flag: for i2 in data[choice]: print("\t", i2) choice2 = input("选择进入2>>:") # 选择第二层,打印第三层 if choice2 in data[choice]: while not exit_flag: for i3 in data[choice][choice2]: print("\t\t", i3) choice3 = input("选择进入>>3:") if choice3 in data[choice][choice2]: for i4 in data[choice][choice2][choice3]: print("\t\t", i4) choice4 = input("已到最后一层,按b返回>>:") if choice4 == "b": pass # pass为占位符 elif choice4 == "q" or choice4 != "b": exit_flag = True elif choice3 == "b": break elif choice3 == "q": exit_flag = True else: print("%s 不在选项中,请重新输入\n" % choice3) elif choice2 == "b": break elif choice2 == "q": exit_flag = True else: # 以上都要用elif,如果choice2==b用了if,在次一层退出的时候都会打印下一句 print("%s 不在选项中,请重新输入\n" % choice2) elif choice == "q": exit_flag = True else: print("%s 不在选项中,请重新输入\n" % choice)
65a717000b11939efec5855069f0cbcc0956072d
davismariotti/SpaceAdventure
/src/game.py
7,442
3.65625
4
from os import system, name from time import sleep import random rooms = ["Engine Room", "Bridge", "Crew Quarters", "Meal Room"] has_key = False has_hat = False has_talked_to_captain = False has_talked_to_security_commander = False has_talked_to_bartender_about_hat = False secret_password = random.randint(10, 99) def my_print(statement, newline=True): for character in statement: print(character, end="", flush=True) sleep(.02) if newline: print() sleep(.15) def intro(): my_print("Welcome to the space explorer USS-1092, it's really cold out here!") my_print("How are you adventurer? Can you rescue us from certain death?") my_print("Yesterday, our main warp drives failed, and we can't get into the engine room to fix it.") my_print("Can you help us fix it?") room_select() def room_select(): my_print("Choose a room from the following options:") choice = display_choices(rooms) if choice == 1: engine_room() elif choice == 2: bridge() elif choice == 3: crew_quarters() elif choice == 4: meal_room() def engine_room(): clear() if not has_key: my_print("The door is locked...") room_select() else: my_print("You open the engine room!") my_print("Everyone on the ship is super grateful, and the space ship is restored!") my_print("The USS-1092 can explore the galaxy once again!") def bridge(): global has_talked_to_captain, has_talked_to_security_commander clear() my_print("You've made it to the bridge.") my_print("The security commander is asking for the secret password...") sleep(1) my_print("[Security Commander] What is the secret password? ", newline=False) password = input() if password == str(secret_password): my_print("[Security Commander] Ok, you can talk to the captain now") sleep(3) my_print("[Captain] Hello! How can I help you?") sleep(1) my_print("." * 100) sleep(1) my_print("[Captain] What's that? You need the key to the engine room?") sleep(.5) my_print("[Captain] We actually can't find it either! Try seeing if the bartender knows anything.") has_talked_to_captain = True else: my_print("[Security Commander] You can't be in here!") my_print("[Security Commander] Come back when you have the password!") sleep(1) my_print("[Security Commander] ........ The bartender might give it to you if you're smart!") has_talked_to_security_commander = True sleep(2) room_select() def crew_quarters(): global has_hat clear() my_print("You've entered the crew quarters") my_print("What do you want to do?") choices = ["Go to another room", "Take a nap"] if has_talked_to_bartender_about_hat: choices.append("Grab a hat") choice = display_choices(choices) if choice == 1: room_select() elif choice == 2: my_print("zZZz" * 125) sleep(2) my_print("That was a nice nap!") sleep(2) crew_quarters() elif choice == 3: my_print("You grabbed the hat!") sleep(1) has_hat = True crew_quarters() def meal_room(): clear() my_print("You've entered the meal room") my_print("Some strange people hanging out here...") my_print("What do you want to do?") choice = display_choices(["Go to another room", "Talk to the bartender", "Eat a meal"]) if choice == 1: room_select() elif choice == 2: bartender() else: my_print("What a great meal!") sleep(2) meal_room() def bartender(): global has_key, has_talked_to_bartender_about_hat clear() my_print("[Bartender] What do you want?") choices = [ "I'd like a daquiri!", "Nothing, nevermind" ] if has_talked_to_security_commander: choices.append("I've heard something about you knowing the secret password to the bridge, can you tell me more?") if has_talked_to_captain: choices.append("Ask about the engine room") choice = display_choices(choices) if choice == 1: my_print("[Bartender] Sure thing! Enjoy!") elif choice == 2: my_print("[Bartender] No problem, have a good day!") elif choice == 3: if not has_hat: my_print("[Bartender] Ok, I'll help you out, but I forgot to get my hat") my_print("[Bartender] Can you get it from the crew quarters?") my_print("[Bartender] Then I'll help you...") has_talked_to_bartender_about_hat = True else: my_print("[Bartender] Thanks for grabbing my hat!") sleep(1) my_print("." * 40) sleep(1) my_print("[Bartender] What's that? You still want the secret password?") sleep(.5) my_print("." * 10) sleep(1) my_print("[Bartender] Ok fine, I'll help you.") sleep(.5) my_print("[Bartender] Ok, the secret password is a number.") my_print("[Bartender] The password's first digit is %d" % (secret_password // 10)) if secret_password % 3 == 0: my_print("[Bartender] The password is divisible by 3") if secret_password % 4 == 0: my_print("[Bartender] The password is divisible by 4") my_print("[Bartender] I am also going to give you three tries to guess the secret password") guesses = 0 while guesses <= 3: try: my_print("[Bartender] What's your guess? ", newline=False) guess = int(input()) if guess == secret_password: my_print("[Bartender] Wow! You got it! The secret password was indeed %d!" % secret_password) break elif guess > secret_password: my_print("[Bartender] Not it! The secret password is smaller!") else: my_print("[Bartender] Not it! The secret password is bigger!") except ValueError: my_print("[Bartender] That was not even a number!") guesses += 1 my_print("[Bartender] Good luck finishing your quest!") elif choice == 4: my_print("[Bartender] What's that? You know about the engine room?") my_print("[Bartender] I'll tell you what, you can have the key!") my_print("[Bartender] I was bound to be found out eventually, but I'm taking the escape pod!") sleep(2) print() my_print("You now have the engine room key!") has_key = True sleep(2) meal_room() def display_choices(choices): try: for i in range(1, len(choices) + 1): my_print(str(i) + ") " + choices[i - 1]) my_print("Enter your choice: ", newline=False) choice = int(input()) if choice > len(choices): my_print("That is not a valid option! Try again.") return display_choices(choices) return choice except ValueError: my_print("That is not a valid option! Try again.") return display_choices(choices) def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') intro()
3aa6c8317cfebf63845ab9f09a098ef3894676cd
a235689741023/python-learning
/3.X_台科大出版/3.X-5.4-字串索引與切片.py
1,011
4.03125
4
""" 取得字串中的字元 1. 透過索引值(index) 2. 使用切片(slice) >>取某段字串 3. 使用 split() >>分割字串 字串不能賦予值(會發生錯誤),if重新賦予 >>是建立新字串 而非修改原字串 """ # index str1 = "Hello" print(str1[0]) print(str1[-1]) # slice # 字串[ 起始: 結束: 間隔] # split # 字串.split( 分割符號, 分割次數) str2 = "Do \none \nthing \nat a time!" print(str2.split()) # 沒有指定 >>以 空格 和 換行符號(\n) 分割 print(str2.split(' ', 1)) # 將26個小寫英文字母反轉輸出 letters = "" for x in range(97, 123): #小寫字母97~122,大寫字母65~90 letters += str(chr(x)) # chr() 回傳ASCll對應的字元,ord() 回傳字元對應的ASCll碼 print(letters) revletters = letters[::-1] print(revletters) # 將數字反轉輸出 letters = "" for y in range(48, 58): #數字 48~57 letters += str(chr(y)) print(letters) revletters = letters[::-1] print(revletters) # .join() 連結字串
64555ddb17b3d566d342cd3b99f27671dd05bdcf
ivoryli/myproject
/class/phase1/day16/exercise05.py
1,683
3.828125
4
''' 准备:   -- 创建敌人类(编号/姓名/攻击力/血量/攻击速度...)   -- 创建敌人列表 练习:    1. 查找所有死人. 2. 查找编号是101的敌人 3. 查找所有活人. 4. 计算所有敌人攻击力总和 5. 查找所有攻击速度在5--10之间的敌人 6. 查找所有敌人的姓名 ''' from day16.common.custom_list_tools import ListHelper class Enemy: def __init__(self,id,name,atk,hp,atk_speed): self.id = id self.name = name self.atk = atk self.hp = hp self.atk_speed = atk_speed def __str__(self): return "Enemy(%d,%s,%d,%d,%d)"%(self.id,self.name,self.atk,self.hp,self.atk_speed) L = [ Enemy(100,"张三",10,50,5), Enemy(101,"李四",15,20,7), Enemy(102,"王五",5,0,2), Enemy(103,"莉莉",20,0,13), Enemy(104,"芳芳",17,30,9) ] #    1. 查找所有死人. for item in ListHelper.find_all(L,lambda enemy : enemy.hp == 0): print(item) print() # 2. 查找编号是101的敌人 target = ListHelper.first(L,lambda enemy : enemy.id == 101) print(target) print() # 3. 查找所有活人. for item in ListHelper.find_all(L, lambda enemy : enemy.hp > 0): print(item) print() # 4. 计算所有敌人攻击力总和 result = ListHelper.sum(L,lambda enemy : enemy.atk) print(result) print() # 5. 查找所有攻击速度在5--10之间的敌人 for item in ListHelper.find_all(L,lambda enemy : 5 <= enemy.atk_speed <= 10): print(item) print() # 6. 查找所有敌人的姓名 for item in ListHelper.select(L,lambda enemy : enemy.name): print(item)
f0e55e996b838f3e82584d54f2a402188b9ec404
melli0505/Algorithm2020-2
/Recursion_fibo.py
222
3.734375
4
def fibo(n): count = 0 first = 0 second = 1 while count < n: second = first + second first = second - first count += 1 return second n = int(input()) print(fibo(n))
4b324912d32ea64253766cb2b8ab7ed5f15e464b
rabiazaka/project
/min.py
163
3.828125
4
import math def function_power(): a = (int(input("Enter any no: "))) b = (int(input("Enter value for power: "))) print(a.__pow__(b)) print(abs(a))
d7fb6f1877863eef4e9f0516d3d7b9a8e59ed2d2
SlaviGigov/SoftUni
/Exam_Preparations/ExamPrep-2-2.py
503
3.671875
4
import re pattern = r"(#|\|)(?P<name>[A-Za-z\s]+)(\1)(?P<date>[0-9]{2}/[0-9]{2}/[0-9]{2})(\1)(?P<cal>[0-9][0-9]{0,3}|10000)(\1)" matches = re.finditer(pattern, input()) all_cal = 0 food = [] for match in matches: result = match.groupdict() all_cal += int(match.group("cal")) food.append(result) print(f"You have food to last you for: {all_cal//2000} days!") for k in food: print(f"Item: {k['name']}, Best before: {k['date']}, Nutrition: {k['cal']}") # 100/100 - usage of groupdict()
ef4e70e6759460cf26c577fb15de5173300ffa2f
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/sublist/6921fc3d6e8b460eb70a25dcf09c860e.py
210
3.65625
4
SUBLIST = 0b01 SUPERLIST = 0b10 EQUAL = 0b11 UNEQUAL = 0b00 def check_lists(l1, l2): l1, l2 = set(l1), set(l2) retval = 0 if l1 >= l2: retval |= SUPERLIST if l1 <= l2: retval |= SUBLIST return retval
54f668a6eb7919aa597c2857e5c1824d4f9116f8
yiluheihei/AdventOfCode
/10.py
2,014
3.5625
4
from collections import Counter with open("input/10_input.txt") as f: dat = f.read().splitlines() dat = [int(x) for x in dat] dat.sort() dat.append(max(dat) + 3) def next_adpt(curr_adpt, adpts): adpts.sort() if curr_adpt + 1 in adpts: n_adpt = curr_adpt + 1 diff_jolt = 1 elif curr_adpt + 2 in adpts: n_adpt = curr_adpt + 2 diff_jolt = 2 elif curr_adpt + 3 in adpts: n_adpt = curr_adpt + 3 diff_jolt = 3 else: raise AssertionError("different jolt must be one of 1,2, and 3") return n_adpt, diff_jolt curr = 0 jolt_1_diff = 0 jolt_3_diff = 0 while True: curr, diff_jolt = next_adpt(curr, dat) if diff_jolt == 1: jolt_1_diff += 1 if diff_jolt == 3: jolt_3_diff += 1 if curr == max(dat): break print("The result of part 1 is", jolt_3_diff * jolt_1_diff) # part2 def get_jolt(dat): curr = 0 # jolt_diff_1 = 0 # jolt_diff_3 = 0 diff_jolt = [] while True: curr, jolt = next_adpt(curr, dat) diff_jolt.append(jolt) if curr == max(dat): break return diff_jolt jolt = get_jolt(dat) # part 1 # jolt_n = Counter(jolt) # jolt_n[1] * jolt_n[3] # use recrusive directly, too too too slow # def distinct_ways(chain, curr): # if curr == chain[0]: # return 1 # elif curr == chain[1]: # return 1 # elif curr == chain[2]: # return 2 # elif curr == chain[3]: # return 4 # else: # return sum([distinct_ways(chain, i) for i in range(curr-3, curr) if i in chain]) # distinct_ways(chain, 163) # use cache def distinct_ways2(chain, curr, cache): if curr in cache: return cache[curr] cache[curr] = sum([distinct_ways2(chain, i, cache) for i in range((curr-3), curr) if i in chain]) return cache[curr] cache = {chain[0]:1, chain[1]:1, chain[2]:2, chain[3]:4} part2 = distinct_ways2(chain, chain[-1], cache) print("part2", part2)
c1d18f07bbada8ef87a66a502df5f123f1f5fc50
gkevinb/aoc-2020
/day1/refactor.py
472
3.6875
4
import itertools import math def get_combinations(sequence, times): for combination in itertools.combinations(numbers, times): if sum(combination) == 2020: return combination with open('input.txt') as f: numbers = [int(line.rstrip()) for line in f] answer = math.prod(get_combinations(numbers, 2)) print(f"Task 1 first part answer: {answer}") answer = math.prod(get_combinations(numbers, 3)) print(f"Task 1 second part answer: {answer}")
1a0e80170af35ccc25474656a17ef508b155f199
chandanmanjunath/Learn_python_the_hard_way_solved
/LPTHW/ex21.py
520
3.8125
4
def add(a,b): print "addition of %d and %d" % (a,b) return a+b def sub(a,b): print "subtraction of %d and %d" % (a,b) return a-b def mul(a,b): print "multiply of %d and %d" % (a,b) return a*b def div(a,b): print "division of %d and %d" % (a,b) return a/b age=add(10,20) height=sub(25,10) weight=mul(3,4) id=div(10,5) print "values age %d height %d weight %d id %d" % (age,height,weight,id) value=add(age,(sub(height,(mul(weight,div(id,2))) ))) print "the value is %d" % value
c3015a9b9038f592489812dc4b1b4e5a768364a1
yinhuax/leet_code
/datastructure/dp_exercise/ClimbStairs.py
599
3.828125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Mike # @Contact : 597290963@qq.com # @Time : 2021/2/12 21:44 # @File : ClimbStairs.py class ClimbStairs(object): def __init__(self): pass def climbStairs(self, n: int) -> int: """ 动态规划,一共两种状态,1,2, 初始化为dp[1] = 1, dp[2] = 2 :param n: :return: """ if n == 1: return 1 dp = [0] * (n + 1) dp[1] = 1 dp[2] = 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]
308ef528a3c16da2f87ed93e00e6a672c251c19f
rctorr/TECP0006FSPYOL2102
/Sesion-01/helado.py
713
4.03125
4
# 1. Imprimir la lista de opciones en la pantalla # 2. Leer la opción elegida por el usuario # 3. En base a la opción del usuario imprimir el valor del helado print(""" ---------------------- 1. Helado con oreo 2. Helado con m&m 3. Helado con fresas 4. Helado con brownie ---------------------- """) opcion_str = input("Elige el topping: ") opcion = int(opcion_str) if opcion == 1: precio = 19 elif opcion == 2: precio = 25 elif opcion == 3: precio = 22 elif opcion == 4: precio = 28 else: precio = 0 if precio == 0: print("El Helado elegido no existe!") else: # print("El valor del helado es ${:.2f} M.N.".format(precio)) print(f"El valor del helado es ${precio:.2f} M.N.")
aae1be159b4d32b3f35c341ca2146a323f60293b
sandeeprah/vanguard
/techlib/mechanical/compressor/air.py
1,206
3.59375
4
def humidityRatio(P, T, RH): # Antoine Constants A = 8.07131 B = 1730.63 C = 233.426 T_C = T - 273.15 # convert temperature to degC for antoine equation f = A - B/(C+T_C) Pw_sat_mmHg = pow(10,f) # gets saturation pressure in mmHg Pw_sat = 133.32*Pw_sat_mmHg # gets saturation pressure in Pa Pw = Pw_sat*RH/100 # get partial pressure of water vapor in Pa X = 0.62198*Pw/(P-Pw) # get humidity ratio return X def moistAirDensity(P, T, RH): rho_ma = None # moist air density # Antoine Constants A = 8.07131 B = 1730.63 C = 233.426 T_C = T - 273.15 # convert temperature to degC for antoine equation f = A - B/(C+T_C) Pw_sat_mmHg = pow(10,f) # gets saturation pressure in mmHg Pw_sat = 133.32*Pw_sat_mmHg # gets saturation pressure in Pa Pw = Pw_sat*RH/100 # get partial pressure of water vapor in Pa X = 0.62198*Pw/(P-Pw) # get humidity ratio MWda = 0.02897 R = 8.314 Rda = R/MWda MWw = 0.018 Rw = R/MWw print("Pw_sat is {}".format(Pw_sat)) print("X is {}".format(X)) print("f is {}".format(f)) rho_da = P/(Rda*T) rho_ma = rho_da*(1+X)/(1+X*(Rw/Rda)) return rho_ma
105788f8ed4a43a689ac61a2d8946f55193b0348
bonoron/Atcoder
/Binary Search Tree 2.py
1,209
3.984375
4
def insert(tree,node): parent=None child=root while child is not None: parent=child if node<child:child=tree[parent][0] else:child=tree[parent][1] if node<parent:tree[parent][0]=node else:tree[parent][1]=node def In_order(node): if node is None:return In_order(tree[node][0]) print(" {}".format(node), end="") In_order(tree[node][1]) def Pre_order(node): if node is None:return print(" {}".format(node), end="") Pre_order(tree[node][0]) Pre_order(tree[node][1]) def find(x,key): while x is not None and key!=x: if key<x:x=tree[x][0] else:x=tree[x][1] return x n=int(input()) tree,root={},None for i in range(n): order=input().split() if order[0]=="print": In_order(root);print() Pre_order(root);print() elif order[0]=="find": if find(root,int(order[1])) is not None:print("yes") else:print("no") elif order[0]=="insert": num=int(order[1]) if root is None: root=num tree[root]=[None,None] else: tree[num]=[None,None] insert(tree,num)
c2bf8902b252a2d1dae9214628b98656814bc330
easyfly007/practice
/udacity/ww01/sgd/bp/back_propagation.py
1,589
3.671875
4
import numpy as np def sigmoid(x): """ Calculate sigmoid """ return 1 / (1 + np.exp(-x)) x = np.array([0.5, 0.1, -0.2]) target = 0.6 learnrate = 0.5 weights_input_hidden = np.array([[0.5, -0.6], [0.1, -0.2], [0.1, 0.7]]) weights_hidden_output = np.array([0.1, -0.3]) ## Forward pass hidden_layer_input = np.dot(x, weights_input_hidden) # print(hidden_layer_input) hidden_layer_output = sigmoid(hidden_layer_input) output_layer_in = np.dot(hidden_layer_output, weights_hidden_output) output = sigmoid(output_layer_in) ## Backwards pass ## TODO: Calculate error error = target - output # TODO: Calculate error gradient for output layer del_err_output = error* output *(1-output) # TODO: Calculate error gradient for hidden layer del_err_hidden = del_err_output*weights_hidden_output *hidden_layer_output*(1- hidden_layer_output) del_err_hidden = np.dot(del_err_output, weights_hidden_output) * hidden_layer_output * (1 - hidden_layer_output) # TODO: Calculate change in weights for hidden layer to output layer delta_w_h_o = del_err_output * hidden_layer_output*learnrate # x=np.mat(x) print(x) # x2 = np.mat(x) # print(x2) # print(del_err_hidden) # TODO: Calculate change in weights for input layer to hidden layer delta_w_i_h = del_err_hidden * x[:, None] * learnrate # delta_w_i_h = del_err_hidden * x * learnrate print('Change in weights for hidden layer to output layer:') print(delta_w_h_o) print('Change in weights for input layer to hidden layer:') print(delta_w_i_h)
98ea0b22b3288145b167a5db843e2162069ef367
madaniel/json
/json_parser.py
7,454
3.609375
4
import urllib2 import json import os # # # Functions # # # def get_all_values(json_dict, target_key): # Helper function for get_all_values_dict() if isinstance(json_dict, dict): return get_all_values_dict(json_dict, target_key) values_list = [] if isinstance(json_dict, list): for item in json_dict: result = get_all_values_dict(item, target_key) if result: values_list.extend(result) return values_list def get_all_values_dict(json_dict, target_key, values_list=None): """ :param json_dict: JSON object :param target_key: key to find :param values_list: list to be values of target key :return: list of all the values found """ if values_list is None: values_list = [] assert isinstance(json_dict, dict), "Can handle only dict as JSON root" # Getting deep into the JSON tree first using recursion for key, value in json_dict.iteritems(): # Handling dictionary if isinstance(value, dict): get_all_values_dict(value, target_key, values_list) # Handling list if isinstance(value, list): # Check if list contains dict for item in value: # If so, send it to get_value for searching if isinstance(item, dict): get_all_values_dict(item, target_key, values_list) # Search for the target key if target_key in json_dict: values_list.append(json_dict) # Return the list [if not empty] to the function caller if values_list: return values_list def count_keys(json_dict, target_key): # Helper function to count_keys_dict() if isinstance(json_dict, dict): return count_keys_dict(json_dict, target_key) count = 0 if isinstance(json_dict, list): for item in json_dict: count += count_keys_dict(item, target_key) return count def count_keys_dict(json_dict, target_key, count=0): """ :param json_dict: JSON object [dict only] :param target_key: key to find :param count: number of target key instances :return: number of instances found """ assert isinstance(json_dict, dict), "can handle only dict as JSON root" for key, value in json_dict.iteritems(): # Handling dictionary if isinstance(value, dict): # Accumulating the count from all function call count += count_keys(value, target_key) # Handling list if isinstance(value, list): # Check if list contains dict for item in value: # If so, send it to get_value for searching if isinstance(item, dict): # Accumulating the count from all function call count += count_keys(item, target_key) # Count the key if target_key in json_dict: count += 1 return count def get_value(json_dict, target_key, get_all=False): """ :param json_dict: JSON object :param target_key: key to find :param get_all: Search on all JSONs on list :return: value or list of values found on JSON """ # Helper function to get_value_dict() if isinstance(json_dict, dict): return get_value_dict(json_dict, target_key) if isinstance(json_dict, list): found = [] for item in json_dict: value = get_value_dict(item, target_key) if value: if not get_all: return value else: found.append(value) return found def get_value_dict(json_dict, target_key): """ :param json_dict: JSON object :param target_key: key to find :return: value of the target key In case of multiple instances, the 1st key value found will be returned """ assert isinstance(json_dict, dict), "can handle only dict as JSON root" # The key found on the current dict if target_key in json_dict: return json_dict[target_key] # The key not found for key, value in json_dict.iteritems(): # Current key is a dict if isinstance(value, dict): result = get_value(value, target_key) if result is not None: return result # Current key is a list if isinstance(value, list): # Check if the list contains dict for item in value: # If so, send it to get_value for searching if isinstance(item, dict): result = get_value(item, target_key) if result is not None: return result def get_json(url): # Read the Json from web req = urllib2.urlopen(url) # Transfer object into python dictionary return json.load(req) def print_json(dict_data): # Transfer dictionary into json format [None -> null] if isinstance(dict_data, dict) or isinstance(dict_data, list): print json.dumps(dict_data, sort_keys=True, indent=4, separators=(',', ': ')) else: print "Error - no data given" def write_json(json_data, filename, json_path="C:\\"): """ :param json_data: JSON object / python dictionary :param filename: string of the filename :param json_path: default path to save the file :return: filename with its path """ # Setting the path to JSON folder json_filename = os.path.join(json_path, filename) # Writing JSON data with open(json_filename, 'w') as f: json.dump(json_data, f, sort_keys=True, indent=4, separators=(',', ': ')) return json_filename def read_json(filename, json_path): """ :param filename: string of the filename :param json_path: path to the filename :return: dictionary of JSON """ # Setting the path to JSON folder json_filename = os.path.join(json_path, filename) # Reading JSON data with open(json_filename, 'r') as f: return json.load(f) # Compare 2 JSONs line by line def compare_json(source, target, excluded=None): """ :param source: Baseline recorded JSON :param target: JSON under test :param excluded: List of strings which should not be checked :return: True if equals or empty list if equals without excluded list """ if source == target: return True # List for adding the diff lines diff = [] # Writing JSONs to files tmp_source_json = write_json(source, "tmp_source.json") tmp_target_json = write_json(target, "tmp_target.json") # Reading the files into lists with open(tmp_source_json) as src: source_content = src.readlines() with open(tmp_target_json) as tar: target_content = tar.readlines() # Comparing each line for source_line, target_line in zip(source_content, target_content): if not source_line == target_line: # removing spaces and extra chars from string target_line = target_line.strip().split(":")[0].strip('"') if target_line not in excluded: diff.append(target_line) # Removing JSONs files src.close() tar.close() try: os.remove(tmp_source_json) os.remove(tmp_target_json) # In case the file does not exists except WindowsError: print "\n\n! ! !failed to delete tmp JSON files ! ! !\n" return diff
47621027cf6e6c1fbdf9021af1c57c60742be54e
xiewenwenxie/168206
/168206134/sum.py
218
3.890625
4
def sum(arr): if len(arr)==1: return arr[0] else: arr2=arr[1:] return arr[0]+sum(arr2) arr=[2,3,8,6,7] if len(arr) ==0: print("the arr is null") else: print sum(arr)
00245f692b74f4db47e36a1464fcf269b6d615d2
Alex-Angelico/data-structures-and-algorithms
/python/code_challenges/tree_intersection/tree_intersection/tree_intersection.py
939
3.90625
4
# from tree import Node, QueueNode, Queue, BinaryTree, BinarySearchTree def tree_intersection(tree1, tree2): list1 = tree1.inOrder() list2 = tree2.inOrder() common_list = [] def commonality_checker(small_list, big_list): for i, value in enumerate(small_list): if small_list.count(value) > 1 and small_list.index(value) < i: pass elif big_list.count(value) > 0: common_list.append(value) if not len(list1) or not len(list2): return None elif list1 < list2: commonality_checker(list1, list2) else: commonality_checker(list2, list1) return common_list if common_list else None if __name__ == '__main__': tree1 = BinarySearchTree() tree2 = BinarySearchTree() tree1.add(4) tree1.add(2) tree1.add(5) tree2.add(2) tree2.add(1) tree2.add(4) print(tree_intersection(tree1, tree2))
50b6976848ff0d671d4c4ab73b8162a9215f2997
KikeGN/CargarDataset
/DataSet.py
490
3.5
4
#LUIS ENRIQUE GUZMAN NIÑO import numpy as np import urllib # URL for the Pima Indians Diabetes dataset (UCI Machine Learning Repository) url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv" # download the file raw_data = urllib.urlopen(url) # load the CSV file as a numpy matrix dataset = np.loadtxt(raw_data, delimiter=",") print(dataset.shape) # separate the data from the target attributes X = dataset[:,0:7] y = dataset[:,8] iris = load_iris() print(iris)
ae2242f2da6d5353985bdd659d930ef2e750a1fc
AdarshRevankar/Crack-it
/Algorithms/Prime.py
1,690
4.34375
4
import time # Check if integer is Prime # Prime number is number divisible by itself or 1 # # Eg: 2, 3, 5, 7, 11 .. etc # # Unit : 1 # Version 1 def is_prime_v1(n): """Return true if 'n' is a prime number. False otherwise""" if n == 1: return False # 1 is not prime for d in range(2, n): if n % d == 0: return False return True # version 2 # Logic: # The prime number factor is as follows: # 36 = 1 x 36 -+ # 2 * 18 | # 3 * 12 | # 4 * 9 | # 6 * 6 --+ # 4 * 9 | # 12 * 3 | # 18 * 2 | # 36 * 1 --+ # Here the number repeats after sqrt(n) * sqrt(n) # Also, the number can be NOT A PERFECT SQUARE, works fine. # This is used in V2 import math def is_prime_v2(n): """Return true if 'n' is a prime number. False otherwise""" if n == 1: return False max_divisor = math.floor(math.sqrt(n)) for d in range(2, max_divisor): if n % d == 0: return False return True # version 3 # if input is even then it will be prime # wasting into loop is not correct # Hence we can save time def is_prime_v3(n): """Return true if 'n' is a prime number. False otherwise""" if n == 1: return False # if n is even if n == 2: return True if n > 2 and n % 2 == 0: return False max_divisor = math.floor(math.sqrt(n)) for d in range(3, 1 + max_divisor): if n % d == 0: return False return True # ===== Test Function ===== count = 0 N = 50000 t0 = time.time() for i in range(1, N): is_prime_v3(i) t1 = time.time() print("Time required : ", t1 - t0) # Pseudo Prime
e13c5043ee43d00da98fb3c11493f98bf420248e
MarkTLite/BackEnd_Coding
/Python---Practice/3.loops/loop2.py
232
4.15625
4
courseName="Python for Beginners 2017" for letter in courseName: print("Current Letter is",letter) Girls=["Angel","Jackie","Martha","Sheena","Delilah"] for each_girl in Girls: print("Current girl you are playing:",girl)
c9e53e369304d69ebfcaf0f3547111b08e1b524b
saravananprakash1997/Python_Logical_Programs
/string_anagram.py
315
4.46875
4
#python program to check whether the input strings are anagram are not. string1=input("enter the string 1 :") string2=input("enter the string 2 :") sorted1=string1.sort() sorted2=string2.sort() if sorted1==sorted2: print("Yes,the given strings are anagrams") else: print("No,the given strings are not anagrams")
de0b9a26ec57c4446c01080aec1d82e575e14db0
Cola1995/s3
/面向对象/迭代器.py
311
3.625
4
class Foo: def __init__(self,n): self.n=n def __iter__(self): return self def __next__(self): self.n+=1 if self.n==100: raise StopIteration('jiezhu') return self.n f=Foo(10) # print(f.__next__()) # print(f.__next__()) for i in f: print(i)
0e5812a3368e64230d00ba4c0ef038512a7f1815
DieusGD/Proyecto-web-python
/python-curso/conditionals.py
685
4.03125
4
# x = 30 # #if un tipo de pregunta # if x == 30: # print("x es 30") # else: # print("x no es 30") # color = "blue" # if color == "red": # print("the color is red") # #comparacion adicional # elif color == "blue": # print("color blue") # else: # print("any color") # name = "Ryan" # lastname = "Carterr" # if name == "Ryan": # if lastname == "Carter": # print("eres Ryan Carter") # else: # print("no eres Ryan Carter") #and not or x = 15 y = 3 if x > 2 and x <= 10: print("x es mayor que 2 y menor o igual a 10") if x > 2 or x <=20: print("x es mayor que 2 y menor o igual a 10") if (not(x == y)): print("x no es igual que y")
8e093b23567a2399bafcf78602bb822a35ad72dc
danielsoler/diamond
/diamond.py
544
3.8125
4
def diamond(number): number_2 = number // 2 number_3 = 1 result_1 = '' if number <= 0 or number % 2 == 0: return None else: for x in range(0, number + 1): if x % 2 != 0: result_1 = result_1 + ' ' * number_2 + ('*' * x) + '\n' number_2 = number_2 - 1 for y in reversed(range(0, number - 1)): if y % 2 != 0: result_1 = result_1 + ' ' * number_3 + ('*' * y) + '\n' number_3 = number_3 + 1 return result_1
33a0c27e8ab82bd39c433b0d4450dca4cb0173a1
emryswei/coding_problems
/minDepth_binary_tree.py
1,939
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 21 12:06:44 2019 @author: tracy Find Minimum Depth of a Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. minimum depth不是指最少层数,是最短路径。如最短路径=1,即只有2个node相连,minimum depth = 2,不是1 从root node开始,到leaf node。 root node是level-1, 下一层的leaf node是level-2 leaf node定义:leaf node的left,right子节点都是Null,才叫leaf node """ ''' Time complexity of above solution is O(n) ''' class Node: def __init__(self, value): self.value = value self.left = None self.right = None def minDepth(root): if root is None: return 0 if root.left is None and root.right is None: return 1 if root.left is None: return minDepth(root.right) + 1 if root.right is None: return minDepth(root.left) + 1 return min(minDepth(root.left), minDepth(root.right)) + 1 # Driver Program root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Minimum depth of the binary tree is:", minDepth(root)) ''' 如果用BFS的方法 ''' def bfsMinDepth(root): if root is None: return 0 if root.left is None and root.right is None: return 1 left = bfsMinDepth(root.left) right = bfsMinDepth(root.right) if left is None: return right + 1 if right is None: return left + 1 return min(left, right) + 1 # Driver Program root = Node(6) root.left = Node(7) root.right = Node(73) root.left.left = Node(34) root.left.right = Node(55) print("Minimum depth of the binary tree by BFS is:", bfsMinDepth(root))
dbfb8e859fe3394efa5d035c8c6da52ab61ca76e
Mark-Seaman/UNC-CS350-2017
/Exercises/Results/pham5336/Exam 3/files.py
643
4
4
# files.py from csv import reader, writer # Read rows and columns from a CSV file def read_csv(filepath): with open(filepath) as f: return [row for row in reader(f) if row] # Read the text from a file def read_file(filepath): with open(filepath) as f: return f.read()[:-1] # Write rows and columns to a CSV file def write_csv(filepath, data): with open(filepath, 'w') as f: w = writer(f) for row in data: w.writerow(row) # Write the text string to a file def write_file(filepath, text): with open(filepath, 'w') as f: f.write(text+"\n")
7f9e0c9a31d306cdf69ba873f0c4c0e03fa0cea9
2008winstar/python
/median.py
232
3.546875
4
input_number = input('enter a series of number: ') number_list = input_number.split(' ') number_list.sort() print(number_list) if len(number_list) % 2 == 1: print(number_list[int((len(number_list) - 1) / 2)]) print(help(map))
852a17b9de81b66695903729decfacf44955e2b6
bermec/python
/src/pfepy/mmcarthy.py
520
4.09375
4
# Hey guys i'm having an issue. this is my code: score = input ("Please enter a score between 0.0 & 1.0:") score = float(score) if score >= 0.9: print ("A") elif score >= 0.8: print ("B") elif score >= 0.7: print ("C") elif score >= 0.6: print ("D") elif score < 0.6: print( "F") try: score > float(1.0) score < float(0.0) score = s except: score > float(1.0) print ("Please enter a value less than 1.0") score < float(0.0) print ("Please enter a value greater than 0.0")
bf82f3a252cac297492645c090f8d061ad0f659a
dshapiro1dev/RuCoBo
/src/examples/iterators/practice_list.py
2,848
4.3125
4
import unittest class ListTestCase(unittest.TestCase): """Set up a group of tests""" # These tests will see just how good you are with Lists. You can see some supporting material here if you # think you'll need it https://docs.python.org/3/tutorial/datastructures.html def test_sort_list_in_reverse_alphabetical_order(self): """Take the list below and return it in alphabetical order""" yak_breeds = ["Jiulong yak", "Sibu yak", "Huanhu yak", "Plateau yak", "Jiali yak"] sorted_list = [] #Make this value have the list in alphabetical order self.assertEqual(sorted_list, ["Sibu yak", "Plateau yak", "Jiulong yak", "Jiali yak", "Huanhu yak"]) def test_get_tenth_from_last_item(self): """Go through the list and return the item that is tenth from the last""" long_list = ["Jame", "Mary", "John", "Patricia", "Robert", "Jennifer", "Michael", "Linda", "William", "Elizable", "David", "Barbara", "Richard", "Susan", "Joseph", "Jessica", "Thomas", "Sarah", "Charles", "Karen", "Christopher", "Nancy"] tenth_from_last = "?" #make this return the 10th item from the last in the list self.assertEqual("Richard", tenth_from_last) def test_remove_words_longer_than_four_letters(self): """Go through the list and remove any word that has more than 4 letters""" original_list = ['apple', 'apple', 'pear', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] better_list = [] # make this list only have words that have 4 letters or less self.assertEqual(['pear', 'kiwi', 'pear'], better_list) def test_combine_two_lists(self): """Combine the two lists and return the 3rd, 4th and 5th largest numbers""" first_list = [1, 3, 5, 67, 98, 13, 35, 36] second_list = [35, 3263, 20, 15, 10, 158] third_fourth_fifth_largest = [] #make this list have the 3rd, 4th, and 5th largest across both lists self.assertEqual([98, 67, 36], third_fourth_fifth_largest) def test_find_the_most_common_pet(self): """Return the single word that occurs the most in the list""" word_list = ['cat', 'dog', 'cat', 'hamster', 'cat', 'dog', 'dog', 'dog', 'cat', 'parrot', 'dog', 'cat', 'hamster', 'parrot', 'hamster', 'goldfish', 'dog', 'dog', 'goldfish', 'monkey', 'camel', 'yak', 'cat', 'parrot', 'hamster', 'hamster', 'goldfish', 'monkey', 'shark', 'yak', 'yak', 'yak', 'parrot', 'dog', 'parrot', 'monkey', 'scorpion', 'shark', 'dog', 'goldfish', 'goldfish', 'cat'] most_common_pet = "?" # set this variable according to the single animal that shows up most often in the list self.assertEqual('dog', most_common_pet) if __name__ == '__main__': unittest.main()
784c65d8d1afbd06df02b319d6029ca8692d241f
BrenoSDev/PythonStart
/Introdução a Programação com Python/Repetiçoes07.py
97
4.03125
4
fim = int(input('Digite o último número a imprimir: ')) x = 0 while x <= fim: print(x) x += 2
05402f437301aa5a79cecbe346271a0bb600660f
Zhenye-Na/leetcode
/python/1920.build-array-from-permutation.py
1,384
3.65625
4
# 1920. Build Array from Permutation # Given a zero-based permutation nums (0-indexed), build an array ans of # the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. # A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive). # Example 1: # Input: nums = [0,2,1,5,3,4] # Output: [0,1,2,4,5,3] # Explanation: The array ans is built as follows: # ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] # = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]] # = [0,1,2,4,5,3] # Example 2: # Input: nums = [5,0,1,2,3,4] # Output: [4,5,0,1,2,3] # Explanation: The array ans is built as follows: # ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]] # = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]] # = [4,5,0,1,2,3] # Constraints: # 1 <= nums.length <= 1000 # 0 <= nums[i] < nums.length # The elements in nums are distinct. # Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)? class Solution: def buildArray(self, nums: List[int]) -> List[int]: if not nums or len(nums) == 0: return nums ret = [0 for _ in range(len(nums))] for i in range(len(nums)): ret[i] = nums[nums[i]] return ret
cfe3ed2a8ac29d956180f490fab6fda588a3d433
wilsonchang17/Leetcode-practice
/Symmetric Tree.py
536
3.859375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSymmetric(self, root: TreeNode) -> bool: def find(r,l): if(r == None and l==None): return True if(r!=None and l!=None and r.val==l.val): return find(r.right,l.left) and find(r.left,l.right) return find(root.right,root.left)
b17748568a3d80b2fd20b2d289cba3b1c1c10848
Bklyn/adventofcode
/2016/9.py
3,754
3.9375
4
#!/usr/bin/env python '''--- Day 9: Explosives in Cyberspace --- Wandering around a secure area, you come across a datalink port to a new part of the network. After briefly scanning it for interesting files, you find one file in particular that catches your attention. It's compressed with an experimental format, but fortunately, the documentation for the format is nearby. The format compresses a sequence of characters. Whitespace is ignored. To indicate that some sequence should be repeated, a marker is added to the file, like (10x2). To decompress this marker, take the subsequent 10 characters and repeat them 2 times. Then, continue reading the file after the repeated data. The marker itself is not included in the decompressed output. If parentheses or other characters appear within the data referenced by a marker, that's okay - treat it like normal data, not a marker, and then resume looking for markers after the decompressed section. For example: ADVENT contains no markers and decompresses to itself with no changes, resulting in a decompressed length of 6. A(1x5)BC repeats only the B a total of 5 times, becoming ABBBBBC for a decompressed length of 7. (3x3)XYZ becomes XYZXYZXYZ for a decompressed length of 9. A(2x2)BCD(2x2)EFG doubles the BC and EF, becoming ABCBCDEFEFG for a decompressed length of 11. (6x1)(1x3)A simply becomes (1x3)A - the (1x3) looks like a marker, but because it's within a data section of another marker, it is not treated any differently from the A that comes after it. It has a decompressed length of 6. X(8x2)(3x3)ABCY becomes X(3x3)ABC(3x3)ABCY (for a decompressed length of 18), because the decompressed data from the (8x2) marker (the (3x3)ABC) is skipped and not processed further. What is the decompressed length of the file (your puzzle input)? Don't count whitespace. --- Part Two --- Apparently, the file actually uses version two of the format. In version two, the only difference is that markers within decompressed data are decompressed. This, the documentation explains, provides much more substantial compression capabilities, allowing many-gigabyte files to be stored in only a few kilobytes. For example: (3x3)XYZ still becomes XYZXYZXYZ, as the decompressed section contains no markers. X(8x2)(3x3)ABCY becomes XABCABCABCABCABCABCY, because the decompressed data from the (8x2) marker is then further decompressed, thus triggering the (3x3) marker twice for a total of six ABC sequences. (27x12)(20x12)(13x14)(7x10)(1x12)A decompresses into a string of A repeated 241920 times. (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN becomes 445 characters long. Unfortunately, the computer you brought probably doesn't have enough memory to actually decompress the file; you'll have to come up with another way to get its decompressed length. What is the decompressed length of the file using this improved format? ''' import re import fileinput marker = re.compile ('\((\d+)x(\d+)\)') def decode (input, recurse=False): idx = 0 outlen = 0 while idx < len (input): m = marker.search (input, idx) if m: length, count = int (m.group(1)), int (m.group (2)) outlen += m.start() - idx if not recurse: outlen += count * length else: # print count, idx, input[m.end():m.end()+length] outlen += count * decode (input[m.end():m.end()+length], True) idx = m.end () + length pass else: outlen += len (input) - idx idx = len (input) pass pass return outlen with open ('9.txt') as f: input = f.read ().strip () print decode (input, False) print decode (input, True)
35234ded5271959b59b88599a83f54b1ae118909
TheCacophonyProject/audio-classifier
/python/code/untitled7.py
526
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 21 13:02:15 2019 @author: tim """ import csv lines = [['Bob', 'male', '27'], ['Smith', 'male', '26'], ['Alice', 'female', '26']] header = ['name', 'gender', 'age'] with open("test.csv", "w", newline='') as f: writer = csv.writer(f, delimiter=',') writer.writerow(header) # write the header # write the actual content line by line for l in lines: writer.writerow(l) # or we can write in a whole # writer.writerows(lines)
565f24f3ceca0f5f3ea03935d4bddde2eb4c6b0e
BioGeek/euler
/problem009.py
1,036
4.09375
4
# A Pythagorean triplet is a set of three natural numbers, a b c, for which, # # a^2 + b^2 = c^2 # # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. print [(a*b*c) for a in range(1,1000) for b in range(1,1000-a) for c in \ range(1,1000-a-b+1) if a+b+c==1000 and a**2+b**2==c**2][0] # 31875000 # # real 0m25.645s # user 0m25.510s # sys 0m0.080s # Faster solution from tskww on the forum: # First, a little analysis reveals the following properties. For all triples, # a^2+b^2 = c^2; a+b > c, c > a, c > b. We can also define b > a. Since a + b + # c = 1000, it follows that 500 > c > 334. (If c > 500, then a+b > c doesn't # hold. If c < 334 and b > a, then c > b doesn't hold.) So, in Python: # for c in xrange(334,500): # for a in xrange(1, (1000-c)/2): # b = (1000 - c) - a # if a**2 + b**2 == c**2: # print a*b*c # real 0m0.068s # user 0m0.060s # sys 0m0.000s
cb61bb94364026318dbcbe812e840bda5b7f909f
itssamiracle/coding-learning
/python-learning/sumofsquares.py
735
3.90625
4
#!/usr/bin/env python3 import math def leastsquares(num,array = {},counter=1): print(counter) biggestsquareofnum = math.floor(math.sqrt(num)) biggestsquare = math.floor(math.sqrt(counter)) print(math.sqrt(num)) if biggestsquareofnum == math.sqrt(num): return 1 if biggestsquare == math.sqrt(counter): array[counter] = 1 else: a = array[counter - biggestsquare**2]+1 tracker = biggestsquare while tracker > 0: a = min(a,array[counter-tracker**2]+1) tracker = tracker-1 #o(sqrtn) array[counter] = a if counter == num: return array[counter] newarray = array newcounter = counter+1 return leastsquares(num, newarray, newcounter) #o(n)*o(sqrt(n)) if __name__ == "__main__": print(leastsquares(120))
87e3194d9815ae10122a3704259102f8678d2df2
bondgeodima/second
/start/t1.py
1,970
3.703125
4
""" # Шифр цезаря a = int(3) b = 'i am caesar'.strip() alfavit = " abcdefghijklmnopqrstuvwxyz" shifr = [] for i in b: shifr.append(alfavit[(alfavit.index(i)+a)%len(alfavit)]) mySTR = "".join(shifr) print('Result: "{}"'.format(mySTR)) """ """ s = '0ab10c2CaB12'.strip() def rle_decode(s): repeat = "" res = "" for e in s: if e.isdigit(): repeat += e else: if repeat: res += e * int(repeat) else: res += e repeat = "" return res print(rle_decode(s)) """ """ s = '15.5 mile in yard'.strip().split() d = {"mile": 1609, "yard": 0.9144, "foot": 0.3048, "inch": 0.0254, "km": 1000, "m": 1, "cm": 0.01, "mm": 0.001} x = float(s[0]) * (d[s[1]] / d[s[3]]) print("{:.2e}".format(x)) """ """ In = str (input('Enter your name: ')) print ('Hello ' + (In)) """ """ s = 100 i = 1 ss = "" while s > 0: ss = ss + i*str(i) i += 1 s -= 1 print(" ".join(list(str(ss[:i-1])))) """ """ s = int(input()) ss = '' for i in range(1, s+1): if len(ss) < s: ss += i*str(i) print(' '.join(list(str(ss[:i])))) """ """ def get_int(start_message, error_message, end_message): while True: if start_message: print(start_message) start_message = None try: s = int(input()) print(end_message) return s break except: print(error_message) x = get_int('Input int number:', 'Wrong value. Input int number:', 'Thank you.') """ """ x = (-12+6/17)/(((1+2)**4)-5*8) print(x) """ """ while True: try: x = int(input()) if x == -10 or (x > -5 and x <= 3) or (x>8 and x<12) or x>=16: print('True') else: print('False') except: print("not str") """ s = input() ss = s.title().replace('_','') # for i in range(0, len(ss)): # ss[i] = ss[i].capitalize() # ss = "".join(ss) print(ss)
d8654d96ba8b33cd60265e5ba0df68eddb91d7e4
huilongan/Python
/QueueT.py
1,210
3.796875
4
class Empty(Exception): pass class LinkedQueue: class _Node: __slots__='_element','_next' def __init__(self,element,next): self._element=element self._next=next def __init__(self): self._head=self._Node(None,None) self._tail=None self._size=0 def __len__(self): return self._size def is_empty(self): return self._size==0 def top(self): return self._head._next._element def dequeue(self): if self.is_empty(): raise Empty("The queue is empty!") old=self._head._next self._head._next=old._next self._size -=1 return old._element def enqueue(self,e): new=self._Node(e,None) if self.is_empty(): self._head._next=new else: self._tail._next=new self._tail=new self._size +=1 if __name__=='__main__': test=LinkedQueue() for i in range(10): test.enqueue(i) test.top() len(test) test.is_empty() for i in range(10): test.dequeue() test.dequeue() test.is_empty() len(test)
eb94ece6517f38e0359a596b97c4913ce75a6249
JohnnySu-SJTUer/LeetCodeLearning
/17_medium_letterCombinations.py
525
3.515625
4
class Solution: def letterCombinations(self, digits: str): if not digits: return [] self.DigitDict = [' ', '1', "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"] res = [''] for d in digits: res = self.letterCombBT(int(d), res) return res def letterCombBT(self, digit, oldStrList): return [dstr + i for i in self.DigitDict[digit] for dstr in oldStrList] if __name__=='__main__': s = Solution() print(s.letterCombinations("23"))
805d8f438c3c2e881751e11dcb7d8a1dc0b299f4
PULIYUAN/Data-Structure
/balanced_parentheses.py
1,497
4.1875
4
class Stack(object): def __init__(self, limit=10): self.stack = [] # 存放元素→列表 self.limit = limit # 栈容量极限 def push(self, data): # 判断栈是否溢出 if len(self.stack) >= self.limit: raise IndexError('超出栈容量极限') self.stack.append(data) def pop(self): if self.stack: return self.stack.pop() else: # 空栈不能被弹出元素 raise IndexError('pop from an empty stack') def peek(self): # 查看栈的栈顶元素(最上面的元素) if self.stack: return self.stack[-1] def is_empty(self): #判断是否为空栈 return not bool(self.stack) def size(self): # 返回栈的大小 return len(self.stack) #括号字符串匹配检测 def balanced_parenthese(parentheses): """[括号字符串匹配检测] Args: parentheses ([str]): [要检测的括号字符串] Returns: [bool]: [是/否] """ stack = Stack(len(parentheses)) for parenthese in parentheses: if parenthese == "(": stack.push(parenthese) elif parenthese == ")": if stack.is_empty(): return False stack.pop() return stack.is_empty() if __name__ == '__main__': parentheses = input("Please input parentheses:") print(parentheses + ":" + str(balanced_parenthese(parentheses)))
5a3fb2c72524b1a8da458f693b79ee56bf6c66b0
nordsieck/python-problems
/leetcode/test_17.py
2,327
3.65625
4
import unittest from typing import * class Solution: def letterCombinations(self, digits: str) -> List[str]: result = [] ltr = { "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], "6": ["m", "n", "o"], "7": ["p", "q", "r", "s"], "8": ["t", "u", "v"], "9": ["w", "x", "y", "z"], } if len(digits) == 0: return [] if len(digits) == 1: return ltr[digits[0]] if len(digits) == 2: for i in ltr[digits[0]]: for j in ltr[digits[1]]: result.append(i + j) return result if len(digits) == 3: for i in ltr[digits[0]]: for j in ltr[digits[1]]: for k in ltr[digits[2]]: result.append(i + j + k) return result # len(digits) == 4 for i in ltr[digits[0]]: for j in ltr[digits[1]]: for k in ltr[digits[2]]: for l in ltr[digits[3]]: result.append(i + j + k + l) return result class TestSolution(unittest.TestCase): def testFn(self): s = Solution() data = [["23", ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]], ["", []], ["2", ["a", "b", "c"]], ["5678", ["jmpt","jmpu","jmpv","jmqt","jmqu","jmqv","jmrt","jmru","jmrv","jmst","jmsu","jmsv","jnpt","jnpu","jnpv","jnqt","jnqu","jnqv","jnrt","jnru","jnrv","jnst","jnsu","jnsv","jopt","jopu","jopv","joqt","joqu","joqv","jort","joru","jorv","jost","josu","josv","kmpt","kmpu","kmpv","kmqt","kmqu","kmqv","kmrt","kmru","kmrv","kmst","kmsu","kmsv","knpt","knpu","knpv","knqt","knqu","knqv","knrt","knru","knrv","knst","knsu","knsv","kopt","kopu","kopv","koqt","koqu","koqv","kort","koru","korv","kost","kosu","kosv","lmpt","lmpu","lmpv","lmqt","lmqu","lmqv","lmrt","lmru","lmrv","lmst","lmsu","lmsv","lnpt","lnpu","lnpv","lnqt","lnqu","lnqv","lnrt","lnru","lnrv","lnst","lnsu","lnsv","lopt","lopu","lopv","loqt","loqu","loqv","lort","loru","lorv","lost","losu","losv"]], ] for a, b in data: self.assertEqual(s.letterCombinations(a), b)
e801c4bdd55356ba295e2c08b52868a1dc99f3b9
Kabi4/SmallPythonProjects
/distance_two_cities.py
2,251
4.03125
4
def distance_calc(a,b,c,d): distance=((c-a)**2+(d-b)**2)**(1/2) print(distance) def user_input(): a,b=map(int,input('Enter the first city Coordinates : ').split()) c,d=map(int,input('Enter the Second city Coordinates : ').split()) distance_calc(a,b,c,d) def main(): print("Here we are to find the distance between the two cities from its longitudes and latitudes : ") user_input() main() ''' from pygeocoder import Geocoder import numpy as np import sys def get_distance(locA, locB): #use haversine forumla earth_rad = 6371.0 dlat = np.deg2rad(locB[0] - locA[0]) dlon = np.deg2rad(locB[1] - locA[1]) a = np.sin(dlat/2) * np.sin(dlat/2) + \ np.cos(np.deg2rad(locA[0])) * np.cos(np.deg2rad(locB[0])) * \ np.sin(dlon/2) * np.sin(dlon/2) c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a)) return earth_rad * c def get_latlongs(location): return Geocoder.geocode(location)[0].coordinates def convert_km_to_miles(km): miles_per_km = 0.621371192 return km * miles_per_km def main(): #get first city print 'Type the first City: ' cityA = raw_input() #get second city print 'Type the second city: ' cityB = raw_input() #get units units = '' while (units != 'km') & (units != 'm'): print 'Type distance units (miles or kilometers): ' units = str.lower(raw_input()) if units in ['clicks', 'km', 'kilometers', 'kilometer']: units = 'km' elif units in ['m', 'mile', 'miles']: units = 'm' else: print 'units not recognised, please try again' #find the distance in km try: distance = get_distance(get_latlongs(cityA), get_latlongs(cityB)) #display the distance if units == 'km': print str(distance),' km' else: distance = convert_km_to_miles(distance) print str(distance), ' miles' except: print 'Error raised. Are the input cities correct?' if __name__ == '__main__': sys.exit(main()) '''
d3dfd046707fc8ee1462f222f9aa944790e4af09
Xiaoctw/LeetCode1_python
/贪心法/最长连续递增序列_674.py
486
3.609375
4
from typing import * class Solution: def findLengthOfLCIS(self, nums: List[int]) -> int: if len(nums) < 1: return 0 max_len = 1 beg = 0 for i in range(1, len(nums)): if nums[i] > nums[i - 1]: max_len = max(max_len, i - beg + 1) else: beg = i return max_len if __name__ == '__main__': sol = Solution() nums = [2, 2, 2, 2, 2] print(sol.findLengthOfLCIS(nums))
f35c8ab378b20318066ba0e712f1dddf69373f06
Mhmdaris15/free-python-project
/Regular/Recursion.py
732
4.1875
4
def recursion_fibonacci(n): if n <= 1: return n else: return recursion_fibonacci(n-1) + recursion_fibonacci(n-2) n_terms = int(input('Input n_terms : ')) # Check if the number is valid if n_terms <= 0: raise ValueError else: print('Fibonacci Series:') for i in range(1, n_terms): print(recursion_fibonacci(i)) def factorial(n): if n <= 1: return n else: return n * factorial(n-1) num = int(input('Input n_factorial : ')) if num < 0: print("Invalid input ! Please enter a positive number.") elif num == 0: print("Factorial of number 0 is 1") else: print("Factorial of number", num, "=", factorial(num))
d6e699386e0228e0f4c7acdcd5ea5c99e7592a79
juliaziqingcai/NSERC-USRA-2019
/JULIACOPY/Inactive_Code/EstimateN_Experimental_Prototypes/Median_Of_Medians_Vs_Median_Of_Samples.py
4,165
3.984375
4
''' This program compares the accuracy of using the median of the medians versus the median of the samples overall to approximate the median of a set. Done for the May 8th 2019 set of tests after the bounded inequality. The median of medians is currently obtained through bucket sorting through groups of 5 for greater run-time efficiency, but can also be modified for other group sizes. Inlcudes a test wrapper function for repeated and continous testing. ''' import math import random def get_approximated_medians(n,k): ''' Obtains two approximated medians: 1) The median of medians through bucket sort in groups of 5 2) The median of the overall samples Returns these two in a list n = set size k = related to the number of samples to take ''' random.seed() samples = list() for i in range((10*k)+5): # iterate index = random.randint(0, (n-1)) samples.append(index) medians = list() for j in range(0, (2*k) + 1): subsection = samples[(5*j):(5*j)+5] subsection.sort() medians.append(subsection[2]) medians.sort() samples.sort() return [medians[k], samples[(5*k)+2]] def single_run( n, delta, k): ''' Compares a single run of the median of medians and the median of samples to the true median. Prints report, and returns both medians. n = size of set delta = margin of error k = related to samples taken. ''' medians = get_approximated_medians(n, k) approximate_median = medians[0] sample_median = medians[1] real_median = math.floor(n/2) '''TEST ONLY CODE for one run print("\nMedian of Medians : " + str(approximate_median)) print("Median of Samples : " + str(sample_median)) print("True Median : " + str(n/2)) ''' return [approximate_median, sample_median] def sample_median_better(test_num, n, delta, k): ''' Tests if the median of the medians or the median of samples is closer to the true median on average with a printed report. test_num = number of test runs for algorithm n = set size delta = margin of error k = related to number of samples taken ''' sample_median_success = 0 for i in range(test_num): medians = get_approximated_medians(n, k) approximate_median = medians[0] sample_median = medians[1] real_median = math.floor(n/2) if (abs(real_median - sample_median) < abs(real_median - approximate_median)): sample_median_success += 1 probability = sample_median_success / test_num print("\n\n") print("# Trials : " + str(test_num)) print("N : " + str(n)) print("Delta : " + str(delta)) print("K : " + str(k)) print("Real Median : " + str(real_median)) print("Pr[sample median is better] : " + str(probability)) def test_wrapper(): ''' This is the test wrapper for the overall program. Allows repeated and overall comparisons between the median of medians and the median of samples by prompting the user for values to plug in the terminal. ''' print("\n\n") test_num = int(input("How many tests do you want to run? ")) n= int(input("What set size do you want to use? ")) delta = float(input("What delta do you want to use? ")) k = int(input("What k value do you want to use? ")) sample_median_better(test_num, n, delta, k) choice = (input("\nDo you want to try another run (Y/N)? ")).upper() while (choice != "N"): print("\n\n") test_num = int(input("\n\nHow many tests do you want to run? ")) n= int(input("What set size do you want to use? ")) delta = float(input("What delta do you want to use? ")) k = int(input("What k value do you want to use? ")) sample_median_better(test_num, n, delta, k) choice = input("\nDo you want to try another run (Y/N)? ") # Tests #sample_median_better(1000, 10000, 0.1, 2) #test_wrapper()