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
63af7fc13de270e6f2e13d0fe1d07a5605a0c5a9
manasacharyya25/DSA
/Trees/10. Diameter of a Tree.py
1,316
4.0625
4
""" Diameter of a Tree = Max(1 + LeftHeight + RightHeight, Max(LeftDiameter, RightDiameter))' Calculating Height of tree at each recursion increases time complexity to O(n^2) To reduuce this, we memoise height of each node """ class Node: def __init__(self, key): self.data = key self.left = None self.right = None class Solution: height_map = dict() @staticmethod def height(root): if not root: return 0 if root.data in Solution.height_map: return Solution.height_map[root.data] Solution.height_map[root.data] = 1 + max(Solution.height(root.left), Solution.height(root.right)) @staticmethod def diameter_util(root): if not root: return 0 if root.left: lheight = Solution.height_map[root.left.data] else: lheight = 0 if root.right: rheight = Solution.height_map[root.right.data] else: rheight = 0 ldiameter = Solution.diameter_util(root.left) rdiameter = Solution.diameter_util(root.right) return max(1+lheight+rheight, max(ldiameter, rdiameter)) @staticmethod def diameter(root): Solution.height(root) Solution.diameter_util(root)
6c2e3568a27b9a974396e926281f47ff671d0319
Dayoming/PythonStudy
/codingdojang/minesweeper/minesweeper_01.py
763
3.90625
4
# 표준 입력으로 2차원 리스트의 가로(col)와 세로(row)가 입력되고 # 그 다음 줄부터 리스트의 요소로 들어갈 문자가 입력됩니다. # 이때 2차원 리스트 안에서 * 은 지뢰이고 .은 지뢰가 아닙니다. # 지뢰가 아닌 요소에는 인접한 지뢰의 개수를 출력하는 프로그램을 만드세요. from random import * print("시작할 행과 열을 입력해주세요.") col, row = map(int, input("> ").split()) matrix = [] for i in range(row): matrix_in = [] for j in range(col): num = randrange(0, 10) if num >= 5: num = '*' else: num = '.' matrix_in.append(num) print(num, end='') print() matrix.append(matrix_in)
a1e608d164b4a5365be3ca061a9b80843e1efb56
ashokpandiyana/PYY
/Matrix.py
270
4.15625
4
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] def rotateImage(m): N = len(m) for r in range(N): for c in range(r): m[r][c], m[c][r] = m[c][r], m[r][c] print(m) for r in m : r.reverse() return m print(rotateImage(matrix))
5ecfeefa0476b35b33c5884ca25728166b05d780
Navajyoth/Anand-Python
/Anand python/unit2/u2prob17.py
105
3.5625
4
def reverse(s): for i in reversed(open(s).readlines()): print i.strip() reverse('cat.txt')
942efa6bf7a6c25987ca2d179d497e235e2409f1
jrsfahham/Projetos_Python
/Calculadora/calculadora2.py
2,314
3.609375
4
class Calculadora: def __init__(self): self.historico = [] def mostrar_historico(self): for operacao in self.historico: print(operacao[0]) print(operacao[1]) print() def adicao(self, *args): soma = 0 operando = [] for num in args: operando.append(str(num)) soma += num operando = ' + '.join(operando) + ' = ' operacao = [operando, soma] self.historico.append(operacao) return soma def subtracao(self, *args): if len(args) > 2: args = list(args) operando = [str(n) for n in args] diferenca = args[0] args.pop(0) for num in args: diferenca -= num else: operando = [str(args[0]), str(args[1])] diferenca = args[0] - args[1] operando = ' - '.join(operando) + ' = ' operacao = [operando, diferenca] self.historico.append(operacao) return diferenca def multiplicacao(self, *args): if len(args) > 2: args = list(args) operando = [str(n) for n in args] produto = args[0] args.pop(0) for num in args: produto *= num else: operando = [str(args[0]), str(args[1])] produto = args[0] * args[1] operando = ' * '.join(operando) + ' = ' operacao = [operando, produto] self.historico.append(operacao) return produto def divisao(self, *args): if len(args) > 2: args = list(args) operando = [str(n) for n in args] quociente = args[0] args.pop(0) for num in args: quociente /= num else: operando = [str(args[0]), str(args[1])] quociente = args[0] / args[1] operando = ' / '.join(operando) + ' = ' operacao = [operando, quociente] self.historico.append(operacao) return quociente if __name__ == "__main__": cal = Calculadora() print(cal.adicao(1, 2, 3, 4, 5)) print(cal.subtracao(20, 5, 4, 10)) print(cal.multiplicacao(5, 10, 6)) print(cal.divisao(100, 5, 4)) cal.mostrar_historico()
94aea2f830bf6c1577ff3c514ab824cfcce245da
lei-diva/AirBnB_clone
/tests/test_models/test_user.py
4,054
3.5
4
#!/usr/bin/python3 """New testing module""" import unittest from models.base_model import BaseModel from models.user import User import os class TestMyUser(unittest.TestCase): """Class TestMyUser to test class User""" def setUp(self): """setting up each test""" self.new = User() self.base = BaseModel() self.base2 = BaseModel() def tearDown(self): """cleaning up after each test""" del self.new del self.base del self.base2 # os.remove("file.json") def test_empty_strings_before(self): """Check if the strings are empty before assignment""" self.assertFalse(self.new.email) self.assertFalse(self.new.password) self.assertFalse(self.new.first_name) self.assertFalse(self.new.last_name) def test_methods_exist(self): """Check if the methods are present""" assert self.new.__init__ is not None assert self.new.save is not None assert self.new.to_dict is not None assert self.new.updated_at is not None assert self.new.__str__ is not None def test_attributes_exist(self): """Assign attributes and check if they are not None""" self.new.email = \ 'holbertonschoolisthebestschoolever@this.world' self.new.password = 'imnottellingyoumypassword' self.new.first_name = 'Diva' self.new.last_name = 'Mapatelian' self.assertNotEqual(self.new.email, None) self.assertNotEqual(self.new.password, None) self.assertNotEqual(self.new.first_name, None) self.assertNotEqual(self.new.last_name, None) def test_attributes_are_correct(self): """Check if assigments happened as intended""" self.new.email = 'holbertonschoolisthebestschoolever@this.world' self.new.password = 'imnottellingyoumypassword' self.new.first_name = 'Diva' self.new.last_name = 'Mapatelian' self.assertEqual(self.new.email, 'holbertonschoolisthebestschoolever@this.world') self.assertEqual(self.new.password, 'imnottellingyoumypassword') self.assertEqual(self.new.first_name, 'Diva') self.assertEqual(self.new.last_name, 'Mapatelian') def test_if_str(self): """Check if the attributes are strings""" self.new.email = 'holbertonschoolisthebestschoolever@this.world' self.new.password = 'imnottellingyoumypassword' self.new.first_name = 'Diva' self.new.last_name = 'Mapatelian' self.assertTrue(type(self.new.email) == str) self.assertTrue(type(self.new.password) == str) self.assertTrue(type(self.new.first_name) == str) self.assertTrue(type(self.new.last_name) == str) def test_right_class(self): """Check if the instance belongs to a right class""" self.assertIs(type(self.base), BaseModel) self.assertIsInstance(self.new, User) # check if file.json exists before running # def test_json_exists(self): # self.assertFalse(os.path.exists("file.json")) def test_save(self): """check if save() writes in an empty file""" self.new.save() self.assertFalse(os.stat("file.json").st_size == 0) def test_json_size_changed(self): """Check the size of file.json, invoke save() and check if the size have changed""" before = os.stat('file.json').st_size self.base.save() after = os.stat('file.json').st_size self.assertFalse(before == after) def test_too_many_str(self): """Pass too many/no parameters to __str__""" with self.assertRaises(TypeError) as omg: self.new.save('omg', 'lol', 'dolls') self.assertTrue(omg) def test_too_many_dict(self): """Pass too many/no parameters to to_dict()""" with self.assertRaises(TypeError) as omg: self.new.save('omg', 'lol', 'dolls') self.assertTrue(omg) def test_too_many_save(self): """Pass too many/no parameters to save()""" with self.assertRaises(TypeError) as omg: self.new.save('omg', 'lol', 'dolls') self.assertTrue(omg) if __name__ == '__main__': unittest.main()
bcc39f2a12d96a3bb60e33388b7c8e5df72b673e
tharmoth/MountainCart
/q_learning.py
2,982
3.78125
4
import random import numpy as np import math from method import RandomMethod class QLearning(RandomMethod): """ Attempts to solve the mountain cart problem using Q-Learning. Based on the q-learning method described in Watkins, Christopher JCH, and Peter Dayan. "Q-learning." Machine learning 8.3-4 (1992): 279-292. """ def __init__(self, environment, print_progress=True): super().__init__(environment, print_progress) self.location_bins = 12 self.velocity_bins = 12 # q_table holds the model that q learning uses to predict the best action self.q_table = np.zeros([self.location_bins, self.velocity_bins, self.env.action_space.n]) # Reset's the model for multiple runs def reset_model(self): self.convergence_graph = [] self.q_table = np.zeros([self.location_bins, self.velocity_bins, self.env.action_space.n]) # Convert the continuous data to discrete def _bin_data(self, state_in): # Scale the position max_location = self.env.observation_space.high[0] + abs(self.env.observation_space.low[0]) location_scaled = \ math.floor((state_in[0] + abs(self.env.observation_space.low[0])) / max_location * self.location_bins) # Limit max and min values, else scale the velocity max_velocity = self.env.observation_space.high[1] velocity_scaled = math.floor((state_in[1] + max_velocity) / (max_velocity * 2) * self.velocity_bins) return location_scaled - 1, velocity_scaled - 1 # Sets the epsilon greedy policy def _select_action(self, state, train=False): location, velocity = self._bin_data(state) if train and random.uniform(0, 1) < self.epsilon: return self.env.action_space.sample() else: return np.argmax(self.q_table[location][velocity]) def _model(self): # initialize the model state = self.env.reset() location, velocity = self._bin_data(state) # Position of Cart, Velocity of Cart done = False self.time_steps = 0 while not done: # either do something random or do the models best predicted action action = self._select_action(state, train=True) # save the old state location_old, velocity_old = location, velocity # run the simulation state, reward, done, info = self.env.step(action) # convert the continuous state data to discrete data location, velocity = self._bin_data(state) # Q(S,A) = Q(S,A) + a * [R + gamma * max_a(Q(S',A)) - Q(S,A)] # update the q learning model next_max = np.max(self.q_table[location][velocity]) old_value = self.q_table[location_old][velocity_old][action] self.q_table[location_old][velocity_old][action] \ += self.alpha * (reward + self.gamma * next_max - old_value) self.time_steps += 1
e042f78b089f494b07bf60b80202c41f41d2d2f7
zar777/exercises
/test_riccardo/map_words.py
436
3.78125
4
def map_words(words, way): if way == 'l': result = [] for word in words: result.append(len(word)) return result elif way == 'm': a = map(lambda word: len(word), words) return a elif way == 'c': return [len(word) for word in words] if __name__ == '__main__': words = ['ciao', 'sono', 'riccardo', 'il', 'puttaniere', 'bastardo'] print map_words(words, 'm')
9328e1d938bfeef31dde7ba410031c01e86b63e2
driddic/anwala.github.io
/Assignment/A2/twtA2.py
2,677
3.515625
4
''' prerequisites: 0. create a twitter account 1. obtain your access tokens: https://apps.twitter.com/ 1.0 create new app 2. install tweepy (pip install tweepy) credit: http://docs.tweepy.org/en/v3.4.0/streaming_how_to.html http://adilmoujahid.com/posts/2014/07/twitter-analytics/ https://pythonprogramming.net/twitter-api-streaming-tweets-python-tutorial/ Tweet JSON:, use http://jsonviewer.stack.hu/ to view object https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json rate limiting: https://developer.twitter.com/en/docs/basics/rate-limiting streaming rate limiting: https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/connecting.html ''' #Import the necessary methods from tweepy library from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import time import re #get keys from: https://apps.twitter.com/ #consumer key, consumer secret, access token, access secret. ckey = 'lTXqzqSptLXqggl6mo7iCeYR2' csecret = '4aNO3iMo6ZtpuHt3Ssj7EA5bKdZ6SVuHxQO2vamjksC0v2lRVl' atoken = '170079373-9R0y6xZPIwHXpnJoWzytGpcwLvSUPY5GijrZC4TL' asecret = 'qRjsuf8lKMOgwcU9YSa5ItIu1XCFAq4uz99Oc4ZA6DquA' class listener(StreamListener): def on_data(self, data): tweet = data.split(',"text":"')[1].split('","source:')[0] print(tweet) saveTime = str(time.time())+'::'+tweet saveTofile=open('a2try1.json','a') saveTofile.write(data) saveTofile.write('\n') saveTofile.close() return True def on_error(self, status): print( status ) if status_code == 420: #returning False in on_data disconnects the stream return False return True def on_data(self, data): #learn about tweet json structure: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/intro-to-tweet-json tweetJson = json.loads(data) #tweet = tweetJson['text'] username = tweetJson['user']['screen_name'] links = tweetJson['entities']['urls'] if( len(links) != 0 and tweetJson['truncated'] == False ): links = self.getLinksFromTweet(links) print( username ) for l in links: print('\t', l) print () #print('...sleep for 5 seconds') time.sleep(5) return True def getLinksFromTweet(self, linksDict): links = [] url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>' urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', url) for uri in linksDict: links.append( uri['expanded_url'] ) return links #handles Twitter authetification and the connection to twitter API auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=["rockets"])
0913f3e934cb073268da44bc837865acbdb2fd65
philoxmyu/pro-python
/polymorphic_test.py
853
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 17-9-9 下午4:34 # @Author : philoxmyu # @Contact : philoxmyu@gmail.com ''' 多态的概念其实不难理解,它是指对不同类型的变量进行相同的操作,它会根据对象(或类)类型的不同而表现出不同的行为。 有了继承,才有了多态,不同类的对象对同一消息会作出不同的相应 ''' class Animal(object): def __init__(self, name): self.name = name def greet(self): print 'Hello, I am %s.' % self.name class Dog(Animal): def greet(self): print 'WangWang.., I am %s.' % self.name class Cat(Animal): def greet(self): print 'MiaoMiao.., I am %s' % self.name def hello(animal): animal.greet() if __name__ == "__main__": dog = Dog('dog') hello(dog) cat = Cat('cat') hello(cat)
bfd26ce7153bd69825957e5415787ec4788b2b56
mahendran19/forRapid
/4.Cricket score.py
1,782
3.59375
4
class Cric: balls=int(input("How many balls:")) array=[] b1=0 #first batsman initial score b2=0 #second batsman initial score def totalruns(self): for i in range(1,Cric.balls+1): Runs=int(input("Enter the Runs:")) Cric.array.append(Runs) print("Runs:=",Cric.array) self.teamscore=sum(Cric.array) print("----------------------------------------") print("----------------------------------------") def ballbyball(self): print("Ball\tRun") for i in range(0,Cric.balls,1): print(i+1,"\t",Cric.array[i]) def Sachin(self): self.batting='Sachin' for i in range(0,Cric.balls,1): if(self.batting=='Sachin'): Cric.b1=Cric.b1+Cric.array[i] if(self.batting=='Sachin'): if(Cric.array[i]%2!=0): self.batting='Dhoni' elif(self.batting=='Dhoni'): if(Cric.array[i]%2!=0): self.batting='Sachin' if((i+1)%6==0): if(self.batting=="Sachin"): self.batting="Dhoni" else: self.batting="Sachin" print("Total Runs:=",self.teamscore) print("The first batsman(sachin) Runs:",Cric.b1) def dhoni(self): Cric.b2=self.teamscore-Cric.b1 print("The second batsman(Dhoni) Runs:",Cric.b2) a=Cric() a.totalruns() a.ballbyball() a.Sachin() a.dhoni()
291181243e8d7fed7dac0cbad571dbf4901736d2
ehmsu/Python-Tests
/December._26_Exercises_for_Ch._9.py
2,340
3.75
4
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> from typing import List >>> def remove_neg(num_list): for thing in num_list: if item < 0: num_list.remove(thing) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) File "<pyshell#5>", line 3, in remove_neg if item < 0: NameError: name 'item' is not defined >>> def remove_neg(num_list): for thing in num_list: if thing < 0: num_list.remove(thing) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) >>> def remove_neg(num_list): for thing in num_list: if thing < 0: num_list.remove(thing) print(num_list) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) [1, 2, 3, 6, -1, -3, 2] [1, 2, 3, 6, -3, 2] >>> def remove_neg(num_list): for thing in num_list: for chicken in thing: if thing < 0: num_list.remove(thing) print(num_list) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) File "<pyshell#15>", line 3, in remove_neg for chicken in thing: TypeError: 'int' object is not iterable >>> def remove_neg(num_list): for thing in num_list: if thing < 0: num_list.remove(thing) print(num_list) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) [1, 2, 3, 6, -1, -3, 2] [1, 2, 3, 6, -3, 2] >>> def remove_neg(num_list): for thing in num_list: if thing < 0: num_list.remove(thing) num_list.remove(thing) print(num_list) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) [1, 2, 3, 6, -1, 2] Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) File "<pyshell#21>", line 5, in remove_neg num_list.remove(thing) ValueError: list.remove(x): x not in list >>> def remove_neg(num_list): for thing in num_list: if thing < 0: num_list.remove(thing) for another_thing in num_list: if another_thing < 0: num_list.remove(another_thing) print(num_list) >>> remove_neg([1, 2, 3, -3, 6, -1, -3, 2]) [1, 2, 3, 6, 2] >>>
0091b61ec3b551b803420806b80804838bcffbbf
PasunoorNikhil/LeetCode-Practise
/1455.py
599
3.859375
4
" Check If a Word Occurs As a Prefix of Any Word in a Sentence " class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: li=sentence.split() for x in range(len(li)): word = li[x] i, j = 0, len(word) - 1 m, n = 0, len(searchWord) - 1 while i <= j and m <= n: if word[i] == searchWord[m]: i+= 1 m+=1 if i == len(searchWord) : return x + 1 else: break return -1
847b5ecb7bfa59719f4839d12185a5d21b6080c4
Codewithml/coding-problems-solutions
/stacks-queues/stack/stack-lists/testStackLists.py
1,155
3.609375
4
import unittest from stackLists import Stack class TestStackLists(unittest.TestCase): def test_end_to_end(self): print('Test: Empty stack') stack = Stack() self.assertEqual(stack.peek(), None) self.assertEqual(stack.pop(), None) print('Test: One element') stack = Stack() stack.push(5) self.assertEqual(stack.size(), 1) self.assertEqual(stack.pop(), 5) self.assertEqual(stack.peek(), None) print('Test: More than one element') stack = Stack() stack.push(1) stack.push(2) stack.push(3) self.assertEqual(stack.size(), 3) self.assertEqual(stack.pop(), 3) self.assertEqual(stack.peek(), 2) self.assertEqual(stack.pop(), 2) self.assertEqual(stack.peek(), 1) self.assertEqual(stack.isEmpty(), False) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.peek(), None) self.assertEqual(stack.isEmpty(), True) print('Success: test_end_to_end') def main(): test = TestStackLists() test.test_end_to_end() if __name__ == '__main__': main()
323fda581dd56c590f6b3e313c2b8740de6e383c
Ankit-py/Stone-Paper-Scissors-game
/stone_paper_scissors.py
1,482
3.890625
4
import random p1=0 p2=0 choices = ['rock','paper','scissors'] while True: print("\033c") roll1 = random.choice(choices) roll2 = random.choice(choices) print("wins : "+str(p1)+"player 1 : ",roll1) print("wins : "+str(p2)+"player 2 : ",roll2) if roll1 == 'scissors' and roll2 == 'scissors': print("") print("scissors + scissors = Tied") elif roll1 == 'scissors' and roll2 == 'paper': print("") print("Player 1 WINS !! scissors cut paper") p1 +=1 elif roll1 == 'scissors' and roll2 == 'rock': print("") print("player 2 WINS !! rock crushed scissors") p2+=1 if roll1 == 'rock' and roll2 == 'rock': print("") print("rock + rock = Tied") elif roll1 == 'rock' and roll2 == 'scissors': print("") print("player 1 WINS !! rock crushed scissors") p1 +=1 elif roll1 == 'rock' and roll2 == 'paper': print("") print("player 2 WINS !! paper covered rock") p2+= 1 if roll1 == 'paper' and roll2 == 'paper': print("") print("paper + paper = tied") elif roll1 == 'paper' and roll2 == 'rock': print("") print("player 1 WINS !! paper covered rock") p1 +=1 elif roll1 == 'paper' and roll2 == 'scissors': print("") print("player 2 WINS !! scissors cut paper") p2 += 1 print("") input("Again ? (Y/n)")
ced487c069429e6fc4ff4f5bff67cc7e76a0a6c6
acorovic/ProjektovanjeAlgoritama
/vezba02/example.py
474
3.75
4
import random import time def random_list (min, max, elements): list = random.sample(range(min, max), elements) return list list = random_list(1, 100, 50) print (list) #TO DO: #---------------------------------------------------------------- start_time = time.clock() def foo(): print ("blah") foo() end_time = time.clock() - start_time print ("Duration: ", end_time) #----------------------------------------------------------------
f4040e3b1d020264fb03e540b67358bebe637900
arcaputo3/algorithms
/other/median_sequence.py
3,223
3.765625
4
""" Various median finding methods. """ import heapq class MaxHeapObj(object): """ Max Heap Wrapper """ def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val def __eq__(self, other): return self.val == other.val def __str__(self): return str(self.val) class MinHeap(object): """ MinHeap Implementation """ def __init__(self): self.h = [] def heappush(self, x): heapq.heappush(self.h, x) def heappop(self): return heapq.heappop(self.h) def __getitem__(self, i): return self.h[i] def __len__(self): return len(self.h) class MaxHeap(MinHeap): """ MaxHeap Implementation """ def heappush(self, x): heapq.heappush(self.h,MaxHeapObj(x)) def heappop(self): return heapq.heappop(self.h).val def __getitem__(self, i): return self.h[i].val class MedianHeap(): """ Left: MaxHeap, Right: MinHeap o o / \ / \ """ def __init__(self, arr=[]): """ Optional: pass an array to initialize. """ self._min_heap = MinHeap() self._max_heap = MaxHeap() for i in arr: self.insert(i) def insert(self, item): """ Inserts item into MedianHeap. """ # Empty case if not self._min_heap and not self._max_heap: self._max_heap.heappush(item) elif self._max_heap: # Ensure minmax invariant if item >= self._max_heap[0]: self._min_heap.heappush(item) else: self._max_heap.heappush(item) # Keep difference in lengths less than 2 if len(self._min_heap) > len(self._max_heap) + 1: self._max_heap.heappush( self._min_heap.heappop() ) elif len(self._max_heap) > len(self._min_heap) + 1: self._min_heap.heappush( self._max_heap.heappop() ) def median(self): """ Returns current median. """ if self._min_heap and self._max_heap: # Even number of items case if len(self._min_heap) == len(self._max_heap): return (self._min_heap[0] + self._max_heap[0])/2 # o.w. return head of heap with more items elif len(self._min_heap) == len(self._max_heap) + 1: return self._min_heap[0] else: return self._max_heap[0] # Single item case - max_heap filled first if self._max_heap: return self._max_heap[0] return None def __len__(self): """ Returns total length of MedianHeap """ return len(self._max_heap) + len(self._min_heap) def len(self): """ Returns length of items in left and right heaps resp. """ return { 'left_max': len(self._max_heap), 'right_min': len(self._min_heap) } if __name__ == "__main__": # Test Cases med_heap = MedianHeap(range(101, -1, -1c)) print(med_heap.median()) print(len(med_heap)) print(med_heap.len())
c8f9bcf52f1bf56fdbd3526780ee5e64415511c4
iishipatel/Pytest-testApp
/src/Services/student_service.py
1,600
3.75
4
# from Database.db import get_db import sqlite3 DATABASE_NAME = "student.db" def get_db(): conn = sqlite3.connect(DATABASE_NAME) return conn def create_tables(): tables = [ """CREATE TABLE IF NOT EXISTS students( id INTEGER PRIMARY KEY, name TEXT NOT NULL, address TEXT NOT NULL ) """ ] db = get_db() cursor = db.cursor() for table in tables: cursor.execute(table) def get_students(): db = sqlite3.connect(DATABASE_NAME) cursor = db.cursor() statement = "SELECT * FROM students" cursor.execute(statement) return cursor.fetchall() def get_by_id(id): db = sqlite3.connect(DATABASE_NAME) cursor = db.cursor() statement = "SELECT id, name, address FROM students WHERE id = ?" cursor.execute(statement, [id]) return cursor.fetchone() def insert_student(id, name, add): db = sqlite3.connect(DATABASE_NAME) cursor = db.cursor() statement = "INSERT INTO students(id, name, address) VALUES (?, ?, ?)" cursor.execute(statement, [id, name, add]) db.commit() return True def update_student(id, name, add): db = sqlite3.connect(DATABASE_NAME) cursor = db.cursor() statement = "UPDATE students SET name = ?, address = ? WHERE id = ?" cursor.execute(statement, [name, add, id]) db.commit() return True def delete_student(id): db = sqlite3.connect(DATABASE_NAME) cursor = db.cursor() statement = "DELETE FROM students WHERE id = ?" cursor.execute(statement, [id]) db.commit() return True
29ce1121459ec51873e5e2b7934b81d4b473ca0e
nunes-moyses/Projetos-Python
/Projetos Python/pythonexercicios/des100.py
278
3.71875
4
def maior(*num): c = mai = 0 for n in num: if c == 0: mai = n c += 1 if n > mai: mai = n print(f'Entre {num} temos {len(num)} números e o maior é {mai}') maior(1, 2, 6, 4) maior(6, 5, 5) maior(-2, 7, 2, 0) maior(8)
fd1829b57fb3a5047e45dcb7834c1a61f2d74a8e
arun777888/classes
/dict1.py
2,661
4.03125
4
''' user = { 'name':'arun', 'age':23, 'marks': 100, 'hobby':'chess' } user1={ 'state':'u.k', 'city':'rishikesh' } user.update(user1) print(user) ''' # Returns a dictionary with the specified keys and values # takes 2 arguments ''' x = ('key1', 'key2', 'key3') y = 0 user = dict.fromkeys(x) print(user) ''' # or ''' d={} d=dict.fromkeys ('abc',' 24') print(d) ''' ''' cube={} for i in range(1,10): cube[i]= i**3 print(cube) ''' ''' user={} user['name'] = input('what is your name =') user['age'] = int(input('enter your age =')) user['place']= input(' enter your place =') print(user) ''' # concate dictionaries ''' dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic4 = {} for i in (dic1, dic2, dic3): dic4.update(i) print(dic4) ''' # if want this ''' m={ 'k':dic1, 'l':dic2, 'p':dic3 } print(m) ''' #wap to sum all the item in dict ''' my_dict = {'data1':100,'data2':-54,'data3':247} print(sum(my_dict.values())) ''' # or ''' user = {'data1':10,'data2':4,'data3':2} result=0 for i in user: result=result + user[i] print(result) ''' # Write a Python program to multiply all the items in a dictionary. ''' user = {'data1':10,'data2':4,'data3':2} result=1 for i in user: result=result * user[i] print(result) ''' #Write a Python program to map two lists into a dictionary. ''' keys = ['red', 'green', 'blue'] values = [6,8,12] user = dict(zip(keys, values)) print(user) ''' #Write a Python program to sort a dictionary by key. ''' user = {'red': 1, 'green': 2, 'black': 3, 'white': 4 } for i in sorted(user): print(i,user[i]) ''' # counting of words in string ''' s='goodboy' s1={} for i in s: s1[i] = s.count(i) print(s1) ''' ##counting of char in list ''' s=[1,1,4,4,5,6,'age', 'fire','kite','age'] s1={} for i in s: s1[i] = s.count(i) print(s1) ''' ## ''' def word_count(str): counts = dict() words = str.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown fox jumps over the lazy dog.')) ''' c=dict({'name':input('enter the name='), 'age' :input('enter the age=')}) print(c)
7619f68619b4140ebf3234e2c2a630316ad0d922
karimjamali/Class9
/sample1.py
505
3.9375
4
def func1(): print 'Hello World' def func2(arg1='SanFrancisco',arg2='Las Vegas', arg3='Mekkah'): print arg1,arg2,arg3 class MyClass(object): def __init__(self,x,y): self.x=x self.y=y def sum(self): return self.x + self.y class NewClass(MyClass): def product(self): return self.x * self.y print 'How Python processes an import' #print "This is the __name__ var: {}".format(__name__) if __name__ == "__main__": print 'This code is not importable, only executable'
d4ab4a183a34d070b1ef735495e14cda4a27ec63
Jordan-Camilletti/Project-Euler-Problems
/python/112. Bouncy numbers.py
1,189
4.09375
4
"""Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%.""" def bouncy(n): if(n<100): return False inc=False dec=False for num in range(1,len(str(n))): if(int(str(n)[num-1])>int(str(n)[num])): dec=True elif(int(str(n)[num-1])<int(str(n)[num])): inc=True return(inc and dec) perA=19602 perB=2178 num=perA+perB while((perA/(perA+perB))<0.99): num+=1 if(bouncy(num)): perA+=1 else: perB+=1 print(num,(perA/(perA+perB)))
c221f8fb2b0d0eadf97422ad1d96be5f77b55cac
Lstedmanfalls/Algorithms
/Python_Algos/users_and_bank_accounts/users_with_bank_accounts.py
3,128
4.125
4
# make_withdrawal(self, amount) - have this method decrease the user's balance by the amount specified # display_user_balance(self) - have this method print the user's name and account balance to the terminal (eg. "User: Guido van Rossum, Balance: $150 # BONUS: transfer_money(self, other_user, amount) - have this method decrease the user's balance by the amount and add that amount to other other_user's balance # Create a BankAccount class # The BankAccount class should have a balance. When a new BankAccount instance is created, if an amount is given, the balance of the account should initially be set to that amount; otherwise, the balance should start at $0. # The account should also have an interest rate, saved as a decimal (i.e. 1% would be saved as 0.01), which should be provided upon instantiation. (Hint: when using default values in parameters, the order of parameters matters!) # The class should also have the following methods: # deposit(self, amount) - increases the account balance by the given amount # withdraw(self, amount) - decreases the account balance by the given amount if there are sufficient funds; if there is not enough money, print a message "Insufficient funds: Charging a $5 fee" and deduct $5 # display_account_info(self) - print to the console: eg. "Balance: $100" # yield_interest(self) - increases the account balance by the current balance * the interest rate (as long as the balance is positive) # have both the User and BankAccount classes in the same file # only create BankAccount instances inside of the User's __init__ method # only call BankAccount methods inside of the methods in the User class class bank_account: def __init__(self, int_rate, balance): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdraw(self, amount): if self.balance > 0: self.balance -= amount else: self.balance -= 5 print("Insufficient funds: Charging a $5 fee") return self def make_transfer(self, amount, recipient): self.withdraw(amount) recipient.deposit(amount) return self def display_account_info(self): return self def yield_interest(self): if self.balance > 0: self.balance += (self.balance * self.int_rate) return self class User: def __init__(self, user_name): self.name = user_name self.account = bank_account(int_rate = 0.02, balance = 0) def make_withdrawl(self, amount): self.account.withdraw(amount) return self def make_deposit(self, amount): self.account.deposit(amount) return self def make_transfer(self, amount, recipient): self.account.make_transfer(self, amount, recipient) return self def display_user_account(self): print(self.name, "'s balance is", (f"${self.account.balance}")) return self first = User("User 1") second = User("User 2") third = User("User 3") first.make_deposit(10).display_user_account()
1af9d6f978b668ebb105c2c047d8a843ad71a86a
eduardo-zepeda-j/pruebas-python
/ListaOrtogonal.py
1,487
3.8125
4
class Node: def __init__(self,data=None): self.data = data self.next = None self.prev = None self.up = None self.down = None class lista_ortogonal: def __init__(self): self.head = Node(None) def create(self,n,m): p =Node() q =Node() r =Node() for i in range(n): for j in range(m): p.data = input('Inserte dato') p.next = None p.down = None if j==0: p.prev == None if self.head == None: self.head = p q = p else: p.prev = q q.next = p q=p if i == 0: p.up = None q = p else: p.up = r r.down = p r = r.next r = self.head while r.down != None: r = r.down def mostrar(self): if self.head != None: p = self.head while p!=None: q = p while q!=None: print(q.data) q = q.next p = p.down else: print('Lista Vacia') prueba = lista_ortogonal() prueba.create(2,2) prueba.mostrar()
4f1f6229b61e5cd1495ca9f0fe0f9142766b156c
Aistulike/iteration
/Iteration_class exercises_task2.py
253
4.125
4
#Aiste Sabonyte #22-10-14 #Iteration_revision exercises_task2 message = input("Please enter the message:") number = int(input("please enter the number of times you want the message being printed:")) for count in range(number): print(message)
ab42d84bd8eb7d9396b00122e9028b26a9fe27d2
LlamaBoiq/pp-length-machine
/length_scaler.py
422
3.8125
4
import random running = True while running: input() head = "D" body = "=" balls = "8" bodylen = random.randrange(1, 20) if bodylen <= 3: print("Got a small pecker there pal") elif bodylen <= 11: print("Its got some decent size") elif bodylen >= 12: print("Phew were working with a monster!") print("{0}{1}{2}".format(balls, body * bodylen, head))
114237b9a9e39676c72842fe083ab5fad6e4740b
CTingy/CheckiO
/electronic/03_Brackets.py
1,724
3.75
4
def checkio(expression): exp_list = [] result = [] dic = {')': '(', ']': '[', '}': '{'} for exp in expression: if exp in ['(', '[', '{']: exp_list.append(exp) elif exp in [')', ']', '}']: try: result.append(exp_list.pop() == dic[exp]) except: return False return all(result) & (not exp_list) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("((5+3)*2+1)") == True, "Simple" assert checkio("{[(3+1)+2]+}") == True, "Different types" assert checkio("(3+{1-1)}") == False, ") is alone inside {}" assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert checkio("2+3") == True, "No brackets, no problem" ''' def checkio(data): stack=[""] brackets={"(":")","[":"]","{":"}"} for c in data: if c in brackets: stack.append(brackets[c]) elif c in brackets.values() and c!=stack.pop(): return False return stack==[""] --------------------------------------------------------- def checkio(expression): s = ''.join(c for c in expression if c in '([{}])') while s: s0, s = s, s.replace('()', '').replace('[]', '').replace('{}', '') if s == s0: return False return True --------------------------------------------------------- def checkio(str): str = ''.join([c for c in str if c in '()[]{}']) while any(b in str for b in ('()', '[]', '{}')): str = str.replace('()', '').replace('[]', '').replace('{}', '') return not str '''
73eaa29428a441880a17dc58961bda96f435fdaa
noam20-meet/meetl1201819
/lab6.py
740
3.875
4
'''' from turtle import Turtle import turtle import random class Square(Turtle): def __init__(self,size): Turtle.__init__(self) self.shapesize(size) self.shape("square") def random_color(self): colors= ["yellow", "pink", "blue", "green"] c= random.randint(0,3) self.color(colors[c]) s= Square(8) s.random_color() turtle.mainloop() ''' import turtle from turtle import Turtle class Hexagon (Turtle): def __init__(self, size): Turtle.__init__(self) self.size=size turtle.penup() turtle.begin_poly() for i in range(6): turtle.forward(100) turtle.right(60) turtle.end_poly() s= turtle.get_poly() turtle.register_shape("hexagon", s) self.shape("hexagon") t1=Hexagon(50) turtle.mainloop()
05ceb1c9597878731d17c1b6982208b4c0b99a21
TEAMLAB-Lecture/text-processing-dkswndms4782
/text_processing.py
871
3.703125
4
def normalize(input_string): # 띄어쓰기 기준으로 단어들의 배열 만들기 splited_string = input_string.split() normalized_string = "" # " "같은 경우 예외처리 if len(splited_string) == 0: return "" # 각 단어들 더해주고 한칸만 띄워주기 for i in range(len(splited_string)): normalized_string += splited_string[i] + " " # 마지막 단어 다음에 띄어쓰기를 없애주기 위해 [:-1]슬라이싱 추가 return normalized_string[:-1].lower() def no_vowels(input_string): # 모음 배열 생성 vowel = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] no_vowel_string = input_string # 모음이 해당 string에 있을때 그 모음을 ""로 대체 for i in vowel: no_vowel_string = no_vowel_string.replace(i, "") return no_vowel_string
b9263e1b7e81d9acde1c9f1c868987ceb98313c4
yadleo/DSIP
/strings_lists/practice/prime_for.py
323
4.21875
4
# Example input() statement number = int(input('Please enter a number: ')) l = range(number) l = l[2:len(l) - 1] prime = True for num in l: if number % num == 0: print('The number you inputted is not a prime number.') prime = False break if prime == True: print('The number you inputted is a prime number.')
a40dcd7f7c9f1548a6e9f6c873e4d41dca43422c
CantOkan/Automata-Theory
/DFA/DFA1.py
2,335
3.6875
4
class ANode(object):#initial State def __init__(self,s,i): self.s=s self.i=i def transition(self): print("A") if(len(self.s)>=self.i): if(self.s[self.i]=="0"): print(self.s[self.i]+"-(go to B)") b.transition(self.i+1) elif(self.s[self.i]=="1"): print(self.s[self.i]+"-(go to B)") b.transition(self.i+1) else: print("It is not a Final State X") class BNode(object):#State def __init__(self,s): self.s=s def transition(self,i): self.i=i if(len(self.s)>self.i): if(self.s[self.i]=="1"): print(self.s[self.i]+"-(go to C)") c.transition(self.i+1) elif(self.s[self.i]=="0"): print(self.s[self.i]+"-(go to C)") c.transition(self.i+1) else: print("It is not a Final State X") class CNode(object):#Final State def __init__(self,s): self.s=s def transition(self,i): self.i=i if(len(self.s)>self.i): if(self.s[self.i]=="1"): print(self.s[self.i]+"-(go to D)") d.transition(self.i+1) elif(self.s[self.i]=="0"): print(self.s[self.i]+"-(go to D)") d.transition(self.i+1) else: print("in Final State ") print("It is a String") class DNode(object):#Dead State def __init__(self,s): self.s=s def transition(self,i): self.i=i if(len(self.s)>self.i): if(self.s[self.i]=="1"): print(self.s[self.i]+"-(go to D)") d.transition(self.i+1) elif(self.s[self.i]=="0"): print(self.s[self.i]+"-(go to D)") d.transition(self.i+1) else: print("It is not a Final State(Trap State) X") s1="01" print(s1) a=ANode(s1, 0) b=BNode(s1) c=CNode(s1) d=DNode(s1) a.transition() print("****************************************") #second string test s2="10" print(s2) a=ANode(s2, 0) b=BNode(s2) c=CNode(s2) d=DNode(s2) a.transition() print("****************************************") #third string test s3="101" print(s3) a=ANode(s3, 0) b=BNode(s3) c=CNode(s3) d=DNode(s3) a.transition()
66794a4ad1e567c1f2bcd7e99efbde9cdb46230b
Leonard-AI-Program/AI_Program_Template
/AI102_logistic_reg.py
4,449
3.765625
4
#%% Load packages import pandas as pd import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib import seaborn as sns # Sklearn is a package with multiple tools useful for machine learning models on Python from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score,classification_report,confusion_matrix from sklearn import datasets #%% #%% Import data & preprocessing df = pd.read_csv('https://raw.githubusercontent.com/ala-ism/AI_Program_Template/master/Sprinkler_data.csv') df = df[['Height', 'Flow', 'Distance_water_source_x', 'Distance_water_source_y', 'Zone']] df.head() #%% Create input & output tables X = df[['Distance_water_source_x', 'Distance_water_source_y']].values # we only take the first two features. y = df['Zone'].values #%% ''' To judge of the performance of a model, we need to split our data in a training set - which will be used to fit the model - and a testing set - with data previously unseen by the model. Sklearn provides tools to shuffle and split the data accordingly. See: https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html''' X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=0) #%% We create a function to visualize the main metrics ''' In classification several metrics can be used to evaluate the quality of a predictor. The function we are defining here use classification report, confusion matrices and accuracy score: https://en.wikipedia.org/wiki/Confusion_matrix https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html ''' def generateClassificationReport(y_test, y_pred): print(classification_report(y_test, y_pred)) print(confusion_matrix(y_test, y_pred)) print('accuracy is ',accuracy_score(y_test, y_pred)) #%% CLASSIFICATION MODELS # LOGISTIC REGRESSION # https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(solver="lbfgs", multi_class = 'multinomial') classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test, y_pred) # Exercise 1 : Test several parameters of the Logistic Regression function, # for instance the regularization coefficient C (see documentation) # (advanced: write a for loop and print the results) #%% DECISION TREE # https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier() classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test, y_pred) # Exercise 2 : Test several parameters of the Decision tree # (advanced: print one decision tree : https://scikit-learn.org/stable/modules/generated/sklearn.tree.plot_tree.html) #%% OTHER MODELS USED FOR CLASSIFICATION #NAIVE BAYES from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test,y_pred) #%% SUPPORT VECTOR MACHINE'S from sklearn.svm import SVC classifier = SVC() classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test,y_pred) #%% K-NEAREST NEIGHBOUR from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=8) classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test,y_pred) #%% ''' SOLUTION EX 1 ''' for c in [0.001, 0.5 , 10]: classifier = LogisticRegression(C=c, solver="lbfgs", multi_class = 'multinomial') classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) generateClassificationReport(y_test, y_pred) # %% ''' Solution Ex 2 ''' from sklearn import tree for max_depth in [1, 2, 3, 5]: clf = DecisionTreeClassifier(max_depth = max_depth) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) generateClassificationReport(y_test, y_pred) tree.plot_tree(clf, filled=True) plt.show()
6abf8898e20a7d3e040b6e000fee03a8dabab8eb
samantabueno/python
/CursoEmVideo/CursoEmVideo_ex091.py
577
3.671875
4
from random import randint from time import sleep from operator import itemgetter game = {'Player1': randint(1, 6), 'Player2': randint(1, 6), 'Player3': randint(1, 6), 'Player4': randint(1, 6)} for key, value in game.items(): print(f'The player {key} get the number {value} in the dice.') sleep(1) ranking = list() ranking = sorted(game.items(), key=itemgetter(1), reverse=True) print('=-'*30) print('-------RANKING--------') print(ranking) for pos, value in enumerate(ranking): print(f'In {pos+1} position: {value[0]} got {value[1]}')
01ef562f6d9d80c435c187eb6bd8b20ee89177df
ryrimnd/basic-python-d
/d-funcrv.py
620
3.65625
4
#def fungsisaya3(x): # return x #print(fungsisaya3("owo")) ''' def fungsisaya4(angka): while angka <= 10: print(angka) angka += 1 print("Selesai") def fungsisaya4(angka): while angka <= 10: print(angka) angka += 1 if angka == 5: return print("Selesai") def fungsisaya4(angka): while angka <= 10: print(angka) angka += 1 if angka == 5: break print("Selesai") fungsisaya4(1) ''' def fungsisaya5(): def fungsisaya6(): x = 10 + 10 return x return fungsisaya6() print(fungsisaya5())
26d6d68a370cba5d0a37b8607ba45b7d842662bc
JamCrumpet/Lesson-notes
/Lesson 4 if statements/4.5_numerical_comparisons.py
285
4.21875
4
# the following code checks if someone is 18 years old age = 18 print(age == 18) x = 17 if x != 42: print("That is not equal to x. Please try again.") # you can also include mathematical compairsons such as more or less than print(x < 20) print(x > 10) print(x < 10)
c45727661740a3b1e669ad95c567f4f8622c477a
Vaultence/conways-game-of-life
/pygameGameOfLife.py
4,014
3.71875
4
import pygame, sys, time, random from pygame.locals import * # set up the grid dimensions and display scaling PIXEL_SIZE = 25 GRID_WIDTH = 6 GRID_HEIGHT = 6 # Defines the interval of time that elapses between generations in milliseconds GENERATION_AGE = 500 # An identity function which returns the same grid def Identity(grid, row, col): return grid[row][col] # Counts the number of live neighbours (cells with a value of 1) where # a neighbour may wrap around to the other side of the grid, horizontally # or vertically def CountLiveNeighbours(grid, row, col): height = len(grid) width = len(grid[0]) count = ( grid[row-1][col-1] + grid[row-1][col] + grid[row-1][(col+1) % width] + grid[row][col-1] + grid[row][(col+1) % width] + grid[(row+1) % height][col-1] + grid[(row+1) % height][col] + grid[(row+1) % height][(col+1) % width] ) return count # Creates a printable copy of the grid for display in the console def PrintGrid(grid): rows = [] for row in grid: rows.append(' '.join(str(col) for col in row)) return '\n'.join(rows) # Conway's Game of Life rule - decides who lives and who dies! def GameOfLifeRule(grid, row, col): isAlive = grid[row][col] == 1 numNeighbours = CountLiveNeighbours(grid, row, col) # Any live cell with fewer than two live neighbors dies, as if by underpopulation. if (isAlive and numNeighbours < 2): return 0 # Any live cell with two or three live neighbors lives on to the next generation. if (isAlive and (numNeighbours == 2 or numNeighbours == 3)): return 1 # Any live cell with more than three live neighbors dies, as if by overpopulation. if (isAlive and (numNeighbours >= 4)): return 0 # Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. if (not isAlive and numNeighbours == 3): return 1 return 0 # Given a grid, returns a new grid with the rule applied def Generation(grid, rule): rows = len(grid) cols = len(grid[0]) next_generation = [[None for col in range(cols)] for row in range(rows)] for row in range(rows): for col in range(cols): next_generation[row][col] = rule(grid, row, col) return next_generation # Draws a grid on a windowSurface using the scaling in PIXEL_SIZE # Live cells are WHITE and dead cells are BLACK def DrawGrid(surface, grid): BLACK = (0, 0, 0) WHITE = (255, 255, 255) for row in range(len(grid)): top = row * PIXEL_SIZE for column in range(len(grid[row])): color = WHITE if grid[row][column] == 1 else BLACK left = column * PIXEL_SIZE pygame.draw.rect(surface, color, (left, top, PIXEL_SIZE, PIXEL_SIZE)) def RunGame(seedFunction): generation = seedFunction() print ('Running game with seed:') print (PrintGrid(generation)) # set up pygame pygame.init() windowSurface = pygame.display.set_mode((PIXEL_SIZE * GRID_HEIGHT, PIXEL_SIZE * GRID_WIDTH), 0) pygame.display.set_caption('Conway\'s Game of Life') pygame.time.set_timer(pygame.USEREVENT, GENERATION_AGE) # run the game loop while True: for event in pygame.event.get(): if (event.type == pygame.USEREVENT): generation = Generation(generation, GameOfLifeRule) DrawGrid(windowSurface, generation) pygame.display.update() elif event.type == pygame.QUIT: pygame.quit() sys.exit() # Returns a grid which has a glider that will wrap around def GliderGrid(): return [ [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0] ] # Returns a random grid of GRID_HEIGHT and GRID_WIDTH def RandomGrid(): return [[random.randint(0, 1) for col in range(GRID_WIDTH)] for row in range(GRID_HEIGHT)] RunGame(RandomGrid)
496ea6314c6280dcc956e7aef8943af21c309cba
pqnguyen/CompetitiveProgramming
/platforms/leetcode/CloneGraph.py
739
3.84375
4
# https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1392/ """ # Definition for a Node. class Node: def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors """ class Solution: def cloneGraph(self, node: 'Node') -> 'Node': m = {} cloneNode = self.dfs(node, m) return cloneNode def dfs(self, node, m): if not node: return None cloneNode = Node(node.val, []) m[node] = cloneNode for neighbor in node.neighbors: if neighbor not in m: self.dfs(neighbor, m) for neighbor in node.neighbors: cloneNode.neighbors.append(m[neighbor]) return cloneNode
b11c221980f3a1c47a3de32d59e1ce8775d181af
tinnso/ipdownload
/download.py
5,699
3.53125
4
import threading from urllib.request import urlretrieve import requests import os import datetime import logging class DownloadThread(threading.Thread): """ @author jason @desc download class inherit from thread for easy show thread name and time @date 2020/7/14 """ def __init__(self, url, start_pos, end_pos, f): """ construct of current class :param url: the target url for download :param start_pos: start position of current download thread :param end_pos: end position of current download thread :param f: file handler (IO low level) """ super(DownloadThread, self).__init__() self.url = url self.start_pos = start_pos self.end_pos = end_pos self.fd = f def download(self): """ download part of the target file by using Range attribute of request head :return: None """ logging.debug('start thread:%s at %s' % (self.getName(), get_current_time())) headers = {'Range': 'bytes=%s-%s' % (self.start_pos, self.end_pos)} res = requests.get(self.url, headers=headers) self.fd.seek(self.start_pos) self.fd.write(res.content) logging.debug('Stop thread:%s at%s' % (self.getName(), get_current_time())) self.fd.close() def run(self): """ override run method :return: None """ self.download() def get_current_time(): """ get current time of system :return: current time """ return datetime.datetime.now() def download_file_multi_thread(url, directory=None): """ download the target file with 8 threads :param url: target file url :param directory: directory where you want to put the downloading file :return: 0 if success, other if failed, 1 for download size didn't match """ ret = 0 #return 1 # test code file_name = url.split('/')[-1] file_size = int(requests.head(url).headers['Content-Length']) logging.debug('%s file size:%s' % (file_name, file_size)) thread_num = 8 threading.BoundedSemaphore(thread_num) # allowed number of thread step = file_size // thread_num mtd_list = [] start = 0 end = -1 tmp_file_name = file_name + "_tmp" if directory is not None: tmp_file_name = directory + "/" + tmp_file_name # this operation will refresh the temp file if it exists tmp_file = open(tmp_file_name, 'w') tmp_file.close() mtd_list = [] # open temp file then download with multi thread with open(tmp_file_name, 'rb+')as f: file_no = f.fileno() while end < file_size - 1: start = end + 1 end = start + step - 1 if (end + thread_num - 1) >= file_size - 1: end = file_size - 1 logging.debug('Start:%s,end:%s' % (start, end)) dup = os.dup(file_no) fd = os.fdopen(dup, 'rb+', -1) t = DownloadThread(url, start, end, fd) t.start() mtd_list.append(t) for i in mtd_list: i.join() f.close() # check the size of the file current_file_size = os.path.getsize(tmp_file_name) if current_file_size != file_size: logging.error("download failed,file size not match, original is %d, %d downloaded" % (file_size, current_file_size)) ret = 1 return ret if directory is not None: file_name = directory + "/" + file_name # remove the file if exists if os.path.exists(file_name): os.remove(file_name) # rename the temp name to normal os.rename(tmp_file_name, file_name) ret = 0 return ret def download_callback(block_number, block_size, data_size): """ callback for urlretrieve :param block_number: number of block :param block_size: size of one block :param data_size: total size of target file :return: none """ per = 100 * block_number * block_size / data_size if per > 100: per = 100 logging.debug('total size %d, %.2f%% \r' % (data_size, per)) def normal_download(url, directory): """ use normal method to download one file :param url: url of target file :param directory: sub folder at execute path, like download at where this program run :return: 0 if success, other if error, 1 for urlretrieve execute error """ original_name = url.split('/')[-1] tmp_file_name = directory + "/" + original_name + "_tmp2" file_name = directory + "/" + original_name file_size = int(requests.head(url).headers['Content-Length']) logging.debug('%s file size:%s' % (original_name, file_size)) try: urlretrieve(url, tmp_file_name, download_callback) except Exception as e: logging.error(e) return 1 current_file_size = os.path.getsize(tmp_file_name) if current_file_size != file_size: logging.error("download failed,file size not match, original is %d, %d downloaded" % (file_size, current_file_size)) ret = 1 return ret # remove the file if exists if os.path.exists(file_name): os.remove(file_name) u # rename the temp name to normal os.rename(tmp_file_name, file_name) return 0 if __name__ == "__main__": logging.basicConfig(level=logging.NOTSET) start_time = datetime.datetime.now() # test URL test_url = 'https://bulkdata.uspto.gov/data/patent/grant/redbook/fulltext/2020/ipg200107.zip' download_file_multi_thread(test_url, "downloaded") end_time = datetime.datetime.now() time_passed = end_time - start_time logging.debug(time_passed)
21e9fa1b4091fa0b78ccba840530ac667ffc3d22
cheshta-kabra/C-98
/countWords.py
276
4.28125
4
def countWord(): fileName=input('Enter any File name present in your PC') no_of_words=0 f=open(fileName) for line in f: words=line.split() no_of_words=no_of_words+len(words) print (len(words)) print(no_of_words) countWord()
f9b3b3b2ddb9c7294df0920e52cfeecbfb45de67
yywecanwin/PythonLearning
/day05/19.全局变量.py
610
3.890625
4
# -*- coding: utf-8 -*- # author:yaoyao time:2019/12/18 """ 全局变量 在函数外面定义的变量 特点: 可以在改程序文件的任何一个地方使用 前提时先定义后使用 """ # 定义全局变量 a = 20 def func1(num1,num2): print(num1 + num2) # 在函数内部对全局变量赋值,并不是修改全局变量的值,而是在定义一个同名的局部变量 # a = 10 # print(a) # 10 #要想在函数内部修改全局变量,必须: #1.先声明全局变量:使用关键字global global a a = 300 print(a) func1(12,12) print(a)
86f8bc1f60aefeb43e9dcd92dfc9546776244fcb
oguznsari/Improving-DNNs
/3-Gradient_Checking/gradient-checking.py
12,802
4.6875
5
""" Final assignment for this week! In this assignment you will learn to implement and use gradient checking. You are part of a team working to make mobile payments available globally, and are asked to build a deep learning model to detect fraud--whenever someone makes a payment, you want to see if the payment might be fraudulent, such as if the user's account has been taken over by a hacker. But backpropagation is quite challenging to implement, and sometimes has bugs. Because this is a mission-critical application, your company's CEO wants to be really certain that your implementation of backpropagation is correct. Your CEO says, "Give me a proof that your backpropagation is actually working!" To give this reassurance, you are going to use "gradient checking". Let's do it!""" import numpy as np from testCases import * from gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, gradients_to_vector def forward_propagation(x, theta): """ Implement the Linear forward propagation (compute J -- J(theta) = theta * x) Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: J -- the value of function J, computed using the formula J(theta) = theta * x """ J = x * theta return J x, theta = 2, 4 J = forward_propagation(x, theta) print("J = " + str(J)) # Implement the backward propagation step (derivative computation) -- the derivative of J(theta) = theta*x # with respect to theta.You should get dtheta = partial J / partial theta = x def backward_propagation(x, theta): """ Computes the derivative of J with respect to theta Arguments: x -- a real-valued input theta -- our parameter, a real number as well Returns: dtheta -- the gradient of the cost with respect to theta """ dtheta = x return dtheta x, theta = 2, 4 dtheta = backward_propagation(x, theta) print("dtheta = " + str(dtheta)) """ Gradient check: First compute "gradapprox" Then compute the gradient using backward propagation, and store the result in a variable "grad" Finally, compute the relative difference between "gradapprox" and the "grad" You will need 3 Steps to compute this formula: - compute the numerator using np.linalg.norm(...) - compute the denominator. You will need to call np.linalg.norm(...) twice. - divide them. If this difference is small (say less than 10^{-7}), you can be quite confident that you have computed your gradient correctly. Otherwise, there may be a mistake in the gradient computation.""" def gradient_check(x, theta, epsilon = 1e-7): """ Implement the backward prop Arguments: x -- a real-valued input theta -- our parameter, a real number as well epsilon -- tiny shift to the input to compute approximated gradient Returns: difference -- difference between the approximated gradient and the backward propagation gradient """ # compute the "gradapprox". epsilon is small enough, no need to worry about limit thetaplus = theta + epsilon thetaminus = theta - epsilon J_plus = thetaplus * x J_minus = thetaminus * x gradapprox = (J_plus - J_minus) / (2 * epsilon) grad = x numerator = np.linalg.norm(grad - gradapprox) denominator = np.linalg.norm(grad) + np.linalg.norm(gradapprox) difference = numerator / denominator if difference < 1e-7: print("The gradient is correct!") else: print("The gradient is wrong!") return difference x, theta = 2, 4 difference = gradient_check(x, theta) print("difference = " + str(difference)) # difference = 2.919335883291695e-10 --> since the difference is smaller than the 10^{-7} threshold, gradient is correct """ In the more general case, your cost function J has more than a single 1D input. When you are training a neural network, theta actually consists of multiple matrices W[l] and biases b[l]! It is important to know how to do a gradient check with higher-dimensional inputs. Let's do it!""" """ N-dimensional gradient checking Let's look at your implementations for forward propagation and backward propagation.""" def forward_propagation_n(X, Y, parameters): """ Implements the forward propagation (and computes the cost) Arguments: X -- training set for m examples Y -- true "labels" for m examples parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": W1 -- weight matrix of shape (5, 4) b1 -- bias vector of shape (5, 1) W2 -- weight matrix of shape (3, 5) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector of shape (1, 1) Returns: cost -- the cost function (logistic cost for one example) """ # retrieve parameters m = X.shape[1] W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) # Cost logprobs = np.multiply(-np.log(A3), Y) + np.multiply(-np.log(1 - A3), 1 - Y) cost = 1/m * np.sum(logprobs) cache = (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) return cost, cache def backward_propagation_n(X, Y, cache): """ Implement the backward propagation Args: X -- input datapoint, of shape (input size, 1) Y -- true "label" cache -- cache output from forward_propagation_n() Returns: gradients -- A dictionary with the gradients of the cost with respect to each parameter, activation and pre-activation variables. """ m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y dW3 = 1./m * np.dot(dZ3, A2.T) db3 = 1./m * np.sum(dZ3, axis=1, keepdims=True) dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) # dW2 = 1./m * np.dot(dZ2, A1.T) * 2 dW2 = 1./m * np.dot(dZ2, A1.T) db2 = 1./m * np.sum(dZ2, axis=1, keepdims=True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = 1./m * np.dot(dZ1, X.T) # db1 = 4./m * np.sum(dZ1, axis=1, keepdims=True) db1 = 1./m * np.sum(dZ1, axis=1, keepdims=True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3, "dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients # You obtained some results on the fraud detection test set but you are not 100% sure of your model. # Nobody's perfect! Let's implement gradient checking to verify if your gradients are correct. # Want to compare "gradapprox" to the gradient computed by backpropagation """ However, theta is not a scalar anymore. It is a dictionary called "parameters". We implemented a function "dictionary_to_vector()" for you. It converts the "parameters" dictionary into a vector called "values", obtained by reshaping all parameters (W1, b1, W2, b2, W3, b3) into vectors and concatenating them. The inverse function is "vector_to_dictionary" which outputs back the "parameters" dictionary. We have also converted the "gradients" dictionary into a vector "grad" using gradients_to_vector(). You don't need to worry about that. To compute J_plus[i]: Set theta^{+} to np.copy(parameters_values) Set theta[i]^{+} to theta[i]^{+} + epsilon Calculate J[i]^{+} using to forward_propagation_n(x, y, vector_to_dictionary(theta^{+})). To compute J_minus[i]: do the same thing with theta^{-} Compute gradapprox[i] = J[i]^{+} - J[i]^{-} / (2 * epsilon) Thus, you get a vector gradapprox, where gradapprox[i] is an approximation of the gradient with respect to parameter_values[i]. You can now compare this gradapprox vector to the gradients vector from backpropagation. Just like for the 1D case (Steps 1', 2', 3'), compute: difference = |grad - gradapprox|_2} / | grad |_2 + | gradapprox |_2 """ def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7): """ Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters grad -- output of backward_propagation_n, contains gradients of the cost with respect to the parameter s. X -- input datapoint, of shape (input size, 1) Y -- true "label" epsilon -- tiny shift to the input to compute approximated gradient Returns: difference -- difference between approximated gradient and the backward propagation gradient """ # Set up variables parameters_values, _ = dictionary_to_vector(parameters) grad = gradients_to_vector(gradients) num_parameters = parameters_values.shape[0] J_plus = np.zeros((num_parameters, 1)) J_minus = np.zeros((num_parameters, 1)) gradapprox = np.zeros((num_parameters, 1)) # compute gradapprox for i in range(num_parameters): # Compute J_plus[i]. Inputs: "parameters_values, epsilon". Output: "J_plus[i]" # "_" is used because the function you have to outputs two parameters but we only care about the first one thetaplus = np.copy(parameters_values) thetaplus[i][0] += epsilon J_plus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaplus)) # Compute J_minus[i]. Inputs: "parameters_values, epsilon". Output: "J_minus[i]". thetaminus = np.copy(parameters_values) thetaminus[i][0] -= epsilon J_minus[i], _ = forward_propagation_n(X, Y, vector_to_dictionary(thetaminus)) # Compute gradapprox[i] gradapprox[i] = (J_plus[i] - J_minus[i]) / (2 * epsilon) # Compare gradapprox to backward propagation gradients by computing difference. numerator = np.linalg.norm(gradapprox - grad) denominator = np.linalg.norm(gradapprox) + np.linalg.norm(grad) difference = numerator / denominator if difference > 1.2e-7: print("\033[93m" + "There is a mistake in the backward propagation! difference = " + str(difference) + "\033[0m") else: print("\033[92m" + "Your backward propagation works perfectly fine! difference = " + str(difference) + "\033[0m") return difference X, Y, parameters = gradient_check_n_test_case() cost, cache = forward_propagation_n(X, Y, parameters) gradients = backward_propagation_n(X, Y, cache) difference = gradient_check_n(parameters, gradients, X, Y) """ It seems that there were errors in the backward_propagation_n code we gave you! Good that you've implemented the gradient check. Go back to backward_propagation and try to find/correct the errors (Hint: check dW2 and db1). Rerun the gradient check when you think you've fixed it. Remember you'll need to re-execute the cell defining backward_propagation_n() if you modify the code. Can you get gradient check to declare your derivative computation correct? Even though this part of the assignment isn't graded, we strongly urge you to try to find the bug and re-run gradient check until you're convinced backprop is now correctly implemented.""" """ Note Gradient Checking is slow! Approximating the gradient with partial J / partial theta approx= J(theta + epsilon) - J(theta - epsilon) / {2 * epsilon} is computationally costly. For this reason, we don't run gradient checking at every iteration during training. Just a few times to check if the gradient is correct. Gradient Checking, at least as we've presented it, doesn't work with dropout. You would usually run the gradient check algorithm without dropout to make sure your backprop is correct, then add dropout. Congrats, you can be confident that your deep learning model for fraud detection is working correctly! You can even use this to convince your CEO. :) Gradient checking verifies closeness between the gradients from backpropagation and the numerical approximation of the gradient (computed using forward propagation). Gradient checking is slow, so we don't run it in every iteration of training. You would usually run it only to make sure your code is correct, then turn it off and use backprop for the actual learning process."""
78f8df9264eb758ec260c1fce8b79f262656249e
bluella/hackerrank-solutions-explained
/src/Arrays/Array Manipulation.py
1,101
3.75
4
#!/usr/bin/env python3 """ https://www.hackerrank.com/challenges/crush Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. """ import math import os import random import re import sys def arrayManipulation(n, queries): """ Args: n (int): len of zero arr. queries (list): 2d list with queries Returns: int: max element""" arr = [0] * (n + 1) # increase first el by query amount and decrease last of query amount for i in queries: arr[i[0] - 1] += i[2] arr[i[1]] -= i[2] # this way it's easy compute each el resulting value in one run ans = 0 current = 0 for i in arr: current += i if current > ans: ans = current return ans if __name__ == "__main__": ex_arr = [[1, 5, 3], [4, 8, 7], [6, 9, 1]] zero_arr_len = 10 result = arrayManipulation(zero_arr_len, ex_arr) print(result)
4184879cf3022c5feb62d02a313e946dd5a7ce13
novaprotocolio/ranking-consensus
/ranking.py
199
3.5
4
for n in range(1, 1000000): for i in range(2, n-1): if n % i == 0: break elif i == n-2: break # print("%d" % n) # print("\nDONE!")
8cf917cbfb8b8f2178e239af4712de0bf35800bd
jms0923/docker_tcp
/sensor_input.py
1,264
3.546875
4
import json class sensing: def __init__(self): # 센서 명 선언. self.sen_01 = 'sensor_01' self.sen_02 = 'sensor_02' self.sen_03 = 'sensor_03' self.listSensorName = [] self.listSensorValue = [] self.listSensorName.append(self.sen_01) self.listSensorName.append(self.sen_02) self.listSensorName.append(self.sen_03) def sensing(self): # 센싱 값 입력 받음. for i in range(len(self.listSensorName)): print('plz enter ' + self.listSensorName[i] + ' data : ', end='') self.listSensorValue.append(input()) jsonStr = self.makeJsonStr(self.listSensorName, self.listSensorValue) return jsonStr # json object로 만들어줌. def makeJsonStr(self, listSensorName, listSensorValue): strJson = '{' for i in range(len(listSensorName)): strJson += '"' + listSensorName[i] + '":"' + listSensorValue[i] + '"' if i < len(listSensorName) - 1: strJson += ',' else: strJson += '}' # print(strJson) # jsonObj = json.loads(strJson) # jsonObj = json.dumps(strJson) # print(type(jsonObj)) return strJson
3e8f82ef9052ee5c45bd6dcb8265b9854a5f958b
jbanerje/Beginners_Python_Coding
/loop_list.py
306
3.953125
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 16 16:33:47 2017 @author: jagan """ list1 = ['apple','orange','banana','grapes','kiwi'] list2 = [] for item in list1: if (item =='orange'): print ("I found it!") list2.append(item) print(list2) #else: #print("couldn't find")
1d154720142a9109822bd371f08300aab971fcf5
pavoli/becoming_true_pythonista
/functions/func_1.py
378
4.03125
4
# -*- coding: utf-8 -*- #! /usr/local/bin/python3 __author__ = 'p.olifer' def square(x): return x * x def cube(x): return x * x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4, 5]) squares3 = my_map(cube, [1, 2, 3, 4, 5]) print(squares) print(squares3)
70a18a2b1d0f5a4c4fbd59034b3d7d1c2470ed31
Swastik-Saha/Python-Programs
/Find_The_Largest_Of_3_Numbers.py
116
3.640625
4
def largest(num1,num2,num3): large = num1 if num2>large: large = num2 if num3>large: large=num3 print large
09c24584e116654ee8655d3a51f50eb8a05f6d56
jakehoare/leetcode
/python_1_to_1000/277_Find_the_Celebrity.py
1,588
4
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/find-the-celebrity/ # Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. # The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them. # Now you want to find out who the celebrity is or verify that there is not one. # The only thing you are allowed to do is to ask questions "Does A know B?". You need to find out the celebrity (or # verify there is not one) by asking as few questions as possible (in the asymptotic sense). # Find the only candidate by testing each person. If the candidate knows that person, the candidate is not a celebrity # and the new candidate is the test person. If the candidate doesn't know that person, then that person is not a # celebrity. Note that there can be only one or zero celebrities. # Then verify whether the candidate if valid. # Time - O(n) # Space - O(1) # The knows API is already defined for you. # @param a, person a # @param b, person b # @return a boolean, whether a knows b def knows(a, b): return class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ candidate = 0 for i in range(1, n): if knows(candidate, i): candidate = i for i in range(n): if i == candidate: continue if not knows(i, candidate) or knows(candidate, i): return -1 return candidate
89c1b463b68e90d0690966c0a73f99cc66bef75e
anishLearnsToCode/python-training-1
/day_3/lists.py
450
3.984375
4
""" List [] - mutable (modify) - iterable - strings are immutable (you cant modify a string) - range i immutable - len() can be used on any iterable """ """ Time Complexity: O(1) Space Complexity: O(1) """ numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23] print(numbers) print(type(numbers)) print(len(numbers)) # add elements # append(value) # insert(position, value) # Removing elements # pop(position=-1) --> element # remove(value) # del keyword
bd727e9837c3195421a57d67d04352b584a71ecb
RANJITHA-v/python-programming
/BEGINNER LEVEL/multi.py
111
3.5625
4
n=int(raw_input()) prvar = '' for i in range(1,6): mul=n*i prvar = prvar+' '+ str(mul) print prvar
48bce97b49644e94ffce004db43329f5a91c2bfd
avholloway/100DaysOfCode
/day21.py
5,239
3.53125
4
from random import randint from math import hypot, sin from turtle import Turtle, Screen class SnakeGame: def __init__(self): self.screen = Screen() self.screen.setup(width=600, height=600) self.screen.title("Snake") self.screen.bgcolor("black") self.screen.colormode(255) self.screen.tracer(0) self.snake = Snake() self.food = Food() self.scoreboard = Scoreboard() self.setup_keybindings() self.running = True self.run() self.screen.mainloop() def setup_keybindings(self): self.screen.onkeyrelease(self.snake.face_up, "Up") self.screen.onkeyrelease(self.snake.face_down, "Down") self.screen.onkeyrelease(self.snake.face_left, "Left") self.screen.onkeyrelease(self.snake.face_right, "Right") self.screen.onkeyrelease(self.screen.bye, "Escape") self.screen.listen() def run(self): if self.running: self.snake.slither() self.screen.update() if self.snake.has_crashed(): self.game_over() if self.snake.is_eating(self.food): self.level_up() self.screen.ontimer(self.run, 100) def level_up(self): self.scoreboard.add_point() self.snake.add_segment() self.food.relocate() def game_over(self): self.running = False self.scoreboard.game_over() class Snake(Turtle): def __init__(self): super().__init__() self.UP = 90 self.DOWN = 270 self.LEFT = 180 self.RIGHT = 0 self.SEGWIDTH = 21 self.segments = [] self.create_head() self.add_segment() self.add_segment() def create_head(self): self.head = self.base_segment() self.segments.append(self.head) self.update_color() def base_segment(self): segment = Turtle(shape="square") segment.penup() return segment def add_segment(self): segment = self.base_segment() segment.goto(self.segments[-1].position()) self.segments.append(segment) self.update_color() def slither(self): for i in range(len(self.segments) - 1, 0, -1): self.segments[i].goto(self.segments[i - 1].position()) self.head.forward(self.SEGWIDTH) self.can_turn = True return self def update_color(self): self.segments[-1].color( int((sin((.3 * len(self.segments)) + 0) * 127) + 127.5), int((sin((.3 * len(self.segments)) + 2) * 127) + 127.5), int((sin((.3 * len(self.segments)) + 4) * 127) + 127.5) ) def face_up(self): if self.can_turn and self.head.heading() not in [self.UP, self.DOWN]: self.can_turn = False self.head.setheading(self.UP) def face_down(self): if self.can_turn and self.head.heading() not in [self.DOWN, self.UP]: self.can_turn = False self.head.setheading(self.DOWN) def face_left(self): if self.can_turn and self.head.heading() not in [self.LEFT, self.RIGHT]: self.can_turn = False self.head.setheading(self.LEFT) def face_right(self): if self.can_turn and self.head.heading() not in [self.RIGHT, self.LEFT]: self.can_turn = False self.head.setheading(self.RIGHT) def is_eating(self, food): return self.head.distance(food) < 7 def has_crashed(self): return self.has_collided_with_wall() or self.has_collided_with_tail() def has_collided_with_wall(self): return (self.head.ycor() >= 273 or self.head.ycor() <= -273 or self.head.xcor() >= 273 or self.head.xcor() <= -273) def has_collided_with_tail(self): for segment in self.segments[1:]: if self.head.distance(segment) < 7: return True return False class Food(Turtle): def __init__(self): super().__init__() self.penup() self.color("coral") self.shape("square") self.shapesize(stretch_wid=0.5, stretch_len=0.5) self.relocate() def relocate(self): while True: x, y = randint(-12, 12) * 21, randint(-12, 12) * 21 dist = hypot(self.position()[0] - x, self.position()[1] - y) if dist > 21 * 6: self.curr_pos = self.position() break self.goto(x, y) class Scoreboard(Turtle): def __init__(self): super().__init__() self.penup() self.hideturtle() self.color("white") self.reset_board() def reset_board(self): self.score = 0 self.goto(0, 285) self.update_board() def add_point(self): self.score += 1 self.update_board() def update_board(self): self.clear() self.write(f"Score: {self.score}", False, align="center") def game_over(self): self.goto(0, 0) self.write("Game Over", False, align="center") game = SnakeGame()
8c39882b92bb3723b71b526d832d5ddb786d6a48
yribeiro/ds
/lists.py
6,428
3.9375
4
""" What are linked lists? Sequential list of nodes that contain data, and hold references to other nodes containing data. Great for modelling trajectories, circular elements (polygons) etc. Used in implementations for Queue, Stack and List ADTs. Often used in implementations of adjacency lists for graphs. During implementations every node has a reference to the head and tail nodes to make easy additions and removals. Doubly linked lists not only contain pointers to the next node the sequence (singly linked lists) but also contain pointers to the previous node, allowing for traversal forwards and backwards. Terminology: * Head: The first node in the linked list * Tail: The last node in the linked list * Pointer: Reference to another node * Node: Object containing data and pointer(s) Complexity Analysis: SLL DLL ---------------------------- Search O(n) O(n) Head Insert O(1) O(1) Tail Insert O(1) O(1) Head Remove O(1) O(1) Remove tail O(n) O(1) Remove i O(n) O(n) Singly Linked List tail removal is O(n) because you cannot reset the tail pointer after you have removed it once; and will need to traverse the list to the end (n) to find the new tail. """ from typing import Any, Optional class Node: """ Node class to embed within the Linked List. Can hold any type of data. """ def __init__(self, data: Any, prev: Optional["Node"], next: Optional["Node"]): self.data = data self.prev = prev self.next = next def __str__(self): return str(self.data) class DoublyLinkedList: """ Doubly Linked List implementation in Python. """ def __init__(self): self._size = 0 self._head: Optional["Node"] = None self._tail: Optional["Node"] = None # region magic methods def __len__(self): return self._size def __str__(self): out = [] trav = self._head while trav is not None: out.append(str(trav)) trav = trav.next return str(out) # endregion # region public api def is_empty(self) -> bool: return self._size == 0 def clear(self): trav = self._head while trav is not None: next_node = trav.next trav.prev = trav.next = None trav = next_node self._head = self._tail = None self._size = 0 def prepend(self, data: Any): if self.is_empty(): self._head = self._tail = Node(data=data, prev=None, next=None) else: self._head.prev = Node(data=data, prev=None, next=self._head) self._head = self._head.prev self._size += 1 def append(self, data: Any): if self.is_empty(): self._head = self._tail = Node(data=data, prev=None, next=None) else: self._tail.next = Node(data=data, prev=self._tail, next=None) self._tail = self._tail.next self._size += 1 def first(self) -> Any: if self.is_empty(): raise IndexError("Empty List") return self._head.data def last(self) -> Any: if self.is_empty(): raise IndexError("Empty List") return self._tail.data def remove_first(self) -> Any: if self.is_empty(): raise IndexError("Empty List") data = self._head.data self._head = self._head.next self._size -= 1 # clean up the pointers if self.is_empty(): self._tail = None else: self._head.prev = None return data def remove_last(self) -> Any: if self.is_empty(): raise IndexError("Empty List") data = self._tail.data self._tail = self._tail.prev self._size -= 1 # clean up the pointers if self.is_empty(): self._head = None else: self._tail.next = None return data def _remove_node(self, n: "Node"): # check if head or tail if n.prev is None: return self.remove_first() if n.next is None: return self.remove_last() # continue prev_node, next_node = n.prev, n.next prev_node.next = next_node next_node.prev = prev_node self._size -= 1 data = n.data # clean up memory n = None return data def remove(self, idx: int) -> Any: assert 0 <= idx < self._size, "OutOfBoundsError" # check head and tail removal if idx == 0: return self.remove_first() if idx == self._size - 1: return self.remove_last() trav = self._head for i in range(self._size): if i == idx: break trav = trav.next return self._remove_node(trav) def insert_at(self, idx: int, data: Any) -> bool: # checks assert 0 <= idx < len(self), "Index is out of bounds. Method does not support negative indexing." # handle start and end if idx == 0: self.prepend(data) elif idx == len(self) - 1: self.append(data) else: node_before_position = self._head # get the node just before the position to enter for i in range(len(self)): if i == idx - 1: break node_before_position = node_before_position.next # create a new node and enter into the list new_node = Node(data, prev=node_before_position, next=node_before_position.next) node_before_position.next = new_node # increment the size self._size += 1 return True # endregion if __name__ == "__main__": dll = DoublyLinkedList() for i in range(20): dll.append(i) print(dll) dll.clear() print(dll) for i in range(20): dll.append(i) # remove an element dll.remove(7) print(dll) dll.prepend("HELLOWORLD") print(dll) dll.remove(len(dll) - 1) print(dll) dll.clear() print(dll) # check insertion at random position _ = [dll.append(i) for i in range(10)] dll.insert_at(2, "New Entry") print(dll, f"Size: {len(dll)}")
cab36ef5fafc9942c472be033d48763891f9b52e
gschen/sctu-ds-2020
/1906101033-唐超/Day0226/5.py
214
3.546875
4
#5. (使用循环和判断)输入三个整数x,y,z,请把这三个数由小到大输出。 x,y,z=map(int,input().split()) if y < x: x,y = y,x if z < x: x,z = z,x if z < y: y,z = z,y print(x, y, z)
73a351056873dfbec312ff35081044e07e17039e
PhiphyZhou/Coding-Interview-Practice-Python
/HackerRank/CCI-Trees-isBST.py
1,474
4.1875
4
# Trees: Is This a Binary Search Tree? # https://www.hackerrank.com/challenges/ctci-is-binary-search-tree # Given the root node of a binary tree, can you determine if it's also a binary search tree? # Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None # solution 1 # inorder traversal and put each element in an array, then check if the array is in order def inord(arr, root): if root.left: inord(arr, root.left) # print root.data arr.append(root.data) if root.right: inord(arr, root.right) def check_binary_search_tree_1(root): arr = [] inord(arr, root) # print arr for i in range(len(arr)-1): if arr[i] >= arr[i+1]: return False return True # solution 2 # don't use extra array, compare during the inorder traversal flag = True prev = None def check_inorder(root): global flag, prev if not flag: return if root.left: check_inorder(root.left) if prev: if root.data <= prev: flag = False return prev = root.data if root.right: check_inorder(root.right) def check_binary_search_tree_2(root): check_inorder(root) f = flag return f def buildTree(): root = node(3) root.left = node(2) root.right = node(6) l = root.left r = root.right l.left = node(1) l.right = node(4) r.left = node(5) r.right = node(7) return root r = buildTree() print check_binary_search_tree_2(r)
a68f33817a2dbb1a2992b2b9f7c5dcd8b9688e02
adumont/Calculadora
/main.py
1,574
3.765625
4
import math import os # The screen clear function def screen_clear(): # for mac and linux(here, os.name is 'posix') if os.name == 'posix': _ = os.system('clear') else: # for windows platfrom _ = os.system('cls') # print out some text pila = [] tamanio = 4 def showPila(): l=len(pila) n=min(l,tamanio) print("____________________") for i in range(tamanio-n): print("%d:" % (tamanio-i)) for i in range(n): num = "%f" % pila[l-n+i] pad = ' ' * (17 - len(num)) print("%d: %s%s" % (n-i, pad, num)) print("") while True: screen_clear() showPila() s = input("") s = s.strip() for a in s.split(" "): if a in ["+", "-", "/", "*", "**", "%"]: n2 = pila.pop() n1 = pila.pop() if a == "+": pila.append(n1+n2) elif a == "-": pila.append(n1-n2) elif a == "*": pila.append(n1*n2) elif a == "/": pila.append(n1/n2) elif a == "**": pila.append(n1**n2) elif a == "%": pila.append(n1%n2) elif a.lower() == "drop": pila.pop() elif a.lower() == "dropn": n = int(pila.pop()) for i in range(n): pila.pop() elif a.lower() == "pick": n = int(pila.pop()) pila.append(pila[-n]) elif a.lower() == "swap": n2 = pila.pop() n1 = pila.pop() pila.append(n2) pila.append(n1) elif a.lower() in ["purge", "clear"]: pila=[] elif a.lower() == "len": pila.append(len(pila)) elif a == "pi": pila.append(math.pi) else: pila.append(float(a))
6d311b9e318a3b3280c73ff85a518ec175b4b143
gloria-ho/algorithms
/python/invert_values.py
485
3.984375
4
# https://www.codewars.com/kata/5899dc03bc95b1bf1b0000ad # Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. # invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] # invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] # invert([]) == [] # You can assume that all values are integers. Do not mutate the input array/list. def invert(lst): newLst = [] if len(lst) > 0: for x in lst: newLst.append(-x) return newLst
190a5992c137e856d104feb2147ea8a73c86269c
ShiyuCheng2018/ISTA350_Programming_for_Informatics_App
/assignmengs/assignment_6/hw6.py
3,058
3.78125
4
""" Author: Shiyu Cheng (23329948) ISTA 350 Hw6 SL: Jacob Heller Date: 4/17/20 Summary: Intro to web scrapping. Grabs the data you need from the web, put it into an html parser, and save the result into a file. """ from bs4 import BeautifulSoup import requests, zlib, gzip, os def get_soup(url=None, fname=None, gzipped=False): """ This function has three parameters. The first is a string representing a URL and has a default argument of None. The second is a string named fname representing a filename also with default argument of None. The third is a Boolean named gzipped with a default value of False. True is passed to this parameter if the html to be parsed is gzipped. If the filename is not None, the file is opened and then passed the resulting file pointer to the BeautifulSoup constructor, and return the resulting object. If the url is None, a RuntimeError with a message is returned. If it is not None, a get request is sent to the server. If the response content is zipped, it is unzipped. Then the content is passed to the BeautifulSoup constructor and the resulting object is returned. :param url: string :param fname: string :param gzipped: boolean :return: BeautifulSoup """ if fname: return BeautifulSoup(open(fname)) if not url: raise RuntimeError("Either url or filename must be specified.") request = requests.get(url) if gzipped: return BeautifulSoup(zlib.decompress(request.content, 16 + zlib.MAX_WBITS)) return BeautifulSoup(request.content) def save_soup(fname, soup): """ this function takes two arguments, a filename and a soup object. It saves a textual representation of the soup object in the file. :param fname: string :param soup: soup :return: """ with open(fname, 'w') as file: file.write(repr(soup)) file.close() def scrape_and_save(): """ this function scrapes the following addresses, soupifies the contents, and stores a textual representation of these objects in the files 'wrcc_pcpn.html', 'wrcc_mint.html', and 'wrcc_maxt.html' :return: """ save_soup('wrcc_pcpn.html', get_soup('https://wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+pcpn+none+msum+5+01+F')) save_soup('wrcc_mint.html', get_soup('https://wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+mint+none+mave+5+01+F')) save_soup('wrcc_maxt.html', get_soup('https://wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+maxt+none+mave+5+01+F')) def main(): """ The current directory is checked for any one of the files that scrape_and_save creates. If it is not there, a print statement prints and scrapes and saves the addresses. :return: """ _default = False for html in os.listdir(): if html in ['wrcc_pcpn.html', 'wrcc_mint.html', 'wrcc_maxt.html']: _default = True if not _default: print('---- scraping and saving ----') scrape_and_save()
74d56b01b816bb0c0e187f3c8e34abf6efc894f4
AkOutlaw/MG_HomeWork
/L5_DZ_2.py
440
3.78125
4
# задача "Удаление лищних пробелов" strMy = input('Введите нескольк слов с любым количесвом пробелов: ') normolizedRow = '' tempRow = '' import re tempRow = re.findall('\w+',strMy) for i in range(len(tempRow)): # складываем все слова normolizedRow += tempRow[i] + ' ' # склеиваем добавляя пробел print(normolizedRow)
538cdd1e262db6be14cbffe50df53926b106d3c9
a58982284/cookbook
/house passwoard.py
1,113
4.03125
4
''' 如果密码的长度大于或等于10个字符,且其中至少有一个数字、一个大写字母和一个小写字母, 该密码将被视为足够强大。密码只包含ASCII拉丁字母或数字 re.match("[a-zA-Z0-9]+", password) 9 < len(password) ≤ 64 ''' import re def password(password): if re.match("[a-zA-Z0-9]+", password) and 9 < len(password) <= 64: return True else: return False if __name__ == '__main__': print (password("QwErTy911poqqqq")) print (password('A1213pokl')) print (password('bAse730onE4')) DIGIT_RE = re.compile('\d') UPPER_CASE_RE = re.compile('[A-Z]') LOWER_CASE_RE = re.compile('[a-z]') def checkio(data): """ Return True if password strong and False if not A password is strong if it contains at least 10 symbols, and one digit, one upper case and one lower case letter. """ if len(data) < 10: return False if not DIGIT_RE.search(data): return False if not UPPER_CASE_RE.search(data): return False if not LOWER_CASE_RE.search(data): return False return True
f332d7c1d4092caa94f2222afcf45e26e5e347af
cemalsenel/pythonQuestions
/day03.py
1,008
3.84375
4
text = "Clarusway, Clarusway, Clarusway, \n\tClarusway, Clarusway, Clarusway,\n\t\tClarusway, Clarusway, Clarusway" print(text) a = 2**5 # exponentiation operator b=2*5 # multiplication operator c=27//10 # integer divison operator d=27/10 # float divison operator e=25+10 # addition operator f=25-10 # substraction operator g=32%5 # remainder operator print(a,b,c,d,e,f,g) print('4'+str(4)) print('11-7') print(4+11.0) pi = 3.14 r=5 area = pi* r**2 print(area) a1 =3 b1 =4 c1=None c1=(a1 ** 2 + b1 ** 2) ** 0.5 print(c1) x,y,z,t = 12 , "merhaba" , False , "3+2" print(x,y,z,t) print("ahmet", "mehmet", "hasan") print("ahmet", "mehmet", "hasan", sep ="*") print("ahmet", "mehmet", "hasan", sep = "//") print("ahmet", "mehmet", "hasan", sep = "\n") # Escape Sequences print('merhaba\ney \tyalan\\hayat', '\bsen bana \'nasilsin\' dedin') print("ahmet") print("mehmet") print("hasan") print("ahmet", end = "-") print("ahmet", end = " ") print("hasan") print("clarusway", end = "\n\n") print("istanbul")
394a0a08ea7ed8d609b808902500aab8a1b60fdf
axayjha/algorithms
/bfs.py
680
3.625
4
class vertex(object): def __init__(self, name): self.name=name self.colour=None self.d=None self.p=None s=vertex('s') b=vertex('b') c=vertex('c') d=vertex('d') e=vertex('e') f=vertex('f') g=vertex('g') V=[s,b,c,d,e,f,g] for i in V: i.colour="white" i.d = None i.p=None V[0].colour = "gray" V[0].d=0 V[0].p=None G={s:[b,c], b:[s,d,g], c:[s,f], d:[b,e], e:[d], f:[c], g:[b]} Q=[] Q.append(V[0]) while(len(Q)!=0): u=Q.pop(0) for v in G[u]: if v.colour=="white": v.colour="gray" v.d=u.d+1 v.p=u Q.append(v) print(v.name) u.colour="black"
215443c02c8f65d7e78f6896a697bf0d1065cb74
ryanmcg86/Euler_Answers
/009_Special_Pythagorean_triplet.py
1,309
4.3125
4
'''A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 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. Link: https://projecteuler.net/problem=9''' #Imports import time #Build a is-pythagorean function def isPythag(a, b, c): return a**2 + b**2 == c**2 #Build a findProd function def findProd(): #Define variables start = time.time() num = 1000 triplet = [] #Solve the problem for a in range(1, int(num / 3)): b = a + 1 c = num - a - b while a < b and b < c: if isPythag(a, b, c): triplet = [a, b, c] break b += 1 c = num - a - b a, b, c = triplet[0], triplet[1], triplet[2] prod = str(a * b * c) a, b, c = str(a), str(b), str(c) p = a + ' * ' + b + ' * ' + c n = str(num) print('The Pythagorean triplet for which ') print('a + b + c = 1000 is ' + a + ', ' + b + ', and ' + c + '.') print('The product of ' + p + ' is ' + prod + '.') print('This took ' + str(time.time() - start) + ' seconds to calculate.') #Find the product of the Pythagorean triplet for which a + b + c = 1000 findProd()
eba54b64e9be854bd3c688752ea0e89c4ef1c2d9
chachachill/spoj
/ONP.py
1,430
3.703125
4
from sys import stdin file = stdin def read_line(): return file.readline().strip() def read_int(): return int(read_line()) def string_list_to_int_list(x): return [int(e) for e in x] operand_hash_map = {'(': 0, '+': 1, '-': 2, '*': 3, '/': 4, '^': 5} def is_operand(c): return c in operand_hash_map def precedence(c): return operand_hash_map[c] def is_higher_precedence(a, b): return precedence(a) > precedence(b) def is_expression_start(c): return c == '(' def is_expression_end(c): return c == ')' def find_expression(lst, start=0): operand_stack = [] output_queue = [] while len(lst) > start: char = lst[start] if is_expression_start(char): operand_stack.append(char) elif is_expression_end(char): opr = operand_stack.pop() while opr != '(': output_queue.append(opr) opr = operand_stack.pop() elif is_operand(char): while len(operand_stack) > 0 and is_higher_precedence(operand_stack[-1], char): output_queue.append(operand_stack.pop()) operand_stack.append(char) else: output_queue.append(char) start += 1 return output_queue cases = read_int() for case in range(cases): inp = list(read_line()) print("".join(find_expression(inp)))
e1bf6f85efcc95b18514eb098bea956e93ff1f2b
mahmoodyasir/Python_Assignment_1
/hw_4.py
208
3.96875
4
lists = [] size = int(input("Enter size of the list:")) for i in range(size): num = int(input("Enter number [" + str(i+1) + "]: ")) lists.append(num) lists = list(dict.fromkeys(lists)) print(lists)
d74870048968d4436fd0cfceb95a87f097b2d078
AswinNasiketh/fyp-isd
/trace_analyser/logger.py
380
3.78125
4
#python module to do all printing so it can easily be redirected to a file output rather than console #comment next 3 lines if output to console rather than file is required import sys sys.stdout = open('log.txt', 'w') print('Start') def print_line(*args): print_str = "" for strPart in args: print_str = print_str + str(strPart) + " " print(print_str)
1e4aad73f3b441579b5231aa77c7a618557ecf9a
evaldojr100/Python_Lista_1
/11_degraus.py
435
4.25
4
'''11) (BACKES, 2012) Receba a altura do degrau de uma escada e a altura que o usuário deseja alcançar subindo a escada. Calcule e mostre quantos degraus o usuário deverá subir para atingir seu objetivo. Salve o projeto com o nome “​ 11_degraus ” ​ .''' degrau=float(input("Digite o tamanho do degrau:")) altura=float(input("Digite a altura que desejas subir:")) print("Serão Nescessarios",int(altura/degrau)," degraus")
6c5feca9559af03490396c640adbdc1c0058faf7
iamqingmei/Leetcode-Practice-Python
/217. Contains Duplicate (Easy).py
800
3.890625
4
""" Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. """ class Solution(object): def containsDuplicate(self, nums): #42ms """ :type nums: List[int] :rtype: bool """ s = set(nums) if len(s)<len(nums): return True return False def containsDuplicate(self, nums): #207ms """ :type nums: List[int] :rtype: bool """ nums.sort() if nums is None: return False for i in range (1,len(nums)): print (i) if (nums[i]==nums[i-1]): return True return False
a442dfb2e0ab952d01273f5b569eb21d2bf901b1
RootofalleviI/Python-algo
/algorithms/traverse_2d_array.py
555
4
4
def number_of_ways(n, m): """ Return the number of ways to traverse a 2D array (top-left to bottom-right). You must either go right or down. """ def helper(x, y): if x == y == 0: return 1 if number_of_ways[x][y] == 0: ways_top = 0 if x == 0 else helper(x - 1, y) ways_left = 0 if y == 0 else helper(x, y - 1) number_of_ways[x][y] = ways_top + ways_left return number_of_ways[x][y] number_of_ways = [[0] * m for _ in range(n)] return helper(n - 1, m - 1)
39a542d93177cc21cbeb1540b663b114f24bfba5
wkcosmology/enhanced
/stats/functions.py
1,720
3.5625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # File : functions.py # Author : Kai Wang <wkcosmology@gmail.com> # Date : 05.18.2019 # Last Modified By: Kai Wang <wkcosmology@gmail.com> import numpy as np def double_linear(xs, m, n, c, yc, amp): """double_linear Parameters ---------- x : ndarray the input xs m : float slope for x < c n : float slope for x >= c c : float turn-over point yc : float y value at x = c amp : float global amplitude Returns ------- the y values corresponding to the input xs shape (len(xs)) """ ys = np.empty(len(xs)) ys[xs < c] = (yc + m * xs - m * c)[xs < c] ys[xs >= c] = (yc + n * xs - n * c)[xs >= c] return amp * ys def schechter(xs, amp, x_c, alpha): """schechter Parameters ---------- xs : ndarray the input xs amp : float the amplitude x_c : float turn-over point alpha : float the slope of the power law part Returns ------- the y values corresponding to the input xs shape (len(xs)) """ return amp * (xs / x_c)**alpha * np.exp(-xs / x_c) / x_c def schechter_log(logx, amp, logx_c, alpha): """schechter_log Parameters ---------- logx : ndarray the input log(x) amp : float the amplitude logx_c : float the log of the turn over point alpha : float the slope of the power law part Returns ------- the y values corresponding to the input xs shape (len(logx)) """ return (np.log(10) * amp * np.exp(-10**(logx - logx_c)) * (10**((alpha + 1) * (logx - logx_c))))
33df7cf17f2063685aecb45b9d6d03090e79eee3
lldenisll/learn_python
/Exercícios/paridade.py
130
3.828125
4
numero=int(input("Preencha o número que quer verificar:" )) ver=numero%2 if ver==0: print("par") else: print("ímpar")
82d8c3f98f1ff880675eb27d3f8ecee8d555deb5
subhash4061/Array-2
/game of life.py
1,159
3.515625
4
# TC-O(m*n) # SC-O(1) class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ directions= [[-1 ,-1] ,[-1 ,0] ,[-1 ,1] ,[0 ,-1] ,[0 ,1] ,[1 ,1] ,[1 ,0] ,[1 ,-1]] for i in range(0 ,len(board)): for j in range(len(board[0])): live =0 for d in directions: if 0 <= i+ d[0] < len(board) and 0 <= j + d[1] < len(board[0]): if board[i + d[0]][j + d[1]] == 1 or board[i + d[0]][j + d[1]] == 3: live += 1 if board[i][j] == 1: if live < 2: board[i][j] = 3 if live > 3: board[i][j] = 3 elif board[i][j] == 0: if live == 3: board[i][j] = 2 for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == 2: board[i][j] = 1 if board[i][j] == 3: board[i][j] = 0
3bffc751a15a3a696897066afce74d3fda2ff414
ishantk/DSA2020-1
/Session19.py
3,630
3.9375
4
import hashlib class Word: def __init__(self, word): self.word = word self.frequency = 1 def __str__(self): return "{} [{}]".format(self.word, self.frequency) class HashTable: def __init__(self, capacity=10): self.capacity = capacity self.size = 0 self.buckets = [] for _ in range(capacity): self.buckets.append(None) print(">> HASHTABLE CONSTRUCTED WITH CAPACITY [{}]".format(capacity)) def hashCode(self, word): index = int(hashlib.sha512(word.encode("utf-8")).hexdigest(), 16) % self.capacity return index def put(self, word): index = self.hashCode(word.word.lower()) if self.buckets[index] == None: self.buckets[index] = word self.size += 1 print("^^ {} Inserted in HashTable".format(word.word)) else: self.buckets[index].frequency += 1 print("## {} Frequency Updated to {} in HashTable".format(word.word, word.frequency)) def iterate(self): print("~~~~~~~~~~~~~~") for word in self.buckets: if word != None: print(word) print("~~~~~~~~~~~~~~") def get(self, word): index = self.hashCode(word.word.lower()) return self.buckets[index] def main(): review1 = "Really good institution teachers are very helpful and caring also environment of this college is very attractive Proud to be a part of this college" review2 = "Best institution Education level is high" review3 = "What so ever I am today is due this technology Temple" review4 = "Nice place a big also it provides you good education" review5 = "Great institution with opportunities for those who want it" word1 = "institution" frequency1 = 0 # We need to find frequency of occurrence of word institution in above 5 reviews # 1. Put the data in an effective data structures # > HashTable | Capacity -> number of Words in number of Reviews # 2. Implement an Algorithm to calculate frequency # > Whenever a collision will occur we will increment the count # 3. Implementation of OOPS with Data Structures is preferable :) # > Word : word, frequency, alphabets words1 = review1.split(" ") words2 = review2.split(" ") words3 = review3.split(" ") words4 = review4.split(" ") words5 = review5.split(" ") capacity = len(words1) + len(words2) + len(words3) + len(words4) + len(words5) hTable = HashTable(capacity) print(">> Adding Review1 Words in HashTable:", review1) for word in words1: hTable.put(Word(word)) print("~~~~~~~~~~~~~~~~") print() print(">> Adding Review2 Words in HashTable:", review2) for word in words2: hTable.put(Word(word)) print("~~~~~~~~~~~~~~~~") print() print(">> Adding Review3 Words in HashTable:", review3) for word in words3: hTable.put(Word(word)) print("~~~~~~~~~~~~~~~~") print() print(">> Adding Review4 Words in HashTable:", review4) for word in words4: hTable.put(Word(word)) print("~~~~~~~~~~~~~~~~") print() print(">> Adding Review5 Words in HashTable:", review5) for word in words5: hTable.put(Word(word)) print("~~~~~~~~~~~~~~~~") print() hTable.iterate() print() print("=============================") word = hTable.get(Word("institution")) print(word) word = hTable.get(Word("college")) print(word) print("=============================") if __name__ == '__main__': main()
f5de4fce1eb9303886353e09e5616526cf5b98d4
anemesio/Python3-Exercicios
/Mundo01/ex022.py
386
3.90625
4
nome = str(input('Digite seu nome completo: ')).strip() print('Analisando seu nome...') print('Seu nome em maiscúlas é ', nome.upper()) print('Seu nome em minúsculas é ', nome.lower()) print('Seu nome tem ao todo {} letras'.format(len(nome.replace(' ', '')))) dividido = nome.split() print('Seu primeiro nome é {} e tem {} letras'.format(dividido[0], nome.find(' ')))
b3e29708d3f63f5628552d59d823d81356d2ebe4
zannn3/LeetCode-Solutions-Python
/0221. Maximal Square.py
1,026
3.578125
4
# dp[i][j] means the max side for a square # with its bottomright corner located at (i,j) # dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) # time O(m*n), space O(m*n) class Solution(object): def maximalSquare(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if not matrix or not matrix[0]: return 0 side = 0 m, n = len(matrix), len(matrix[0]) dp = [[0]*(n+1) for _ in range(m+1)] for i in range(1, m+1): for j in range(1, n+1): if matrix[i-1][j-1] == "0": dp[i][j] = 0 else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) side = max(side, dp[i][j]) return side*side """ Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. Example: Input: 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 Output: 4 """
2ae79698a657f51e3c0d38170ee01688c45fd467
Denis-Lima/PPZ-Logica
/Lista 1.py
2,488
4.03125
4
n1 = int(input('Digite um número inteiro: ')) n2 = int(input('Digite outro número inteiro: ')) soma = n1 + n2 print (soma) metros = float(input('Digite um valor em metros para converter em milímetros: ')) milímetros = metros * 1000 print (f'{metros} metros é igual a {milímetros} milímetros') d = int(input('Informe um valor em dias: ')) h = int(input('Informe um valor em horas (inteiras): ')) m = int(input('Informe um valor em minutos: ')) s = int(input('Informe um valor em segundos: ')) dh = d * 24 horas = dh + h hm = horas * 60 minutos = hm + m ms = minutos * 60 segundos = ms + s print (f'Todos os valores convertidos para segundos somam {segundos} segundos') salário = float(input('Qual o seu salário?\n:')) porcentagem = float(input('Qual é a porcentagem de aumento que receberá?(Apenas números)\n:')) aumento = salário * porcentagem/100 novo = salário + aumento print (f'Você receberá um aumento de R${aumento:.2f} e seu novo salário é de R${novo:.2f}!') preço = float(input('Qual o preço do produto?\n:')) porcentagem = float(input('Qual o desconto do produto?(Apenas números)\n:')) desconto = preço * porcentagem/100 pagar = preço - desconto print(f'O desconto foi de R${desconto:.2f} e o preço a pagar ficou em R${pagar:.2f}') dist = float(input('Qual a distância da viagem?(Em km)\n:')) vel = float(input('Qual a velocidade média esperada para a viagem?(Em Km/H)\n:')) horas = dist // vel minutos = (dist % vel)/ vel * 60 print (f"A sua viagem irá durar aproximadamente {horas:.0f}h e {minutos:.0f}'") C = float(input('Digite uma temperatura em Celsius para conversão: ')) F = 9*C/5 + 32 print (f'{C}ºC são {F}ºF') F = float(input('Digite uma temperatura em Fahrenheit para conversão: ')) C = (F-32)*5/9 print (f'{F}ºF são {C}ºC') km = float(input('Quantos quilômetros foram percorridos?\n:')) d = float(input('Por quantos dias o carro foi alugado?\n:')) p1 = 60 * d p2 = 0.15 * km preço = p1 + p2 print (f'O preço a pagar é de {preço:.2f} reais.') cigarros = int(input('Quantos cigarros você fuma por dia?\n:')) anos = int(input('Por quantos anos você têm fumado?\n')) ad = anos * 365 qtd = cigarros * ad minutos = 10 * qtd redução = minutos / 60 / 24 print (f'Sua vida foi reduzida em {redução:.2f} dias por fumar') digitos = 2 ** 1000000 contar = len(str(digitos)) print (f'2 elevado a 1 milhão tem {contar} dígitos!')
edf3db52ffe8dd28ecc01547197d95b87f1591bc
venkatbalaji87/guvi
/loop/SumOfFirstAndLastDigit.py
334
4.0625
4
def firstDigit(number): while(number>=10): number=number/10 return int(number) def lastDigit(number): while(number>0): return number%10 number=int(input("Enter the Number : ")) firstDigit(number) lastDigit(number) print("Sum of First and last digit is :",(firstDigit(number)+lastDigit(number)))
9198e83e1836573e6ddd826ccf850ffe5e12db26
JGUO-2/MLwork
/Fibonacci/Fib_recursion.py
743
3.90625
4
# -*- coding: utf-8 -*- """ 实现斐波那契数列 方法五:递归 """ def Fib_list(n) : if n == 1 or n == 2 : #n为项数,若为1、2时,结果返回为1 return 1 else : m = Fib_list(n - 1) + Fib_list(n - 2) #其他情况下,结果返回前两项之和 return m if __name__ == '__main__': while 1: print("**********请输入要打印的斐波拉契数列项数n的值***********") n = input("enter:") if not n.isdigit(): print("请输入一个正整数!") continue n = int(n) list2 = [0] tmp = 1 while (tmp <= n): list2.append(Fib_list(tmp)) tmp += 1 print(list2)
3a6b1d1fb1da8ba80e8a550ead7f73f55059c27a
dave5801/CodingChallenges
/leetcode/LongestCommonPrefix.py
934
3.625
4
#I'm pretty sure this was an Amazon Problem #https://leetcode.com/problems/longest-common-prefix/ class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' longestPrefix = strs[0] for currentIndexOfEveryWord in range(1,len(strs)): for currentIndexOfWord in range(len(longestPrefix),-1,-1): if longestPrefix[:currentIndexOfWord] == strs[currentIndexOfEveryWord][:currentIndexOfWord]: longestPrefix = longestPrefix[:currentIndexOfWord] break if currentIndexOfWord == 0: longestPrefix = '' break return longestPrefix if __name__ == '__main__': s = Solution() x = s.longestCommonPrefix(["flower","flow","flight"]) print(x)
41e0b5296fff6d5578a8298e7c018cb9812776dd
tamara-louzada/estudos-py-DigitalInnovationOne
/aula11_excecoes_personalizadas.py
804
4.09375
4
#Para criar uma classe error personalizada eh preciso sempre criar uma classe que herde Exception #mesmo que ela fique vazia class Error(Exception): pass class InputError(Error):#herança - InputError herda de Error def __init__(self, message): self.message = message while True:#Sempre executa sem fim try: x = int(input('Entre com uma nota: ')) print(x) if x > 10: #Forçando exceçao raise InputError('Nota nao pode ser maior que 10') elif x<0: raise InputError('Nota nao pode ser menor que 0') break #força a saida do loop quando ele entrar com valor correto except ValueError: print('Valor Invalido. Deve-se digitar apenas numero') except InputError as ex: print(ex)
498376ebac3977ef8b0269addb3e384bdf4fb1aa
TrueFinch/machinelearning
/m1.py
3,301
3.6875
4
import numpy as np from typing import Tuple def single_point_crossover(a: np.ndarray, b: np.ndarray, point: int) -> Tuple[np.ndarray, np.ndarray]: """Performs single point crossover of `a` and `b` using `point` as crossover point. Chromosomes to the right of the `point` are swapped Args: a: one-dimensional array, first parent b: one-dimensional array, second parent point: crossover point Return: Two np.ndarray objects -- the offspring""" left = np.arange(len(a)) <= point right = np.arange(len(a)) > point return np.concatenate((a[left], b[right]), axis=0), np.concatenate((b[left], a[right]), axis=0) def two_point_crossover(a: np.ndarray, b: np.ndarray, first: int, second: int) -> Tuple[np.ndarray, np.ndarray]: """Performs two point crossover of `a` and `b` using `first` and `second` as crossover points. Chromosomes between `first` and `second` are swapped Args: a: one-dimensional array, first parent b: one-dimensional array, second parent first: first crossover point second: second crossover point Return: Two np.ndarray objects -- the offspring""" left = np.arange(len(a)) <= first btw = np.logical_not(np.logical_xor(first < np.arange(len(a)), np.arange(len(a)) < second)) right = second <= np.arange(len(a)) return np.concatenate((a[left], b[btw], a[right]), axis=0), np.concatenate((b[left], a[btw], b[right]), axis=0) def k_point_crossover(a: np.ndarray, b: np.ndarray, points: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Performs k point crossover of `a` and `b` using `points` as crossover points. Chromosomes between each even pair of points are swapped Args: a: one-dimensional array, first parent b: one-dimensional array, second parent points: one-dimensional array, crossover points Return: Two np.ndarray objects -- the offspring""" k = len(a) res_a = np.array([], dtype='i') res_b = np.array([], dtype='i') points = np.append(np.array([0]), points) if len(points) % 2 == 0: points = np.append(points, [k]) for p in range(1, len(points), 2): range1 = np.logical_not(np.logical_xor(points[p - 1] <= np.arange(k), np.arange(k) <= points[p])) res_a = np.concatenate((res_a, a[range1]), axis=0) res_b = np.concatenate((res_b, b[range1]), axis=0) range2 = np.logical_not(np.logical_xor(points[p] < np.arange(k), np.arange(k) < points[p + 1])) res_a = np.concatenate((res_a, b[range2]), axis=0) res_b = np.concatenate((res_b, a[range2]), axis=0) if len(points) % 2 != 0: right = np.arange(k) >= points[len(points) - 1] res_a = np.concatenate((res_a, a[right]), axis=0) res_b = np.concatenate((res_b, b[right]), axis=0) return res_a, res_b # a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # b = np.array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) # prep = lambda x: ' '.join(map(str, x)) # print(*map(prep, single_point_crossover(a, b, 4)), '', sep='\n') # print(*map(prep, two_point_crossover(a, b, 2, 7)), '', sep='\n') # print(*map(prep, k_point_crossover(a, b, np.array([1, 5, 8]))), '', sep='\n') # print(*map(prep, k_point_crossover(a, b, np.array([1, 5]))), '', sep='\n')
6e76e47793564292fb827fd203562b54cefe1178
valeriacavalcanti/IP-2020.1
/20200227/questao03.py
352
3.90625
4
v1, v2, v3 = input("Três valores: ").split() v1, v2, v3 = int(v1), int(v2), int(v3) tri_ret = (v1 * v3) / 2 circulo = 3.14159 * v3**2 trap = ((v1 + v2) * v3) / 2 quad = v2**2 ret = v1 * v2 print(f"Triângulo Retângulo = {tri_ret}") print(f"Círculo = {circulo}") print(f"Trapézio = {trap}") print(f"Quadrado = {quad}") print(f"Retângulo = {ret}")
cecc7c209a4c54f43c375f23dd82b1aa74cf9d5c
2B5/ia-3B5
/module3/preprocessing/errorCorrect.py
232
3.5625
4
from textblob import TextBlob,Word def correct(text): t = TextBlob(text) return str(t.correct()) def spellcheck(text): txt=["She","is","mw","moom"] for w in txt: word=Word(w) print(word.spellcheck())
d6eb144bfa4553c57499f50c89013ddd5cd2bb6b
tommydo89/CTCI
/8. Recursion and Dynamic Programming/booleanEvaluation.py
1,463
4.09375
4
# Given a boolean expression consisting of the symbols 0 (false), 1 (true), & # (AND), I (OR), and /\ (XOR), and a desired boolean result value result, implement a function to # count the number of ways of parenthesizing the expression such that it evaluates to result. def recursiveEvaluate(expression, result): if len(expression) == 1: # base case if toBool(expression) == result: return 1 return 0 ways = 0 for operator_index in range(1, len(expression), 2): # recursively place a parenthesis around everything on the left and the right of an operator left_true = recursiveEvaluate(expression[0:operator_index], True) left_false = recursiveEvaluate(expression[0:operator_index], False) right_true = recursiveEvaluate(expression[operator_index+1:], True) right_false = recursiveEvaluate(expression[operator_index+1:], False) total = (left_true + left_false) * (right_true + right_false) total_true = 0 operator = expression[operator_index] if operator == '^': total_true += (left_true*right_false) + (left_false*right_true) if operator == '&': total_true += (left_true*right_true) if operator == '|': total_true += (left_true*right_true) + (left_true*right_false) + (left_false*right_true) if result == True: ways += total_true else: # we subtract total_true from ways in order to get the possible ways to get False as a result ways += total - total_true return ways def toBool(char): return char == '1'
308be3b6b0493bd5f948b8fbc2544bb399a7105a
kbschroeder/Marymount_BST_Traversal
/Schroeder Search Function.py
1,115
4.15625
4
class new_node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None def search(root, value): # Traverse untill root reaches # to dead end while root != None: # pass right subtree as new tree if value > root.data: root = root.right # pass left subtree as new tree elif value < root.data: root = root.left else: return True # if the key is found return 1 return False def insert(Node, data): # If the tree is empty, return # a new Node if Node == None: return new_node(data) if data < Node.data: Node.left = insert(Node.left, data) elif data > Node.data: Node.right = insert(Node.right, data) return Node if __name__ == '__main__': root = None root = insert(root, 5) insert(root, 3) insert(root, 2) insert(root, 4) insert(root, 7) insert(root, 6) insert(root, 8) if search(root, 1): print("Yes") else: print("No")
a8fbac760c886675f38368ddbd8642441f561c90
Shibaken2017/Algorithm
/sort/heap_sort.py
357
3.640625
4
def hash_func(num): #商を計算する return num//7 def insert_data(input_list,save_list): for ele in input_list: num=hash_func(ele) while save_list[num]!=None: num+=1 save_list[num]=ele print(save_list) return save_list if __name__=="__main__": tmp=[None]*16 input_list=[81,20,45,62,89,66,42,70,44,51,31] insert_data(input_list,tmp)
a2b7c4e2542a1f87592e85bb5a202373ffddc5c2
johndevera/sample_code
/python/quicksort.py
542
3.65625
4
leftFlag = False rightFlag = False lp = x[0] // first position of list rp = x[-1] // last position of list center = x[len(x)/2] // center position of list notDone = True while(notDone): index = 1 for i in range(index:len(x)): if (leftFlag && rightFlag): index = i break if lp > center: // traverse from LHS leftFlag = True if rp < center: //traverse from RHS rightFlag = True swap(lp, rp, x, index) if (x.reachedEnd()): break def swap(lp, rp, x): temp = lp lp = rp rp = temp x[i] = lp x[-(i+1)] = rp
21aeadc36be58a8daa71bd297b5c91a1e56d5ab0
shellyalmo/Learning-Python-3
/practicing_dictionaries_scrabble_project.py
2,079
4.375
4
"""This project is processing data from a scrabble game. It uses dictionaries to organize players, words and points.""" letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] # Combining the lists of letters and points into one dictionary maps a letter to its point value. letter_to_points = {key:value for key,value in zip(letters,points)} # Taking in account blank tiles letter_to_points.update({" " : 0}) #A function that takes a word and returns how many points that word is worth. def score_word(word): total_points = 0 for letter in word: total_points += letter_to_points.get(letter,0) return total_points # test: should return 15: # print(score_word("BROWNIE")) # The data of the game: a dictionary that maps players to a list of the words they have played. player_to_words = {"player1" : ["BLUE", "TENNIS", "EXIT"], "wordNerd": ["EARTH", "EYES", "MACHINE"], "Lexi Con": ["ERASER", "BELLY", "HUSKY"], "Prof Reader": ["ZAP", "COMA", "PERIOD"]} # This function contains the mapping of players to how many points they've scored. def update_point_totals(dictionary_of_player_to_words,player_name): player_to_points = {} words = dictionary_of_player_to_words.get(player_name) player = player_name player_points = 0 for word in words: player_points += score_word(word) player_to_points[player] = player_points return player_to_points # This function takes in a player and a word, and adds that word to the list of words they’ve played. # Then it calls the previous function to check how many points the player has earned. def play_word(player,word): upper_word = word.upper() for player_name in player_to_words.keys(): if player == player_name: player_to_words[player].append(upper_word) return update_point_totals(player_to_words,player) print(letter_to_points) # test: should return {'player1: 45'} # print(play_word("player1","bunny"))
a8908369c5523d8f9d21c108d17207441ea006b8
Aasthaengg/IBMdataset
/Python_codes/p03359/s044146285.py
171
3.5625
4
#!/usr/bin/env python3 import numpy as np import math import re n = input() n = re.split(" ",n) a = int(n[0]) b = int(n[1]) if( b < a ): print(a-1) else: print(a)
364f93d92ebbfae9f281861593bf1ab96d40ab45
ShuyiHuo/Udacity_Project2
/Problem_3.py
2,010
4.0625
4
def mergesort(input): if len(input) <= 1: return input mid = len(input) // 2 left = input[:mid] right = input[mid:] left = mergesort(left) right = mergesort(right) return merge(left, right) def merge(left, right): merged = [] left_index = 0 right_index = 0 while left_index < len(left) and right_index < len(right): if left[left_index] > right[right_index]: merged.append(right[right_index]) right_index += 1 else: merged.append(left[left_index]) left_index += 1 merged += left[left_index:] merged += right[right_index:] return merged def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ if input_list is None or len(input_list) == 0: return -1, -1 if len(input_list) == 1: return input_list[0], 0 input_list = mergesort(input_list) input_list.reverse() # Python method num1 = "" num2 = "" for i in range(len(input_list)): if i % 2 == 0: num1 += str(input_list[i]) if i % 2 == 1: num2 += str(input_list[i]) return int(num1), int(num2) def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print("Pass") else: print("Fail") test_function([[1, 2, 3, 4, 5], [542, 31]]) test_case = [[4, 6, 2, 5, 9, 8], [964, 852]] test_function(test_case) ''' Test case 1: Test if the length of list is 0, then the result should be -1. ''' print(rearrange_digits([])) ''' Test case 2: Test if the list is None, then the result should be -1. ''' print(rearrange_digits(None)) ''' Test case 3: Test if the function is work, then the result should be (964, 852). ''' print(rearrange_digits([4, 6, 2, 5, 9, 8]))
fdaf49d2f87e83515d09203ead72f370cc82451f
Jon1bek/Python_darslari
/17-dars.py
148
3.5625
4
def oraliq(min,max,qadam): sonlar = [] while min<max: sonlar.append(min) min+=qadam return sonlar print(oraliq(1,101,2))
5a499d9cab6afefe0fb05c39ca25c5560edbab40
Majician13/magic-man
/dateTime.py
1,140
4.65625
5
import datetime #Print todays date. currentDate = datetime.date.today() print(currentDate.strftime("%b %d, %Y")) #Print today's date in Python format, Just the month, just the Year. print(currentDate) print(currentDate.month) print(currentDate.year) #Print a special sentence including different aspects of the date. print(currentDate.strftime("Please attend our event %A, %B %d in the year %Y")) #Ask for and print someone's b-day #Please uncomment lines 17, 18, 23, 25, 26 to use this section birthday = input("What's your birthday? mm/dd/yyyy \n") birthdate = datetime.datetime.strptime(birthday, "%m/%d/%Y").date() #Why did we list datetime twice? #because we are calling the strptime function #Which is part of the datetime class #which is in the datetime module print("Your birth month is " + birthdate.strftime("%B")) difference = (currentDate - birthdate) print(difference.days) #Time from here on currentTime = datetime.datetime.now() print(datetime.datetime.strftime(currentTime, "%I:%M %p")) print(currentTime) print(currentTime.hour) print(currentTime.minute) print(currentTime.second)
bf283806ff4f227639a3974a1ee567b768738ddf
nanihari/regular-expressions
/match for a specific string.py
442
4.59375
5
#program that matches a string that has an a followed by zero or more b's. import re def text_match(text): pattern="a*?b" ## ab+ for string that is followed by 1 more b's ## ab{3} can be used/abbb can be used to check str. followed by 3 b's if re.search(pattern, text): return ("match found") else: return ("no found") print(text_match("abccc")) print(text_match("accccb")) print(text_match("ac"))
bdc83af2bc9c4e1abc837e25e4353a4a29abab00
saz2nitk/GADep1109
/bin/sampleTest.py
684
3.546875
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 11 08:58:50 2021 @author: saz2n """ a = [2,3,6,4,5] mx = -1 for i in a: if i>mx: mx = i print(mx) b = [1,4,3,2] mx = -1 for i in b: if i>mx: mx = i print(mx) def findMax(arr): mx = -1 for i in arr: if i>mx: mx = i return(mx) print(findMax(a)) print(findMax(b)) class Arithmetic: def findMax(): pass def findMin(): pass def findAvg(): pass class Nlp: def specialCharRemoval(): pass def tokenization(): pass
85eb13ff9b0d3fc748f437838e51f83fd721a0f0
jmast02/PythonCrashCourse
/dictionary.py
1,022
3.859375
4
best_friend = { 'first_name': 'steve', 'last_name': 'jobs', 'age': 45, 'city': 'boca' } favorite_numbers = { 'steve': 3, 'bob': 5, 'joe': 4, 'rick': 7, 'jon': 9 } print(f"Steve's favorite number is {favorite_numbers['steve']}.") print(f"Bob's favorite number is {favorite_numbers['bob']}.") print(f"Joe's favorite number is {favorite_numbers['joe']}.") print(f"Rick's favorite number is {favorite_numbers['rick']}.") print(f"Jon's favorite number is {favorite_numbers['jon']}.") programming_words = { 'boolean': 'True or False', 'float': 'decimal', 'int': 'whole number', 'dictionary': 'key, value pairs', 'tuple': 'can not change' } print(f" \nthe word boolean means: {programming_words['boolean']}.") print(f" \nthe word float means: {programming_words['float']}.") print(f" \nthe word int means: {programming_words['int']}.") print(f" \nthe word dictionary has: {programming_words['dictionary']}.") print(f" \nthe word tuple: {programming_words['tuple']}.")
b75d27ce40fb942c471e210218d25cf03a95411e
mrwtx1618/py_all
/switch函数.py
1,408
3.984375
4
# -*- coding:UTF-8 -*- #python当中没有switch这个语句,但是可以通过字典来实现switch功能 from __future__ import division #加入这个模块,除法可以直接实现 def add(x,y): return x + y def subtract(x,y): return x - y def multiply(x,y): return x * y def divide(x,y): return x/y def operator(x,o,y): if o == "+": print add(x, y) elif o == '-': print subtract(x, y) elif o =='*': print multiply(x, y) elif o == '/': print divide(x, y) else: pass z = operator(5, '/', 8) # print z ###但是以上这种办法,比如要做除法运算,上面的三次判断都是多余的,所以想用字典的办法来解决问题 operator_dict = {'+':add,'-':subtract,'*':multiply,'/':divide} print type(operator_dict['+']) #这时候通过加号这个键取到的值是一个函数对象 print operator_dict['+'](3,9) print operator_dict.get('*')(3,9) #字典下面有get这个方法来获取key,通过字典来调用函数 def f1(x,o,y): print operator_dict.get(o)(x,y) f1(5, '/', 8) #调用函数 f1(6, '*', 6) #这时候已经没有判断了 ###但如果用户所输入的字符不在字典里面的? ###通过可变参数来接收用户传入的多余的值 def f2(x,o,y): print operator_dict.get(o)(x, y, *args, **kwargs) f2(4, '*', 3) ###一般的if结构都可以通过字典+switch结构来实现
f03325537a367e30e31457bce516c145448aca41
vggithub7/nitkkr
/fourth_ml_lab_odd_even.py
225
4.03125
4
def odd_even(n): if (n%2)==0: print("even") # input("prompt: ") else: print("odd") # input("prompt: ") print("enter a number") a=int(input()) odd_even(a) input("prompt: ")
18cb2c5428fd44a1fcb1e4961814334a96bcd2f9
dyng9409/Nguyen_CSCI3202_Assignment1
/Nguyen_Assignment1.py
4,196
3.953125
4
#Dylan Nguyen #University of Colorado - Boulder #CSCI 3202 Fall 2015 Assignment 1 #Implementation of Various Data Structures from __future__ import print_function import sys import q import stack as s import graph as g import tree as t #testing the implementations def testDequeueOrder(queue): #dequeues items from queue and prints in order while(not queue.isEmpty()): print(queue.pop(),end=' ') return def testUnstackOrder(stack): while(not stack.isEmpty()): print(stack.pop(),end=' ') #unstacks items from stack and prints in order return #-----TESTING QUEUE-----# print('Testing Queue Implementation') #initializing queue with 0 1 2 3 4 5 6 7 8 9 testQ = q.queue() for i in range(0,10): testQ.push(i) print('Testing dequeue order') #output should be 0 1 2 3 4 5 6 7 8 9 testDequeueOrder(testQ) print('\n') #queue should be empty after test print('Testing queue empty...') assert(testQ.isEmpty() is True) print('Queue confirmed empty') print('\n') #-----TESTING STACK-----# print('Testing Stack Implementation') #initializing stack with 0 1 2 3 4 5 6 7 8 9 testStack = s.stack() for i in range(0,10): testStack.push(i) print('Testing unstack order') #output should be 9 8 7 6 5 4 3 2 1 0 testUnstackOrder(testStack) print('\n') print('Testing stack empty') assert(testQ.isEmpty() is True) print('Stack confirmed empty') #stack should now be empty #tests push, pop, and empty print('\n') #-----TESTING TREE-----# print('Testing Tree Implementation') testTree = t.tree() #initializing the tree testTree.addRoot(42) testTree.add(42,2) testTree.add(42,5) testTree.add(5,7) testTree.add(5,10) testTree.add(2,13) testTree.add(2,21) testTree.add(21,12) testTree.add(13,11) testTree.add(10,16) testTree.add(16,6) print('Testing printTree()') #testing print tree #feeding in above tree, output should be: #42 2 13 11 21 12 5 7 10 16 6 testTree.printTree() print('\n') print('Testing add with non-existent parent') #testing add with non existant parent testTree.add(1337,2) print('Test Success') print('Testing add on parent with two existing children') #testing add with full node testTree.add(2,56) print('Test Success') #testing the delete function with same tree #first trying to delete a node with children should result in #error messages being displayed print('Testing delete with two children') #node 2 has children 13 and 21, so will show an error testTree.delete(2) print('Testing delete with 1 child') #node 16 has 1 child so will show an error testTree.delete(16) print('Testing delete on leaves') #node 6 and 11 are leafs so will show no error testTree.delete(11) testTree.delete(6) #confirming that those nodes are deleted using the #find method (also confirms nodes are no longer pointed to) assert(testTree.find(11) is None) assert(testTree.find(6) is None) print('Test Success') #printing tree again, confirming delete #output should be: 42 2 13 21 12 5 7 10 16 print('Re-printing tree to confirm deletes') testTree.printTree() print('\n') #-----TESTING GRAPH-----# print('Testing Graph Implementation') testGraph = g.graph() #initializing graph with 15 vertices for i in range(1,16): testGraph.addVertex(i) #testing adding an existing vertex: print('Testing adding an existing vertex') testGraph.addVertex(2) #intializing edges for i in range(1,15): testGraph.addEdge(i,i+1) testGraph.addEdge(15,1) #test adding existing edge print('Testing adding existing edge') testGraph.addEdge(5,4) #test adding edge between 2 non-existing vertices print('Testing adding an edge between non-existing vertices') testGraph.addEdge(42,24) #test adding edge between existing and non existing vertices print('Testing adding an edge between existing and non-existing vertices') testGraph.addEdge(5,1024) #test find 5 vertices print('Testing findVertex') #output should be 2 and 4 testGraph.findVertex(3) #output should be 7 and 9 testGraph.findVertex(8) #output should be 14 and 1 testGraph.findVertex(15) #output should be 5 and 7 testGraph.findVertex(6) #output should be 11 and 13 testGraph.findVertex(12) #test finding non-existent vertex print('Testing findVertex on non-existing vertex') testGraph.findVertex(1337)
3d7c428dedbea32733ea6bc6ed13390177381072
NERC-DTP-Students/climate-predictor
/climatepredictor/gui.py
34,938
3.75
4
""" Main GUI file. Builds the GUI and calls functions to calculate the temperature of the planet in the upper and lower atmosphere and on the surface. Classes: + Slider: builds the albedo slider where the user can adjust the composition of the surface of the planet Functions: + make_value_entry: function for making entry box + make_simmple_entry: function for making entry box + check_initial_total: checks that the initial surface composition adds up to 100% + check_final_total: checks that the final surface composition adds up to 100% + entry_change: moves the slider if the composition of the planet is changed in the entry box + make_slider_entry: creates entry box for the slider + make_radio_button: makes a radio button + make_check_button: makes a check box + on_closing: closes the plot + changed: calls the execute_main function once the slider changes + execute_main: updates variables and makes a plot when a key is pressed + show_plot: solve equations with updated inputs and embed plot into GUI + add_labels: adds labels to the GUI + reveal: reveals the advanced options + hide: hides the advanced options + reveal_plot: advanced plotting options + hide_plot: basic plotting options """ from tkinter import * from tkinter import ttk from tkinter import messagebox import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg) import numpy as np from config import * from time_slider_range import max_time from plot import make_plot from energymodel import solve_over_time, calculate_albedo class Slider(Frame): '''Creates a class for the slider GUI function that controls the relative land cover proportions ''' LINE_COLOR = "#476b6b" LINE_WIDTH = 3 BAR_COLOR_INNER = "#5c8a8a" BAR_COLOR_OUTTER = "#c2d6d6" BAR_RADIUS = 10 BAR_RADIUS_INNER = BAR_RADIUS-5 DIGIT_PRECISION = '.1f' # for showing in the canvas # the aesthetics def __init__(self, master, width=400, height=80, min_val=0, max_val=1, init_lis=None, show_value=True): Frame.__init__(self, master, height=height, width=width) self.master = master if init_lis is None: init_lis = [min_val] self.init_lis = init_lis self.max_val = max_val self.min_val = min_val self.show_value = show_value self.H = height self.W = width self.canv_H = self.H self.canv_W = self.W self.changed = False if not show_value: self.slider_y = self.canv_H/2 # y pos of the slider else: self.slider_y = self.canv_H*2/5 self.slider_x = Slider.BAR_RADIUS # x pos of the slider (left side) self.bars = [] self.selected_idx = None # current selection bar index i = 0 for value in self.init_lis: pos = (value-min_val)/(max_val-min_val) # sets the position of the bar based on the initial values given ids = [] bar = {"Pos": pos, "Ids": ids, "Value": value, "Idx": i} # current value is set to the initial value self.bars.append(bar) i = i+1 self.canv = Canvas(self, height=self.canv_H, width=self.canv_W) self.canv.pack() self.canv.bind("<Motion>", self._mouseMotion) # when the mouse is moved self.canv.bind("<B1-Motion>", self._moveBar) # when left button is pressed and held down # add the slider line self.__addTrack(self.slider_x, self.slider_y, self.canv_W-self.slider_x, self.slider_y) # add each slider with position and index for bar in self.bars: bar["Ids"] = self.addBar(bar["Pos"], bar["Idx"]) # initial percentages self.forest_perc = DoubleVar(master, 9.4) self.ice_perc = DoubleVar(master, 10) self.water_perc = DoubleVar(master, 71) self.desert_perc = DoubleVar(master, 9.6) self.canv.create_text(self.canv_W-2*self.slider_x, self.canv_H-0.8*self.slider_y, text='desert', fill='white') self.changed = True def getValues(self): """gets the values for each marker in the slider""" values = [bar["Value"] for bar in self.bars] return values def _mouseMotion(self, event): """passes the x coordinate of the mouse and the y coordinate of the mouse. If the mouse is inside a slider will change the cursor to a hand""" x = event.x y = event.y selection = self.__checkSelection(x, y) if selection[0]: # if a slider is selected self.canv.config(cursor="hand2") # change cursor to hand self.selected_idx = selection[1] # retrieve the index of the selected slider else: self.canv.config(cursor="") self.selected_idx = None def _moveBar(self, event): x = event.x y = event.y if self.selected_idx is None: return False pos = self.__calcPos(x) idx = self.selected_idx self.moveBar(idx, pos) # set the values in the entry boxes values = self.getValues() sorted_values = np.array(sorted(values)) sorted_list = sorted(values) n = 0 pos = np.zeros(3) # deals with if the sliders are dragged over each other for value in values: pos[n] = sorted_list.index(value) n = n+1 percentages = np.concatenate((np.array([sorted_values[0]]), np.diff(sorted_values), np.array([100 - sorted_values[-1]])), axis=0) self.forest_perc.set(np.round(percentages[int(pos[0])], 1)) self.ice_perc.set(np.round(percentages[int(pos[1])], 1)) self.water_perc.set(np.round(percentages[int(pos[2])], 1)) self.desert_perc.set(np.round(percentages[3], 1)) def __addTrack(self, startx, starty, endx, endy): # add initial slider line self.canv.create_line(startx, starty, endx, endy, fill=Slider.LINE_COLOR, width=Slider.LINE_WIDTH) # add desert text and oval R = Slider.BAR_RADIUS r = Slider.BAR_RADIUS_INNER y = endy x = endx self.canv.create_text(self.canv_W-2*self.slider_x, self.canv_H-0.8*self.slider_y, text="desert") self.canv.create_oval(x-R, y-R, x+R, y+R, fill=Slider.BAR_COLOR_OUTTER, width= 2, outline="") self.canv.create_oval(x-r, y-r, x+r, y+r, fill=Slider.BAR_COLOR_INNER, outline="") return id # def __addBar(self, pos, idx): def addBar(self, pos, idx): names = ['forest', 'ice', 'water', 'desert'] colours = ['green', 'white', 'blue', 'yellow'] """@ pos: position of the bar, ranged from (0,1)""" if pos < 0 or pos > 1: raise Exception("Pos error - Pos: "+str(pos)) R = Slider.BAR_RADIUS r = Slider.BAR_RADIUS_INNER L = self.canv_W - 2*self.slider_x y = self.slider_y x = self.slider_x+pos*L # draw coloured lined for each of the sliders positions = [bar["Pos"] for bar in self.bars] pos_list = sorted(positions) n = 0 indx = np.zeros(3) for posit in pos_list: indx[n] = positions.index(posit) n = n+1 self.canv.create_line(self.slider_x+pos_list[2]*L, y, self.slider_x+L, y, fill=colours[3], width=Slider.LINE_WIDTH) self.canv.create_line(self.slider_x+pos_list[1]*L, y, self.slider_x+pos_list[2]*L, y, fill=colours[int(indx[2])], width=Slider.LINE_WIDTH) self.canv.create_line(self.slider_x+pos_list[0]*L, y, self.slider_x+pos_list[1]*L, y, fill=colours[int(indx[1])], width=Slider.LINE_WIDTH) self.canv.create_line(self.slider_x, y, self.slider_x+pos_list[0]*L, y, fill=colours[int(indx[0])], width=Slider.LINE_WIDTH) id_outer = self.canv.create_oval(x-R, y-R, x+R, y+R, fill=Slider.BAR_COLOR_OUTTER, width=2, outline="") id_inner = self.canv.create_oval(x-r, y-r, x+r, y+r, fill=Slider.BAR_COLOR_INNER, outline="") # from gui import changed if self.changed: changed() if self.show_value: y_value = y+Slider.BAR_RADIUS+8 id_value = self.canv.create_text(x, y_value, fill='white', text=names[idx]) return [id_outer, id_inner, id_value] else: return [id_outer, id_inner] # def __moveBar(self, idx, pos): def moveBar(self, idx, posit, entry=False): if entry and idx > 0: c_value = self.bars[idx-1] pos = (c_value["Value"]+posit*100)/100 else: pos = posit """slider will be moved""" ids = self.bars[idx]["Ids"] for id in ids: self.canv.delete(id) # self.bars[idx]["Ids"] = self.__addBar(pos, idx) self.bars[idx]["Ids"] = self.addBar(pos, idx) self.bars[idx]["Pos"] = pos self.bars[idx]["Value"] = pos*(self.max_val - self.min_val)+self.min_val def __calcPos(self, x): """calculate position from x coordinate""" pos = (x - self.slider_x)/(self.canv_W-2*self.slider_x) if pos < 0: return 0 elif pos > 1: return 1 else: return pos def __checkSelection(self, x, y): """ To check if the position is inside the bounding rectangle of a Bar Return [True, bar_index] or [False, None] """ for idx in range(len(self.bars)): id = self.bars[idx]["Ids"][0] bbox = self.canv.bbox(id) if bbox[0] < x and bbox[2] > x and bbox[1] < y and bbox[3] > y: return [True, idx] return [False, None] # what happens when the entries are changed def check_initial_total(): current_tot = forest.get() + ice.get() + water.get() if current_tot > 100: messagebox.showwarning("WARNING","Environment fractions add up to more than 100%") return FALSE else: desert.set(100-current_tot) return TRUE def check_final_total(): current_tot = forest_final.get() + ice_final.get() + water_final.get() if current_tot > 100: messagebox.showwarning("WARNING","Environment fractions add up to more than 100%") return FALSE else: desert_final.set(100-current_tot) return TRUE def entry_change(event=None, index=0): """called when the entry boxes are changed by the user in the slider class""" # add function to deal with errors if the box is empty if index < 4: test = check_initial_total() if test: if index == 0: try: pos = forest.get() slider.moveBar(posit = pos/100, idx = index, entry=True) pos = ice.get() slider.moveBar(posit = pos/100, idx = 1, entry=True) pos = water.get() slider.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 if index == 1: try: pos = ice.get() slider.moveBar(posit = pos/100, idx = 1, entry=True) pos = water.get() slider.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 if index == 2: try: pos = water.get() slider.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 if index > 3: test = check_final_total() print(test) if test: if index == 4: try: pos = forest_final.get() slider_final.moveBar(posit = pos/100, idx = index-4, entry=True) pos = ice_final.get() slider_final.moveBar(posit = pos/100, idx = 1, entry=True) pos = water_final.get() slider_final.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 if index == 5: try: pos = ice_final.get() slider_final.moveBar(posit = pos/100, idx = 1, entry=True) pos = water_final.get() slider_final.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 if index == 6: try: pos = water_final.get() slider_final.moveBar(posit = pos/100, idx = 2, entry=True) except TclError: pos = 0 return # slider entries def make_slider_entry(root, label, variable, rowno, colno, type): new_label=ttk.Label(root,text=label,width=10) new_label.grid(row=rowno, column=colno, sticky=(N, S, E, W)) new_entry=ttk.Entry(root, width=10, textvariable=variable) new_entry.grid(row=rowno, column=colno+1, sticky=(N, S, E, W)) new_entry.bind('<KeyRelease>', lambda event: entry_change(event, index = type), add= '+') def make_value_entry(root, caption, rowno, default_initial, default_rate, unit): '''Creates a GUI entry window with boxes to enter the initial value and rate of change (eg. cloud cover initial percent and percent rate of change Runs execute_main when entry is changed :root: main GUI frame :caption: name of variable :rowno: row within GUI frame to place entry :default_initial: default initial value of variable :default_rate: rate of change of variable :unit: unit of variable (eg. %) ''' label = ttk.Label(root, width=10, text=caption) label.grid(row=rowno, column=0, sticky=(N, S, E, W)) entry = ttk.Entry(root, width=10, textvariable=default_initial) entry.grid(row=rowno, column=1, sticky=(N, S, E, W)) entry.bind('<KeyRelease>', execute_main) label = ttk.Label(root, width=10, text=unit) label.grid(row=rowno, column=2, sticky=(N, S, E, W)) entry = ttk.Entry(root, width=10, textvariable=default_rate) entry.grid(row=rowno, column=3, sticky=(N, S, E, W)) entry.bind('<KeyRelease>', execute_main) label = ttk.Label(root, width=20, text=unit+' per time interval') label.grid(row=rowno, column=4, sticky=(N, S, E, W)) def make_simple_entry(root, label, variable, rowno, colno): '''Creates a GUI entry window with a single box to enter a value Runs execute_main when entry is changed :root: main GUI frame :label: text to label entry box :rowno: row number within GUI frame to place entry :variable: default initial value of variable :colno: column number within GUI frame to place entry ''' new_label = ttk.Label(root, text=label, width=10) new_label.grid(row=rowno, column=colno, sticky=(N, S, E, W)) new_entry = ttk.Entry(root, width=10, textvariable=variable) new_entry.grid(row=rowno, column=colno+1, sticky=(N, S, E, W)) new_entry.bind('<KeyRelease>', execute_main) # function for making a Radiobutton def make_radio_button(frame,name,variable_in,value_in,rowno): '''Creates a GUI radiobutton Runs execute_main when button is clicked :frame: main GUI frame :name: text to label entry box :variable_in: name of variable that controls radiobuttons :value_in: default initial value of variable :rowno: row number within GUI frame to place button ''' radio_button=ttk.Radiobutton(frame,text=name,variable=variable_in, value=value_in, command = lambda : execute_main(None)) radio_button.grid(column=0,row=rowno,sticky=(N, S, E, W)) # function for making a Checkbutton def make_check_button(frame,name,variable_in,initial_state,rowno): '''Creates a GUI check button Runs execute_main when button is clicked :frame: main GUI frame :name: text to label entry box :variable_in: name of variable that controls radiobuttons :initial_state: default initial value of variable :rowno: row number within GUI frame to place button ''' check_button=ttk.Checkbutton(frame,text=name, variable=variable_in, onvalue='On', offvalue='Off', command = lambda : execute_main(None)) check_button.grid(column=0, row=rowno, sticky=(N, S, E, W)) def on_closing(): '''Closes all matplotlib plots when GUI is closed so that program stops running''' plt.close('all') root.destroy() def changed(): #print('change') execute_main(0) return #update variables and make plot when key is pressed def execute_main(pressed): '''Updates all global variables from GUI, sends them solve and plot function This function is run every time a change is made in the GUI Throws warnings when max time duration is exceeded or Y axis is not selected ''' global co2_initial_update global co2_rate_update global cloud_initial_update global cloud_rate_update global albedo_initial_update global albedo_rate_update global epsilon1_initial_update global epsilon1_rate_update global epsilon2_initial_update global epsilon2_rate_update global solar_flux_update global forest_update global ice_update global water_update global desert_update global time_interval_update global time_duration_update global xaxis_update global Ts_update global T1_update global T2_update global forest_final_update global ice_final_update global water_final_update global desert_final_update cloud_initial_update = cloud_initial.get() cloud_rate_update = cloud_rate.get() albedo_initial_update = albedo_initial.get() albedo_rate_update = albedo_rate.get() epsilon1_initial_update = epsilon1_initial.get() epsilon1_rate_update = epsilon1_rate.get() epsilon2_initial_update = epsilon2_initial.get() epsilon2_rate_update = epsilon2_rate.get() solar_flux_update = solar_flux.get() forest_update = forest.get() ice_update = ice.get() water_update = water.get() desert_update = desert.get() time_interval_update = int(float(time_interval.get())) time_duration_update = int(float(time_duration.get())) xaxis_update = xaxis.get() Ts_update = Ts_switch.get() T1_update = T1_switch.get() T2_update = T2_switch.get() forest_final_update = forest_final.get() ice_final_update = ice_final.get() water_final_update = water_final.get() desert_final_update = desert_final.get() # check if at least one temp is being plotted on y axis if Ts_update=='Off'and T1_update=='Off'and T2_update=='Off': messagebox.showwarning("WARNING","At least one T on the Y Axis must be selected.") # check that rates of change don't exceed max during time duration global_max = [] if cloud_rate_update !=0: max_duration = max_time(100, cloud_initial_update, (cloud_rate_update/time_interval_update)) if time_duration_update > max_duration: global_max.append(max_duration) if albedo_rate_update !=0: max_duration = max_time(1, albedo_initial_update, (albedo_rate_update/time_interval_update)) if time_duration_update > max_duration: global_max.append(max_duration) if epsilon1_rate_update !=0: max_duration = max_time(1, epsilon1_initial_update, (epsilon1_rate_update/time_interval_update)) if time_duration_update > max_duration: global_max.append(max_duration) if epsilon2_rate_update !=0: max_duration = max_time(1, epsilon2_initial_update, (epsilon2_rate_update/time_interval_update)) if time_duration_update > max_duration: global_max.append(max_duration) if bool(global_max)==True: messagebox.showwarning("WARNING",("Duration must be less than {:.1f} years with given change.").format(min(global_max))) time_duration_update = min(global_max) time_duration.set(min(global_max)) show_plot() def show_plot(): '''Solves energy balance equations with updated inputs and embeds outplot into GUI ''' delta_Solar = 0 # solar doesn't currently have option to change in GUI calcs_per_timestep = 10 if albedo_initial_update == 0 and albedo_rate_update == 0: albedo, albedo_rate = calculate_albedo(water_update, water_final_update, ice_update, ice_final_update, forest_update, forest_final_update, desert_update, desert_final_update, cloud_initial_update, cloud_rate_update, time_interval_update, time_duration_update) else: albedo = albedo_initial_update albedo_rate = albedo_rate_update solution, t = solve_over_time(solar_flux_update,albedo,epsilon1_initial_update,epsilon2_initial_update,time_interval_update,time_duration_update,albedo_rate,epsilon1_rate_update,epsilon2_rate_update,delta_Solar,calcs_per_timestep) fig = make_plot(solution, t, Ts_update, T1_update, T2_update, xaxis_update, cloud_initial_update,cloud_rate_update, albedo, albedo_rate, epsilon1_initial_update, epsilon1_rate_update, epsilon2_initial_update, epsilon2_rate_update) gui_plot = FigureCanvasTkAgg(fig, outputframe) gui_plot.get_tk_widget().grid(row = 1, column = 0, sticky=(N, S, E, W)) # create tkinter object root = Tk() root.protocol("WM_DELETE_WINDOW", on_closing) root.title('Climate Predictor') root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) #set style - currently having problems when packaging so have commented this out #root.tk.call('source',sys.path[0]+'/climatepredictor/sun-valley.tcl') #root.tk.call('set_theme','dark') # create mainframe m=29 #number of rows in mainframe mainframe = ttk.Frame(root, padding="12 12 12 12") mainframe.grid(column=0, row=0, sticky=(N, S, E, W)) mainframe.columnconfigure(0, weight=1) for i in range(m): mainframe.rowconfigure(i, weight=1) #make frame for changing variables - row 0-n of mainframe n=29 #rowspan of varframe in main frame varframe=ttk.Frame(mainframe, padding="12 12 12 12") varframe.grid(column=0, row=0, sticky=(N, S, E, W),rowspan=n) varframe.columnconfigure(0, weight=1) varframe.columnconfigure(1, weight=1) #configure all rows to have same weight for i in range(n): varframe.rowconfigure(i, weight=1) # make frame for plot options - row 1 of mainframe r=10 # rowspan of plot frame outputframe=ttk.Frame(mainframe, padding="12 12 12 12") outputframe.grid(column=2, row=0, sticky=(N, S, E, W),rowspan=r) outputframe.columnconfigure(2, weight=1) outputframe.columnconfigure(3, weight=1) for i in range(m): outputframe.rowconfigure(i, weight=1) # make frame for plot options - row n+1 to m mainframe p=10 #rowspan of plot frame plotframe=ttk.Frame(mainframe, padding="12 12 12 12") plotframe.grid(column=2, row=r+1, sticky=(N, S, E, W),rowspan=p) plotframe.columnconfigure(2, weight=1) plotframe.columnconfigure(3, weight=1) for i in range(p): plotframe.rowconfigure(i, weight=1) ######################## Customise Variable Frame ############################# #initialize default values into tkinter variables cloud_initial = DoubleVar(root,value = cloud_initial_update) cloud_rate = DoubleVar(root,value = cloud_rate_update) albedo_initial = DoubleVar(root,value = albedo_initial_update) albedo_rate = DoubleVar(root,value = albedo_rate_update) epsilon1_initial = DoubleVar(root,value = epsilon1_initial_update) epsilon1_rate = DoubleVar(root,value = epsilon1_rate_update) epsilon2_initial = DoubleVar(root,value = epsilon2_initial_update) epsilon2_rate = DoubleVar(root,value = epsilon2_rate_update) solar_flux = DoubleVar(root,value = solar_flux_update) time_interval = IntVar(value = time_interval_update) time_duration = StringVar(value= time_duration_update) variable_title=ttk.Label(varframe, text='Variable Options',width=30,font='bold') variable_title.grid(column=0,row=0, sticky=(N, S, E, W)) #create frame for labels - row=1, column=0 in variable frame #spans the same number of rows as the make_new_entry thing so it lines up q=2 #rowspan of frame label_frame=ttk.Frame(varframe,padding="12 12 12 12") label_frame.grid(row=1,column=0,columnspan=2,rowspan=q,sticky=(N, S, E, W)) label_frame.columnconfigure(0, weight=1) label_frame.columnconfigure(1, weight=1) for i in range(q): label_frame.rowconfigure(i, weight=1) def add_labels(root,rowno): variable_label=ttk.Label(root, text='Variable',width=5) variable_label.grid(column=0,row=rowno, sticky=(N, S, E, W)) intial_amount_label=ttk.Label(root, text='Initial amount',width=10) intial_amount_label.grid(column=1,row=rowno, sticky=(N, S, E, W)) change_label=ttk.Label(root, text='Change',width=10) change_label.grid(column=3,row=rowno, sticky=(N, S, E, W)) #add our cloud cover entry options and title in rows 1, 2 in variable frame # make_value_entry(root,caption,rowno,default_initial, default_rate, unit): add_labels(label_frame,0) make_value_entry(label_frame,'Cloud cover', 1, cloud_initial, cloud_rate, '%') #functions for button for advanced frame def reveal(): return button.grid_remove(), advanced_frame.grid(column=0,row=2+q,sticky=(N, S, E, W),rowspan=k,columnspan=2), hide_button.grid(row=1+q,column=1),slider_frame.grid_remove(),slider_frame_final.grid_remove() def hide(): return button.grid(), advanced_frame.grid_remove(),hide_button.grid_remove(), slider_frame.grid(row=2+q+k,column=0,columnspan=2,rowspan=rowspanf,sticky=(N, S, E, W)), slider_frame_final.grid(column = 0, row = 8+q+k,columnspan=2,rowspan=2,sticky=(N, S, E, W)) #add buttons for advanced options in row 1+q button=ttk.Button(varframe,text='Advanced Options',command=reveal) button.grid(row=1+q, column=0) hide_button=ttk.Button(varframe,text='Hide Advanced Options',command=hide) hide_button.grid(row=1+q,column=0) hide_button.grid_remove() #add advanced frame dropdown in variable frame row 5 k=5 #rowspan advanced_frame=ttk.Frame(varframe,padding="12 12 12 12") advanced_frame.grid(column=0,row=2+q,sticky=(N, S, E, W),rowspan=k,columnspan=2) for i in range(5): advanced_frame.columnconfigure(i, weight=1) for i in range(k): advanced_frame.rowconfigure(i, weight=1) make_value_entry(advanced_frame,'Albedo',1,albedo_initial,albedo_rate,'') make_value_entry(advanced_frame,u'\u03B5\u2081',2,epsilon1_initial,epsilon1_rate,'') make_value_entry(advanced_frame,u'\u03B5\u2082',3,epsilon2_initial,epsilon2_rate,'') solar_label=ttk.Label(advanced_frame,text=u'S\u2080/present day solar flux') solar_label.grid(column=1,row=5, sticky=(N, S, E, W)) solar_entry=ttk.Entry(advanced_frame,textvariable=solar_flux,width=5) solar_entry.grid(column=3,row=5, sticky=(N, S, E, W)) solar_entry.bind('<KeyRelease>', execute_main) advanced_frame.grid_remove() #add initial land use widget here, row 2+q+k in variable frame rowspanf=8 slider_frame=ttk.Frame(varframe,padding="12 12 12 12") slider_frame.grid(row=2+q+k,column=0,columnspan=2,rowspan=rowspanf,sticky=(N, S, E, W)) slider_frame.columnconfigure(0, weight=1) slider_frame.columnconfigure(1, weight=1) for i in range(rowspanf): slider_frame.rowconfigure(i, weight=1) forest = DoubleVar(slider_frame,25) ice = DoubleVar(slider_frame,25) water = DoubleVar(slider_frame,25) desert = DoubleVar(slider_frame,25) slider_title=ttk.Label(slider_frame,text='Land Uses - Initial',) slider_title.grid(row=0,column=0,sticky=(N, S, E, W)) slider_note=ttk.Label(slider_frame,text='Enter values in descending order') slider_note.grid(row=0,column=1,sticky=(N, S, E, W)) # initial positions on the slider (calculated from initial percentages) init_positions = [9.6,19.6,90] # create the slider slider = Slider(slider_frame, width = 400, height = 60, min_val = 0, max_val = 100, init_lis = init_positions, show_value = True) slider.grid(row=2,column=0,columnspan=2) # Entry boxes for the different values # use make_simple_entry(root,label,variable,rowno,colno): forest = slider.forest_perc ice = slider.ice_perc water = slider.water_perc desert = slider.desert_perc forest_value = make_slider_entry(slider_frame,'Forest',slider.forest_perc,4,0, type = 0) ice_value = make_slider_entry(slider_frame,'Ice',slider.ice_perc,5,0, type = 1) water_value = make_slider_entry(slider_frame,'Water',slider.water_perc,6,0, type = 2) desert_value = make_slider_entry(slider_frame,'Desert',slider.desert_perc,7,0, type = 3) #final land use widget here rowspanf=8 slider_frame_final=ttk.Frame(varframe,padding="12 12 12 12") slider_frame_final.grid(row=10+q+k,column=0,columnspan=2,rowspan=rowspanf,sticky=(N, S, E, W)) #span just one row as had to put in later slider_frame_final.columnconfigure(0, weight=1) slider_frame_final.columnconfigure(1, weight=1) for i in range(rowspanf): slider_frame_final.rowconfigure(i, weight=1) slider_title_final=ttk.Label(slider_frame_final,text='Land Uses - final') slider_title_final.grid(row=0,column=0,sticky=(N, S, E, W)) slider_note_final=ttk.Label(slider_frame_final,text='Enter values in descending order') slider_note_final.grid(row=0,column=1,sticky=(N, S, E, W)) # initial positions on the slider (calculated from initial percentages) init_positions_final = [9.6,19.6,90] # create the slider slider_final = Slider(slider_frame_final, width = 400, height = 60, min_val = 0, max_val = 100, init_lis = init_positions_final, show_value = True) slider_final.grid(row=2,column=0,columnspan=2) # Entry boxes for the different values # use make_simple_entry(root,label,variable,rowno,colno): forest_final = slider_final.forest_perc ice_final = slider_final.ice_perc water_final = slider_final.water_perc desert_final = slider_final.desert_perc forest_value_final = make_slider_entry(slider_frame_final,'Forest',slider_final.forest_perc,4,0, type = 4) ice_value_final = make_slider_entry(slider_frame_final,'Ice',slider_final.ice_perc,5,0, type = 5) water_value_final = make_slider_entry(slider_frame_final,'Water',slider_final.water_perc,6,0, type = 6) desert_value_final = make_slider_entry(slider_frame_final,'Desert',slider_final.desert_perc,7,0, type = 7) #add time widget with slider - row 23 in variable frame slider_frame2 = ttk.Frame(varframe) slider_frame2.grid(column = 0, row = 26,columnspan=2,rowspan=2,sticky=(N, S, E, W)) slider_frame2.columnconfigure(0,weight=1) slider_frame2.columnconfigure(1,weight=1) slider_frame2.rowconfigure(0,weight=1) slider_frame2.rowconfigure(1,weight=1) slider_label = ttk.Label(slider_frame2, text='Time:') slider_label.grid(column=0,row=0,sticky=(N, S, E, W)) label = ttk.Label(slider_frame2, width = 13, text = 'Change Interval:') label.grid(row = 1, column = 0, sticky=(N, S, E, W)) entry = ttk.Entry(slider_frame2, width = 4, textvariable = time_interval) entry.grid(row = 1, column = 1, sticky=(N, S, E, W)) entry.bind('<KeyRelease>', execute_main) label = ttk.Label(slider_frame2, width = 10, text = 'years') label.grid(row = 1, column = 2, sticky=(N, S, E, W)) label = ttk.Label(slider_frame2, width = 8, text = 'Duration:') label.grid(row = 1, column = 3, sticky=(N, S, E, W)) value_entry = ttk.Entry(slider_frame2, width = 4, textvariable = time_duration) value_entry.grid(row = 1, column = 4, sticky=(N, S, E, W)) value_entry.bind('<KeyRelease>', execute_main) label = ttk.Label(slider_frame2, width = 6, text = 'years') label.grid(row = 1, column = 5, sticky=(N, S, E, W)) ############################################ Customise plotting frame ########################################### #title frame plot_options_label=ttk.Label(plotframe, text='Plot Options',width=30,font='bold') plot_options_label.grid(column=0,row=0, sticky=(N, S, E, W)) # 4 frames rowspanf=4 xaxis_frame=ttk.Frame(plotframe,padding="12 12 12 12") xaxis_frame.grid(row=1,column=0,columnspan=1,sticky=(N, S, E, W),rowspan=4) xaxis_frame.columnconfigure(0, weight=1) for i in range(rowspanf): xaxis_frame.rowconfigure(i, weight=1) rowspanf=4 yaxis_frame=ttk.Frame(plotframe,padding="12 12 12 12") yaxis_frame.grid(row=1,column=1,sticky=(N, S, E, W),columnspan=1,rowspan=rowspanf) yaxis_frame.columnconfigure(0, weight=1) for i in range(rowspanf): yaxis_frame.rowconfigure(i, weight=1) rowspanf=3 xaxis_advanced=ttk.Frame(plotframe,padding="12 12 12 12") xaxis_advanced.grid(row=1,column=0,sticky=(N, S, E, W),columnspan=1,rowspan=rowspanf) xaxis_advanced.columnconfigure(0, weight=1) for i in range(rowspanf): xaxis_advanced.rowconfigure(i, weight=1) # customise X axis frame xaxis = StringVar() xaxis_label=ttk.Label(xaxis_frame,text='X Axis') xaxis_label.grid(column=0,row=0,sticky=(N, S, E, W)) make_radio_button(xaxis_frame,'Time',xaxis,'time',1) make_radio_button(xaxis_frame,'Cloud cover',xaxis,'cloud cover',2) xaxis.set('time') #set xaxis to a value # customise Y axis frame Ts_switch = StringVar() T1_switch = StringVar() T2_switch = StringVar() yaxis_label=ttk.Label(yaxis_frame,text='Y Axis') yaxis_label.grid(column=0,row=0,sticky=(N, S, E, W)) make_check_button(yaxis_frame,'T surface',Ts_switch,Ts_update,1) make_check_button(yaxis_frame,'T lower atmosphere',T1_switch,T1_update,2) make_check_button(yaxis_frame,'T upper atmosphere',T2_switch,T2_update,3) Ts_switch.set('On') T1_switch.set('On') T2_switch.set('On') # X axis advanced options make_radio_button(xaxis_advanced,'Albedo', xaxis,'albedo',0) make_radio_button(xaxis_advanced,u'\u03B5\u2081',xaxis,'epsilon1',1) make_radio_button(xaxis_advanced,u'\u03B5\u2082',xaxis,'epsilon2',2) xaxis_advanced.grid_remove() ############################ Output Plot Frame ################################ show_plot() #functions for button for advanced axis frame def reveal_plot(): return xaxis_advanced.grid(row=1,column=0,sticky=(N, S, E, W),columnspan=1,rowspan=3), hide_button2.grid(row=5,column=0,sticky=(N, S, E, W)), button2.grid_remove(), xaxis_frame.grid_remove() def hide_plot(): return xaxis_advanced.grid_remove(), hide_button2.grid_remove(), button2.grid(row=5, column=0,sticky=(N, S, E, W)), xaxis_frame.grid(row=1,column=0,columnspan=1,sticky=(N, S, E, W),rowspan=4) hide_button2=ttk.Button(plotframe,text='Hide Advanced X Axis Options',command=hide_plot) hide_button2.grid(row=5,column=0,sticky=(N, S, E, W)) hide_button2.grid_remove() button2=ttk.Button(plotframe,text='Show Advanced X Axis Options',command=reveal_plot) button2.grid(row=5, column=0,sticky=(N, S, E, W)) #add entry for filename filename=StringVar() save_label=ttk.Label(plotframe,text='Saved plot name',padding='12 12 12 12') save_label.grid(row=6,column=0) save_entry=ttk.Entry(plotframe,textvariable=filename) save_entry.grid(row=6,column=1) # add save button def save_plot(): plt.savefig(fname=filename.get()+'.png') button_save=ttk.Button(plotframe,text='Save Plot',command=save_plot) button_save.grid(row=5, column=1,sticky=(N, S, E, W)) if __name__ =='__main__': execute_main root.mainloop()
7b982a2735e94707c872f607339e8fb3b33f4888
ryanchang1005/ALG
/array/LeetCode 56 Merge Intervals.py
693
3.609375
4
""" 合併重疊的區段 input = [[1, 3], [2, 6], [8, 10], [15, 18]] output = [[1, 6], [8, 10], [15, 18]] 思路 先排序 這樣只有下面3種狀況 1. [ A ] [ B ] 2. [ A ] [ B ] 3. [ A ] [ B ] 新區段 = (A.start, max(A.end, B.end)) """ def solve(data): arr = sorted(data) ret = [data[0]] for it in arr[1:]: if ret[-1][0] <= it[0] and it[0] <= ret[-1][1]: # 重疊 ret[-1][1] = max(ret[-1][1], it[1]) else: ret.append(it) return ret if __name__ == "__main__": # [[1, 6], [8, 10], [15, 18]] print(solve([[1, 3], [2, 6], [8, 10], [15, 18]])) # [[1, 5]] print(solve([[1, 4], [4, 5]]))
3bdf6f32ab0423bdf9e938d06dfbb7721e6eb0e9
dranzzer/gw2-waypoint
/overlay.py
333
3.6875
4
#Importing the library from tkinter import * #Create an instance of tkinter window or frame win= Tk() #Setting the geometry of window win.geometry("600x350") #Create a Label Label(win, text= "Hello World! ",font=('Helvetica bold', 15)).pack(pady=20) #Make the window jump above all win.attributes('-topmost',True) win.mainloop()