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
6cc3d71d373f2814eb88934cd65dff1bb5ac6e1a
hiteshhbr0103/mentorif
/Palandrom.py
318
3.875
4
from Task1 import Task as task word = input('Pllease enter number a word :') if(task.is_digit(word)): print("Invalid attempt. Please try again") else: res = task.palandrom(word) if (res == word): print("The Given word is a Palandrom") else: print("The given word is not a Palandrom")
2070ba6994dd98d6110abc2429adc8689b59e7fc
melycm/Guess-a-Number
/step1.py
411
4.1875
4
number = int(input("I am thinking of a number between 1 and 10. What's the number? ")) secret_number = 5 while number != secret_number: if number < secret_number: number = int(input("Nope, try again. What's the number? ")) if number == secret_number: number = int(input("Yes! You win!")) if number > secret_number: number = int(input("Nope, try again. What's the number? "))
2bbd9ef3f026df7369efd5ec50022151adaa988d
kim-byoungkwan/Coding_Test_1
/백준_9093_1w(문자열)_단어뒤집기_B1(복습).py
451
3.609375
4
n = int(input()) for i in range(n): string=input() string = string + " " stack = [] stack_final = [] for j in string: if j !=" ": stack.append(j) else: while stack: stack_final.append(stack.pop()) stack_final.append(" ") for m in range(len(stack_final)): print(stack_final[m],end='')
faa87c49d546a9666b15f37118a6fae9a2237163
MAYURI212/python_demp_mayuri
/1St_3rd.py
394
3.96875
4
dic = {} n = int(input("Enter number of elements : ")) a = list(input("\nEnter the numbers : ").split()) print("\nList is : ", a) for i in a: if i not in dic.keys(): dic[i] = 1 else: dic[i] = dic[i] + 1 print("\nDictionary:", dic) l2 = [[k, v] for k, v in dic.items()] l3 = [(k, v) for k, v in dic.items()] print("\nList of list:", l2) print("\nList of tuples:", l3)
91a8333d0f120527fda85bc6eb4bcd4bd402b157
brianchiang-tw/HackerRank
/Python/Python Functionals/Map and Lambda Function/map_and_lambda_function.py
461
4.21875
4
cube = lambda x: x**3# complete the lambda function def fibonacci(n): # return a list of fibonacci numbers fib_list = [0] * n # Initialization for first two terms if n >= 1: fib_list[0] = 0 if n >= 2: fib_list[1] = 1 for i in range(2, n): fib_list[i] = fib_list[i-1] + fib_list[i-2] return fib_list if __name__ == '__main__': n = int(input()) print(list(map(cube, fibonacci(n))))
4b231915d0c4c2afa75f115aad1deedbb8d3c233
Jackyzzk/Algorithms
/动态规划-斐波那契数列-02-0198. 打家劫舍.py
1,520
3.671875
4
class Solution(object): """ 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金, 影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统, 如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 输入: [1,2,3,1] 输出: 4 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 偷窃到的最高金额 = 1 + 3 = 4 。 输入: [2,7,9,3,1] 输出: 12 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 偷窃到的最高金额 = 2 + 9 + 1 = 12 。 链接:https://leetcode-cn.com/problems/house-robber """ def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 n = len(nums) if n < 3: return max(nums) opt = [0] * n opt[0], opt[1] = nums[0], max(nums[0], nums[1]) for i in range(2, n): opt[i] = max(opt[i - 1], nums[i] + opt[i - 2]) return opt[n - 1] def main(): nums = [2, 7, 9, 3, 1] # 12 # nums = [1, 2, 3, 1] # nums = [] # nums = [1] # nums = [2, 1, 1, 2] # 4 test = Solution() ret = test.rob(nums) print(ret) if __name__ == '__main__': main()
362bc088bc133b5f192ef632d9032df851dfdbfd
kellina/python
/3repeticao/07.py
227
4.25
4
# Faça um programa que leia 5 números e informe o maior número. numeros = [] for i in range(5): num = int(input('Digite um numero: ')) numeros.append(num) maior = max(numeros) print('O maior numero foi: ', maior)
a88fb9e59dbc1873271758246397b12b5f584a80
alynsther/RIPSHKCICC
/2.py
9,890
3.515625
4
import math import os from datetime import * import datetime import random import csv import unicodecsv import nltk from nltk.tokenize import sent_tokenize, word_tokenize, RegexpTokenizer from nltk.stem.snowball import SnowballStemmer from nltk.stem import WordNetLemmatizer from numpy import genfromtxt import numpy as np string_list = [] words = [] lolists = [] alldate = [] datelist = [] dfdatelist = [] tokenizer = RegexpTokenizer(r'\w+') wordnet_lemmatizer = WordNetLemmatizer() stemmer = SnowballStemmer("english") number = 3 k = 0 ''' 2nd part of the program. Before running this part, make sure you have: 1. Combined different text files on a day into a big text file (so that every day has one big text file). 2. The big text file should be renamed so that the program can read through days (or you can modify the names inside the program). It reads all those big text files through date. It outputs 4 files: topic_frequency_default.csv, topic_frequency_09.csv, topic_frequency_1.csv and idf.csv. ''' def daterange(start_date, end_date): ''' A function used to construct date range. To be used in generate_date() function. ''' for n in range(int ((end_date - start_date).days)): yield start_date + timedelta(n) def generate_date(): ''' User input a start date and an end date, the function creat a list of dates. The list of days will be used to pick out news articles from the file base (numerous text files) and price from price sources. ''' global alldate, datelist global end_year, end_month, end_day, start_year, start_month, start_day print ' Parsing dates ... ' start_year, start_month, start_day = int(raw_input(" Start year: ")), int(raw_input(" Start month: ")), int(raw_input(" Start day: ")) end_year, end_month, end_day = int(raw_input(" End year: ")), int(raw_input(" End month: ")), int(raw_input(" End day: ")) print ' Dates parsed ' print ' Generating datelist ... ' start_date = datetime.date(start_year, start_month, start_day) end_date = datetime.date(end_year, end_month, end_day) one_day = datetime.timedelta(days = 1) for single_date in daterange(start_date, end_date): alldate.append([single_date.year, single_date.month, single_date.day]) datelist.append(str(single_date.year) + '-' + single_date.strftime('%m') + '-' + single_date.strftime('%d')) print ' Datelist generated ' def generate_date_p(): ''' Partial version. Dates are set to default. 2010-1-1 ~ 2011-1-1 ''' global alldate, datelist global end_year, end_month, end_day, start_year, start_month, start_day print ' Parsing dates ... ' start_year, start_month, start_day = 2010, 1, 1 end_year, end_month, end_day = 2012, 1, 1 print ' Dates parsed ' print ' Generating datelist ... ' start_date = datetime.date(start_year, start_month, start_day) end_date = datetime.date(end_year, end_month, end_day) one_day = datetime.timedelta(days = 1) for single_date in daterange(start_date, end_date): alldate.append([single_date.year, single_date.month, single_date.day]) datelist.append(str(single_date.year) + '-' + single_date.strftime('%m') + '-' + single_date.strftime('%d')) print ' Datelist generated ' def import_y_m_d(alldate): ''' Grab in the text files based on the date list generated in generate_date() function. Besides take another file in based on the date the user inputed, and do all the subsequent prediction. ''' global string_list, number print ' Constructing file base ... ' number = len(alldate) f = [[]] * (len(alldate)) for i in range(len(alldate)): f[i] = open('wsjdate' + str(alldate[i][0])+ '_' + str(alldate[i][1]) + '_' + str(alldate[i][2]) + '.txt', 'r') text = '' for line in f[i]: text = text + line.decode("utf-8").rstrip() + ',' text = text.lower() string_list.append(text) f[i].close() print ' File base constructed ' def choosing_num(): ''' Generate a list of lists of proper amount of lists to put in the texts. ''' global lolists lolists = [[]] * (number) def processing_text(string_list): ''' Tokenize each string from text files. Return a list of lists which contains a tokenized sentence namely every words in that sentence. ''' print ' Tokenizing word list ... ' wordsList = lolists for i in range(number): wordsList[i] = tokenizer.tokenize(string_list[i]) print ' Word list tokenized ' return wordsList def process_content(words): ''' Filter the tokenized words in each string by their pos. Currently only take into account the verbs and nouns. Also lemmatizes words, get rid of plural form and tenses and so on. Also removes the 's, 't, 'll... things. Return a list of lists which contains every lemmatized words. ''' print ' Filtering part of speech ... ' pos_tag = {"NN", "VB", "JJ", "RB", "RBR", "RBS", "JJR", "JJS", "NNP", "NNPS", "NNS", "VBD", "VBG", "VBN", "VBP", "VBZ"} k = {u'll', u'e', u'm', u're', u'ag', u'u', u's', u't', u'd', u'p', u'f', u've'} pos_list = [] for j in range(number): pos = [] for i in words[j][0:]: word_s = nltk.word_tokenize(i) if nltk.pos_tag(word_s)[0][1] in pos_tag: #print word_s, nltk.pos_tag(word_s)[0] pos.append(wordnet_lemmatizer.lemmatize(wordnet_lemmatizer.lemmatize(word_s[0]), pos = 'v')) else: continue pos = [x for x in pos if x not in k] pos_list.append(pos) print 'File', str(j), 'filtered. ' print ' Part of speech filtered ' return pos_list def file2wo_rept(): with open('wo_rept_f.csv', 'rU') as wo_rept_f: reader = unicodecsv.reader(wo_rept_f, encoding = 'utf-8') wo_rept = [rec for rec in csv.reader(wo_rept_f, delimiter = ',')][0] return wo_rept def count_frequency(wo_rept, pos_list): ''' Construct frequency vector based on the list without repetition. Count the frequency of each words that appeared in the pos_list. Return the big frequency matrix with columns = word's frequency count and rows = every text file. ''' print ' Constructing frequency vector ... ' frequency = [[]] * len(pos_list) for i in range(len(pos_list)): frequency[i] = [pos_list[i].count(word) for word in wo_rept] # for j in range(len(wo_rept)): # count = pos_list[i].count(wo_rept[j]) # frequency[i].append(count) print ' Frequency vector constructed ' return frequency def topic_matrix2file(TopicMatrix, method): np.savetxt('TopicMatrix_' + str(method) + '.csv', TopicMatrix, delimiter=",") def file2topic_matrix(): TopicMatrix_default = genfromtxt('TopicMatrix_default.csv', delimiter=',') TopicMatrix_09 = genfromtxt('TopicMatrix_09.csv', delimiter=',') TopicMatrix_1 = genfromtxt('TopicMatrix_1.csv', delimiter=',') return TopicMatrix_default, TopicMatrix_09, TopicMatrix_1 def tfidf(frequency): newFrequency = (np.array(frequency).T).tolist() l = len(newFrequency[0]) #wordInDocument = [] idf = [] for i in range(len(newFrequency)): documentNumber = len([x for x in newFrequency[i] if x != 0]) # for j in range (l): # if newFrequency[i][j] != 0: # documentNumber += 1 #wordInDocument.append(documentNumber) #for i in range (len(wordInDocument)): idf.append(math.log(float(l) /documentNumber)) for i in range (len(newFrequency)): newFrequency[i] = [x * idf[i] for x in newFrequency[i]] # for j in range (l): # newFrequency[i][j] = newFrequency[i][j] * idf[i] normalizedFrequency = np.array(newFrequency).T.tolist() #normList = [] for i in range(len(normalizedFrequency)): norm = math.sqrt(sum([x ** 2 for x in normalizedFrequency[i]])) # norm = 0 # for j in range(len(normalizedFrequency[i])): # norm += normalizedFrequency[i][j] ** 2 # norm = math.sqrt(norm) #normList.append(norm) if norm == 0: continue normalizedFrequency[i] = [x / norm for x in normalizedFrequency[i]] # for j in range(len(normalizedFrequency[i])): # normalizedFrequency[i][j] = normalizedFrequency[i][j] / norm finalF = np.array(normalizedFrequency).T.tolist() return finalF,idf def convertToTopicFrequency(TopicMatrix, tfidf_frequency): return np.dot(TopicMatrix,tfidf_frequency) def topic_frequency2file(topic_frequency, method): np.savetxt('topic_frequency_' + str(method) + '.csv', topic_frequency, delimiter=",") def idf2file(idf): with open('idf.csv', 'wb') as idf_f: writer = unicodecsv.writer(idf_f, encoding = 'utf-8') writer.writerows([idf]) def main(): wo_rept = file2wo_rept() TopicMatrix_default, TopicMatrix_09, TopicMatrix_1 = file2topic_matrix() generate_date() print datelist import_y_m_d(alldate) print string_list, len(string_list) print number choosing_num() pos_list = process_content(processing_text(string_list)) frequency = count_frequency(wo_rept, pos_list) tfidf_frequency,idf = tfidf(frequency) topic_frequency_default = convertToTopicFrequency(TopicMatrix_default, tfidf_frequency) topic_frequency_09 = convertToTopicFrequency(TopicMatrix_09, tfidf_frequency) topic_frequency_1 = convertToTopicFrequency(TopicMatrix_1, tfidf_frequency) topic_frequency2file(topic_frequency_default, 'default') topic_frequency2file(topic_frequency_09, '09') topic_frequency2file(topic_frequency_1, '1') idf2file(idf) main()
59a2bd1ab53b6faec422709a87f6365a937513ee
MsMansiDhruv/Hackerrank-Solutions
/Data-Structures/Trees/Swap_nodes_algo.py
2,181
3.828125
4
#!/bin/python3 import os import sys from queue import Queue # # Complete the swapNodes function below. # class Node: def __init__(self, val, level): self.info = val self.level = level self.left = None self.right = None def inorder(root, item): if root: inorder(root.left, item) item.append(root.info) inorder(root.right, item) def createTree(indexes): #using queue to create the tree: BFS q = Queue() root = Node(1, 1) maxlevel = 1 q.put(root) for left, right in indexes: cur = q.get() if left != -1: leftNode = Node(left, cur.level + 1) cur.left = leftNode q.put(leftNode) if right != -1: rightNode = Node(right, cur.level + 1) cur.right = rightNode q.put(rightNode) #Finally the q is empty, and cur is at lowest level. Because there are always [-1, -1]s at the end of the indexes maxlevel = cur.level return (root, maxlevel) def swap(root, k): if root.left: swap(root.left, k) if root.right: swap(root.right, k) if root.level in k: root.left, root.right = root.right, root.left return root def swapNodes(indexes, queries): # # Write your code here. # #Create tree sys.setrecursionlimit(1500) root, maxLevel = createTree(indexes) ret = [] #Swap nodes for k in queries: item = [] h = [x for x in range(1, maxLevel) if x%k == 0] root = swap(root, h) inorder(root, item) ret.append(item) return ret if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) indexes = [] for _ in range(n): indexes.append(list(map(int, input().rstrip().split()))) queries_count = int(input()) queries = [] for _ in range(queries_count): queries_item = int(input()) queries.append(queries_item) result = swapNodes(indexes, queries) fptr.write('\n'.join([' '.join(map(str, x)) for x in result])) # fptr.write(str(result)) fptr.write('\n') fptr.close()
aa3f7774e2d7fb64c42c4b908516683da7d6f0ae
UCD-pbio-rclub/Pithon_Julin.M
/Chapter3/Dice.py
415
3.796875
4
import random for x in range(1,11): dice1 = random.randint(1,6) dice2 = random.randint(1,6) total = dice1 + dice2 print("the the total is:", total) if (total == 7 or total == 11): print("Wow! a", total, "was thrown") if (dice1 == dice2): print("Wow, a double:",dice1,"+",dice2) if (total > 10): print("Good throw!") if (total < 4): print("Bad luck!")
9711f883505854069674e7dcee3c4a426cccb5c2
Jap-Leen/Exun-19-WWCD-Day-2
/Program12.py
233
4.0625
4
# Complexity: E def func(x): # This function takes a number and prints the factors print("The factors of",x,"are:") for i in range(1, x): if x % i == 0: print(i) num = input("Enter a number: ") func(num)
583aa724530e6b819d1335b441cb05646c5fe1a9
JakeRead-GH/Research-Co-op
/U09_P05/U09_P05_Turtler.py
31,397
3.921875
4
"""///////////////////////////////////////////////////////////////////////////// Turtler Jake Read Created: January 22, 2020 File Name: U09_P05_Turtler.py This program allows the user to play a game like Frogger, where you have to move a turtle up the screen to reach safe spots while avoiding cars and water in order to reach the next level. There are 4 levels and each one has a new feature. At the end of the game your time to complete will be displayed. The program is set up to allow for easy testing for each level. Simply change the level variable at the start of the main program to choose a level from 1 - 4, or 5 for the closing screen. Variable List: level- The current level, ends program when it reaches 5 testing- A boolean that checks if the user is testing different levels in order to load required items not_hit- A boolean that checks if the turtle has taken a hit win- A boolean that means the game has ended with a win left_pad_taken- A boolean that shows the left lily pad is taken central_pad_taken- A boolean that shows the central lily pad is taken right_pad_taken- A boolean that shows the right lily pad is taken lives- How many lives the user has left delay- Allows the logs to move less frequently than the cars by counting down sink_countdown- A countdown that activates the sinking lily pads start- The time at the start of the game end- The time at the end of the program Documented Errors: - I couldn't get the water to kill the turtle properly as when the log moves it dissapears briefly, which will cause the turtle to touch the water. The code I had to make the water dangerous is commented out if you want to look at it. I spent about an hour trying to fix this but I didn't even get close. Logically it should be working it just doesn't and I've checked every variable in the section for discrepencies and found nothing. It's frustrating because it's a pretty important part of the game. - I couldn't find any other errors, if your trying to find more just use the testing feature, it makes it way easier. /////////////////////////////////////////////////////////////////////////////""" import turtle, random, time """///////////////////////////////////////////////////////////////////////////// turtle_module_set_up sets up the turtle module for use in the rest of the program Variable List: screen- The screen used for the program main- The turtle that draws the main screen of each level lives_display- The turtle that shows the user how many lives they have left /////////////////////////////////////////////////////////////////////////////""" def turtle_module_set_up(): global screen, main, lives_display screen = turtle.Screen() screen.setup(648, 420) main = turtle.Turtle() main.speed(0) main.hideturtle() lives_display = turtle.Turtle() lives_display.speed(0) lives_display.hideturtle() lives_display.penup() """///////////////////////////////////////////////////////////////////////////// title_screen creates the title screen for the program. The cars in the background still move in this section to make it animated. Variable List: space_not_pressed- A boolean that checks if space has been pressed /////////////////////////////////////////////////////////////////////////////""" def title_screen(): global space_not_pressed turtle.speed(0) turtle.fillcolor("lightGrey") turtle.hideturtle() turtle.penup() turtle.goto(-150, -50) turtle.pendown() turtle.begin_fill() turtle.goto(150, -50) turtle.goto(150, 100) turtle.goto(-150, 100) turtle.goto(-150, -50) turtle.end_fill() turtle.penup() turtle.fillcolor("black") turtle.goto(0, 10) turtle.write("Turtler", True, align = "center", font = ("Arial", 50, "underline") ) turtle.goto(0, -30) turtle.write("Press [Space] to Continue", True, align = "center", font = ("Arial", 18, "normal") ) space_not_pressed = True screen.onkey(stop_screen, "space") screen.listen() while space_not_pressed: move_cars() """///////////////////////////////////////////////////////////////////////////// instructions_screen creates the instructions screen for the program. This screen also has the car's animations in the background. /////////////////////////////////////////////////////////////////////////////""" def instructions_screen(): global space_not_pressed turtle.speed(0) turtle.fillcolor("lightGrey") turtle.hideturtle() turtle.penup() turtle.goto(-290, -160) turtle.pendown() turtle.begin_fill() turtle.goto(290, -160) turtle.goto(290, 195) turtle.goto(-290, 195) turtle.goto(-290, -160) turtle.end_fill() turtle.penup() turtle.fillcolor("black") turtle.goto(0, 120) turtle.write("Instructions", True, align = "center", font = ("Arial", 50, "underline") ) turtle.goto(-275, 90) turtle.write("- Use the WASD keys to move.", font = ("Arial", 18, "normal") ) turtle.goto(-275, 60) turtle.write("- Avoid cars and water as you move up the screen.", font = ("Arial", 18, "normal") ) turtle.goto(-275, 30) turtle.write("- If you're hit you'll lose a life. You have 3", font = ("Arial", 18, "normal") ) turtle.goto(-275, 5) turtle.write(" lives for each level.", font = ("Arial", 18, "normal") ) turtle.goto(-275, -25) turtle.write("- When all three turtles have made it to the safe", font = ("Arial", 18, "normal") ) turtle.goto(-275, -50) turtle.write(" zone, the next level will begin. There are 4 levels.", font = ("Arial", 18, "normal") ) turtle.goto(-275, -80) turtle.write("- In later levels there are logs you have to use to", font = ("Arial", 18, "normal") ) turtle.goto(-275, -105) turtle.write(" cross a river and lily pads that occasionally sink.", font = ("Arial", 18, "normal") ) turtle.goto(0, -150) turtle.write("Press [Space] to Begin", True, align = "center", font = ("Arial", 18, "normal") ) space_not_pressed = True screen.onkey(stop_screen, "space") screen.listen() while space_not_pressed: move_cars() """///////////////////////////////////////////////////////////////////////////// stop_screen is the function that's called when space is pressed. It ends both the title and instructions screens. /////////////////////////////////////////////////////////////////////////////""" def stop_screen(): global space_not_pressed turtle.clear() space_not_pressed = False """///////////////////////////////////////////////////////////////////////////// main_screen creates the playable screen for the program. A different layout will be created depending on the current level. Variable List: y_pos- A changing y position to create the different strips of colour x_pos- A changing x position to creat the 3 ending lily pads /////////////////////////////////////////////////////////////////////////////""" def main_screen(): global main, level y_pos = -210 for a in range(7): if level == 1: if a == 0 or a == 3: main.fillcolor("green") elif a == 6: main.fillcolor("lightBlue") else: main.fillcolor("grey") else: if a == 0 or a == 3: main.fillcolor("green") elif a == 1 or a == 2: main.fillcolor("grey") else: main.fillcolor("lightBlue") main.penup() main.goto(-324, y_pos) main.pendown() main.begin_fill() main.penup() main.goto(324, y_pos) main.pendown() main.goto(324, y_pos + 60) if a == 1 or (a == 4 and level == 1): main.pencolor("yellow") main.setheading(180) for b in range(22): main.forward(20) main.penup() main.forward(10) main.pendown() main.pencolor("black") else: main.penup() main.goto(-324, y_pos + 60) main.pendown() main.goto(-324, y_pos) main.end_fill() y_pos = y_pos + 60 main.fillcolor("green") x_pos = -207 main.penup() for c in range(3): main.goto(x_pos, 150) main.begin_fill() main.goto(x_pos + 60, 150) main.goto(x_pos + 60, 210) main.goto(x_pos, 210) main.goto(x_pos, 150) main.end_fill() x_pos = x_pos + 177 """///////////////////////////////////////////////////////////////////////////// initialize_turtle sets up the turtle's shape, size, speed, and random starting position. Variable List: move_speed- The distance the turtle moves with each key press turtle_x- The x position of the turtle turtle_y- The y position of the turtle /////////////////////////////////////////////////////////////////////////////""" def initialize_turtle(): global move_speed, turtle_x, turtle_y turtle.hideturtle() turtle.shape("turtle") turtle.shapesize(2,2) turtle.setheading(90) move_speed = 29.5 turtle_x = 0 turtle_y = -183 turtle.penup() turtle.speed(0) turtle.goto(turtle_x, turtle_y) turtle.showturtle() """///////////////////////////////////////////////////////////////////////////// initialize_cars sets up the features for all of the cars and puts them into parallel lists. The positions of the cars differ depending on level. Variable List: cars- A list that contains all of the cars image- The picture of each car to be placed on a turtle xpos- A list containing the x positions of the cars ypos- A list containing the y positions of the cars speed- A list containing the speeds of the cars /////////////////////////////////////////////////////////////////////////////""" def initialize_cars(): global cars, xpos, ypos, speed, level cars = [] image = "greenbugcar.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) image = "redcar2.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) image = "grey_car2.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) image = "yellow_car2.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) image = "blue_van2.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) image = "red_lorry2.gif" screen.register_shape(image) cars.append(turtle.Turtle(shape=image) ) for a in range(6): cars[a].speed(0) cars[a].penup() xpos = [] ypos = [0, 0, 0, 0, 0, 0] speed = [] if level == 1: ypos[0] = -120 ypos[1] = 60 ypos[2] = -60 ypos[3] = 120 ypos[4] = -60 ypos[5] = 120 else: ypos[0] = -60 ypos[1] = -60 ypos[2] = -1000 ypos[3] = -1000 ypos[4] = -120 ypos[5] = -120 #Green Car xpos.append(-50) speed.append(25) cars[0].goto(xpos[0], ypos[0]) #Red Car xpos.append(-200) speed.append(25) cars[1].goto(xpos[1], ypos[1]) #Grey Car xpos.append(-180) speed.append(15) cars[2].goto(xpos[2], ypos[2]) #Yellow Car xpos.append(180) speed.append(15) cars[3].goto(xpos[3], ypos[3]) #Blue Van xpos.append(180) speed.append(15) cars[4].goto(xpos[4], ypos[4]) #Red Lorry xpos.append(-180) speed.append(15) cars[5].goto(xpos[5], ypos[5]) """///////////////////////////////////////////////////////////////////////////// initialize_logs creates all of the logs and places them on the screen in a preset position. Variable List: logs- A list containing all of the logs image- The picture of each car to be placed on a turtle logx- A list containing the x positions of all the logs logy- A list containing the y positions of all the logs /////////////////////////////////////////////////////////////////////////////""" def initialize_logs(): global logs, logx, logy, logs_left, logs_right logs = [] image = "log2.gif" screen.register_shape(image) logs.append(turtle.Turtle(shape=image) ) image = "log3.gif" screen.register_shape(image) logs.append(turtle.Turtle(shape=image) ) image = "log4.gif" screen.register_shape(image) logs.append(turtle.Turtle(shape=image) ) image = "log5.gif" screen.register_shape(image) logs.append(turtle.Turtle(shape=image) ) logx = [] logy = [0, 0, 0, 0] logx.append(-200) logx.append(150) logx.append(-150) logx.append(180) if level == 2: logy[0] = 60 logy[1] = 120 logy[2] = 120 logy[3] = 60 else: logy[0] = 60 logy[1] = -1000 logy[2] = -1000 logy[3] = 60 for a in range(4): logs[a].speed(0) logs[a].penup() logs[a].goto(logx[a], logy[a]) """///////////////////////////////////////////////////////////////////////////// initialize_lily_pads creates all of the lily pads and places them on the screen in a preset position. Variable List: lily_pads- A list containing all of the lily pads image- The picture of each car to be placed on a turtle padsx- A list containing the x positions of all the lily pads /////////////////////////////////////////////////////////////////////////////""" def initialize_lily_pads(): global lily_pads lily_pads = [] image = "lily_pad2.gif" screen.register_shape(image) for a in range(6): lily_pads.append(turtle.Turtle(shape=image) ) padsx = [] padsx.append(-206.5) padsx.append(-147.5) padsx.append(-29.5) padsx.append(29.5) padsx.append(147.5) padsx.append(206.5) for b in range(6): lily_pads[b].speed(0) lily_pads[b].penup() lily_pads[b].goto(padsx[b], 120) """///////////////////////////////////////////////////////////////////////////// left allows the turtle to move left when [a] is pressed. It can't move off the screen /////////////////////////////////////////////////////////////////////////////""" def left(): global turtle_x, move_speed turtle_x = turtle_x - move_speed """///////////////////////////////////////////////////////////////////////////// right allows the turtle to move right when [d] is pressed. It can't move off the screen /////////////////////////////////////////////////////////////////////////////""" def right(): global turtle_x, move_speed turtle_x = turtle_x + move_speed """///////////////////////////////////////////////////////////////////////////// up allows the turtle to move up when [w] is pressed. It can't move off the screen /////////////////////////////////////////////////////////////////////////////""" def up(): global turtle_y, move_speed turtle_y = turtle_y + move_speed """///////////////////////////////////////////////////////////////////////////// down allows the turtle to move down when [s] is pressed. It can't move off the screen /////////////////////////////////////////////////////////////////////////////""" def down(): global turtle_y, move_speed turtle_y = turtle_y - move_speed """///////////////////////////////////////////////////////////////////////////// move_turtle moves the turtle to a new position based on movement instructions from the user. It also checks to see if a lily pad has been filled Variable List: turtle_x- The new x corrdinate of the turtle turtle_y- The new y coordinate of the turtle /////////////////////////////////////////////////////////////////////////////""" def move_turtle(): global turtle_x, turtle_y, turtle, left_pad_taken, central_pad_taken, right_pad_taken turtle.goto(turtle_x, turtle_y) if turtle.xcor() == -177 and turtle.ycor() == 171 and left_pad_taken == False: turtle.stamp() turtle_x = 0 turtle_y = -183 turtle.goto(turtle_x, turtle_y) left_pad_taken = True elif turtle.xcor() == 0 and turtle.ycor() == 171 and central_pad_taken == False: turtle.stamp() turtle_y = -183 turtle.goto(turtle_x, turtle_y) central_pad_taken = True elif turtle.xcor() == 177 and turtle.ycor() == 171 and right_pad_taken == False: turtle.stamp() turtle_x = 0 turtle_y = -183 turtle.goto(turtle_x, turtle_y) right_pad_taken = True """///////////////////////////////////////////////////////////////////////////// move_car moves the cars to the right or left. If they goes off the side of the screen they teleport back to the other side. /////////////////////////////////////////////////////////////////////////////""" def move_cars(): global car, xpos, ypos, speed for a in range(6): if a == 0 or a == 1: xpos[a] = xpos[a] + speed[a] if xpos[a] > 300: xpos[a] = -300 else: xpos[a] = xpos[a] - speed[a] if xpos[a] < -300: xpos[a] = 300 cars[a].goto(xpos[a], ypos[a]) """///////////////////////////////////////////////////////////////////////////// move_logs moves the logs once for every 5 times the cars move. This allows them to move at the same speed as the turtle so they can cary it. If the turtle is on a log it will be pulled along. If the turtle's hitbox leaves the logs hit box while over water it will die, or at least it should anyway but that sections turned off because the logs kill the turtle when they move. If the logs leave the screen they reappear on the opposite side. Variable List: logs_left- The left hitboxes of the logs logs_right- the right hitboxes of the logs /////////////////////////////////////////////////////////////////////////////""" def move_logs(): global logs, logx, logy, delay, logs_left, logs_right, turtle_x, turtle_y, not_hit delay = delay - 1 if delay == 0: logs_left = [] logs_right = [] logs_left.append(logs[0].xcor() - 75) logs_right.append(logs[0].xcor() + 75) logs_left.append(logs[1].xcor() - 115) logs_right.append(logs[1].xcor() + 115) logs_left.append(logs[2].xcor() - 38) logs_right.append(logs[2].xcor() + 38) logs_left.append(logs[3].xcor() - 75) logs_right.append(logs[3].xcor() + 75) for a in range(4): if turtle.ycor() > (logs[a].ycor() - 30) and turtle.ycor() < (logs[a].ycor() + 30): if turtle.xcor() > logs_left[a] and turtle.xcor() < logs_right[a]: if a == 0 or a == 3: turtle_x = turtle_x + 29.5 else: turtle_x = turtle_x - 29.5 #else: #not_hit = False if a == 0 or a == 3: logx[a] = logx[a] + 29.5 if logx[a] > 350: logx[a] = -350 else: logx[a] = logx[a] - 29.5 if logx[a] < -350: logx[a] = 350 logs[a].goto(logx[a], logy[a]) turtle.goto(turtle_x, turtle_y) delay = 5 """///////////////////////////////////////////////////////////////////////////// sink_lily_pads causes the lily pads to flash a few times and then sink. one of the 3 sets of lily pads sink at random every few seconds. I didn't until now that the original lily pads move, so mine are stationary. Variable List: sinking- The randomly selected set of lily pads that sinks /////////////////////////////////////////////////////////////////////////////""" def sink_lily_pads(): global lily_pads, sink_countdown, sinking if sink_countdown == 30: sinking = random.randint(1, 3) if sink_countdown == 20: for a in range(6): lily_pads[a].showturtle() sink_countdown = sink_countdown - 1 if sink_countdown <= 15 and sink_countdown % 2 == 0 and sink_countdown > 1: if sinking == 1: lily_pads[0].hideturtle() lily_pads[1].hideturtle() elif sinking == 2: lily_pads[2].hideturtle() lily_pads[3].hideturtle() else: lily_pads[4].hideturtle() lily_pads[5].hideturtle() elif sink_countdown <= 15 and sink_countdown % 2 == 1 and sink_countdown > 1: if sinking == 1: lily_pads[0].showturtle() lily_pads[1].showturtle() elif sinking == 2: lily_pads[2].showturtle() lily_pads[3].showturtle() else: lily_pads[4].showturtle() lily_pads[5].showturtle() if sink_countdown == 0: sink_countdown = 30 """///////////////////////////////////////////////////////////////////////////// check_hit creates the hitboxes of the cars andthe turtle and updates not_hit when the hitboxes overlap. Variable List: cars_left- A list containing the left hit box of every car cars_right- A list containing the right hit box of every car cars_top- A list containing the top hit box of every car cars_bottom- A list containing the bottom hit box of every car turtle_left_x- The turtle's left hitbox turtle_right_x- The turtle's right hitbox turtle_top_y- The turtle's top hitbox turtle_bottom_y- The turtle's bottom hitbox /////////////////////////////////////////////////////////////////////////////""" def check_hit(): global turtle_x, turtle_y, turtle, not_hit, lives, cars, turtle_left_x global turtle_right_x, turtle_top_y, turtle_bottom_y, lives_display turtle_left_x = turtle.xcor()- 20 turtle_right_x = turtle.xcor() + 20 turtle_top_y = turtle.ycor() + 25 turtle_bottom_y = turtle.ycor() - 20 #Cars cars_left = [] cars_right = [] cars_top = [] cars_bottom = [] cars_left.append(cars[0].xcor() - 15) cars_right.append(cars[0].xcor() + 20) cars_top.append(cars[0].ycor() + 10) cars_bottom.append(cars[0].ycor() - 10) cars_left.append(cars[1].xcor() - 30) cars_right.append(cars[1].xcor() + 40) cars_top.append(cars[1].ycor() + 10) cars_bottom.append(cars[1].ycor() - 15) cars_left.append(cars[2].xcor() - 40) cars_right.append(cars[2].xcor() + 30) cars_top.append(cars[2].ycor() + 10) cars_bottom.append(cars[2].ycor() - 10) cars_left.append(cars[3].xcor() - 40) cars_right.append(cars[3].xcor() + 30) cars_top.append(cars[3].ycor() + 10) cars_bottom.append(cars[3].ycor() - 15) cars_left.append(cars[4].xcor() - 50) cars_right.append(cars[4].xcor() + 40) cars_top.append(cars[4].ycor() + 23) cars_bottom.append(cars[4].ycor() - 22) cars_left.append(cars[5].xcor() - 70) cars_right.append(cars[5].xcor() + 55) cars_top.append(cars[5].ycor() + 25) cars_bottom.append(cars[5].ycor() - 25) for a in range(6): if turtle_right_x > cars_left[a] and turtle_left_x < cars_right[a] and turtle_top_y > cars_bottom[a] and turtle_bottom_y < cars_top[a]: not_hit = False #Water at the top of the screen (This water actually will kill you) if turtle.xcor() < -207 and turtle.ycor() == 171: not_hit = False elif turtle.xcor() > -147 and turtle.xcor() < -30 and turtle.ycor() == 171: not_hit = False elif turtle.xcor() > 30 and turtle.xcor() < 147 and turtle.ycor() == 171: not_hit = False elif turtle.xcor() > 207 and turtle.ycor() == 171: not_hit = False if not_hit == False: screen.onkey(None, "a") screen.onkey(None, "d") screen.onkey(None, "w") screen.onkey(None, "s") lives = lives - 1 not_hit = True turtle_x = 0 turtle_y = -183 time.sleep(1) turtle.goto(turtle_x, turtle_y) screen.onkey(left, "a") screen.onkey(right, "d") screen.onkey(up, "w") screen.onkey(down, "s") lives_display.clear() lives_display.goto(-300, 170) lives_display.write("Lives: " + str(lives), font = ("Arial", 16, "normal") ) """///////////////////////////////////////////////////////////////////////////// check_off_screen checks the turtle coordinates to make sure it hasnt gone off the screen. If it has it loses a life. /////////////////////////////////////////////////////////////////////////////""" def check_off_screen(): global turtle_x, turtle_y, not_hit if turtle_x > 300 or turtle_x < -300 or turtle_y < -210 or turtle_y > 210: not_hit = False """///////////////////////////////////////////////////////////////////////////// check_best_time calculates the time it took the user to complete the game using the start and end values taken previously. It then compares this time to the current best time stored in a file. If the user was faster than the best time then the best time is updated to be the users time. The time is then split into minutes and seconds for a nicer display later in the program. If you're using the test option a preset time will be used to keep the top time fair. Variable List: file- The file that contains the fastest completion of the game completion_time- The time it took the user to complete the game minutes- The minutes in the completion time seconds- The additional seconds of the completion time best_time- The fastest the game has been completed best_minutes- The minutes in the best time best_seconds- The additional seconds of the best time /////////////////////////////////////////////////////////////////////////////""" def check_best_time(): global start, end, minutes, best_minutes, seconds, best_seconds, completion_time if testing != True: completion_time = round(end - start, 2) file = open("best_time.txt") best_time = float(file.readline().strip() ) file.close() if completion_time < best_time: best_time = completion_time file = open("best_time.txt", 'w') file.write(str(best_time) ) file.close() seconds = completion_time % 60 minutes = (completion_time - seconds) / 60 best_seconds = best_time % 60 best_minutes = (best_time - best_seconds) / 60 """///////////////////////////////////////////////////////////////////////////// closing_screen creates the final screen of the program. Depending on wether the user won or lost, they'll get an appropriate screen. In addiition the users completion time and the best time are displayed. The turtle will move across the screen under the information when the screen first loads. Variable List: message- A parameter that determines if the user won or lost /////////////////////////////////////////////////////////////////////////////""" def closing_screen(message): global turtle_x, completion_time, best_time, seconds, best_seconds, minutes, best_minutes screen.clear() initialize_turtle() screen.bgcolor("lightBlue") main.goto(0, 80) if message == "win": main.write("You Win!", True, align = "center", font = ("Arial", 40, "normal") ) main.goto(0, -45) main.write("Completion Time: " + str(int(minutes) ) + " min " + str(int(seconds) ) + "s", True, align = "center", font = ("Arial", 20, "normal") ) main.goto(0, -80) main.write("Best Time: " + str(int(best_minutes) ) + " min " + str(int(best_seconds) ) + "s", True, align = "center", font = ("Arial", 20, "normal") ) else: main.write("You Ran Out of Lives!", True, align = "center", font = ("Arial", 40, "normal") ) main.goto(0, 5) main.write("Thanks for Playing!", True, align = "center", font = ("Arial", 40, "normal") ) turtle_x = -400 turtle.goto(turtle_x, -110) turtle.setheading(0) for a in range(25): turtle_x = turtle_x + 30 turtle.goto(turtle_x, -110) time.sleep(0.1) ## Main Program turtle_module_set_up() level = 1 if level > 1: testing = True else: testing = False main_screen() initialize_cars() title_screen() instructions_screen() initialize_turtle() screen.onkey(left, "a") screen.onkey(right, "d") screen.onkey(up, "w") screen.onkey(down, "s") screen.listen() playing = True not_hit = True win = False left_pad_taken = False central_pad_taken = False right_pad_taken = False lives = 3 lives_display.goto(-300, 170) lives_display.write("Lives: " + str(lives), font = ("Arial", 16, "normal") ) delay = 5 sink_countdown = 30 if testing: if level > 1: initialize_logs() if level > 2: initialize_lily_pads() if level == 5: completion_time = 165 win = True else: start = time.time() while lives != 0 and level != 5: move_turtle() move_cars() if level > 1: move_logs() if level == 4: sink_lily_pads() check_hit() check_off_screen() if left_pad_taken and central_pad_taken and right_pad_taken and level: level = level + 1 if level < 5: left_pad_taken = False central_pad_taken = False right_pad_taken = False lives = 3 main_screen() lives_display.clear() lives_display.goto(-300, 170) lives_display.write("Lives: " + str(lives), font = ("Arial", 16, "normal") ) initialize_cars() initialize_logs() if level > 2: initialize_lily_pads() else: win = True screen.onkey(None, "a") screen.onkey(None, "d") screen.onkey(None, "w") screen.onkey(None, "s") if win: end = time.time() check_best_time() closing_screen("win") else: closing_screen("lose") screen.exitonclick()
25d4d3768756f795d702b8c8a5e8d2b41e643711
siregabriel/practicas
/python.py
572
3.984375
4
nombre_hijo = "Liam" #name = input() <<<VARIABLE #print("GabrielR Systems 3.2") <<<SOLO POR ADORNARME #print(f"Hola, {name}")<<<FUNCION print(nombre_hijo) #<<< OJO no debe de llevar comas para mostrarse i = 28 print(f"f is {i}") f = 2.8 print(f"f is {f}") b = True print(f"b is {b}") n = None print(f"n is {n}") x = 27 if x > 29: print("x is positive") elif x < 28: print("x is negative") else: print("x is zero") nombre = "Alicia" name = "Alice" name[2] #esto de arriba cuenta e imprime la SEGUNDA LETRA de "Alice" coordinates = (10, 19.8) coordinates[1]
34486639494a3010f4b18cb8e5a4eee64f7cf945
AdamBrauns/CompletePythonUdemyCourse
/section_3/dictionary.py
803
4.65625
5
# Declaring a dictionary my_dict = {'key1': 'value1', 'key2': 'value2'} print(my_dict) print(my_dict['key1']) # Example price_lookup = {'apple': 2.99, 'oranges': 1.99, 'milk': 5.80} print(price_lookup['apple']) # Example of dictionary and key inside a dictionary d = {'k1': 123, 'k2':[0, 1, 2], 'k3':{'insideKey': 100}} print(d) print(d['k2'][2]) print(d['k3']['insideKey']) # Example of making an item upper case inside the dictionary d = {'key1': ['a', 'b', 'c']} my_list = d['key1'] letter = my_list[2] print(letter.upper()) print(d['key1'][2].upper()) # Assigning new values d = {'k1': 100, 'k2': 200} print(d) d['k3'] = 300 print(d) d['k1'] = 'NEW VALUE' print(d) # Other useful methods d = {'k1': 100, 'k2': 200, 'k3': 300} print(d.keys()) print(d.values()) # Returns a tuple print(d.items())
ab5c132eb299b782186ec845832cf404dc6a50c9
AKKamath/ImageCompression
/ImageComp.py
3,179
3.625
4
from PIL import Image import math import numpy as np # Class to allow keeping track of x and y easier class Point(object): def __init__(self, x, y): self.x = int(x) self.y = int(y) # Keeps track of RGB values of a pixel class Pixel(object): def __init__(self, color = [-1, -1, -1], topLeft = Point(0, 0), bottomRight = Point(0, 0)): self.R = int(color[0]) self.G = int(color[1]) self.B = int(color[2]) self.topLeft = topLeft self.bottomRight = bottomRight # The main class class QuadTree(): def __init__(self, image): # Store image pixelmap self.image = image.load() self.x = image.size[0] self.y = image.size[1] # Total levels in tree self.levels = int(np.log2(max(self.x, self.y) - 1) + 2) # Array of nodes self.tree = [] for i in range(self.levels): self.tree.append([]) # Place nodes into array self.createNode(0, Point(0, 0), Point(self.x - 1, self.y - 1)) def createNode(self, pos, topLeft, bottomRight): # Check if node is a leaf node if(topLeft.x == bottomRight.x and topLeft.y == bottomRight.y): self.tree[pos].append(Pixel(self.image[topLeft.x, topLeft.y], topLeft, bottomRight)) return Pixel(self.image[topLeft.x, topLeft.y], topLeft, bottomRight) # Store relevant positions mid = Point((topLeft.x + bottomRight.x) / 2, (topLeft.y + bottomRight.y) / 2) topMid = Point((topLeft.x + bottomRight.x) / 2, topLeft.y) leftMid = Point(topLeft.x, (topLeft.y + bottomRight.y) / 2) rightMid = Point(bottomRight.x, (topLeft.y + bottomRight.y) / 2) bottomMid = Point((topLeft.x + bottomRight.x) / 2, bottomRight.y) nodes = [] # Create children of current node nodes.append(self.createNode(pos + 1, topLeft, mid)) if(topLeft.x != bottomRight.x): nodes.append(self.createNode(pos + 1, Point(topMid.x + 1, topMid.y), rightMid)) if(topLeft.y != bottomRight.y): nodes.append(self.createNode(pos + 1, Point(leftMid.x, leftMid.y + 1), bottomMid)) if(topLeft.x != bottomRight.x and topLeft.y != bottomRight.y): nodes.append(self.createNode(pos + 1, Point(mid.x + 1, mid.y + 1), bottomRight)) R, G, B = 0, 0, 0 # Store requisite color information for i in nodes: R = R + i.R G = G + i.G B = B + i.B R = R / len(nodes) G = G / len(nodes) B = B / len(nodes) # Update current node with values self.tree[pos].append(Pixel([R, G, B], topLeft, bottomRight)) return Pixel([R, G, B], topLeft, bottomRight) def disp(self, level): # Invalid height given if(level >= self.levels): print("Invalid tree level") return # Create a new image img = Image.new("RGB", (self.x, self.y), "black") pixels = img.load() # Move from starting to last node on given height for i in self.tree[level]: x1 = i.topLeft.x y1 = i.topLeft.y x2 = i.bottomRight.x y2 = i.bottomRight.y for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): # Set colour pixels[x,y] = (i.R, i.G, i.B) # Display image img.show() img_name = raw_input("Enter name of image\n") img = Image.open(img_name).convert("RGB") tree = QuadTree(img) A = input("Input tree level (0 = Most Compressed - " + str(tree.levels - 1) + " = Original Image)") tree.disp(A)
446999d1607ae547a3bae0eb9a27f7ab11887c5e
RogueWaverly/LearningPython
/scratch.py
1,945
3.953125
4
import numpy as np print("1.\tHello, World!") print("2.\tRoll Die") print("3.\tGuess a Number") print("4.\tMad Libs") choice = input("Pick a program: ") if( choice==1 ): print("Hello, World!") elif( choice==2 ): again = 1 while( again ): roll = np.random.randint(1,7) print(roll) again = input("Would you like to roll again? (1/0) ") elif( choice==3 ): def isNum(guess): try: return float(guess) except ValueError: return 0 def diffBetween(num, guess): return num-guess def compare (num, guess): diff = diffBetween(num, guess) if( diff<0 ): print("Your number is too high.") return 0 elif( diff>0 ): print("Your number is too low.") return 0 else: print("That's correct!") return 1 again = 1 while( again ): num = np.random.randint(1,11) isCorrect = 0 while( not isCorrect ): guess = 0 while( not guess ): guess = isNum(raw_input("Guess a number between 1 and 10: ")) isCorrect = compare(num, guess) again = input("Would you like to play again? (1/0) ") elif( choice==4 ): def isNum(guess): try: float(guess) return 1 except ValueError: return 0 again = 1 while( again ): noun1 = raw_input("Enter a noun: ") noun2 = raw_input("Enter another noun: ") emotion1 = raw_input("Enter an emotion: ") emotion2 = raw_input("Enter another emotion: ") numString = raw_input("Enter a number: ") while( not isNum(numString) ): numString = raw_input("Enter a number: ") num = float(numString) print("Some say the world will end in %s," % noun1) print("Some say in %s." % noun2) print("From what I've tasted of %s" % emotion1) print("I hold with those who favor %s." % noun1) print("But if it had to perish %0.2f times," % num) print("I think I know enough of %s" % emotion2) print("To say that for destruction %s" % noun2) print("Is also great") print("And would suffice.") again = input("Would you like to play again? (1/0) ")
0fe2f1d91038e39605eec2920b47c220684b2320
jdht1992/PythonScript
/mutable_inmurable.py
821
4.375
4
# Tuples are an ordered sequences of items, just like lists. The main difference between # tuples and lists is that tuples cannot be changed (immutable) unlike lists which can (mutable). my_list = [1, 2, 3] print(my_list) print(id(my_list)) my_list.append(4) print(my_list) print(id(my_list)) my_list[0] = 0 print(my_list) print(id(my_list)) # Tuples are immutable which means that after initializing a tuple, # it is impossible to update individual items in a tuple. t = (3, 7, 4, 2) # this is impossible # t[0] = 's' # Initialize tuple tup1 = ('Python', 'SQL') # Initialize another Tuple tup2 = ('R',) # Create new tuple based on existing tuples new_tuple = tup1 + tup2 print(new_tuple) tuple1 = (4, 5, 6, 1) print(tuple1) print(id(tuple1)) # changed its id tuple1 += (9,) print(tuple1) print(id(tuple1))
63bdc8f364b981f3b24cf4f6ba27a661860ef5a2
sq2141/Data-analysis-practice-notes
/Data analysis and visualization using Python/13_selecting_entries.py
806
4.15625
4
import numpy as np import pandas as pd from pandas import Series, DataFrame ser1 = Series(np.arange(3),index=['a','b','c']) ser1 = 2*ser1 print ser1 # Grab value by index print ser1['b'] print ser1[2] print ser1[0:3] print ser1[['c','a']] # Grab values by logic print ser1[ser1>1] # We can also set values by logic ser1[ser1>3]=10 print ser1 # Selecting data in a DataFrame dframe = DataFrame(np.arange(25).reshape(5,5),index=['NYC','LA','CHI','SF','DC'], columns=['a','b','c','d','e']) print dframe # Selecting by column print dframe['b'] print dframe[['b','c','e']] print dframe[dframe['c']>8] # grab all entries where the entry in the c column is greater than 8 # Get a boolean dataframe print dframe > 10 # Can also use ix to label index (get row data) print dframe.ix['LA'] print dframe.ix[2]
1679653fb4f5f7ee2b5c594d68b712e03cdaf8b3
Tanya3108/StandardBetweennessCentrality
/SBC.py
10,776
3.65625
4
#!/usr/bin/env python3 import re import itertools import copy ROLLNUM_REGEX = "201[0-9]{4}" class Graph(object): name = "Tanya" email = "tanya18109@iiitd.ac.in" roll_num = "2018109" def __init__ (self, vertices, edges): """ Initializes object for the class Graph Args: vertices: List of integers specifying vertices in graph edges: List of 2-tuples specifying edges in graph """ self.vertices = vertices ordered_edges = list(map(lambda x: (min(x), max(x)), edges)) self.edges = ordered_edges self.validate() def validate(self): """ Validates if Graph if valid or not Raises: Exception if: - Name is empty or not a string - Email is empty or not a string - Roll Number is not in correct format - vertices contains duplicates - edges contain duplicates - any endpoint of an edge is not in vertices """ if (not isinstance(self.name, str)) or self.name == "": raise Exception("Name can't be empty") if (not isinstance(self.email, str)) or self.email == "": raise Exception("Email can't be empty") if (not isinstance(self.roll_num, str)) or (not re.match(ROLLNUM_REGEX, self.roll_num)): raise Exception("Invalid roll number, roll number must be a string of form 201XXXX. Provided roll number: {}".format(self.roll_num)) if not all([isinstance(node, int) for node in self.vertices]): raise Exception("All vertices should be integers") elif len(self.vertices) != len(set(self.vertices)): duplicate_vertices = set([node for node in self.vertices if self.vertices.count(node) > 1]) raise Exception("Vertices contain duplicates.\nVertices: {}\nDuplicate vertices: {}".format(vertices, duplicate_vertices)) edge_vertices = list(set(itertools.chain(*self.edges))) if not all([node in self.vertices for node in edge_vertices]): raise Exception("All endpoints of edges must belong in vertices") if len(self.edges) != len(set(self.edges)): duplicate_edges = set([edge for edge in self.edges if self.edges.count(edge) > 1]) raise Exception("Edges contain duplicates.\nEdges: {}\nDuplicate vertices: {}".format(edges, duplicate_edges)) def dict1(self): #This function creates a dictionary of all the vertices and the value of them will be a list of those vertices directly connected to them. l=[] for i in self.edges: i=list(i) l.append(i) d={} for i in l: if i[0] not in d: d[i[0]]=[] if i[1] not in d: d[i[1]]=[] for i in l: for k in d: if i[0]==k: d[k].append(i[1]) elif i[1]==k: d[k].append(i[0]) else: pass return d def shortestpath(self,start,end): #this function finds the shortest path between the start vertices and end vertices. d=self.dict1() l1=[] a=start for i in d[a]: l1.append([a,i]) if i==end: return [a,i] #returns the path when start and end are directly connected (dis=1) a1=0 while a1==0: for i in l1: n=len(i) for j in d[i[n-1]]: if j not in i: i2=copy.deepcopy(i) i2.append(j) l1.append(i2) #appends the vertices point being used in the shortest path if j==end: #returns the shortest path return i2 else: a1=0 i2=[] if a1==0: return None #if there is no shortest path, none is returned . But one pre condition here is that the graph is connected , thus None will never be returned. def min_dist(self, start_node, end_node): ''' Finds minimum distance between start_node and end_node Args: start_node: Vertex to find distance from end_node: Vertex to find distance to Returns: An integer denoting minimum distance between start_node and end_node ''' short=self.shortestpath(start_node,end_node) #finds the shortest path between start node and end node. if short==None: return None else: shortlength=len(short) #length of shortest path gives us min_dist return shortlength raise NotImplementedError def all_shortest_paths(self,start_node, end_node): """ Finds all shortest paths between start_node and end_node Args: start_node: Starting node for paths end_node: Destination node for paths Returns: A list of path, where each path is a list of integers. """ mindist=self.min_dist(start_node,end_node) #finds the minimum distance between start and end node. path=[] a=self.all_paths(start_node,end_node,mindist,path) #finds all the paths between start and end node that have len=mindist (i.e finds all the shortest path) return a raise NotImplementedError def all_paths(self,node, destination, dist, path): """ Finds all paths from node to destination with length = dist Args: node: Node to find path from destination: Node to reach dist: Allowed distance of path path: path already traversed Returns: List of path, where each path is list ending on destination Returns None if there no paths """ d=self.dict1() l=[] l.append(node) path.append(l) d1=0 while d1<int(dist-1): #execute loop till mentioned distance is not reached . One is subtracted because the starting node is already appended in the list path2=list(path) for i in path2: for j in d[i[d1]]: #j takes the value of all consecutive vertices i2=list(i) if j not in i: #if the node is already not in the path , then append it to the path list. i2.append(j) path.append(i2) d1+=1 path3=list(path) for i in path3: if i in path2: path.remove(i) #removes the path(incomplete path) got from previous loop mainpath=[] for i in path: if i[dist-1]==destination: mainpath.append(i) #path is appended only if last node is equal to the destination if mainpath==[]: return None else: return mainpath raise NotImplementedError def X(self,l): #finds the number of shortest path between two coordinates x=l[0] y=l[1] a=self.all_shortest_paths(x,y) n=len(a) return n def Y(self,l,node): #finds the number of shortest path between two coordinates passing through a node x=l[0] y=l[1] a=self.all_shortest_paths(x,y) b=[] for i in a: if node in i: b.append(i) n=len(b) return n def betweenness_centrality(self, node): """ Find betweenness centrality of the given node Args: node: Node to find betweenness centrality of. Returns: Single floating point number, denoting betweenness centrality of the given node """ NodePairs=[] n=len(self.vertices) for i in self.vertices: for j in self.vertices: if i!=j and i!=node and j!=node: #checking if these nodes are not equal to each other or to the node whose betweenness centrality is to be found if [i,j] not in NodePairs and [j,i] not in NodePairs: #checking if these node pairs do not already exist NodePairs.append([i,j]) #creating node pairs s=0 for i in NodePairs: nx=self.X(i) ny=self.Y(i,node) nyx=ny/nx s+=nyx g=(s*2)/((n-1)*(n-2)) #calculating betweenness centrality by substituting correct values in the formula. return g raise NotImplementedError def top_k_betweenness_centrality(self,m=[]): """ Find top k nodes based on highest equal betweenness centrality. Returns: List integers, denoting top k nodes based on betweenness centrality and their value """ l={} for i in self.vertices: l[i]=self.betweenness_centrality(i) #dict of nodes and their betweenness centrality value max1=max(list(l.values())) #max1 stores the max betweenness centrality value for i in l: if l[i]==max1: #checking if the BC value equal to the max value , if yes it is appended in list m m.append(i) return (m,max1) raise NotImplementedError def answer(self): (a,max1)=self.top_k_betweenness_centrality() k=len(a) #tells number of top nodes a=str(a) a=a.replace("[","") #removing brackets from a to change format of output a=a.replace("]","") if k==1: print("Answer:k= 1 , SBC=",max1,", Top '1' node:",a) else: print("Answer:k=",k,", SBC=",max1,", Top '",k,"' nodes:",a) return if __name__ == "__main__": vertices =[1, 2, 3, 4, 5, 6] edges = [[1, 2], [1, 5], [2, 3], [2, 5], [3, 4], [4, 5], [4, 6]] graph = Graph(vertices, edges) s=graph.answer()
eea087550c04c4d2745300780445d511c7957430
icidicf/python
/online_coding/string/reverseOrderingOfWords.py
521
4.125
4
#!/usr/bin/python import sys import re if (len(sys.argv) < 2): print "please enter input test string"; sys.exit(0); inputStr=sys.argv[1]; #version 1 #tempStr=inputStr.split(" "); tempStr=re.split('\s+',inputStr); tempResult=[]; outStr=""; for i in tempStr: part=i[::-1]; tempResult.append(part); outStr=" ".join(tempResult); print "just reverse the word , not change the word order " + outStr; #version 3 print "not reverse the word , change the order of the words " + ' '.join(reversed(inputStr.split()))
7b09cdd469e9ede3bad9bab81a4d8b1272ace612
dougtc1/algorithms1
/Python/Proyecto/proyectosintkinter.py
33,186
3.921875
4
# # Proyecto-primera_entrega.py # # Descripcion: Este es un juego llamado "Connect TableroHorizontale dots" en el que dos # jugadores, bien sea persona vs maquina o persona vs persona, tratan de # completar la mayor cantidad de cuadros en un tablero de dimensiones # elegidas por el usuario. # # Autores: # Roberto Camara Carnet:11-10235 Grupo: 46 # Douglas Torres Carnet:11-11027 Grupo:28 # # Ultima modificacion: ??/06/2014 # ######TKINTER##### from tkinter import * from tkinter import ttk # Importacion de la libreria que permite escoger una posicion a marcar # al azar a la computadora from random import * # Definicion de Clase class Jugadores: NombreJugador1 = "" NombreJugador2 = "" grupo = Jugadores() # Definicio de funciones ################################################################################ ######################## F U N C I O N E S ##################################### ################################################################################ # Definicion de funcion que inicializa los datos del programa #------------------------------------------------------------------------------# def Inicializacion (filas: int, columnas: int) -> (list,list,list): # Precondicion: filas>=2 and columnas>=2 # Postcondicion: len(TableroHorizontal)==filas*(columnas-1) and\ # len(TableroVertical)==(filas-1)*columnas and\ # len(TableroCuadros)==(filas-1)*(columnas-1) and\ # all((TableroHorizontal[i][j] == "0") for i in range(filas)\ # for j in range(columnas-1))and\ ((TableroVertical[i][j] == "0")\ # for i in range(filas-1) for j in range(columnas) and\ # ((TableroCuadros[i][j] == "0") for i in range(filas-1)\ # for j in range(columnas-1))) TableroCuadros = [] TableroHorizontal = [] TableroVertical = [] for i in range(filas): TableroHorizontal.append([]) for j in range(columnas-1): TableroHorizontal[i].append("0") for i in range(filas-1): TableroVertical.append([]) for j in range(columnas): TableroVertical[i].append("0") for i in range(filas-1): TableroCuadros.append([]) for j in range(columnas-1): TableroCuadros[i].append("0") return TableroHorizontal,TableroVertical,TableroCuadros # Definicion de funcion que imprime el tablero cada vez que se modifica #------------------------------------------------------------------------------# def ImprimirTablero(TableroHorizontal: list, TableroVertical: list,\ TableroCuadros:list) -> (list,list,list): # Precondicion: len(TableroHorizontal) >=2 and len(TableroVertical) >=2 and\ # len(TableroCuadros) >=2 # Postcondicion: True // Esta funcion no modifica ninguna variable que recibe,\ # solo imprime los tableros en un formato mas amigable para el usuario print("***HORIZONTAL***") print() for i in TableroHorizontal: print(" ".join(i)) print("***VERTICAL***") print() for i in TableroVertical: print(" ".join(i)) print("***CUADROS***") print() for i in TableroCuadros: print(" ".join(i)) # Definicion de funcion que permite al jugador 1 hacer su jugada #------------------------------------------------------------------------------# def Jugador1(TableroHorizontal: list,TableroVertical: list,TableroCuadros: list,\ filas: int,columnas: int,TurnoActual: int) -> (list,list,list,int): # Precondicion: len(TableroHorizontal)==filas*(columnas-1) and\ # len(TableroVertical)==(filas-1)*columnas and\ # len(TableroCuadros)==(filas-1)*(columnas-1) and\ # filas>=2 and columnas>=2 and (TurnoActual==2) # Postcondicion: len(TableroHorizontal)==filas*(columnas-1) and \ # len(TableroVertical)==(filas-1)*columnas and\ # len(TableroCuadros)==(filas-1)*(columnas-1)""" turno = True # Variable que se usa para especificar si un jugador\ # puede seguir jugando opcion = 0 # Variable que especifica el tipo de raya que desea marcar\ # el usuario TurnoActual = 1 # Variable que especifica el turno de quien juega while (turno): print ("Turno jugador 1") opcion = int(input("Presione 1 para horizontal, 2 para vertical,\ 3 para guardar o cualquier otra tecla para salir: ")) if (opcion == 1): TableroHorizontal = MarcarLineaHorizontal(TableroHorizontal) elif (opcion == 2): TableroVertical = MarcarLineaVertical(TableroVertical) elif (opcion == 3): GuardarPartida("archivo.txt") break else: quit() TableroCuadros,turno = HacerCuadros(TableroHorizontal,TableroVertical,\ TableroCuadros,filas,columnas,1,\ turno) #print(turno) ImprimirTablero(TableroHorizontal,TableroVertical,TableroCuadros) return TableroHorizontal,TableroVertical,TableroCuadros,TurnoActual # Definicion de funcion que permite al jugador 2 hacer su jugada #------------------------------------------------------------------------------# def Jugador2(TableroHorizontal: list,TableroVertical: list,TableroCuadros: list,\ filas: int,columnas: int,TipoJugador: int,TurnoActual: int) -> (list,list,\ list,int): # Precondicion: (TipoJugador==1 or TipoJugador==2) and\ # len(TableroHorizontal)==filas*(columnas-1) and \ # len(TableroVertical)==(filas-1)*columnas and\ # len(TableroCuadros)==(filas-1)*(columnas-1) and \ # filas>=2 and columnas>=2 and TurnoActual==1 # Postcondicion: len(TableroHorizontal)==filas*(columnas-1) and\ # len(TableroVertical)==(filas-1)*columnas and \ # len(TableroCuadros)==(filas-1)*(columnas-1) # Aqui se usa un while para definir el turno de cada jugador turno = True # Variable que se usa para espeecificar si un jugador puede\ # seguir jugando TurnoActual = 2 # Variable que especifica el turno del jugador que esta\ # jugando opcion = 0 # Variable que especifica el tipo de raya que desea marcar el\ # usuario N = filas-1 M = columnas-1 while (turno): if (TipoJugador == 2): print("Es humano","\n") print("Turno jugador 2\n") opcion = int(input("Presione 1 para horizontal, 2 para vertical,\ 3 para guardar o cualquier otra tecla para salir: ")) if (opcion == 1): TableroHorizontal = MarcarLineaHorizontal(TableroHorizontal) elif (opcion == 2): TableroVertical = MarcarLineaVertical(TableroVertical) elif (opcion == 3): GuardarPartida("archivo.txt") break else: quit() TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,filas,\ columnas,2,turno) print (turno) ImprimirTablero(TableroHorizontal,TableroVertical,TableroCuadros) else: print("Es computadora","\n") print("Turno jugador 2\n") for i in range (N): for j in range (M): if ((TableroHorizontal[i][j] == "1") and\ (TableroVertical[i][j] == "1") and\ (TableroHorizontal[i+1][j] == "1") and\ (TableroVertical[i][j+1] != "1")): TableroVertical[i][j+1] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,\ filas,columnas,\ 2,turno) elif((TableroHorizontal[i][j] == "1") and\ (TableroVertical[i][j] == "1") and\ (TableroVertical[i][j+1] == "1") and\ (TableroHorizontal[i+1][j] != "1")): TableroHorizontal[i+1][j] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,\ filas,columnas,\ 2,turno) elif((TableroHorizontal[i][j] == "1") and\ (TableroHorizontal[i+1][j] == "1") and\ (TableroVertical[i][j+1] == "1") and\ (TableroVertical[i][j] != "1")): TableroVertical[i][j] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,\ filas,columnas,\ 2,turno) elif((TableroVertical[i][j] == "1") and\ (TableroHorizontal[i+1][j] == "1") and\ (TableroVertical[i][j+1] == "1") and\ (TableroHorizontal[i][j] != "1")): TableroHorizontal[i][j] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,\ filas,columnas,\ 2,turno) # Aqui deberia haber una verificacion de que todavia se puede seguir jugando, es decir que hay cuadros sin completar opcion = randint(1,2) if (opcion == 1): i,j = randint(0,N),randint(0,M-1) TableroHorizontal[i][j] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,filas,\ columnas,2,turno) elif (opcion == 2): i,j = randint(0,N-1),randint(0,M) TableroVertical[i][j] = "1" TableroCuadros,turno = HacerCuadros(TableroHorizontal,\ TableroVertical,\ TableroCuadros,filas,\ columnas,2,turno) else: quit() ImprimirTablero(TableroHorizontal,TableroVertical,TableroCuadros) return TableroHorizontal,TableroVertical,TableroCuadros,TurnoActual # Definicion de funcion que imprime las instrucciones #------------------------------------------------------------------------------# def Instrucciones () -> (str): # Precondicion: True # Postcondicion: True // Esta funcion imprime las instrucciones del juego # y no modifica ninguna varriable del juego print("\n") print ("Cada jugador en su turno debe seleccionar entre dos puntos, \ horizontales o verticales, para trazar una raya \n") print ("El objetivo del juego es completar la mayor cantidad de cuadrados \n") print ("Al marcar una raya en el tablero ocurre un cambio de turno a menos \ que el jugador complete un cuadrado con dicha raya, caso en el que puede volver a jugar \n") print ("Al final del juego gana el jugador con mayor cantidad de cuadros marcados \n") # Definicion de funcion que marca una linea horizontal en el tablero #------------------------------------------------------------------------------# def MarcarLineaHorizontal(TableroHorizontal: list) -> (list): # Precondicion: len(TableroHorizontal) >=2 # Postcondicion: TableroHorizontal[lineafila][lineacolumna] == "1" lineafila = 0 # Esta variable especifica la fila en donde va a marcar\ # una linea el jugador que este jugando lineacolumna = 0 # Esta variable especifica la columna en donde va a marcar\ # una linea el jugador que este jugando lineafila = int(input('Escribe la fila donde quieres hacer la linea: ')) lineacolumna = int(input('Escribe la columna donde quieres hacer la linea: ')) TableroHorizontal[lineafila][lineacolumna] = "1" return TableroHorizontal # Definicion de funcion que marca una linea vertical en el tablero #------------------------------------------------------------------------------# def MarcarLineaVertical(TableroVertical: list) -> (list): # Precondicion: len(TableroVertical) >=2 # Postcondicion: TableroVertical[lineafila][lineacolumna] == "1" lineafila = 0 # Esta variable especifica la fila en donde va a marcar\ # una linea el jugador que este jugando lineacolumna = 0 # Esta variable especifica la columna en donde va a marcar\ # una linea el jugador que este jugando lineafila = int(input('Escribe la fila donde quieres hacer la linea: ')) lineacolumna = int(input('Escribe la columna donde quieres hacer la linea: ')) TableroVertical[lineafila][lineacolumna] = "1" return TableroVertical # Definicion de funcion que marca un cuadrado en el tablero y dice de que jugador fue #------------------------------------------------------------------------------# def HacerCuadros(TableroHorizontal: list, TableroVertical: list,TableroCuadros:\ list,filas: int,columnas: int,jugador: int,turno: bool) -> (list,bool): # Precondicion:len(TableroHorizontal)==filas*(columnas-1) and\ # len(TableroVertical)==(filas-1)*columnas and\ # len(TableroCuadros)==(filas-1)*(columnas-1) and\ # filas>=2 and columnas >=2 and (jugador == 1 or jugador == 2) and turno # Postcondicion: any((TableroCuadros[i][j] == 1) for i in range(filas-1)\ # for j in range(columnas-1) \ if jugador == 1 and\ # ((TableroHorizontal[i][j] == "1") and (TableroVertical[i][j] == "1") and\ # (TableroHorizontal[i+1][j] == "1") and (TableroVertical[i][j+1] == "1") and\ # (TableroCuadros[i][j] != "1") and (TableroCuadros[i][j] != "2"))) or\ # (any((TableroCuadros[i][j] == 2) for i in range(filas-1)\ # for j in range(columnas-1) if jugador == 2 and\ # ((TableroHorizontal[i][j] == "1") and (TableroVertical[i][j] == "1") and\ # (TableroHorizontal[i+1][j] == "1") and (TableroVertical[i][j+1] == "1") and\ # (TableroCuadros[i][j] != "1") and (TableroCuadros[i][j] != "2"))) N = filas-1 M = columnas-1 for i in range (N): for j in range (M): if ((TableroHorizontal[i][j] == "1") and \ (TableroVertical[i][j] == "1") and \ (TableroHorizontal[i+1][j] == "1") and\ (TableroVertical[i][j+1] == "1") and \ (TableroCuadros[i][j] == "0")): if (jugador == 1): TableroCuadros[i][j] = "1" turno = True return TableroCuadros,turno elif (jugador == 2): TableroCuadros[i][j] = "2" turno = True return TableroCuadros,turno else: quit() else: turno = False return TableroCuadros,turno # Definicion de funcion que permite cargar una partida especificada por el usuario #------------------------------------------------------------------------------# def CargarPartida(archivo: str) -> (list,list,list,int,int,int,int,int,int,str,str): # Precondicion: archivo == "partida1.txt" # Postcondicion: filas>=2 and columnas>=2 Atributos = [] Partida = open("archivo.txt") Atributos = Partida.readlines() print (Atributos) filas = Atributos[0] columnas = Atributos[1] CantidadDeJugadores = Atributos[2] TurnoActual = Atributos[3] NombreJugador1 = Atributos[4] if ("CPU" == Atributos[5]): NombreJugador2 = Atributos[5] TipoJugador = 1 else: NombreJugador2 = Atributos[5] TipoJugador = 2 for i in range(7,filas+7): TableroHorizontal[i-7] = Atributos[i] for i in range(filas+8,columnas+filas+7): TableroVertical[i-filas-8] = Atributos[i] for i in range(columnas+filas+8,(filas-1)+columnas+filas+8): TableroCuadros[i-columnas-filas-8] = Atributos[i] return TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,filas,\ columnas,PuntajeJugador1,PuntajeJugador2,TurnoActual,NombreJugador1,\ NombreJugador2 # Definicion de funcion que guarda una partida #------------------------------------------------------------------------------# def GuardarPartida(archivo) -> (str): # Precondicion: filas>=2 and columnas>=2 # Postcondicion: archivo == "partida1.txt" print("La partida ha sido guardada!") # Definicion de funcion que imprime el puntaje al momento de la partida #------------------------------------------------------------------------------# def Puntaje(TableroCuadros: list, PuntajeJugador1: int, PuntajeJugador2: int)\ -> (int,int): # Precondicion: len(TableroCuadros)>=2 and PuntajeJugador1>=0 and\ # PuntajeJugador2>=0 # Postcondicion: (PuntajeJugador1 == (sum( 1 for i in range (filas-1)\ # for j in range (columnas-1) \ # if TableroCuadros[i][j]=="1"))) and\ # (PuntajeJugador2 == (sum( 1 for i in range (filas-1) \ # for j in range (columnas-1) if TableroCuadros[i][j]=="2")) for i in range(filas-1): for j in range(columnas-1): if (TableroCuadros[i][j] == "1"): PuntajeJugador1 = PuntajeJugador1 + 1 elif (TableroCuadros[i][j] == "2"): PuntajeJugador2 = PuntajeJugador2 + 1 else: pass return PuntajeJugador1,PuntajeJugador2 # Definicion de funcion que imprime el puntaje final de la partida #------------------------------------------------------------------------------# def PuntajeFinal(PuntajeJugador1: int,PuntajeJugador2: int,filas: int,\ columnas: int) -> (str): # Precondicion:PuntajeJugador1 + PuntajeJugador2 == (filas-1)*(columnas-1) # Postcondicion: (resultado == PuntajeJugador1>PuntajeJugador2) or \ # (resultado == PuntajeJugador1<PuntajeJugador2) or\ # (resultado == PuntajeJugador1=PuntajeJugador2) resultado = "" if (PuntajeJugador1 > PuntajeJugador2): resultado = "Ha ganado el jugador 1" elif (PuntajeJugador1 < PuntajeJugador2): resultado = "Ha ganado el jugador 2" else: resultado = "Ha habido un empate" print (resultado) # Definicion de funcion que especifica el turno de juego #------------------------------------------------------------------------------# def Turno (TipoJugador: list,TableroHorizontal: list,TableroVertical: list,\ TableroCuadros: list,filas: int,columnas: int,azar: int) -> (list,list,list) : # Precondicion: (TipoJugador==1 or TipoJugador==2) and\ # len(TableroHorizontal)==filas*(columnas-1) and \ # len(TableroVertical)==(filas-1)*columnas and # len(TableroCuadros)==(filas-1)*(columnas-1) and filas>=2 and \ # columnas>=2 and (azar==1 or azar==2) # Postcondicion: (PrimerTurno = Jugador1(TableroHorizontal,TableroVertical,\ #TableroCuadros,filas,columnas,TurnoActual) and\ # SegundoTurno = Jugador2(TableroHorizontal,TableroVertical,TableroCuadros,\ # filas,columnas,TipoJugador,TurnoActual)) or\ # (PrimerTurno = Jugador2(TableroHorizontal,TableroVertical,TableroCuadros,\ # filas,columnas,TipoJugador,TurnoActual) and\ # SegundoTurno = Jugador1(TableroHorizontal,TableroVertical,TableroCuadros,\ # filas,columnas,TurnoActual)) PrimerTurno = Jugador1 # Variable que hace el llamado al jugador x al\ # que le corresponde jugar de primero SegundoTurno = Jugador2 # Variable que hace el llamado al jugador y al\ # que le corresponde jugar de segundo # Nota: 'x' e 'y' vienen dados por el azar si se escoge el modo de juego\ # de dos personas if (TipoJugador == 1): PrimerTurno = Jugador1(TableroHorizontal,TableroVertical,TableroCuadros,\ filas,columnas,TurnoActual) SegundoTurno = Jugador2(TableroHorizontal,TableroVertical,TableroCuadros,\ filas,columnas,TipoJugador,TurnoActual) elif (TipoJugador == 2): if (azar == 1): PrimerTurno = Jugador1(TableroHorizontal,TableroVertical,\ TableroCuadros,filas,columnas,TurnoActual) SegundoTurno = Jugador2(TableroHorizontal,TableroVertical,\ TableroCuadros,filas,columnas,\ TipoJugador,TurnoActual) elif (azar == 2): PrimerTurno = Jugador2(TableroHorizontal,TableroVertical,\ TableroCuadros,filas,columnas,\ TipoJugador,TurnoActual) SegundoTurno = Jugador1(TableroHorizontal,TableroVertical,\ TableroCuadros,filas,columnas,\ TurnoActual) return PrimerTurno,SegundoTurno ##################### def MarcarLinea(event): TOL = 8 CELLSIZE = 50 OFFSET = 50 CIRCLERAD = 2 DOTOFFSET = 50 GAME_H = 400 GAME_W = 400 x,y = event.x,event.y startx = CELLSIZE * ((x-OFFSET)//CELLSIZE) + DOTOFFSET starty = CELLSIZE * ((y-OFFSET)//CELLSIZE) + DOTOFFSET tmpx = (x-OFFSET)//CELLSIZE tmpy = (y-OFFSET)//CELLSIZE dx = ((x-OFFSET)-(x-OFFSET//CELLSIZE)*CELLSIZE) dy = ((y-OFFSET)-(y-OFFSET//CELLSIZE)*CELLSIZE) orient = orientacion(dx,dy,TOL) if orient == HORIZONTAL: endx = startx + CELLSIZE endy = starty else: endx = startx endy = starty + CELLSIZE #print "line drawn: %d,%d to %d,%d" % (startx,starty,endx,endy) canvas.create_line(startx,starty,endx,endy) def orientacion(dx,dy,TOL): if abs(dx) < TOL: if abs(dy) < TOL: return None # mouse in corner of box; ignore else: orient = VERTICAL elif abs(dy) < TOL: orient = HORIZONTAL else: return None def mostrar_coordenadas(event): x, y = event.x, event.y mensaje = 'Clic en la posición (%d, %d)' % (x, y) #canvas.create_line(x,x2,y,y2, width=2) print(mensaje) return x,y ###################### # Definicion de funcion que imprime el menu del juego y permite escoger el tipo de juego #------------------------------------------------------------------------------# def ModoJuego()-> (int,bool): # Precondicion: True # Postcondicion: ((seleccion== 1) or (seleccion == 2) or (seleccion == 3) or\ # (seleccion == 4) or (seleccion == 5)) and filas>=2 and columnas>=2 and\ # len(TableroHorizontal) >=2 and len(TableroVertical) >=2 and\ # len(TableroCuadros) >=2 seleccion = 0 # Variable que especifica la seleccion del menu hecha\ # por el usuario filas = 0 # Variable que guarda la cantidad de filas que quiere el\ # usuario en el tablero columnas = 0 # Variable que guarda la cantidad de columnas que quiere el\ # usuario en el tablero print ("\n\n\tBienvenido a Connect TableroHorizontale dots!\n") print ("Aqui se le presentan las siguientes opciones: \n") print ("1) - Partida de 1 jugador") print ("2) - Partida de 2 jugadores") print ("3) - Cargar partida") print ("4) - Instrucciones") print ("5) - Salir \n") seleccion = int(input("Introduzca una opcion y presione enter: ")) if (seleccion == 1): # Aqui va la inicializacion de datos realizando la llamada a la funcion filas = int(input('Escribe el numero de filas del tablero: ')) columnas = int(input('Escribe el nuemro de columnas del tablero: ')) root = Tk() root.geometry("600x480") canvas = Canvas(root, bg='white',width = 400, height = 400) for i in range (filas): for j in range (columnas): canvas.create_oval(40*i+10,40*j+10,40*i+10+2*2,40*j+10+2*2,fill="black") canvas.pack() TableroHorizontal,TableroVertical,\ TableroCuadros = Inicializacion(filas,columnas) TipoJugador = 1 PuntajeJugador1 = 0 PuntajeJugador2 = 0 TurnoActual = 1 NombreJugador1 = "" NombreJugador2 = "" return TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,\ filas,columnas,PuntajeJugador1,PuntajeJugador2,TurnoActual,\ NombreJugador1,NombreJugador2 elif (seleccion == 2): # Aqui va la inicializacion de datos realizando la llamada a la funcion # Adicionalmente se dice el tipo de jugador que es el jugador 2 filas = int(input('Escribe el numero de filas del tablero: ')) columnas = int(input('Escribe el nuemro de columnas del tablero: ')) root = Tk() root.title = ("Connect the dots") root.configure(background='white') root.geometry("800x800") canvas = Canvas(root, bg='white',width = 800, height = 800) salir = Button(canvas, text="Salir",command = Salir,font= ("Agency FB",14),\ width=10).place(x=150,y=535) guardar = Button(canvas,text="Guardar",command = GuardarPartida("archivo.txt"),\ font= ("Agency FB",14),width=10).place(x= 500,y=535) x = 150-(filas*10) y = 100-(columnas*10) for i in range (filas): for j in range (columnas): canvas.create_oval(50 +(50*i+x*2.5),50 +(50*j+y*2.5),\ (x*2.5)+(50*i+50+2*2),\ (y*2.5)+(50*j+50+2*2),fill="black") canvas.pack() canvas.bind("<Button-1>",mostrar_coordenadas) NombreJugador1 = "Douglas" NombreJugador2 = "Roberto" TableroHorizontal,TableroVertical,\ TableroCuadros = Inicializacion(filas,columnas) TipoJugador = 2 PuntajeJugador1 = 0 PuntajeJugador2 = 0 TurnoActual = 0 #NombreJugador1 = "" #NombreJugador2 = "" nombre1 = Label(canvas, text=NombreJugador1,font= ("Agency FB",14),\ width=10).place(x=25,y=150) nombre2 = Label(canvas, text=NombreJugador2,font= ("Agency FB",14),\ width=10).place(x=665,y=150) return TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,\ filas,columnas,PuntajeJugador1,PuntajeJugador2,TurnoActual,\ NombreJugador1,NombreJugador2 elif (seleccion == 3): # Aqui el programa carga la partida de un archivo TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,filas,\ columnas,PuntajeJugador1,PuntajeJugador2,TurnoActual,\ NombreJugador1,NombreJugador2 = CargarPartida("archivo.txt") return TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,\ filas,columnas,PuntajeJugador1,PuntajeJugador2,TurnoActual,\ NombreJugador1,NombreJugador2 elif (seleccion == 4): # Aqui se imprimen las instrucciones del juego al llamarse a la funcion instruccion Instrucciones() elif (seleccion == 5): quit() # Definicion de funcion que permite salir del juego en cualquier momento #------------------------------------------------------------------------------# def Salir() -> (): # Precondicion: True // No recibe parametros de entrada # Postcondicion: (seleccion == 1) or (seleccion == 2) #seleccion = 0 # Variable que especifica la eleccion del usuario si\ # desea salir quit() # print ("Esta funcion te permite salir del juego en cualquier momento") ####################### PROGRAMA PRINCIPAL ##################################### TableroHorizontal = [] # Lista que guarda la matriz del tablero de rayas\ # horizontales TableroVertical = [] # Lista que guarda la matriz del tablero de rayas\ # verticales TableroCuadros = [] # Lista que guarda la matriz del tablero de cuadros TipoJugador = 0 # Variable entera que almacena el tipo de jugador que es\ # jugador 2, si es humano o maquina filas = 0 # Variable entera que especifica la cantidad de filas que se\ # usaran en los tableros columnas = 0 # Variable entera que especifica la cantidad de columnas\ # que se usaran en los tableros azar = 0 # Variable entera que especifica el jugador que empieza a jugar\ # de primero en caso de ser humano vs humano TurnoActual = 0 # Variable entera que especifica cual jugador esta\ # jugando al momento PuntajeJugador1 = 0 # Variable entera que almacena la puntuacion del\ # jugador 1 PuntajeJugador2 = 0 # Variable entera que almacena la puntuacion del\ # jugador 2 MovimientosMaximos = 0 # Variable entera que almacena la cantidad maxima\ # de rayas posibles # Precondicion: True // Como toda la interaccion del usuario es con las\ # funciones, las precondiciones de estas seran las que especifiquen todos los\ # datos validos en el programa TableroHorizontal,TableroVertical,TableroCuadros,TipoJugador,filas,columnas,\ PuntajeJugador1,PuntajeJugador2,TurnoActual,NombreJugador1,\ NombreJugador2 = ModoJuego() """nombre1=StringVar() nombre2=StringVar() nombre1.set(grupo.NombreJugador1) nombre2.set(grupo.NombreJugador2) label1 = Label(root, textvariable=nombre1, anchor = NE, fg = 'black') label2 = Label(root, textvariable=nombre2, anchor = NW, fg = 'black') label1.pack() label2.pack() """ azar = randint(1,2) print (azar) MovimientosMaximos = ((((filas-1)*(columnas)) + ((filas)*(columnas-1)))//2) ImprimirTablero(TableroHorizontal,TableroVertical,TableroCuadros) for i in range(MovimientosMaximos): print() print ("Esta es la puntuacion de:",grupo.NombreJugador1,":",PuntajeJugador1) print ("Esta es la puntuacion de:",grupo.NombreJugador2,":",PuntajeJugador2) print() PrimerTurno,SegundoTurno = Turno(TipoJugador,TableroHorizontal,\ TableroVertical,TableroCuadros,filas,\ columnas,azar) PuntajeJugador1,PuntajeJugador2 = Puntaje(TableroCuadros,PuntajeJugador1,\ PuntajeJugador2) PuntajeFinal(PuntajeJugador1,PuntajeJugador2,filas,columnas) root.mainloop() # Postcondicion: all((TableroCuadros[i][j] != "0") for i in range(filas-1)\ # for j in range(columnas-1)) ################################################################################ #############################COMENTARIOS######################################## ################################################################################ # Discutir uso de funcion Puntaje o agregarlo a la clase Estudiante # Instrucciones va fuera de modo de juego, colocar instrucciones como una pestaña de ayuda # Lo que diga el puntaje debe ir llamado en HacerCuadros para evitar que sume 1 punto cada turno por cada cuadro que ya se haya marcado (Parece ser mas util usarlo como clase en este modo) # Hay que usar un while para el ciclo principal # El booleano del while se va a verificar con TableroCuadros en cada funcion de cada jugador # En caso de que se convierta en falso, debe salirse del ciclo # Aun no se me ocurre ninguna forma en el caso de que se finalice el juego con el jugador que jugo de primero en el turno # MovimientosMaximos es la cota # En Jugador2 donde juega la maquina, no se esta usando la funcion de marcar linea y para evitar que randint escoga una posicion ya marcada habria que agregarle ese "atributo" a las funciones de marcar linea para que cada jugador tenga esa verificacion
f9b4d9dcf9bd07b776a772bc6e6a2f89d5f255c0
gaurangbansal/pythonGLA
/is_pangram.py
253
3.921875
4
def is_pangram(s): a='qwertyuiopasdfghjklzxcvbnm' s=s.lower() for i in a: if i in s: continue else: return False return True s=input('Enter a string : ') print (is_pangram(s))
c10a44b5248223581c6fb3e81cc1dd8287b37b53
andrewghaddad/OOP
/OOP/Notes/Week4/week4.py
1,345
4.125
4
# Decision structures and boolean logic # so far our programs have been deterministic and sequential a = 5 b = 10 print(a > b and a > 1) # False print(a > 1 and b > a) # True print(a == 5 and b < 100) # True print(a > 1 and b < 1 and b < a) # False print(a > 1 and b > 1 and b < a) # False print(a > b or a > 1) # True print(a > 1 or b > a) # True print(a == 5 or b < 100) # True print(a > 1 or b < 1 or b < a) # True print(a > 1 or b > 1 or b < a) # True print(not True) # False print(not False) # True print(4 < 2) # False print(not (4 < 2)) # True print(not (not (4 < 2))) # False print() # String comparison (ascii) print("dog < cat =", "dog" < "cat") # False print("fish < alligator =", "fish" < "alligator") # False print("elephant == tiger =", "elephant"=="tiger") # False print("bat != honey badger =", "bat" != "honey badger") # True print("bat > bank =", "bat" > "bank") # True print("bat < bats =", "bat" < "bats") # True print("Z < a =", "Z" < "a") # True # the ascii values for all upper case letters is less than the ascii values # for all lower case letters ("Z" < "a") # within the same, the ascii values are sorted in alphabetical order ("A" < "Z") # string manipulation # .lower, .upper apple = "Apple" print(apple.lower()) print(apple.upper()) # len # counts the number of characters in a string print(len(apple)) # 5
ca426e436bc1e4c3a5f1de5e6852110807be1d58
haadeescott/green_calculator
/basic_calculator/calculator.py
4,727
4.15625
4
from tkinter import * import tkinter.font as font root = Tk() root.title(" GREEN CALCULATOR ") # entry texbox e= Entry(root, width=35, borderwidth=5, bg='#C0FFDC') e.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def button_cleartext(): e.delete(0,END) def button_click(number): # e.delete(0, END) # number will be inserted at the front instead # e.insert(0, number) # therefore need to reverse order of insertion by converting entry of numbers into string current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def button_add(): first_number = e.get() # to allow number to be passed outside of function global f_num global math math = "addition" f_num = float(first_number) e.delete(0, END) def button_equal(): second_number=e.get() e.delete(0, END) if math == "addition": e.insert(0, f_num + float(second_number)) if math == "subtraction": e.insert(0, f_num - float(second_number)) if math == "division": e.insert(0, f_num / float(second_number)) if math == "multiplication": e.insert(0, f_num * float(second_number)) def button_subtract(): first_number = e.get() # to allow number to be passed outside of function global f_num global math math = "subtraction" f_num = float(first_number) e.delete(0, END) def button_divide(): first_number = e.get() # to allow number to be passed outside of function global f_num global math math = "division" f_num = float(first_number) e.delete(0, END) def button_multiply(): first_number = e.get() # to allow number to be passed outside of function global f_num global math math = "multiplication" f_num = float(first_number) e.delete(0, END) # initialize buttons myFont = font.Font(weight="bold") # cannot pass parameters in button, use lambda instead button_0= Button(root, text="0", padx=40, pady=20, command=lambda: button_click(0), bg= '#59F19B') button_1= Button(root, text="1", padx=40, pady=20, command=lambda: button_click(1), bg='#71F9AC') button_2= Button(root, text="2", padx=40, pady=20, command=lambda: button_click(2), bg='#71F9AC') button_3= Button(root, text="3", padx=40, pady=20, command=lambda: button_click(3), bg='#71F9AC') button_4= Button(root, text="4", padx=40, pady=20, command=lambda: button_click(4), bg='#8EFEBF') button_5= Button(root, text="5", padx=40, pady=20, command=lambda: button_click(5), bg='#8EFEBF') button_6= Button(root, text="6", padx=40, pady=20, command=lambda: button_click(6), bg='#8EFEBF') button_7= Button(root, text="7", padx=40, pady=20, command=lambda: button_click(7), bg='#9EFEC8') button_8= Button(root, text="8", padx=40, pady=20, command=lambda: button_click(8), bg='#9EFEC8') button_9= Button(root, text="9", padx=40, pady=20, command=lambda: button_click(9), bg='#9EFEC8') button_add= Button(root, text="+", padx=39, pady=20, command=button_add, bg='#47BB7A') button_equal= Button(root, text="=", padx=96, pady=20, command=button_equal, bg='#47BB7A') button_clear= Button(root, text="Clear", padx=78, pady=20, command=button_cleartext, bg='#59F19B') button_subtract= Button(root, text="-", padx=40, pady=20, command=button_subtract, bg= '#3EB673') button_divide= Button(root, text="÷", padx=40, pady=20, command=button_divide, bg='#3EB673') button_multiply= Button(root, text="×", padx=40, pady=20, command=button_multiply, bg='#3EB673') # -------------- button_0['font']=myFont button_1['font']=myFont button_2['font']=myFont button_3['font']=myFont button_4['font']=myFont button_5['font']=myFont button_6['font']=myFont button_7['font']=myFont button_8['font']=myFont button_9['font']=myFont button_add['font']=myFont button_equal['font']=myFont button_clear['font']=myFont button_subtract['font']=myFont button_divide['font']=myFont button_multiply['font']=myFont # paste buttons on screen button_1.grid(row=3, column=0) button_2.grid(row=3, column=1) button_3.grid(row=3, column=2) button_4.grid(row=2, column=0) button_5.grid(row=2, column=1) button_6.grid(row=2, column=2) button_7.grid(row=1, column=0) button_8.grid(row=1, column=1) button_9.grid(row=1, column=2) button_0.grid(row=4, column=0) button_clear.grid(row=4, column=1, columnspan= 2) button_add.grid(row=5, column=0) button_equal.grid(row=5, column=1, columnspan=2) button_subtract.grid(row=6, column=0) button_multiply.grid(row=6, column=1) button_divide.grid(row=6, column=2) root.mainloop()
410486e24096047701de0737fdbf928814954ed1
vanstek/daily-kata
/Number sum.py
420
4.1875
4
#Sum of Numbers #Level: 7 kyu ''' Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. Note: a and b are not ordered! ''' #my answer def get_sum(a,b): return sum(x for x in range(min(a,b),max(a,b)+1)) #better answer def get_sum(a,b): return sum(range(min(a, b), max(a, b) + 1))
3d63d5b1a6fd20fea79fda10768430d1c9f12c9e
mayor-william/automatas-2-ejercicios-python
/factorial.py
1,052
4.25
4
import math """ Simple código que devuelve el factorial de un numero dado Para calcular dicho valor, hay que multiplicar el numero dado, por su antecesor mientas sea superior a 1 Ejemplo del factorial de 5 seria: 5 * 4 * 3 * 2 * 1 = 120 """ def factorial(x, n): """ Función recursiva que calcula el factorial Tiene que recibir: x=>El ultimo valor calculado n=>El numero a multiplicar """ if (n > 0): # Se va llamando a ella misma mientras el valor sea superior a 0 x = factorial(x, n - 1) x = x * n else: x = 1 return x def main(): try: numero = int(("inserta un numero ")) # Ejecutamos la función recusiva para el calculo calculo = factorial(1, numero) print "El factorial de %s es %s" % (numero, calculo) except: print("\nTiene que ser un valor numerico") if __name__ == "__main__": main()
d5d7f63933e484bf2b12b6f2dba153fc169ef089
Lis-cyber/Python-Course
/b_datatype.py
1,700
4.625
5
# Data Types # In programming, data type is an important concept. # Variables can store data of different types, and different types can do different things. # Python has the following data types built-in by default, in these categories: # Strings print("Hello World") print("""Hello World""") # Integer print(10) # Float print(30.1) # Boolean True, False # List --> Se puede cambiar [10, 20, 30, 55] # Tuples --> no se puede cambiar, inmutable (10, 20, 30, 55) # Dictionaries print(type({"name": "Ryan", "lastaname": "Ray", "surname": "Fazt"})) # None Sin tipo definido # -------------------------------------------------------------------------- # Setting the Specific Data Type # If you want to specify the data type, you can use the following constructor functions: # Example Data Type # x = str("Hello World") str # x = int(20) int # x = float(20.5) float # x = complex(1j) complex # x = list(("apple", "banana", "cherry")) list # x = tuple(("apple", "banana", "cherry")) tuple # x = range(6) range # x = dict(name="John", age=36) dict # x = set(("apple", "banana", "cherry")) set # x = frozenset(("apple", "banana", "cherry")) frozenset # x = bool(5) bool # x = bytes(5) bytes # x = bytearray(5) bytearray # x = memoryview(bytes(5)) memoryview
e67738aade64f8ff3bd3201193310905efc362ca
Shady-Data/05-Python-Programming
/studentCode/lab2c.py
796
4.09375
4
# Calculate the cost of an item with the added calculated tax amount. def taxCalculator(): # hard coded item price and sales tax cost for the moment itemPrice = 12.96 salesTax = .06 # calaculate the cost by adding the original price with the product of the original price times the sales tax totalItemCost = itemPrice + (itemPrice*salesTax) # return the calculated total cost of the item return totalItemCost # call the function and print the results print("$%.2f"% taxCalculator()) # functional lambda expression that takes 2 arugments to accomplish the same as taxCalculator funcItemCostCalc = lambda itemCost, calcTax: itemCost+(itemCost*calcTax) # call the stored lambda function with appropriate cost and salestax print("$%.2f"% funcItemCostCalc(14.99, 0.06))
afe30555dd9e6f541c2f56bbc6f5b378cee7b86c
billemil/PullRequestAssignment
/lone_sumbug.py
355
3.625
4
def lone_sum(a, b, c): if a == b and a == c and b == c: return 0 elif a >= b: return c elif a == c: return b elif b == c: return a else: return a + b + c print(lone_sum(1,1,1)) print(lone_sum(2,2,3)) print(lone_sum(1,2,1)) print(lone_sum(1,2,2)) print(lone_sum(1,2,3))
47755e2e0d26b9d6dfaed721d5b97b9f67eb61fb
rfa7/spam
/testy/spam/prog1.py
243
3.546875
4
a = 5 for i in (1, 2, 3, 4): print i print('zmiana ABCD') print('test6') print(7) print(8) print(9) # KOMENTARZ if a > 4: print('Wartosc zmiennej \'a\' jest wieksza niz 4') else: print ('Wartosc zmiennej a nie jest wieksza od 4')
1784990655c38079a5a1697cd80e6c3c4bd6e4f6
3152gs/Practice_Problems
/Codes/SecondMax.py
281
3.90625
4
'''Find second largest element of list''' a= [2,3,1,76,43,5,9] max1=a[0] max2=a[0] b=[] for i in range(0, len(a)): if not a[i]>max1: b.append(a[i]) else: max1=a[i] for i in range (0, len(b)): if b[i]>max2: max2=b[i] print (max1) print (max2)
d5551c95302ce0f1edb23c347d2ded5b1d3f6c5d
Qondor/Python-Daily-Challenge
/Daily Challenges/Daily Challenge #37 - Name Swap/name_shuffle.py
219
3.71875
4
def name_shuffler(name): """Name shuffler. Changes place of first and last name. """ name = name.split() return f'{name[-1]} {name[0]}' if __name__ == "__main__": print(name_shuffler('Emma McClane'))
7c5783b9030e4384f17e921c9ea91c69a634321a
cicily-qq/pythontraining
/file_read.py
955
3.8125
4
def file_view(file_name, line_num): if line_num.strip()==':': begin='1' end='-1' (begin,end)=line_num.split(':') if begin=='': begin='1' if end=='': end='-1' if begin=='1' and end=='-1': prompt='的全文' elif begin=='1': prompt='从开始到%s' %end elif end=='-1': prompt='%s到结束'%begin else: prompt='从%s行到%s行',%(begin,end) print('\n文件%s%s的内容如下:\n' %(file_name,prompt)) begin=int(begin)-1 end=int(end) lines=end-begin f=open(file_name) for i in range(begin): f.readline() if lines<0: print(f.read()) else: for j in range(lines): print(f.readline(),end='') f.close() file_name=input('please enter the filename:'); line_num=input('please enter rows[lke 13:21 or :21 or 21: or ]:') file_view(file_name, line_num)
cc63db79706aa6b525cc49b3871d3f9d456b718b
kongtianyi/cabbird
/leetcode/factorial_trailing_zeroes.py
434
3.515625
4
#time limit exceeded def _trailingZeroes(n): count=0 while n>0: t=n%5 if not t: count+=1 else: n=n-t n-=5 return count def trailingZeroes(n): count=0 while n: n/=5 count+=n return count if __name__=="__main__": print trailingZeroes(5) print trailingZeroes(4) print trailingZeroes(10) print trailingZeroes(1808548329)
a836b57cac8452276391fd4b7e765adffbc9485f
nopri/nopri.github.io
/monkey.py
53,762
3.53125
4
# # Simple implementation of The Monkey Programming Language # interpreter in Python # Monkey.py # (c) Noprianto <nopri.anto@icloud.com>, 2019 # Website: nopri.github.io # License: MIT # Version: 0.9 # # Compatible with Python 2 and Python 3 # Minimum Python version: 2.3 # # Based on code (in Go programming language) in book: # WRITING AN INTERPRETER IN GO # # For Monkey Programming Language interpreter in Java, please # download Monkey.java or Monkey.jar (minimum Java version: 5.0). # # How to use monkey.py: # - Standalone # - No command line argument: interactive # python monkey.py # Monkey.py 0.9 # Press ENTER to quit # >> let hello = "Hello World" # >> hello # "Hello World" # >> # - Command line argument: try to interpret as file # python monkey.py test.monkey # If exception occurred: interpret the argument as monkey code # python monkey.py "puts(1,2,3)" # 1 # 2 # 3 # null # - Library # Please see the example below # # In monkey.py, it is possible to set initial environment # when the interpreter is started. This allows integration # with external applications. For example: # code: # # try: # from StringIO import StringIO # except: # from io import StringIO # # from monkey import * # # d = {'hello': 'Hello, World', 'test': True} # e = MonkeyEnvironment.from_dictionary(d) # o = StringIO() # Monkey.evaluator_string('puts(hello); puts(test); ERROR;', e, output=o) # r = o.getvalue() # print(r) # # output: # # Hello, World # true # ERROR: identifier not found: ERROR # # import sys import os MONKEYPY_VERSION = '0.9' MONKEYPY_TITLE = 'Monkey.py %s' %(MONKEYPY_VERSION) MONKEYPY_MESSAGE = 'Press ENTER to quit' MONKEYPY_LINESEP = os.linesep class MonkeyToken: ILLEGAL = 'ILLEGAL' EOF = 'EOF' IDENT = 'IDENT' INT = 'INT' ASSIGN = '=' PLUS = '+' MINUS = '-' BANG = '!' ASTERISK = '*' SLASH = '/' LT = '<' GT = '>' COMMA = ',' SEMICOLON = ';' LPAREN = '(' RPAREN = ')' LBRACE = '{' RBRACE = '}' FUNCTION = 'FUNCTION' LET = 'LET' TRUE = 'true' FALSE = 'false' IF = 'if' ELSE = 'else' RETURN = 'return' EQ = '==' NOT_EQ = '!=' STRING = 'STRING' LBRACKET = '[' RBRACKET = ']' COLON = ':' def __init__(self, type_='', literal=''): self.type = type_ self.literal = literal class MonkeyLexer: KEYWORDS = { 'fn': MonkeyToken.FUNCTION, 'let': MonkeyToken.LET, 'true': MonkeyToken.TRUE, 'false': MonkeyToken.FALSE, 'if': MonkeyToken.IF, 'else': MonkeyToken.ELSE, 'return': MonkeyToken.RETURN, } VALID_IDENTS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' VALID_NUMBERS = '0123456789' WHITESPACES = [' ', '\t', '\r', '\n'] def __init__(self, input_='', position=0, read=0, ch=''): self.input = input_ self.position = position self.read = read self.ch = ch def read_char(self): if self.read >= len(self.input): self.ch = '' else: self.ch = self.input[self.read] self.position = self.read self.read += 1 def peek_char(self): if self.read >= len(self.input): return '' else: return self.input[self.read] def new_token(self, token, t, ch): token.type = t token.literal = ch return token def next_token(self): t = MonkeyToken() self.skip_whitespace() if self.ch == '=': if self.peek_char() == '=': ch = self.ch self.read_char() t = self.new_token(t, MonkeyToken.EQ, ch + self.ch) else: t = self.new_token(t, MonkeyToken.ASSIGN, self.ch) elif self.ch == '+': t = self.new_token(t, MonkeyToken.PLUS, self.ch) elif self.ch == '-': t = self.new_token(t, MonkeyToken.MINUS, self.ch) elif self.ch == '!': if self.peek_char() == '=': ch = self.ch self.read_char() t = self.new_token(t, MonkeyToken.NOT_EQ, ch + self.ch) else: t = self.new_token(t, MonkeyToken.BANG, self.ch) elif self.ch == '/': t = self.new_token(t, MonkeyToken.SLASH, self.ch) elif self.ch == '*': t = self.new_token(t, MonkeyToken.ASTERISK, self.ch) elif self.ch == '<': t = self.new_token(t, MonkeyToken.LT, self.ch) elif self.ch == '>': t = self.new_token(t, MonkeyToken.GT, self.ch) elif self.ch == ';': t = self.new_token(t, MonkeyToken.SEMICOLON, self.ch) elif self.ch == '(': t = self.new_token(t, MonkeyToken.LPAREN, self.ch) elif self.ch == ')': t = self.new_token(t, MonkeyToken.RPAREN, self.ch) elif self.ch == ',': t = self.new_token(t, MonkeyToken.COMMA, self.ch) elif self.ch == '+': t = self.new_token(t, MonkeyToken.PLUS, self.ch) elif self.ch == '{': t = self.new_token(t, MonkeyToken.LBRACE, self.ch) elif self.ch == '}': t = self.new_token(t, MonkeyToken.RBRACE, self.ch) elif self.ch == '': t.literal = '' t.type = MonkeyToken.EOF elif self.ch == '"': t.literal = self.read_string() t.type = MonkeyToken.STRING elif self.ch == '[': t = self.new_token(t, MonkeyToken.LBRACKET, self.ch) elif self.ch == ']': t = self.new_token(t, MonkeyToken.RBRACKET, self.ch) elif self.ch == ':': t = self.new_token(t, MonkeyToken.COLON, self.ch) else: if self.is_letter(self.ch): t.literal = self.read_ident() t.type = self.lookup_ident(t.literal) return t elif self.is_digit(self.ch): t.literal = self.read_number() t.type = MonkeyToken.INT return t else: t = self.new_token(t, MonkeyToken.ILLEGAL, self.ch) self.read_char() return t def read_ident(self): pos = self.position while True: if not self.ch: break test = self.is_letter(self.ch) if not test: break self.read_char() ret = self.input[pos:self.position] return ret def read_number(self): pos = self.position while True: if not self.ch: break test = self.is_digit(self.ch) if not test: break self.read_char() ret = self.input[pos:self.position] return ret def read_string(self): pos = self.position + 1 while True: self.read_char() if self.ch == '"' or self.ch == '': break # ret = self.input[pos:self.position] return ret def lookup_ident(self, s): ret = MonkeyLexer.KEYWORDS.get(s) if ret: return ret return MonkeyToken.IDENT def is_letter(self, ch): return ch in MonkeyLexer.VALID_IDENTS def is_digit(self, ch): return ch in MonkeyLexer.VALID_NUMBERS def skip_whitespace(self): while (self.ch in MonkeyLexer.WHITESPACES): self.read_char() def new(s): l = MonkeyLexer() l.input = s l.read_char() return l new = staticmethod(new) class MonkeyNode: def __init__(self): pass def token_literal(self): return '' def string(self): return '' class MonkeyStatement(MonkeyNode): def __init__(self): pass def statement_node(self): pass class MonkeyExpression(MonkeyNode): def __init__(self): pass def expression_node(self): pass class MonkeyIdentifier(MonkeyExpression): def __init__(self, value=''): self.token = MonkeyToken() self.value = value def token_literal(self): return self.token.literal def string(self): return self.value class MonkeyLetStatement(MonkeyStatement): def __init__(self): self.token = MonkeyToken() self.name = MonkeyIdentifier() self.value = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): ret = self.token_literal() + ' ' ret += self.name.string() ret += ' = ' # if self.value: ret += self.value.string() # ret += ';' return ret class MonkeyReturnStatement(MonkeyStatement): def __init__(self): self.token = MonkeyToken() self.return_value = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): ret = self.token_literal() + ' ' if self.return_value: ret += self.return_value.string() # ret += ';' return ret class MonkeyExpressionStatement(MonkeyStatement): def __init__(self): self.token = MonkeyToken() self.expression = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): if self.expression: return self.expression.string() # return '' class MonkeyBlockStatement(MonkeyStatement): def __init__(self): self.token = MonkeyToken() self.statements = [] def is_empty(self): return len(self.statements) == 0 def token_literal(self): return self.token.literal def string(self): ret = '%s{%s' %(MONKEYPY_LINESEP, MONKEYPY_LINESEP) # for s in self.statements: ret += '%s;%s' %(s.string(), MONKEYPY_LINESEP) # ret += '}%s' %(MONKEYPY_LINESEP) return ret class MonkeyIntegerLiteral(MonkeyExpression): def __init__(self, value=None): self.token = MonkeyToken() self.value = value def token_literal(self): return self.token.literal def string(self): return self.token.literal class MonkeyStringLiteral(MonkeyExpression): def __init__(self, value=''): self.token = MonkeyToken() self.value = value def token_literal(self): return self.token.literal def string(self): return self.token.literal class MonkeyFunctionLiteral(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.parameters = [] self.body = MonkeyBlockStatement() def token_literal(self): return self.token.literal def string(self): params = [] for p in self.parameters: params.append(p.string()) # ret = self.token_literal() ret += '(' ret += ', '.join(params) ret += ')' ret += self.body.string() # return ret class MonkeyCallExpression(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.function = MonkeyExpression() self.arguments = [] def token_literal(self): return self.token.literal def string(self): args = [] for a in self.arguments: args.append(a.string()) # ret = self.function.string() ret += '(' ret += ', '.join(args) ret += ')' # return ret class MonkeyBoolean(MonkeyExpression): def __init__(self, value=None): self.token = MonkeyToken() self.value = value def token_literal(self): return self.token.literal def string(self): return self.token.literal class MonkeyPrefixExpression(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.operator = '' self.right = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): ret = '(' ret += self.operator ret += self.right.string() ret += ')' # return ret class MonkeyInfixExpression(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.left = MonkeyExpression() self.operator = '' self.right = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): ret = '(' ret += self.left.string() ret += ' ' + self.operator + ' ' ret += self.right.string() ret += ')' # return ret class MonkeyIfExpression(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.condition = MonkeyExpression() self.consequence = MonkeyBlockStatement() self.alternative = MonkeyBlockStatement() def token_literal(self): return self.token.literal def string(self): ret = 'if' ret += self.condition.string() ret += ' ' ret += self.consequence.string() # if not self.alternative.is_empty(): ret += ' else ' ret += self.alternative.string() # return ret class MonkeyArrayLiteral(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.elements = [] def token_literal(self): return self.token.literal def string(self): elements = [] for e in self.elements: elements.append(e.string()) # ret = '[' ret += ', '.join(elements) ret += ']' # return ret class MonkeyIndexExpression(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.left = MonkeyExpression() self.index = MonkeyExpression() def token_literal(self): return self.token.literal def string(self): ret = '(' ret += self.left.string() ret += '[' ret += self.index.string() ret += '])' # return ret class MonkeyHashLiteral(MonkeyExpression): def __init__(self): self.token = MonkeyToken() self.pairs = {} def token_literal(self): return self.token.literal def string(self): pairs = [] for k in self.pairs.keys(): v = self.pairs.get(k) pairs.append('%s:%s' %(k.string(), v.string())) # ret = '{' ret += ', '.join(pairs) ret += '}' # return ret class MonkeyParser: LOWEST = 1 EQUALS = 2 LESSGREATER = 3 SUM = 4 PRODUCT = 5 PREFIX = 6 CALL = 7 INDEX = 8 PRECEDENCES = { MonkeyToken.LPAREN: CALL, MonkeyToken.EQ: EQUALS, MonkeyToken.NOT_EQ: EQUALS, MonkeyToken.LT: LESSGREATER, MonkeyToken.GT: LESSGREATER, MonkeyToken.PLUS: SUM, MonkeyToken.MINUS: SUM, MonkeyToken.SLASH: PRODUCT, MonkeyToken.ASTERISK: PRODUCT, MonkeyToken.LBRACKET: INDEX, } def __init__(self): self.lexer = None self.cur_token = None self.peek_token = None self.errors = [] self.prefix_parse_fns = {} self.infix_parse_fns = {} # self.register_prefix(MonkeyToken.IDENT, self.parse_identifier) self.register_prefix(MonkeyToken.INT, self.parse_integer_literal) self.register_prefix(MonkeyToken.BANG, self.parse_prefix_expression) self.register_prefix(MonkeyToken.MINUS, self.parse_prefix_expression) self.register_prefix(MonkeyToken.TRUE, self.parse_boolean) self.register_prefix(MonkeyToken.FALSE, self.parse_boolean) self.register_prefix(MonkeyToken.LPAREN, self.parse_grouped_expression) self.register_prefix(MonkeyToken.IF, self.parse_if_expression) self.register_prefix(MonkeyToken.FUNCTION, self.parse_function_literal) self.register_prefix(MonkeyToken.STRING, self.parse_string_literal) self.register_prefix(MonkeyToken.LBRACKET, self.parse_array_literal) self.register_prefix(MonkeyToken.LBRACE, self.parse_hash_literal) # self.register_infix(MonkeyToken.PLUS, self.parse_infix_expression) self.register_infix(MonkeyToken.MINUS, self.parse_infix_expression) self.register_infix(MonkeyToken.SLASH, self.parse_infix_expression) self.register_infix(MonkeyToken.ASTERISK, self.parse_infix_expression) self.register_infix(MonkeyToken.EQ, self.parse_infix_expression) self.register_infix(MonkeyToken.NOT_EQ, self.parse_infix_expression) self.register_infix(MonkeyToken.LT, self.parse_infix_expression) self.register_infix(MonkeyToken.GT, self.parse_infix_expression) self.register_infix(MonkeyToken.LPAREN, self.parse_call_expression) self.register_infix(MonkeyToken.LBRACKET, self.parse_index_expression) def next_token(self): self.cur_token = self.peek_token self.peek_token = self.lexer.next_token() def parse_program(self): program = MonkeyProgram() while self.cur_token.type != MonkeyToken.EOF: s = self.parse_statement() if s: program.statements.append(s) self.next_token() return program def parse_statement(self): if self.cur_token.type == MonkeyToken.LET: return self.parse_let_statement() elif self.cur_token.type == MonkeyToken.RETURN: return self.parse_return_statement() else: return self.parse_expression_statement() return None def parse_let_statement(self): s = MonkeyLetStatement() s.token = self.cur_token if not self.expect_peek(MonkeyToken.IDENT): return None # s.name = MonkeyIdentifier() s.name.token = self.cur_token s.name.value = self.cur_token.literal if not self.expect_peek(MonkeyToken.ASSIGN): return None # self.next_token() s.value = self.parse_expression(self.LOWEST) if self.peek_token_is(MonkeyToken.SEMICOLON): self.next_token() # return s def parse_return_statement(self): s = MonkeyReturnStatement() s.token = self.cur_token self.next_token() s.return_value = self.parse_expression(self.LOWEST) if self.peek_token_is(MonkeyToken.SEMICOLON): self.next_token() # return s def parse_expression_statement(self): s = MonkeyExpressionStatement() s.token = self.cur_token s.expression = self.parse_expression(self.LOWEST) # if self.peek_token_is(MonkeyToken.SEMICOLON): self.next_token() # return s def parse_block_statement(self): block = MonkeyBlockStatement() block.token = self.cur_token # self.next_token() while not self.cur_token_is(MonkeyToken.RBRACE) and \ not self.cur_token_is(MonkeyToken.EOF): s = self.parse_statement() if s is not None: block.statements.append(s) self.next_token() # return block def parse_expression(self, precedence): prefix = self.prefix_parse_fns.get(self.cur_token.type) if prefix is None: self.no_prefix_parse_fn_error(self.cur_token.type) return None left_exp = prefix() # while not self.peek_token_is(MonkeyToken.SEMICOLON) and \ precedence < self.peek_precedence(): infix = self.infix_parse_fns.get(self.peek_token.type) if infix is None: return left_exp # self.next_token() left_exp = infix(left_exp) # return left_exp def parse_identifier(self): ret = MonkeyIdentifier() ret.token = self.cur_token ret.value = self.cur_token.literal return ret def parse_integer_literal(self): lit = MonkeyIntegerLiteral() lit.token = self.cur_token try: test = int(self.cur_token.literal) except: msg = 'could not parse %s as integer' %(self.cur_token.literal) self.errors.append(msg) return None # lit.value = int(self.cur_token.literal) return lit def parse_string_literal(self): lit = MonkeyStringLiteral() lit.token = self.cur_token lit.value = self.cur_token.literal return lit def parse_array_literal(self): array = MonkeyArrayLiteral() array.token = self.cur_token array.elements = self.parse_expression_list(MonkeyToken.RBRACKET) return array def parse_hash_literal(self): h = MonkeyHashLiteral() h.token = self.cur_token # while not self.peek_token_is(MonkeyToken.RBRACE): self.next_token() key = self.parse_expression(self.LOWEST) # if not self.expect_peek(MonkeyToken.COLON): return None # self.next_token() value = self.parse_expression(self.LOWEST) # h.pairs[key] = value # if not self.peek_token_is(MonkeyToken.RBRACE) and \ not self.expect_peek(MonkeyToken.COMMA): return None # if not self.expect_peek(MonkeyToken.RBRACE): return None # return h def parse_boolean(self): ret = MonkeyBoolean() ret.token = self.cur_token ret.value = self.cur_token_is(MonkeyToken.TRUE) return ret def parse_prefix_expression(self): e = MonkeyPrefixExpression() e.token = self.cur_token e.operator = self.cur_token.literal # self.next_token() e.right = self.parse_expression(self.PREFIX) # return e def parse_infix_expression(self, left): e = MonkeyInfixExpression() e.token = self.cur_token e.operator = self.cur_token.literal e.left = left # precedence = self.cur_precedence() self.next_token() e.right = self.parse_expression(precedence) # return e def parse_grouped_expression(self): self.next_token() e = self.parse_expression(self.LOWEST) # if not self.expect_peek(MonkeyToken.RPAREN): return None # return e def parse_if_expression(self): e = MonkeyIfExpression() e.token = self.cur_token # if not self.expect_peek(MonkeyToken.LPAREN): return None # self.next_token() e.condition = self.parse_expression(self.LOWEST) # if not self.expect_peek(MonkeyToken.RPAREN): return None # if not self.expect_peek(MonkeyToken.LBRACE): return None # e.consequence = self.parse_block_statement() # if self.peek_token_is(MonkeyToken.ELSE): self.next_token() # if not self.expect_peek(MonkeyToken.LBRACE): return None e.alternative = self.parse_block_statement() # return e def parse_function_literal(self): lit = MonkeyFunctionLiteral() lit.token = self.cur_token # if not self.expect_peek(MonkeyToken.LPAREN): return None # lit.parameters = self.parse_function_parameters() # if not self.expect_peek(MonkeyToken.LBRACE): return None # lit.body = self.parse_block_statement() # return lit def parse_function_parameters(self): identifiers = [] # if self.peek_token_is(MonkeyToken.RPAREN): self.next_token() return identifiers # self.next_token() ident = MonkeyIdentifier() ident.token = self.cur_token ident.value = self.cur_token.literal identifiers.append(ident) # while self.peek_token_is(MonkeyToken.COMMA): self.next_token() self.next_token() ident = MonkeyIdentifier() ident.token = self.cur_token ident.value = self.cur_token.literal identifiers.append(ident) # if not self.expect_peek(MonkeyToken.RPAREN): return None # return identifiers def parse_call_expression(self, function): exp = MonkeyCallExpression() exp.token = self.cur_token exp.function = function exp.arguments = self.parse_expression_list(MonkeyToken.RPAREN) return exp def parse_expression_list(self, end): ret = [] # if self.peek_token_is(end): self.next_token() return ret # self.next_token() ret.append(self.parse_expression(self.LOWEST)) # while self.peek_token_is(MonkeyToken.COMMA): self.next_token() self.next_token() ret.append(self.parse_expression(self.LOWEST)) # if not self.expect_peek(end): return None # return ret def parse_index_expression(self, left): exp = MonkeyIndexExpression() exp.token = self.cur_token exp.left = left # self.next_token() exp.index = self.parse_expression(self.LOWEST) # if not self.expect_peek(MonkeyToken.RBRACKET): return None # return exp def cur_token_is(self, t): return self.cur_token.type == t def peek_token_is(self, t): return self.peek_token.type == t def expect_peek(self, t): if self.peek_token_is(t): self.next_token() return True else: self.peek_error(t) return False def peek_error(self, t): m = 'expected next token to be %s, got %s instead' %( t, self.peek_token.type ) self.errors.append(m) def register_prefix(self, token_type, fn): self.prefix_parse_fns[token_type] = fn def register_infix(self, token_type, fn): self.infix_parse_fns[token_type] = fn def no_prefix_parse_fn_error(self, token_type): m = 'no prefix parse function for %s found' %(token_type) self.errors.append(m) def peek_precedence(self): p = self.PRECEDENCES.get(self.peek_token.type) if p: return p # return self.LOWEST def cur_precedence(self): p = self.PRECEDENCES.get(self.cur_token.type) if p: return p # return self.LOWEST def new(l): p = MonkeyParser() p.lexer = l p.next_token() p.next_token() return p new = staticmethod(new) class MonkeyProgram(MonkeyNode): def __init__(self): self.statements = [] def token_literal(self): if len(self.statements) > 0: return self.statements[0].token_literal() else: return '' def string(self): ret = '' for s in self.statements: ret += s.string() return ret class MonkeyHashable: def hash_key(self): pass class MonkeyObject: INTEGER_OBJ = 'INTEGER' BOOLEAN_OBJ = 'BOOLEAN' NULL_OBJ = 'NULL' RETURN_VALUE_OBJ = 'RETURN_VALUE' ERROR_OBJ = 'ERROR' FUNCTION_OBJ = 'FUNCTION' STRING_OBJ = 'STRING' BUILTIN_OBJ = 'BUILTIN' ARRAY_OBJ = 'ARRAY' HASH_OBJ = 'HASH' def __init__(self, value=None, type_=''): self.value = value self.object_type = type_ def type(self): return self.object_type def inspect(self): return '' def inspect_value(self): return self.inspect() class MonkeyObjectInteger(MonkeyObject, MonkeyHashable): def type(self): return self.INTEGER_OBJ def inspect(self): return '%s' %(self.value) def hash_key(self): o = MonkeyHashKey(type_=self.type(), value=self.value) return o class MonkeyObjectString(MonkeyObject, MonkeyHashable): def type(self): return self.STRING_OBJ def inspect(self): return '"%s"' %(self.value) def hash_key(self): o = MonkeyHashKey(type_=self.type(), value=hash(self.value)) return o def inspect_value(self): return self.value class MonkeyObjectBoolean(MonkeyObject, MonkeyHashable): def type(self): return self.BOOLEAN_OBJ def inspect(self): ret = '%s' %(self.value) ret = ret.lower() return ret def hash_key(self): o = MonkeyHashKey(type_=self.type()) if self.value: o.value = 1 else: o.value = 0 return o class MonkeyObjectNull(MonkeyObject): def type(self): return self.NULL_OBJ def inspect(self): return 'null' class MonkeyObjectReturnValue(MonkeyObject): def type(self): return self.RETURN_VALUE_OBJ def inspect(self): return self.value.inspect() class MonkeyObjectError(MonkeyObject): def __init__(self, value=None, message=''): self.message = message self.value = value def type(self): return self.ERROR_OBJ def inspect(self): return 'ERROR: %s' %(self.message) class MonkeyObjectFunction(MonkeyObject): def __init__(self): self.parameters = [] self.body = MonkeyBlockStatement() self.env = MonkeyEnvironment.new() def type(self): return self.FUNCTION_OBJ def inspect(self): params = [] for p in self.parameters: params.append(p.string()) # ret = 'fn' ret += '(' ret += ', '.join(params) ret += ')' ret += self.body.string() # return ret class MonkeyObjectBuiltin(MonkeyObject): def __init__(self, fn=None, value=None): self.fn = fn self.value = value def type(self): return self.BUILTIN_OBJ def inspect(self): return 'builtin function' class MonkeyObjectArray(MonkeyObject): def __init__(self): self.elements = [] def type(self): return self.ARRAY_OBJ def inspect(self): elements = [] for e in self.elements: elements.append(e.inspect()) # ret = '[' ret += ', '.join(elements) ret += ']' # return ret class MonkeyObjectHash(MonkeyObject): def __init__(self): self.pairs = {} def type(self): return self.HASH_OBJ def inspect(self): pairs = [] for k in self.pairs.keys(): v = self.pairs.get(k) pair = '%s: %s' %(v.key.inspect(), v.value.inspect()) pairs.append(pair) # ret = '{' ret += ', '.join(pairs) ret += '}' # return ret class MonkeyHashKey: def __init__(self, type_='', value=None): self.type = type_ self.value = value def __eq__(self, other): if isinstance(other, MonkeyHashKey): if other.type == self.type and other.value == self.value: return True return False def __ne__(self, other): if isinstance(other, MonkeyHashKey): if other.type == self.type and other.value == self.value: return False return True def __hash__(self): h = '%s-%s' %(self.type, self.value) return hash(h) class MonkeyHashPair: def __init__(self): self.key = MonkeyObject() self.value = MonkeyObject() class MonkeyEnvironment: def __init__(self, outer=None): self.store = {} self.outer = outer def get(self, name): obj = self.store.get(name) if obj is None and self.outer is not None: obj = self.outer.get(name) return obj def set(self, name, value): self.store[name] = value return value def debug(self): for k in self.store.keys(): v = self.store.get(k) if v is not None: Monkey.output('%s: %s' %( k, v.inspect(), ) ) def new(): e = MonkeyEnvironment() return e new = staticmethod(new) def new_enclosed(outer): e = MonkeyEnvironment() e.outer = outer return e new_enclosed = staticmethod(new_enclosed) def from_dictionary(d): e = MonkeyEnvironment() if not isinstance(d, dict): return e # for k in d.keys(): v = d.get(k) key = None value = None if type(k) == type(''): key = k else: key = str(k) # if type(v) == type(''): value = MonkeyObjectString(value=v) elif type(v) == type(1): value = MonkeyObjectInteger(value=v) elif type(v) == type(True): value = MonkeyObjectBoolean(value=v) else: value = MonkeyObjectString(value=str(v)) # if key is not None and value is not None: e.set(key, value) return e from_dictionary = staticmethod(from_dictionary) class MonkeyBuiltinFunctions: def len(evaluator, args): if len(args) != 1: return evaluator.new_error( 'wrong number of arguments, got=%s, want=1' %( len(args), ) ) # a = args[0] if isinstance(a, MonkeyObjectString): o = MonkeyObjectInteger() o.value = len(a.value) return o elif isinstance(a, MonkeyObjectArray): o = MonkeyObjectInteger() o.value = len(a.elements) return o else: return evaluator.new_error( 'argument to "len" not supported, got %s' %( a.type() ) ) len = staticmethod(len) def first(evaluator, args): if len(args) != 1: return evaluator.new_error( 'wrong number of arguments, got=%s, want=1' %( len(args), ) ) # a = args[0] if not isinstance(a, MonkeyObjectArray): return evaluator.new_error( 'argument to "first" must be ARRAY, got %s' %( a.type() ) ) # if len(a.elements) > 0: return a.elements[0] # return evaluator.NULL first = staticmethod(first) def last(evaluator, args): if len(args) != 1: return evaluator.new_error( 'wrong number of arguments, got=%s, want=1' %( len(args), ) ) # a = args[0] if not isinstance(a, MonkeyObjectArray): return evaluator.new_error( 'argument to "last" must be ARRAY, got %s' %( a.type() ) ) # length = len(a.elements) if length > 0: return a.elements[length-1] # return evaluator.NULL last = staticmethod(last) def rest(evaluator, args): if len(args) != 1: return evaluator.new_error( 'wrong number of arguments, got=%s, want=1' %( len(args), ) ) # a = args[0] if not isinstance(a, MonkeyObjectArray): return evaluator.new_error( 'argument to "rest" must be ARRAY, got %s' %( a.type() ) ) # length = len(a.elements) if length > 0: o = MonkeyObjectArray() o.elements = a.elements[1:] return o # return evaluator.NULL rest = staticmethod(rest) def push(evaluator, args): if len(args) != 2: return evaluator.new_error( 'wrong number of arguments, got=%s, want=2' %( len(args), ) ) # a = args[0] if not isinstance(a, MonkeyObjectArray): return evaluator.new_error( 'argument to "push" must be ARRAY, got %s' %( a.type() ) ) # o = MonkeyObjectArray() o.elements = a.elements[:] o.elements.append(args[1]) return o push = staticmethod(push) def puts(evaluator, args): for a in args: Monkey.output(a.inspect_value(), evaluator.output) # return evaluator.NULL puts = staticmethod(puts) class MonkeyBuiltins: BUILTINS = { 'len': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.len), 'first': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.first), 'last': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.last), 'rest': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.rest), 'push': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.push), 'puts': MonkeyObjectBuiltin(MonkeyBuiltinFunctions.puts), } def get(f): return MonkeyBuiltins.BUILTINS.get(f) get = staticmethod(get) class MonkeyEvaluator: NULL = MonkeyObjectNull() TRUE = MonkeyObjectBoolean(True) FALSE = MonkeyObjectBoolean(False) def __init__(self): self.output = sys.stdout def eval(self, node, env): if isinstance(node, MonkeyProgram): return self.eval_program(node, env) elif isinstance(node, MonkeyExpressionStatement): return self.eval(node.expression, env) elif isinstance(node, MonkeyIntegerLiteral): o = MonkeyObjectInteger() o.value = node.value return o elif isinstance(node, MonkeyBoolean): return self.get_boolean(node.value) elif isinstance(node, MonkeyPrefixExpression): right = self.eval(node.right, env) if self.is_error(right): return right # return self.eval_prefix_expression(node.operator, right) elif isinstance(node, MonkeyInfixExpression): left = self.eval(node.left, env) if self.is_error(left): return left # right = self.eval(node.right, env) if self.is_error(right): return right # return self.eval_infix_expression(node.operator, left, right) elif isinstance(node, MonkeyBlockStatement): return self.eval_block_statement(node, env) elif isinstance(node, MonkeyIfExpression): return self.eval_if_expression(node, env) elif isinstance(node, MonkeyReturnStatement): val = self.eval(node.return_value, env) if self.is_error(val): return val # o = MonkeyObjectReturnValue() o.value = val return o elif isinstance(node, MonkeyLetStatement): val = self.eval(node.value, env) if self.is_error(val): return val # env.set(node.name.value, val) elif isinstance(node, MonkeyIdentifier): return self.eval_identifier(node, env) elif isinstance(node, MonkeyFunctionLiteral): params = node.parameters body = node.body # o = MonkeyObjectFunction() o.parameters = params o.body = body o.env = env return o elif isinstance(node, MonkeyCallExpression): function = self.eval(node.function, env) if self.is_error(function): return function # args = self.eval_expressions(node.arguments, env) if len(args) == 1 and self.is_error(args[0]): return args[0] # return self.apply_function(function, args) elif isinstance(node, MonkeyStringLiteral): o = MonkeyObjectString() o.value = node.value return o elif isinstance(node, MonkeyArrayLiteral): elements = self.eval_expressions(node.elements, env) if len(elements) == 1 and self.is_error(elements[0]): return elements[0] # o = MonkeyObjectArray() o.elements = elements return o elif isinstance(node, MonkeyIndexExpression): left = self.eval(node.left, env) if self.is_error(left): return left # index = self.eval(node.index, env) if self.is_error(index): return index # return self.eval_index_expression(left, index) elif isinstance(node, MonkeyHashLiteral): return self.eval_hash_literal(node, env) # return None def eval_program(self, program, env): ret = MonkeyObject() for s in program.statements: ret = self.eval(s, env) # if isinstance(ret, MonkeyObjectReturnValue): return ret.value elif isinstance(ret, MonkeyObjectError): return ret # return ret def eval_block_statement(self, block, env): ret = MonkeyObject() for s in block.statements: ret = self.eval(s, env) # if ret: rt = ret.type() if rt == MonkeyObject.RETURN_VALUE_OBJ or \ rt == MonkeyObject.ERROR_OBJ: return ret # return ret def get_boolean(self, val): if val: return self.TRUE # return self.FALSE def eval_prefix_expression(self, operator, right): if operator == '!': return self.eval_bang_operator_expression(right) elif operator == '-': return self.eval_minus_prefix_operator_expression(right) return self.new_error('unknown operator: %s%s' %( operator, right.type())) def eval_infix_expression(self, operator, left, right): if left.type() == MonkeyObject.INTEGER_OBJ and \ right.type() == MonkeyObject.INTEGER_OBJ: return self.eval_integer_infix_expression(operator, left, right) elif left.type() == MonkeyObject.STRING_OBJ and \ right.type() == MonkeyObject.STRING_OBJ: return self.eval_string_infix_expression(operator, left, right) elif operator == '==': return self.get_boolean(left == right) elif operator == '!=': return self.get_boolean(left != right) elif left.type() != right.type(): return self.new_error('type mismatch: %s %s %s' %( left.type(), operator, right.type())) return self.new_error('unknown operator: %s %s %s' %( left.type(), operator, right.type())) def eval_integer_infix_expression(self, operator, left, right): left_val = left.value right_val = right.value # o = MonkeyObjectInteger() if operator == '+': o.value = left_val + right_val return o elif operator == '-': o.value = left_val - right_val return o elif operator == '*': o.value = left_val * right_val return o elif operator == '/': try: o.value = left_val // right_val return o except: return self.NULL elif operator == '<': return self.get_boolean(left_val < right_val) elif operator == '>': return self.get_boolean(left_val > right_val) elif operator == '==': return self.get_boolean(left_val == right_val) elif operator == '!=': return self.get_boolean(left_val != right_val) return self.new_error('unknown operator: %s %s %s' %( left.type(), operator, right.type())) def eval_string_infix_expression(self, operator, left, right): left_val = left.value right_val = right.value # o = MonkeyObjectString() if operator != '+': return self.new_error('unknown operator: %s %s %s' %( left.type(), operator, right.type())) # o.value = left_val + right_val return o def eval_bang_operator_expression(self, right): if right == self.TRUE: return self.FALSE elif right == self.FALSE: return self.TRUE elif right == self.NULL: return self.TRUE return self.FALSE def eval_minus_prefix_operator_expression(self, right): if right.type() != MonkeyObject.INTEGER_OBJ: return self.new_error('unknown operator: -%s' %(right.type())) # val = right.value ret = MonkeyObjectInteger() ret.value = -val # return ret def eval_if_expression(self, expression, env): condition = self.eval(expression.condition, env) if self.is_error(condition): return condition # if self.is_truthy(condition): return self.eval(expression.consequence, env) elif not expression.alternative.is_empty(): return self.eval(expression.alternative, env) else: return self.NULL def eval_identifier(self, node, env): val = env.get(node.value) if val: return val # builtin = MonkeyBuiltins.get(node.value) if builtin: return builtin # return self.new_error('identifier not found: %s' %(node.value)) def eval_expressions(self, exp, env): result = [] # for e in exp: evaluated = self.eval(e, env) if self.is_error(evaluated): result.append(evaluated) return result result.append(evaluated) # return result def eval_index_expression(self, left, index): if left.type() == MonkeyObject.ARRAY_OBJ and \ index.type() == MonkeyObject.INTEGER_OBJ: return self.eval_array_index_expression(left, index) elif left.type() == MonkeyObject.HASH_OBJ: return self.eval_hash_index_expression(left, index) return self.new_error('index operator not supported: %s' %( left.type())) def eval_array_index_expression(self, array, index): idx = index.value max_index = len(array.elements) - 1 # if idx < 0 or idx > max_index: return MonkeyEvaluator.NULL # return array.elements[idx] def eval_hash_literal(self, node, env): pairs = {} # for k in node.pairs.keys(): key = self.eval(k, env) if self.is_error(key): return key # if not isinstance(key, MonkeyHashable): return self.new_error('unusable as hash key: %s' %( key.type() ) ) # v = node.pairs.get(k) val = self.eval(v, env) if self.is_error(val): return val # hashed = key.hash_key() p = MonkeyHashPair() p.key = key p.value = val pairs[hashed] = p # o = MonkeyObjectHash() o.pairs = pairs # return o def eval_hash_index_expression(self, hashtable, index): if not isinstance(index, MonkeyHashable): return self.new_error('unusable as hash key: %s' %( index.type() ) ) # pair = hashtable.pairs.get(index.hash_key()) if pair is None: return self.NULL # return pair.value def apply_function(self, fn, args): if isinstance(fn, MonkeyObjectFunction): extended_env = self.extend_function_env(fn, args) evaluated = self.eval(fn.body, extended_env) return self.unwrap_return_value(evaluated) elif isinstance(fn, MonkeyObjectBuiltin): return fn.fn(self, args) # return self.new_error('not a function: %s' %(fn.type())) def extend_function_env(self, fn, args): env = MonkeyEnvironment.new_enclosed(fn.env) for p in range(len(fn.parameters)): param = fn.parameters[p] env.set(param.value, args[p]) # return env def unwrap_return_value(self, obj): if isinstance(obj, MonkeyObjectReturnValue): return obj.value # return obj def is_truthy(self, obj): if obj == self.NULL: return False elif obj == self.TRUE: return True elif obj == self.FALSE: return False else: return True def new_error(self, message): ret = MonkeyObjectError() ret.message = message return ret def is_error(self, obj): if obj: return obj.type() == MonkeyObject.ERROR_OBJ # return False def new(): e = MonkeyEvaluator() return e new = staticmethod(new) class Monkey: PROMPT = '>> ' def input(s): try: return raw_input(s) except: return input(s) input = staticmethod(input) def output(s, f=sys.stdout): try: f.write('%s%s' %(s, MONKEYPY_LINESEP)) except: pass output = staticmethod(output) def lexer(): Monkey.output(MONKEYPY_TITLE) Monkey.output(MONKEYPY_MESSAGE) while True: inp = Monkey.input(Monkey.PROMPT).strip() if not inp: break l = MonkeyLexer.new(inp) while True: t = l.next_token() if t.type == MonkeyToken.EOF: break Monkey.output( 'Type: %s, Literal: %s' %(t.type, t.literal)) lexer = staticmethod(lexer) def parser(): Monkey.output(MONKEYPY_TITLE) Monkey.output(MONKEYPY_MESSAGE) while True: inp = Monkey.input(Monkey.PROMPT).strip() if not inp: break l = MonkeyLexer.new(inp) p = MonkeyParser.new(l) program = p.parse_program() # if p.errors: Monkey.print_parse_errors(p.errors) continue # Monkey.output(program.string()) parser = staticmethod(parser) def print_parse_errors(e, output=sys.stdout): for i in e: Monkey.output('PARSER ERROR: %s' %(i), output) print_parse_errors = staticmethod(print_parse_errors) def evaluator(): Monkey.output(MONKEYPY_TITLE) Monkey.output(MONKEYPY_MESSAGE) env = MonkeyEnvironment.new() while True: inp = Monkey.input(Monkey.PROMPT).strip() if not inp: break l = MonkeyLexer.new(inp) p = MonkeyParser.new(l) program = p.parse_program() # if p.errors: Monkey.print_parse_errors(p.errors) continue # evaluator = MonkeyEvaluator.new() evaluated = evaluator.eval(program, env) if evaluated: Monkey.output(evaluated.inspect()) evaluator = staticmethod(evaluator) def evaluator_string(s, environ=None, output=sys.stdout): if environ is None or not isinstance(environ, MonkeyEnvironment): env = MonkeyEnvironment.new() else: env = environ l = MonkeyLexer.new(s) p = MonkeyParser.new(l) program = p.parse_program() # if p.errors: Monkey.print_parse_errors(p.errors, output) return # evaluator = MonkeyEvaluator.new() evaluator.output = output evaluated = evaluator.eval(program, env) if evaluated: Monkey.output(evaluated.inspect(), output) evaluator_string = staticmethod(evaluator_string) def main(argv): if len(argv) < 2: Monkey.evaluator() else: t = argv[1] s = t if os.path.exists(t): try: s = open(t).read() except: pass # if s: Monkey.evaluator_string(s) main = staticmethod(main) if __name__ == '__main__': Monkey.main(sys.argv)
6fdfc96e56a72189f893e34a8c0dd9eba5cdee98
Alucarxd/basico_python
/concatenaciones.py
685
4.28125
4
print('Hola ' + 'Mundo') print('Mi nombre es {} {}'.format('Gabriel', 'Garcia')) print('Mi nombre es {0} {1} bienvenido al curso de {2}'.format('Gabriel', 'Garcia', 'Python')) print('Mi nombre es {1} {0} bienvenido al curso de {2}'.format('Gabriel', 'Garcia', 'Python')) # Aqui estoy dando preferencia a la secuencia (en este caso esta variando) print("Mi nombre es {} {} bienvenido al curso de {}".format(input('Ingrese su nombre: '), input('Ingrese su apellido: '), input("Nombre del curso?: "))) # inplementando input a la funcion .format # print('Mi nombre es {0} {1} bienvenido al curso de {2}'.format(input('Ingrese su nombre: '),input('Ingrese su apellido: '), 'Python'))
8f88a897bd026024477371ee049ea213b77a9eab
amyvrm/oss_ass4_grp5
/src/division.py
373
4.09375
4
# division of two number def division(num1, num2): try: return num1/num2 except Exception as e: return e if __name__ == "__main__": print("Please enter two number for division") num1 = int(input("Enter number")) num2 = int(input("Enter number")) print("Division of two number is: {}".format(division(num1, num2)))
74ad34315a2ad956f8b522717b27a186a5937697
Pranavpradee/luminarpython
/venv/exception_handling/OOP/Bank_Class.py
921
3.625
4
class Bank: bankname="SBI" def accreate(self,acno,name): self.acno=acno self.name=name self.minbal=5000 self.balance=self.minbal def deposit(self,amt): self.amt=amt self.balance+=self.amt print(bankname,"your account has credited with amount",self.amt) print("your current balance=",self.balance) def withdraw(self,amnt): self.amnt=amnt if self.amnt>self.balance: print("insufficient balance") else: print # # # print(Bank.balance+self.deposit) # print(Bank.balance-self.withdrawal) # ban= # # # class Person: # def __init__(self,name,age,address): # self.name=name # self.age=age # self.address=address # def printval(self): # print(self.name,self.age,self.address) # obj=Person("pranav",22,"aniyath house,kizhur") # obj.printval()
acc8e4422b4c62eb6d91fea9059c336b96bfbd34
souravs17031999/100dayscodingchallenge
/strings/check_valid_palindromes_remove_char.py
2,609
4.21875
4
# Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # -------------------------------------------------------------------------------------------------------------------------------------------------- # Example 1: # Input: "aba" # Output: True # Example 2: # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. # Note: # The string will only contain lowercase characters a-z. The maximum length of the string is 50000. # ---------------------------------------------------------------------------------------------------------------------------------------------------- # Naive solution will be to traverse through the string, and one by one delete the current char / skip that char and check whether remaining string is palindrome # and finally, return the euqality of s == [::-1], so that if there is no need to deleting the occurence of char for making it palindrome then we can anyway return True # based on last condition which returns True when string is palindrome and doesn't requires any deletion. # TIME : 0(N ^ 2), so, can we do better than this ? # Yes, we can actually apply the two pointers approach which is used for checking if given string is palindrome or not, then we can modify the pointers and check like # if two chars match, then move both towards mid (for convergence for while loop), otherwise there would be two conditions and only these two conditions arises of which : # * one where left pointer is not matched, and after skipping it, all others matched # * one where right pointer is not matched, and after skipping it, all otherse matched. # We can apply above approach which works efficiently in 0(N) time complexity. # -------------------------------------------------------------------------------------------------------------------------------------------------- class Solution: def is_palindrome(self, s, left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True def validPalindrome(self, s: str) -> bool: start, end = 0, len(s) - 1 while start < end: if s[start] == s[end]: start += 1 end -= 1 else: if self.is_palindrome(s, start + 1, end): return True if self.is_palindrome(s, start, end - 1): return True return False return True
a564540d0d799c4fd85fab8502ab12644b5070d7
OgnyanPenkov/Programming0-1
/week1/5-Saturday-Tasks/solutions/sum_of_odds.py
675
3.796875
4
# Това е същата задача като sum_of_odds.py # С разликата, че събираме само нечетните n = input("Enter n: ") n = int(n) # В променлива ще държим сумата на числата от 1 до n # На всяко завъртане в цикъла ще прибавяме към нея total_sum = 0 # В тази променлива ще държим поредното число от 1 до n start = 1 while start <= n: # Събираме само четните числа в total_sum if start % 2 == 1: total_sum += start start += 1 print("The sum is: " + str(total_sum))
db5780847622eef4618cf6875d9a574039bd646c
severin-lemaignan/pyrobomaze
/astar.py
3,149
3.984375
4
import math MAZE_SIZE = (100, 100) END_GOAL = (98,98) class AStar: def __init__(self): self.pos = (1,1) self.maze = [0,] * MAZE_SIZE[0] * MAZE_SIZE[1] # initially, our maze is empty def astar(self, start, goal): cost_to = {} # maps nodes to distance to 'start_node' cost_to[start] = 0 come_from = {} # needed to reconstruct shortest path nodes_to_visit = [(start,0)] # (node, 'total' cost) while nodes_to_visit: node, _ = self.pop_best_node(nodes_to_visit) for neighbour in self.neighbours(node): cost_to.setdefault(neighbour, float('inf')) if cost_to[node] + 1 < cost_to[neighbour]: # new shorter path to v! cost_to[neighbour] = cost_to[node] + 1 nodes_to_visit.append((neighbour, cost_to[neighbour] + \ self.heuristic(neighbour, goal))) come_from[neighbour] = node # finally, reconstruct the path path = [] node = goal while node in come_from: path = [node] + path # append at the front of our path node = come_from[node] return path @staticmethod def heuristic(node, goal): return (node[0] - goal[0])**2 + (node[1] - goal[1])**2 def pop_best_node(self, nodes): """ !! Highly ineffective implementation, and major source of slow down. Can you do better? """ best_node_score = float('inf') best_node_idx = 0 for idx in range(len(nodes)): if nodes[idx][1] < best_node_score: best_node_score = nodes[idx][1] best_node_idx = idx return nodes.pop(best_node_idx) def is_free(self, node): x, y = node if x < 0 or y < 0 or x >= MAZE_SIZE[0] or y >= MAZE_SIZE[1]: return False return self.maze[y * MAZE_SIZE[0] + x] == 0 def neighbours(self, node): x,y = node return [n for n in [(x, y-1), (x, y+1), (x-1, y), (x+1, y)] if self.is_free(n)] def get_next_move(self, obstacles): # update the maze x, y = self.pos if obstacles[0]: self.maze[(y-1) * MAZE_SIZE[0] + x] = 1 if obstacles[1]: self.maze[(y+1) * MAZE_SIZE[0] + x] = 1 if obstacles[2]: self.maze[y * MAZE_SIZE[0] + x+1] = 1 if obstacles[3]: self.maze[y * MAZE_SIZE[0] + x-1] = 1 # run the A* path = self.astar(self.pos, END_GOAL) direction = "" # update pos and return best move if path[0][0] - x == 1: x += 1 direction = "E" elif path[0][0] - x == -1: x -= 1 direction = "W" elif path[0][1] - y == 1: y += 1 direction = "S" elif path[0][1] - y == -1: y -= 1 direction = "N" else: raise Exception("Impossible move!") self.pos = (x,y) return direction
89bc560d250cca7bf06f02a0f9c8516e82184354
trex013/python-programs
/My Python Programs/factor.py
1,537
3.6875
4
class Fraction: de = 1 def __init__(self, nu, de): self.nu = nu self.de = de def __add__(self, other): des = [self.de , other.de] lcm_ = lcm(des) nus = ((lcm_/self.de)*self.nu) + ((lcm_/other.de)*other.nu) return Fraction(nus, lcm_) def __str__(self): return "{} / {}".format(int(self.nu), self.de) def factor(data, tester = 2): for x in data: if x % tester == 0: continue else: return 1 return tester def divideList(iterable, by): value = [] for x in iterable: value.append(int(x/by)) return value def cnt(it, test): for x in it: if test >= x: return True else: return False def mul(arr): d = 1 for x in arr: d *= x return d def factors(data): factors = [] tester = 2 while True: fact = factor(data, tester) data = divideList(data, fact) if fact == 1: tester += 1 if cnt(data, tester): break continue factors.append(fact) return data, factors def lcm(data): x,factors_ = factors(data) return mul(factors_) #x = [250,125,625] #print("LCM: ",lcm(x)) x = Fraction(2,3) + Fraction(1,3) +Fraction(4,3) print(x)
924a88001d4df29adff8917190e5002ba2a04b88
abdul-moize/virtual_environment
/pandas_practice.py
460
3.78125
4
""" this module contains a pandas library example """ import numpy import pandas as pd def pandas_create_custom_df(): """ this function creates a custom dataframe with 1. dates('2013-01-01' to '2013-01-06') as 0 column 2. A, B, C, D as columns 3. random values """ # pandas exercise dates = pd.date_range("20130101", periods=6) df = pd.DataFrame(numpy.random.randn(6, 4), index=dates, columns=list("ABCD")) print(df)
cfeaf3947724635d74e02d15b3bb1fdc5597937a
nachop97m/Practicas-DAI-app-web
/P1/adivinar.py
1,031
4.03125
4
#Practicas DAI. Ejercicio 1. #Adivinar numero entre 1 y 100 (max 10 intentos). #Se mostrara ayuda en cada intento fallido from random import randrange print ("Mini-juego de prueba. Adivine un numero aleatorio entre 1 y 100\n\n") print ("Que comienze el juego!!!\n") numero = randrange(1, 100) intentos = 10 prueba = int(input("Prueba con un numero: ")) while prueba != numero and intentos > 0: if prueba > numero: print ("Fallaste perla. El numero que buscas es mas pequeño...\n") print ("Quedan ", intentos, " intentos\n") prueba = int(input("Prueba otra vez: ")) else: print ("Fallaste perla. El numero que buscas es mas grande...\n") print ("Quedan ", intentos, " intentos\n") prueba = int(input("Prueba otra vez: ")) intentos -= 1 if intentos == 0 and prueba != numero: print ("\n\nEsto no se te da bien, mejor dedicate a otra cosa...\n") else: print ("\n\nMuy bien! Eres un maquina en esto de adivinar numeros\n")
52146cb4687de193a87fc4cbe8c9175e2286104b
HalforcNull/Research_PatternRecognition
/Code/fun4.py
3,860
3.578125
4
""" Lovely Lucky LAMBs ================== Being a henchman isn't all drudgery. Occasionally, when Commander Lambda is feeling generous, she'll hand out Lucky LAMBs (Lambda's All-purpose Money Bucks). Henchmen can use Lucky LAMBs to buy things like a second pair of socks, a pillow for their bunks, or even a third daily meal! However, actually passing out LAMBs isn't easy. Each henchman squad has a strict seniority ranking which must be respected - or else the henchmen will revolt and you'll all get demoted back to minions again! There are 4 key rules which you must follow in order to avoid a revolt: 1. The most junior henchman (with the least seniority) gets exactly 1 LAMB. (There will always be at least 1 henchman on a team.) 2. A henchman will revolt if the person who ranks immediately above them gets more than double the number of LAMBs they do. 3. A henchman will revolt if the amount of LAMBs given to their next two subordinates combined is more than the number of LAMBs they get. (Note that the two most junior henchmen won't have two subordinates, so this rule doesn't apply to them. The 2nd most junior henchman would require at least as many LAMBs as the most junior henchman.) 4. You can always find more henchmen to pay - the Commander has plenty of employees. If there are enough LAMBs left over such that another henchman could be added as the most senior while obeying the other rules, you must always add and pay that henchman. Note that you may not be able to hand out all the LAMBs. A single LAMB cannot be subdivided. That is, all henchmen must get a positive integer number of LAMBs. Write a function called answer(total_lambs), where total_lambs is the integer number of LAMBs in the handout you are trying to divide. It should return an integer which represents the difference between the minimum and maximum number of henchmen who can share the LAMBs (that is, being as generous as possible to those you pay and as stingy as possible, respectively) while still obeying all of the above rules to avoid a revolt. For instance, if you had 10 LAMBs and were as generous as possible, you could only pay 3 henchmen (1, 2, and 4 LAMBs, in order of ascending seniority), whereas if you were as stingy as possible, you could pay 4 henchmen (1, 1, 2, and 3 LAMBs). Therefore, answer(10) should return 4-3 = 1. To keep things interesting, Commander Lambda varies the sizes of the Lucky LAMB payouts: you can expect total_lambs to always be between 10 and 1 billion (10 ^ 9). Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit solution.java Test cases ========== Inputs: (int) total_lambs = 10 Output: (int) 1 Inputs: (int) total_lambs = 143 Output: (int) 3 Use verify [file] to test your solution and see how it does. When you are finished editing your code, use submit [file] to submit your answer. If your solution passes the test cases, it will be removed from your home folder. """ import math def calcMin(total_lambs): # 2^n - 1 = minCount # minCount should less or equal to total_lambs return int(math.floor(math.log(total_lambs+1, 2))) def calcMax(total_lambs): # Fibonacci seq a,b = 1,1 i = 1 total_lambs -= 1 while True: a,b = b,a+b if total_lambs - a >= 0: total_lambs -= a i += 1 else: return i def calcFib(total_lambs): a,b = 1,1 sumFib = 1 for i in range(50): a,b = b,a+b sumFib = sumFib + a if(sumFib <= total_lambs): print(str(i) + ' ' + str(sumFib)) continue return i+1 def answer(total_lambs): # your code here print(calcMax(total_lambs)) print(calcMin(total_lambs)) return calcMax(total_lambs)-calcMin(total_lambs)
3049946d3c0b1ffb402b474f2d8d345e7d40e1aa
Zerl1990/2020_python_workshop
/08_conditionals.py
211
4.3125
4
A = 5 B = 6 if A == B: print("A is equal to B") else: print("A is not equal to B") if A is B and A < 6: print("A is B and A is less than 6") else: print("A is not B and A is not less than 6")
297e8d52f44ddb481fd977c967c63c3b28b4c61f
Leeviiii/Leetcode
/sourcecode/ClimbingStairs.py
503
3.671875
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 if n == 2: return 2 l1 = 1 l2 = 2 l3 = 0 for i in range(3,n+1): l3 = l1 + l2 l1 = l2 l2 = l3 return l3 if __name__ == "__main__": s = Solution() r = s.climbStairs(4) print r
4480159f3fbd1d619eabdf90b0cd292ed29cb88f
sanshitsharma/pySamples
/leetcode/number_of_islands.py
1,554
3.609375
4
#!/usr/bin/python class Island(object): def __init__(self, grid): self.isl = grid self.length = len(grid) self.height = len(grid[0]) def isInbounds(self, r, c): if r < 0 or r >= self.length or c < 0 or c >= self.height: return False return True def isWater(self, r, c): return self.isl[r][c] == '0' class Solution(object): def numIslands(self, grid): """ :type grid: List[List[str]] :rtype: int """ if not grid or len(grid) == 0: return 0 island = Island(grid) count = 0 for i in range(island.length): for j in range(island.height): if island.isl[i][j] == '0': continue count += 1 self.dfs(i, j, island) return count def dfs(self, r, c, island): if not island.isInbounds(r, c) or island.isWater(r, c): return island.isl[r][c] = '0' self.dfs(r-1, c, island) self.dfs(r+1, c, island) self.dfs(r, c-1, island) self.dfs(r, c+1, island) if __name__ == "__main__": #grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]] grid = [['1', '1', '0', '1', '1'], ['1', '1', '1', '1', '1'], ['0', '0', '0', '0', '0'], ['1', '0', '1', '0', '1'], ['0', '1', '0', '1', '0']] #grid = [['1', '0', '1'], ['0', '1', '0'], ['1', '0', '1']] ans = Solution().numIslands(grid) print ans
a987d5b587096c3c3f3066aafc1708ae799c9b93
TheDutchDevil/2IMA15
/RandomizedIncremental.py
8,171
3.5
4
""" A module containing functions and classes related to the randomized incremental algorithm that creates a trapezoidal deconstruction of a simple polygon. """ import gc import math as math from math import floor, sqrt from random import shuffle from DataStructures import Vertex, Edge, Direction import IncrementalDataStructure as ds import VerticalDecomposition as vd def randomize(collection): """ Returns a new collection containing the same data as the provided collection, but in a random order. """ # Copy the collection first to keep the old order intact. c_collection = list(collection) shuffle(c_collection) return c_collection def to_output(original_edges, trapezoids): """Converts the trapezoidal decomposition to the output structure.""" decomp = vd.VerticalDecomposition() trapezoids = sorted(set(trapezoids), key=lambda t: t.leftp.x) for i in range(0, len(trapezoids)): trapezoid = trapezoids[i] print("[{}] {}".format(i, trapezoid), end='') for edge in trapezoid.edges(): if edge in original_edges: decomp.addEdge(edge) else: decomp.addVertEdge(edge) return decomp def decompose_basic(edges): """ Runs the basic randomized incremental algorithm on the provided collection of edges. Returns the vertical decomposition. """ r = ds.BoundingBox.around_edges(edges) edges = randomize(edges) #print(edges) d = ds.TrapezoidSearchStructure.from_bounding_box(r) for i in range(0, len(edges)): edge = edges[i] if edge.is_vertical(): raise ValueError("Vertical edges are not supported. Edge: {}".format(edge)) t_new = ds.TrapezoidalDecomposition.insert(d, edge) ds.TrapezoidSearchStructure.insert(t_new, edge) if i % 1000 == 0: gc.collect() return [l.trapezoid() for l in d.get_leafs()] def log(value): """Returns the result of the logarithm of the provided value with base 2.""" return math.log(value, 2) def N(h): return 2**(h**2) def trace(edges, ss_d): vert_map = {} if len(edges) == 0: return vert_map # First find an initial trapezoid by doing a point location query. vertex = edges[0].p1 t_leafs = list(ss_d.point_location_query(vertex)) # If multiple trapezoids are returned pick the correct one. if len(t_leafs) == 1: t_prev = t_leafs[0].trapezoid() else: # Find the correct trapezoid. for t_leaf in t_leafs: if edges[0].p1.x < edges[0].p2.x and t_leaf.trapezoid().bottom.p1 == vertex: t_prev = t_leaf.trapezoid() break if edges[0].p1.x > edges[0].p2.x and t_leaf.trapezoid().top.p1 == vertex: t_prev = t_leaf.trapezoid() break if t_leaf.trapezoid().get_number_of_intersections(edges[0]) == 2: t_prev = t_leaf.trapezoid() break # If no trapezoid is found, then take the first. t_prev = t_leafs[0].trapezoid() # Add the initial vertex to the mapping. vert_map[vertex] = t_prev.ref_nodes()[0] # Set the previous edge. edge_prev = edges[0] for i in range(1, len(edges)): edge_cur = edges[i] vertex = edge_cur.p1 if not t_prev.contains_vertex(vertex): if t_prev.top == edge_cur: vert_map[vertex] = t_prev.ref_nodes()[0] edge_prev = edge_cur for neighbor_right in t_prev.neighbors_right: for above in neighbor_right.neighbors_left: if above.bottom == t_prev.top: t_prev = above break continue elif t_prev.bottom == edge_cur: for neighbor_left in t_prev.neighbors_left: for below in neighbor_left.neighbors_right: if below.top == t_prev.bottom: t_prev = below break elif t_prev.left() is not None and t_prev.left().intersects(edge_prev): neighbors = list(t_prev.neighbors_left) while len(neighbors) > 0: neighbor = neighbors.pop() lies_on_right = vertex.lies_on(neighbor.right()) \ if neighbor.right() is not None else neighbor.rightp == vertex if neighbor.contains_vertex(vertex) or lies_on_right: t_prev = neighbor break if neighbor.left() is not None and neighbor.left().intersects(edge_prev): neighbors = list(neighbor.neighbors_left) elif t_prev.right() is not None and t_prev.right().intersects(edge_prev): neighbors = list(t_prev.neighbors_right) while len(neighbors) > 0: neighbor = neighbors.pop() lies_on_left = vertex.lies_on(neighbor.left()) \ if neighbor.left() is not None else neighbor.leftp == vertex if neighbor.contains_vertex(vertex) or lies_on_left: t_prev = neighbor break if neighbor.right() is not None and neighbor.right().intersects(edge_prev): neighbors = list(neighbor.neighbors_right) vert_map[vertex] = t_prev.ref_nodes()[0] edge_prev = edge_cur return vert_map def decompose_improved(edges): r = ds.BoundingBox.around_edges(edges) #edges_rand = randomize(edges) #edges_rand = [Edge(Vertex(7, 1), Vertex(3, 1), Direction.Undefined), Edge(Vertex(2, 8), Vertex(6, 9), Direction.Undefined), Edge(Vertex(6, 9), Vertex(10, 6), Direction.Undefined), Edge(Vertex(10, 6), Vertex(11, 2), Direction.Undefined), Edge(Vertex(5, 6), Vertex(2, 8), Direction.Undefined), Edge(Vertex(3, 1), Vertex(1, 4), Direction.Undefined), Edge(Vertex(11, 2), Vertex(9, 3), Direction.Undefined), Edge(Vertex(1, 4), Vertex(4, 4), Direction.Undefined), Edge(Vertex(8, 5), Vertex(7, 1), Direction.Undefined), Edge(Vertex(9, 3), Vertex(8, 5), Direction.Undefined), Edge(Vertex(4, 4), Vertex(5, 6), Direction.Undefined)] edges_rand = [Edge(Vertex(4, 4), Vertex(5, 6), Direction.Undefined), Edge(Vertex(3, 1), Vertex(1, 4), Direction.Undefined), Edge(Vertex(10, 6), Vertex(11, 2), Direction.Undefined), Edge(Vertex(1, 4), Vertex(4, 4), Direction.Undefined), Edge(Vertex(7, 1), Vertex(3, 1), Direction.Undefined), Edge(Vertex(5, 6), Vertex(2, 8), Direction.Undefined), Edge(Vertex(8, 5), Vertex(7, 1), Direction.Undefined), Edge(Vertex(9, 3), Vertex(8, 5), Direction.Undefined), Edge(Vertex(11, 2), Vertex(9, 3), Direction.Undefined), Edge(Vertex(6, 9), Vertex(10, 6), Direction.Undefined), Edge(Vertex(2, 8), Vertex(6, 9), Direction.Undefined)] print(edges_rand) d = ds.TrapezoidSearchStructure.from_bounding_box(r) # Create D1 and T1. t_new = ds.TrapezoidalDecomposition.insert(d, edges_rand[0]) ds.TrapezoidSearchStructure.insert(t_new, edges_rand[0]) # Trace the vertices to their trapezoids. vertex_trace = trace(edges, d) # Calculate the number of loops in which a new trace is determined. nr_of_loops = floor(sqrt(log(len(edges)))) for h in range(0, nr_of_loops): for i in range(N(h), N(h + 1)): _decompose_improved_insert(vertex_trace, edges_rand[i]) vertex_trace = trace(edges, d) for i in range(nr_of_loops + 1, len(edges)): _decompose_improved_insert(vertex_trace, edges_rand[i]) return [l.trapezoid() for l in d.get_leafs()] def _decompose_improved_insert(vertex_trace, edge): """Inserts the provided edge into the structures D and T using the provided trace.""" if edge.is_vertical(): raise ValueError("Vertical edges are not supported. Edge: {}".format(edge)) d_sub = vertex_trace[edge.getStartVertex()] t_new = ds.TrapezoidalDecomposition.insert(d_sub, edge) ds.TrapezoidSearchStructure.insert(t_new, edge)
b29c22190bc2db9e4ea670d49ee70c825afd1d45
Andras-z/LeetCode
/Array/Jump Game.py
965
4.03125
4
'''Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false.''' nums = [2, 3, 1, 1, 4] # Solution 1 # Going forwards. m tells the maximum index we can reach so far. def canJump(self, nums): m = 0 for i, n in enumerate(nums): if i > m: return False m = max(m, i+n) return True # Solution 2 # One-liner version: def canJump(self, nums): return reduce(lambda m, (i, n): max(m, i+n) * (i <= m), enumerate(nums, 1), 1) > 0 # Solution 3 # Going backwards, most people seem to do that, here's my version. def canJump(self, nums): goal = len(nums) - 1 for i in range(len(nums))[::-1]: if i + nums[i] >= goal: goal = i return not goal
3e32652d9b14af2897d6625111931a9d4350748d
artkpv/code-dojo
/hackerrank.com/contests/w35/airports/airports.py
544
3.8125
4
#!python3 import sys def airports(d, x): """ Need to make any airport not less to d to at least one other airport. If not so then find min cost to move airports to satisfy the condition. x = sorted x ?? """ if __name__ == "__main__": q = int(input().strip()) for a0 in range(q): n, d = input().strip().split(' ') n, d = [int(n), int(d)] x = list(map(int, input().strip().split(' '))) result = airports(d, x) print (" ".join(map(str, result)))
c7e3b882aa4935e38789ec9f22fc2fed744c02af
mohit266/Python
/Polymrphm.py
948
3.921875
4
class Person: def __init__(self, name, age): self.name = name self.age = age def print_details(self): return f"\nName of person is {self.name} \n" \ f"Age is {self.age} " class Employee(Person): def __init__(self, name, age, company_name): super().__init__(name, age) self.company_name = company_name def print_details(self): print(super().print_details()) return f"He works in {self.company_name} company " class Programmer(Employee): def __init__(self, name, age, company_name, language): super().__init__(name, age, company_name) self.language = language def print_Details(self): print(super().print_details()) return f"He knows {self.language} language \n" david = Employee("MS", 25, "Cricket") print(david.print_details()) Mohit = Programmer("Mohit", 21, "Metacube", "Python") print(Mohit.print_Details())
bc2b68431afab5cf21b2150aa62bf37acc3d0c18
olliveirasamira/Exercicios-Python
/006.py
194
3.953125
4
n1 = int(input('Digite um número')) print('Este é o triplo desse numero {} '.format(n1*3)) print('Este é o dobro {}'. format(n1*2)) print('Esta é a raiz quadrada {} '.format(n1**(1/2)))
b9778da21189c9ddd8d4ed8361aeaaec87616e22
bienvenidosaez/2asir1415
/04 Python/examen1eval/fibonacci.py
396
3.71875
4
#-*- encoding: utf-8 -*- print ('%s' % u'Indica el término de la sucesión de Fibonacci que quieres: ') nTermino = int(input()) nAntepenultimo = 1 nPenultimo = 1 contador = 2 lTerminos = [nAntepenultimo, nPenultimo] while contador < nTermino: temporal = nAntepenultimo + nPenultimo lTerminos += [temporal] nAntepenultimo = nPenultimo nPenultimo = temporal contador += 1 print lTerminos
1a286f4001de49493bfc6cca352d4326e3c1cedd
theEmbeddedGeorge/EE219-Machine-Learning
/Project5/Code/pro_3.py
3,991
3.625
4
""" PROBLEM 3 Objective Fit a linear regression model with new features to predict # of tweets in the next hour, from data in the PREVIOUS hour. New Fetures from the paper in the preview: 1. number of tweets 2. number of retweets 3. number of followers 4. max numbber of followers 5. time of the data (24 hours represent the day) 6. ranking score 7. impression count 8. number of user 9. number of verified user 10. user mention 11. URL mention 12. list count 13. Max list 14. Friends count 15. number of long tweets Attention: This is NOT the order the following program uses Model: Random Forest Explain your model's training accuracy and the significance of each feature using the t-test and P-value results of fitting the model. """ import datetime import help_functions from sklearn.ensemble import RandomForestRegressor import statsmodels.api as sm # Remember this order! features = ['ranking', 'friends_count', 'impression', 'URL', 'list_num', 'long_tweet', 'day_hour', 'tweets_count', 'verified_user', 'user_count', 'Max_list','retweets_count', 'followers', 'user_mention', 'max_followers'] input_files = ['gohawks', 'gopatriots', 'nfl', 'patriots', 'sb49', 'superbowl'] # tweet-data file names #input_files = ['gohawks'] # tweet-data file names for file_name in input_files: tweets = open('./tweet_data/tweets_#{0}.txt'.format(file_name), 'rb') ######### Perform linear regression for each hashtag file ####### hour_wise_data = help_functions.features_extraction(tweets) X, Y = [], [] print (hour_wise_data.values()[0]) for prev_hour in hour_wise_data.keys(): hour = datetime.datetime.strptime(prev_hour, "%Y-%m-%d %H:%M:%S") next_hour = unicode(hour + datetime.timedelta(hours=1)) if next_hour in hour_wise_data.keys(): Y.append(hour_wise_data[next_hour]['tweets_count']) X.append(hour_wise_data[prev_hour].values()) # random forest regression analysis model = RandomForestRegressor(n_estimators=50, random_state=42) results = model.fit(X, Y) print('The accuracy is: ' + str(results.score(X, Y))) print('Feature importance are: ' + str(results.feature_importances_)) t_val = results.feature_importances_ # lasso/ridge regression analysis # X_const = sm.add_constant(X) # LR_model = sm.OLS(Y, X_const) # LR_results = LR_model.fit_regularized(L1_wt=0, alpha=0.01) # print(LR_results.summary()) # print('P values: ' + str(LR_results.pvalues)) # print('T values: ' + str(LR_results.tvalues)) # t_val = LR_results.tvalues.tolist() # t_val.pop(0) # pop the constant item # # t_val = [abs(i) for i in t_val] # retrive indeces of top three T values in the order of third, second, first indeces = sorted(range(len(t_val)), key=lambda i: t_val[i])[-3:] print('top three features are:') print(features[indeces[2]], features[indeces[1]], features[indeces[0]]) # Extract top three features first_fea, sec_fea, third_fea = [], [], [] for i in range(len(X)): first_fea.append(X[i][indeces[2]]) sec_fea.append(X[i][indeces[1]]) third_fea.append(X[i][indeces[0]]) # Plot diagrams: help_functions.plot_feature(first_fea, Y, file_name, features[indeces[2]]) help_functions.plot_feature(sec_fea, Y, file_name, features[indeces[1]]) help_functions.plot_feature(third_fea, Y, file_name, features[indeces[0]]) print('-'*50) # Top three features for different topics: # gohawks: X1, X4, X12 # ('ranking', 'URL', 'user_mention') # gopatriots: X1, X4, X13 # ('ranking', 'URL', 'max_followers') # nfl: X12, X9, X7 # ('user_mention', 'user_count', 'tweets_count') # patriots: X1, X11, X4 # ('ranking', 'followers', 'URL') # sb49: X12, X11, X10 # ('user_mention', 'followers', 'retweets_count') # Superbowl: X10, X4, X13 # ('retweets_count', 'URL', 'max_followers')
aadb2e5b609111459729a223fe5533c857c2be21
Suraj023/Graphics-Using-Python
/Circle_by_midpoint.py
1,991
3.71875
4
from graphics import * import time def midPoint_Circle(x_coordinate,y_coordinate,radius): x=radius;y=0 win = GraphWin('Midpoint Circle', 600, 500) print("\n\nCoordinates") print(x+x_coordinate,y+y_coordinate) win.plotPixel(x+x_coordinate,y+y_coordinate,"blue") if radius>0: print(x+x_coordinate,-y+y_coordinate) win.plotPixel(x+x_coordinate,-y+y_coordinate,"red") print(y+x_coordinate,x+y_coordinate) win.plotPixel(y+x_coordinate,x+y_coordinate,"red") print(-y+x_coordinate,x+y_coordinate) win.plotPixel(-y+x_coordinate,x+y_coordinate,"red") p=1-radius while x>y: y=y+1 if p<=0: p=p+ 2*y +1 else: x=x-1 p=p+2*y-2*x+1 if x<y: break print(x+x_coordinate,y+y_coordinate) win.plotPixel(x+x_coordinate,y+y_coordinate,"blue") print(-x+x_coordinate,y+y_coordinate) win.plotPixel(-x+x_coordinate,y+y_coordinate,"blue") print(x+x_coordinate,-y+y_coordinate) win.plotPixel(x+x_coordinate,-y+y_coordinate,"blue") print(-x+x_coordinate,-y+y_coordinate) win.plotPixel(-x+x_coordinate,-y+y_coordinate,"blue") if x!=y: print(y+x_coordinate,x+y_coordinate) win.plotPixel(y+x_coordinate,x+y_coordinate,"black") print(-y+x_coordinate,x+y_coordinate) win.plotPixel(-y+x_coordinate,x+y_coordinate,"black") print(y+x_coordinate,-x+y_coordinate) win.plotPixel(y+x_coordinate,-x+y_coordinate,"black") print(-y+x_coordinate,-x+y_coordinate) win.plotPixel(-y+x_coordinate,-x+y_coordinate,"black") def main(): x = int(input("Enter X Coordinate: ")) y = int(input("Enter Y Coordinate: ")) r = int(input("Enter Radius: ")) midPoint_Circle(x,y,r) if __name__ == "__main__": main()
fa30142f735db0f77014daac5f82766fba5c623e
eduardovra/CrackingTheCodingInterview
/chapter_04/q12_paths_with_sum.py
1,059
3.96875
4
from typing import Optional class Node: def __init__(self, value) -> None: self.data = value self.left: Optional[Node] = None self.right: Optional[Node] = None def __repr__(self) -> str: return str(self.data) def sum_tree(node, value, acc): if not node: return 0 times = 0 acc += node.data if acc == value: times += 1 times += sum_tree(node.left, value, acc) times += sum_tree(node.right, value, acc) return times def paths_with_sum(tree, value): # Traverse tree, starting from the root node, # and return how many times the sum of elements # adds up to value if not tree: return 0 paths = sum_tree(tree, value, 0) paths += paths_with_sum(tree.left, value) paths += paths_with_sum(tree.right, value) return paths tree = Node(8) assert paths_with_sum(tree, 8) == 1 tree.left = Node(4) tree.right = Node(10) tree.left.left = Node(2) tree.left.right = Node(6) tree.right.right = Node(20) assert paths_with_sum(tree, 18) == 2
ebe7ff6ce95623a082a5603d88095066267e5751
quant108/Simulation-and-modeling-of-natural-processes
/Week 7/Introduction to Discrete Events Simulation/Traffic.py
3,215
4.25
4
# Coursera - Simulation and modeling of natural processes - Discrete Event Simulation # Importing Libraries import heapq # Defining parameters Tp = 10 # Time taken by 1 car to pass the traffic light Tc = 30 # Latency to change traffic light # Defining the State of traffic class State: def __init__(self): self.cars = 0 self.green = False def already_green(self): # Check if signal is already green return self.green def turn_green(self): # Turn to green signal self.green = True def turn_red(self): # Turn to red signal self.green = False def insert_car(self): # Add one car self.cars = self.cars + 1 def remove_car(self): # Remove all cars self.cars = 0 def waiting_cars(self): # Number of cars waiting in the queue return self.cars def __str__(self): return "Green light status is: " + str(self.green) + "Number of cars are: " + str(self.cars) # Defining an event class Event: def time(self): return self.time def __str__(self): return self.name + "(" + str(self.time) + ")" def __lt__(self, other): return self.time < other.time class Car(Event): def __init__(self, time): self.time = time self.name = "Car" def action(self, queue, state): if not state.already_green(): state.insert_car() if state.waiting_cars() == 1: queue.push(Red2Green(self.time + Tc)) class Red2Green(Event): # Traffic signal turning from red to green def __init__(self, time): self.time = time self.name = "Red2Green" def action(self, queue, state): queue.push(Green2Red(self.time + Tp * state.waiting_cars())) state.turn_green() # turn signal to green state.remove_car() # clear all cars class Green2Red(Event): # Traffic signal turning from green to red def __init__(self, time): self.time = time self.name = "Green2Red" def action(self, queue, state): state.turn_red() # turn signal to red # Defining the queue class Queue: def __init__(self): self.q = [] def push(self, event): heapq.heappush(self.q, event) # pushing in a heap data structure def pop(self): return heapq.heappop(self.q) # popping out from a heap data structure def notempty(self): return len(self.q) # Adding cars to simulate Q = Queue() # Defining a heap for First In First Out Q.push(Car(10)) Q.push(Car(25)) Q.push(Car(35)) Q.push(Car(60)) Q.push(Car(75)) S = State() # Processing events until the queue is empty while Q.notempty() > 0: e = Q.pop() print(e) e.action(Q,S)
a5688ba0a8ad4388939960ece71abdcf825afeeb
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4005/codes/1745_3097.py
325
3.859375
4
x= int(input("tecle qualquer numero para iniciar:")) soma=0 while (x != 0): x=int(input("posicao:")) if(x<0): x=x*(-1) if(x==1 and x!=0): soma=soma+25 elif(x==2 and x!=0): soma=soma+18 elif(x==3): soma=(soma+12) elif(x >= 4 and x <= 10 and x!=0): soma=(soma+14-x) else: 14 print(round(soma-soma*0.24))
1aca501a366d2e63b4339e090506b91cee599d92
VipulGirishKumar/Cinema-Hall-Booking-System
/Project- Cinema Seat Booking.py
6,598
3.765625
4
#Cinema Hall - Seat Booking Booking System print("Cinema Hall - Seat Booking Booking System") seats = [] seats.append([0,0,1,0,1,1,0,1]) seats.append([0,1,1,0,0,1,0,1]) seats.append([1,0,0,1,1,1,0,0]) seats.append([0,1,0,1,1,0,0,1]) seats.append([0,0,1,1,0,1,0,0]) seats.append([1,0,0,1,0,1,1,0]) #Password def password(): if passwd=='python': print("System Online") print("") else: print("Access Denied") sys.exit() #Menu print("") print("\tMENU") print(" 0. Display Menu \n 1. Display Bookings \n 2. Check Seat Availability \n 3. Book Seat \n 4. Book Seat at the front \n 5. Book Seat at the back \n 6. Cancel Booking \n 7. Cancel All Booking \n 8. Load Booking from file \n 9. Save bookings in a file \n 10. Exit " ) print("") #Displays MENU def displayMenu(): print("") print("\tMENU") print(" 0. Display Menu \n 1. Display Bookings \n 2. Check Seat Availability \n 3. Book Seat \n 4. Book Seat at the front \n 5. Book Seat at the back \n 6. Cancel Booking \n 7. Cancel All Booking \n 8. Load Booking from file \n 9. Save bookings in a file \n 10. Exit" ) print("") #Displays all Seats def displayBookings(): print("===========================================") print(" SCREEN ") print("") for row in seats: print("\t",row) print("") print("1 = Seat is Booked.") print("0 = Seat is Available") print("") print("===========================================") print("") #Load Bookings from File def loadBookings(): file = open("seats.txt","r") row = 0 for line in file: data = line.split(",") if len(data)==8: #Only process lines which contain 8 values for column in range (0,8): seats[row][column] = int(data[column]) row = row + 1 file.close() print("Bookings Loaded") #Seat availability checking def checkSeat(): row = int(input("Enter a row number (between 0 and 5)")) column = int(input("Enter a column number (between 0 and 7)")) if seats[row][column]==1: print("This seat is already booked.") else: print("This seat is empty.") #Booking Seat import random def bookSeat(): booked = False F=open("BookingDetails.txt",'a') while booked == False: row = int(input("Enter a row number (between 0 and 5)")) column = int(input("Enter a column number (between 0 and 7)")) if seats[row][column]==1: print("This seat is already booked.") else: print("This seat is empty.") #Details Name=input("Enter Customer Name :") BookingIDD=random.randint(47136834,6753845683) BookingID=str(BookingIDD) F.write("\n") F.write(BookingID+' ') F.write(Name+' ') F.write(str(row)+','+str(column)) print("Booking seat...") seats[row][column]=1 print("We have now booked this seat for you.") print("Your Booking ID is",BookingID) booked=True F.close() #Booking Seat at the front def bookSeatAtFront(): print("Booking seat at the front") F=open("BookingDetails.txt",'a') for row in range(0,6): for column in range(0,8): if seats[row][column]==0: Name=input("Enter Customer Name :") BookingIDD=random.randint(47136834,6753845683) BookingID=str(BookingIDD) F.write("\n") F.write(BookingID+' ') F.write(Name+' ') F.write(str(row)+','+str(column)) print("Booking seat...") print("Row: ", str(row)) print("Column: ", str(column)) seats[row][column]=1 print("We have now booked this seat for you.") F.close() return True print("Sorry the theatre is full - Cannot make a booking") return False #Booking Seat at the Back def bookSeatAtBack(): print("Booking seat at the back") F=open("BookingDetails.txt",'a') for row in range(5,-1,-1): for column in range(7,-1,-1): if seats[row][column]==0: Name=input("Enter Customer Name :") BookingIDD=random.randint(47136834,6753845683) BookingID=str(BookingIDD) F.write("\n") F.write(BookingID+' ') F.write(Name+' ') F.write(str(row)+','+str(column)) print("Booking seat...") print("Row: ", str(row)) print("Column: ", str(column)) seats[row][column]=1 print("We have now booked this seat for you.") F.close() return True print("Sorry the theatre is full - Cannot make a booking") return False #Cancelling Seat Booking def CancelBooking(): booked = False while booked == False: row = int(input("Enter a row number (between 0 and 5)")) column = int(input("Enter a column number (between 0 and 7)")) if seats[row][column]==1: seats[row][column]=0 print("Booking Cancelled") return True else: print("Seat is not booked") return True #Cancelling All Booking def CancelAllBooking(): for row in range(0,6): for column in range(0,8): seats[row][column]=0 print("All Booking Cancelled") #Save Booking in file def saveBookings(): file = open("seats.txt","w") for row in range(0,6): line="" for column in range(0,8): line = line + str(seats[row][column]) + "," line = line[:-1] + ("\n") #Remove last comma and add a new line file.write(line) file.close() print("Booking saved in seats.txt") #Main Program import sys passwd= input("Enter the password to access the booking system:") while True: password() break F1=open("BookingDetails.txt",'w') F1.write("Booking ID"+' ') F1.write("Name of Customer"+' ') F1.write("Seat Number"+' ') F1.close() while True: choice= int(input("Enter your choice:")) print("") if choice==0: displayMenu() elif choice==1: displayBookings() elif choice==2: checkSeat() elif choice==3: bookSeat() elif choice==4: bookSeatAtFront() elif choice==5: bookSeatAtBack() elif choice==6: CancelBooking() elif choice==7: CancelAllBooking() elif choice==8: loadBookings() elif choice==9: saveBookings() else: print("Exiting...") sys.exit() print("") #End of Program
30931ca6d374bf484537f526b3b886dc11db6967
q32854978lhy/leetcode-train
/python/9.回文数.py
542
3.515625
4
# # @lc app=leetcode.cn id=9 lang=python3 # # [9] 回文数 # # @lc code=start class Solution: def isPalindrome(self, x: int) -> bool: str_x=str(x) #if str_x==str_x[::-1]: # return True #else: # return False 简单方法 start=0 end=len(str_x)-1 while start<end : #双指针 if str_x[start]==str_x[end]: start+=1 end-=1 else : return False return True # @lc code=end
c5bed2bfb3d8426b0aa9e9630644340e320e5b9c
tonyiovino/endurance
/endurance2.py
621
3.875
4
quantita_str = input("Inserite la quantità in galloni del carburante: ") quantita = float(quantita_str) consumo_orario_str = input("Inserite il consumo orario: ") consumo_orario = float(consumo_orario_str) if quantita <= 0: print("La quantità del carburante deve essere maggiore di 0.") elif consumo_orario <= 0: print("Il consumo deve essere maggiore di 0.") else: tempo = quantita / consumo_orario ore = int(tempo) tempo = tempo - ore tempo = tempo * 60 minuti = int(tempo) tempo = tempo - minuti tempo = tempo * 60 secondi = int(tempo) print("Tempo in volo: ", ore, "h", minuti, "m", secondi, "s")
3efa8e7d043a71262096c7d969ffd701ee43dc38
enriquehadoop/drawSquare
/fibonacci.py
126
3.796875
4
#serie de fibonacci x = 1 y = 1 suma = 0 print(x) print(y) for i in range(15): suma = x + y y = x x = suma print(suma)
e0f383b9c5b777db00836abf036dbc6419779099
dstilesr/neural-nets-dsr
/neural_nets_dsr/activations/relu.py
370
3.515625
4
from .base import ActivationFunc, T def relu(x: T) -> T: """ Rectified Linear Unit function x -> max(x, 0) :param x: :return: """ return x * (x >= 0) def relu_derivative(x: T) -> T: """ Derivative of ReLU function. :param x: :return: """ return x >= 0 relu_activation = ActivationFunc(relu, relu_derivative, "relu")
950d7864b8b3e975bb8848f4e42bed668ca091c7
Bschoenthaler/VSA-2018
/proj01_ifelse/proj01.py
3,126
4.34375
4
print "HELLO WORLD!!!" Ur_Name = raw_input("What is your name?") print "Your name is " + Ur_Name[0].upper() + Ur_Name[1:].lower() print "I like that name." Fav_color = raw_input("What is your fav color?") print "Your favorite color is " + Fav_color + "." Grade = raw_input("What grade are you in?") print "Oh, your in " + Grade + " grade." Left =12-int(Grade) print "You will graduate highschool in "+ str(Left) + " years!!" x= raw_input("Can I come to your graduation?") if x=="yes": print "Okay, i'll come" print "Thank you for wanting to include me!!" elif x=="sure": print "Okay, I'll come." print "Thank you for wanting to include me!!" elif x== "no thanks": print "Okay, I won't come." print "At least i tried" else: print "Alright I won't go." print "At least i tried" h=raw_input("Are we freinds?") if h== "yes": print "YAY! my first freind!!" elif h== "sure": print "YAY! my first freind!!" elif h=="no": print "Okay, i'll look for a freind somewhere else..." else: print "Okay, i'll look for a freind somewhere else..." print "Hello again " + Ur_Name[0].upper() + Ur_Name[1:].lower() + "!!" y= int(raw_input("What is the current day?[number]")) u= int(raw_input("What is the current month?[number]")) i= int(raw_input("What is your birth month[number]")) o= int(raw_input("What is your birth day[number]")) q= i-u w= 12-(u-i) e= o-y r= 30-(y-o) if i>u: print "The number of months until your birthday is " + str( q) + "." else: print "The number of months until your birthday is " + str( w) + "." if o >= y: print "The number of days until your birthday is " + str( e) + "." else: print "The number of days until your birthday is " + str( r) + "." age = raw_input("How old are you? [number]") if int(age) < 13: print "Your can watch G and PG movies only." elif int(age) >= 13 and int(age) < 17: print "You can watch G, PG, and PG-13 movies" else: print "You can watch G, PG, PG-13 and R rated movies" movie = raw_input("Do you want to see a movie sometime?") if movie =="yes": yes = raw_input("Is 6:30 tomarrow night okay?") if yes == "yes": print "Okay, It's a date!" elif movie =="sure": yes = raw_input("Is 6:30 tomarrow night okay?") if yes == "yes": print "Okay, It's a date!" elif movie == "no": confirm = raw_input("Okay, do you even want to go?") if confirm == "yes": new = raw_input("What time do you want to go?") elif confirm == "sure": new = raw_input("What time do you want to go?") elif confirm == "no": new = raw_input("Okay, I'll take my Spicy memes elsewhere.") else: new = raw_input("Okay, I'll take my Spicy memes elsewhere.") else: confirm = raw_input("Okay, do you even want to go?") if confirm == "yes": new = raw_input("What time do you want to go?") elif confirm == "sure": new = raw_input("What time do you want to go?") elif confirm == "no": new = raw_input("Okay, I'll take my Spicy memes elsewhere.") else: new = raw_input("Okay, I'll take my Spicy memes elsewhere.")
db873c27c39dbf9ae6e9d3918488fb586c015faf
grubbs39/HW2
/MadLib.py
259
3.65625
4
print("Enter two inputs for the mad lib: ") user_input = input() tokens = user_input.split() while tokens[0] != "quit": print(f'Eating{tokens[1]} {tokens[0]} a day keeps the doctor away.') user_input = input() tokens = user_input.split()
d51d6d35a6c1bf52c6a75422f49519ab136fe1b8
wudijqq/dict
/mianshiti.py
798
3.84375
4
def mean(sorted_list): if not sorted_list: return (([],[])) big = sorted_list[-1] small = sorted_list[-2] big_list, small_list = mean(sorted_list[:-2]) big_list.append(small) small_list.append(big) big_list_sum = sum(big_list) small_list_sum = sum(small_list) if big_list_sum > small_list_sum: return((big_list,small_list)) else:mean(sorted_list[:-2]) return ((small_list, big_list)) test = [ [1,2,3,4,5,6,700,800], [10001,10000,100,90,50,1], [x for x in range(1, 11)], [12312,12311,232,210,30,29,3,2,1,1] ] for l in test: l.sort() print() print('Source List: ', l) l1, l2 = mean(l) print('Result List: ', l1, l2) print ('Distance: ', abs(sum(l1) - sum(l2))) print ('-*' * 40)
c0ca4797de97e07e3088e938c5c139bb083b041c
YL928/dailyAlgorithm
/Algorithm/junior/617.merge-two-binary-trees/main.py
302
3.75
4
def mergeTrees(t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 and t2: t1.val += t2.val t1.left = mergeTrees(t1.left, t2.left) t1.right = mergeTrees(t1.right, t2.right) return t1 return t1 or t2
389ee76a9d29d02353f4c7015f1cb77d027234a2
lessunc/python-guanabara
/task052.py
713
3.984375
4
#coding: utf-8 #---------------------------------------------- # Um programa que recebe um número inteiro # e retorna se esse é ou não um número primo. #---------------------------------------------- # Números Primos - Exercício #052 #---------------------------------------------- tot= 0 n = int(input('Digite um número para saber se ele é Primo: ')) for c in range(1, n +1): if n % c == 0: print('\033[1;35m', end='')#printa o número com cor tot+= 1 else: print('\033[m', end='')#printa o número sem cor print(f'{c}', end=' ') print('\033[m') print(f'O número {n} foi divisível {tot} vezes..') if tot== 2: print('Número Primo!\n') else: print('Esse Número Não É Primo!\n')
c9f0968caf7a06f62e45c3b66319d6f6d8d48dd8
ABHISHEKVALSAN/PLACEMENT-PREP
/TESTS/2018/Trexquant/validDates.py
1,380
3.828125
4
# Enter your code here. Read input from STDIN. Print output to STDOU import re def convert(day,month,year): date=year+month+day print int(date) def getDate(text,month,year): D=map(str,range(1,32))+["01","02","03","04","05","06","07","08","09","10","11","12"] for i in D: if i in text: convert(i,month,year) break def getMonDat(text,year): month=["January","February","March","April","May","June","July","August","September","October","November","December",\ "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER",\ "Jan.","Feb.","Mar.","Apr.","May","Jun.","Jul.","Aug.","Sep.","Oct.","Nov.","Dec.",\ "JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC",\ "01","02","03","04","05","06","07","08","09","10","11","12",\ ] i=0 mon="" for m in month: if m in text: text=text.replace(m,"") mon=str((i%12)+1).zfill(2) break i+=1 if len(mon)==2: getDate(text,mon,year) text="" while True: try: line=raw_input() except: break text=text+" "+line lInd=[m.start() for m in re.finditer('[0-9]{4}',text)] for ind in lInd: year=text[ind:ind+4] getMonDat(text[ind-15:ind],year) getMonDat(text[ind+4:ind+15],year)
ff8d067a88b82b501ce3d323ba47e134fd2030c8
dba-base/python-homework
/Day07/选课系统 2/src/Student.py
378
3.59375
4
''' 学生类 ''' class Student(object): #初始化学生姓名,性别,年龄 def __init__(self,name,sex,age): self.stu_name = name self.stu_sex = sex self.stu_age = age self.stu_score = 0 #初始化学生的成绩为0,讲师可更改 def modify_score(self,new_score): self.stu_score = new_score
7cf8470c321d4d87c85f06840b80068dac5e6953
akshayfedee/Secure-Comms-Labs
/luhn.py
6,943
3.875
4
import json import binascii import sys from Crypto.PublicKey import RSA import decimal from operator import mul from functools import reduce def random_digit(): """Return a random digit""" return randint(0, 9) def concat(a, b): """Concatenate two strings""" return a + b def new_range(r): """Given a number a list or a tuple, return a range. If the input is a number, return range(r, r+1). If it is a list or a tuple with exactly two elements then return the range(lower, upper + 1) where lower is the first element and upper is the second. """ if isinstance(r, list) or isinstance(r, tuple) and len(r) == 2: lower = r[0] upper = r[1] else: lower = r upper = r lower = int(lower) upper = int(upper) return range(lower, upper + 1) def new_ranges(rs): """From a list of valid inputs of new_range function, return the chaining of the ranges as a tuple. """ return tuple(chain(*[new_range(r) for r in rs])) def sum_digits(n): """Sum the digits of the number.""" digits = [int(i) for i in str(n)] return sum(digits) def apply_to_odd_positions(f, xs): """Apply the function f to every element in xs that is in a odd position leaving the other values unchanged. """ ys = [] for i, x in enumerate(xs): if i % 2 == 1: ys.append(f(x)) else: ys.append(x) return ys def double(n): """Double of a number""" return 2 * n class Vendor(object): def __init__(self, name, ranges, length): self.name = name self.inns = new_ranges(ranges) self.lengths = new_ranges(length) def new_card(self): length = choice(self.lengths) inn = str(choice(self.inns)) remaining = [str(random_digit()) for _ in range(length - len(inn) - 1)] remaining = reduce(concat, remaining) check_digit = checksum(int(inn + remaining)) result = int(inn + remaining + str(check_digit)) assert(verify(result)) return result def luhn_digits(n): """Given a number, return a list with the digits of Luhn. We call Luhn digits of a number the digits that result from applying the following operations: - Reverse the list of digits - Double the value of every second digit - If the result of this doubling operation is greater than 9 then add the digits of the resulting number. These digits are used in both the algorithm that verifies numbers and the algorithm that produces new checksums. """ digits = [int(i) for i in str(n)] # First, reverse the list of digits. digits.reverse() # Double the value of every second digit. digits = apply_to_odd_positions(double, digits) # If the result of this doubling operation is greater than 9 then # add the digits of the result. digits = apply_to_odd_positions(sum_digits, digits) return digits def verify(n): """Check if the credit card number is a valid.""" # Take the sum of all digits. sum_of_digits = sum(luhn_digits(n)) # The number is valid iff the sum of digits modulo 10 is equal to 0 return sum_of_digits % 10 == 0 def checksum(n): """Checksum digit of the credit card number (with no checksum).""" # Compute the sum of the non-check digits. s = sum(luhn_digits(n * 10)) # Multiply by 9. result = s * 9 # The units digit is the check digit check_digit = result % 10 m = int(str(n) + str(check_digit)) assert(verify(m)) return check_digit def vendor(n, vendors_from_inn): """Return the issuing vendor of the credit card number.""" inns = list(map(str, vendors_from_inn.keys())) for i in inns: if str(n).startswith(i): return vendors_from_inn[int(i)] def generate(v, vendors): """Generate a random valid credit card from a issuing vendor.""" return vendors[v].new_card() if __name__ == "__main__": with open('issuing_networks.json') as f: data = json.loads(f.read()) vendors = {d['name']: Vendor(**d) for d in data['IssuingNetworks']} vendors_from_inn = {inn: name for name, v in vendors.items() for inn in v.inns} def test(): v = choice(list(vendors.keys())) print("Picked a random vendor: {}".format(v)) card = generate(v, vendors) print("New card for that vendor: {}".format(card)) vv = vendor(card, vendors_from_inn) print("Vendor of new card is: {}".format(vv)) print("Is card ok?: {}".format(verify(card))) def menu(): print("What do you want to do?") print("Options: verify | vendor | checksum | generate | test | exit") action = input(">>> ") if action in actions: print() actions[action]() print() menu() def vendor_interactive(): print("Please enter a credit card number: ") n = input(">>> ") try: n = int(n) except ValueError: print("Not a number!") return print(n) v = vendor(n, vendors_from_inn) if not verify(n): print("Invalid credit card number!") return if v is not None: print("The vendor is: {}".format(v)) else: print("I do not know of this inn!") def verify_interactive(): print("Please enter a credit card number: ") n = input(">>> ") try: n = int(n) except ValueError: print("Not a number!") return if verify(n): print("Valid!") else: print("This credit card is invalid!") def checksum_interactive(): print("Please enter a credit card number with no checksum: ") n = input(">>> ") try: n = int(n) except ValueError: print("Not a number!") return print(checksum(n)) def generate_interactive(): vs = list(vendors.keys()) print("Please select one of our vendors:") vendors_list = ["\n ({}) {}".format(i, v) for i, v in enumerate(vs)] print(reduce(concat, vendors_list)) print() try: v = vs[int(input('>>> '))] except ValueError: print("Not a number!") return except IndexError: print("Not in the list!") return print("Credit card number: {}".format(generate(v, vendors))) actions = { "menu": menu, "verify": verify_interactive, "vendor": vendor_interactive, "checksum": checksum_interactive, "generate": generate_interactive, "test": test, "exit": exit} menu()
04f0a7a61793df1a7b5304a352904b8c93cd99a0
akshayrana30/Data-Structures-and-Algorithms
/#1 LeetCode/121. Best Time to Buy and Sell Stock.py
613
3.5625
4
# Runtime: 64 ms, faster than 57.57% of Python3 online submissions for Best Time to Buy and Sell Stock. # Memory Usage: 13.8 MB, less than 98.85% of Python3 online submissions for Best Time to Buy and Sell Stock. class Solution: def maxProfit(self, prices: List[int]) -> int: minimum = float("inf") profit = 0 for i in range(len(prices)): if prices[i]<minimum: minimum = prices[i] elif ((prices[i]-minimum) > profit): profit = prices[i] - minimum return profit
47576f0ad4403c9395369466d093926e442e3785
JohnGoods/Python
/PythonProject/Study/007_For.py
511
3.703125
4
name = "jiangjianghao" sum = 0 for s in name: print(s) for i in range(101): sum = sum + i print(i) if i == 100: print("sum---->%d"%sum) #练习题 print("=====================") s = 'Hello World!' print(s) print("=====================") reSult = s[::-1] print(reSult) print("=====================") newSult = "" max_index = len(reSult)-1 for index,value in enumerate(reSult): #print(index,value) newSult += reSult[max_index - index] print(newSult) print("=====================")
4fe23aaa7f88b443842c5842c59de5bd79e0d0eb
xiaomojie/LeetCode
/Math/264_Ugly_Number_II.py
807
4.09375
4
""" Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. Example: Input: n = 10 Output: 12 Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note: 1 is typically treated as an ugly number. n does not exceed 1690. """ class Solution: # time limited def nthUglyNumber1(self, n): """ :type n: int :rtype: int """ res = 0 while n: res += 1 num = res factors = [2, 3, 5] for f in factors: while num % f == 0: num /= f if num == 1: n -= 1 return res def nthUglyNumber(self, n): print(Solution().nthUglyNumber(406))
cd76c3e4b9e68c819af94ada3748517f898398cf
KeithQuinn/Programming_and_Scripting_Project_2020
/analysis.py
15,242
3.6875
4
#import libraries, keeping all together at the top of the code import pandas as pd # read CSV file import matplotlib.pyplot as plt # for plots import seaborn as sns # for pair plots from scipy import stats # for normality check # read in data from file and set up as dataframe df = pd.read_csv("Fishers IRIS Data Set.csv") # defining variables sepalwidth = df["sepal_width"] sepallength = df["sepal_length"] petalwidth = df["petal_width"] petallength = df["petal_length"] species = df["species"] #============================================= data check ============================================== # check the dataset to ensure there are 5 variables and 150 rows of data print("IRIS Data Set:") print("") print(df.loc[:, df.columns != 'Count']) # Count is included in the data set for single variable scatter # plots. Single variable scatter plots are plotted in univariate analysis, want to ignore "Count" for now. print(""" ========================================================================================================== """) # The line of === is to make the output easier to read. print("The number of each species is: ") print(df["species"].value_counts()) # counting the number of each species, should be 50 of each. # ignoring "Count" as explained above. print(""" ========================================================================================================== """) #=========================================== data summary ============================================== # to output a summary of each variable to a single txt file. As explained previously there is a "Count" # column in the data set which has to be ignored here. The method here was to set up a second # dataframe (df2) and only include the columns of interest from the original dataframe (df). df2 = df[["sepal_width", "sepal_length", "petal_length", "petal_width", "species"]] summary = df2.describe() # provides a summary of the data print("A summary of the data by variable is provided:") print("") print(summary) with open("summary_of_variables.txt", "w") as f: f.write(summary.to_string()) # convert to string to write to text file. #========================== checking if data follows a normal distribution ========================== shapiro_test_sepal_width = (stats.shapiro(sepalwidth)) # defining the variables for the Shapiro-Wilk test. shapiro_test_sepal_length = (stats.shapiro(sepallength)) shapiro_test_petal_width = (stats.shapiro(petalwidth)) shapiro_test_petal_length = (stats.shapiro(petallength)) #shapiro returns the test statistic and the p-value, only interested in the p-value and it's located #at the second poision in the list, position [1]. If the p-value is greater than 0.05 the data is normal. if (shapiro_test_sepal_width[1]) >= 0.05: print("Sepal Width is Normally Distributed") else: print("Sepal Width is not Normally Distributed") print(""" """) # Making it easier to read in the output terminal if (shapiro_test_sepal_length[1]) >= 0.05: print("Sepal Lenght is Normally Distributed") else: print("Sepal Lenght is not Normally Distributed") print(""" """) if (shapiro_test_petal_width[1]) >= 0.05: print("Petal Width is Normally Distributed") else: print("Petal Width is not Normally Distributed") print(""" """) if (shapiro_test_petal_length[1]) >= 0.05: print("Petal Length is Normally Distributed") else: print("Petal Length is not Normally Distributed") print(""" ========================================================================================================== """) #================ histograms as part of univariate analysis ================ plt.figure(figsize=(12,8)) plt.hist(sepalwidth, bins = 20, rwidth = 0.9) plt.title("Sepal_Width") plt.xlabel("Measurment in cm") plt.ylabel("Observations") plt.savefig("Sepal_Width_Hist") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.hist(sepallength, bins = 20, rwidth = 0.9) plt.title("Sepal_Length") plt.xlabel("Measurment in cm") plt.ylabel("Observations") plt.savefig("Sepal_Length_Hist") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.hist(petalwidth, bins = 20, rwidth = 0.9) plt.title("Petal_Width") plt.xlabel("Measurment in cm") plt.ylabel("Observations") plt.savefig("Petal_Width_Hist") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.hist(petallength, bins = 20, rwidth = 0.9) plt.title("Petal_Length") plt.xlabel("Measurment in cm") plt.ylabel("Observations") plt.savefig("Petal_Length_Hist") plt.show(block=False) plt.pause(4) plt.close("all") #================ boxplots as part of univariate analysis ================ plt.figure(figsize=(12,8)) sns.set(style="whitegrid") ax = sns.boxplot(x=species, y = sepalwidth) plt.title("sepal_width_boxplot") plt.savefig("sepal_width_boxplot") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) ax = sns.boxplot(x=species, y = sepallength) plt.title("sepal_length_boxplot") plt.savefig("sepal_length_boxplot") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) ax = sns.boxplot(x=species, y = petalwidth) plt.title("petal_width_boxplot") plt.savefig("petal_width_boxplot") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) ax = sns.boxplot(x=species, y = petallength) plt.title("petal_length_boxplot") plt.savefig("petal_length_boxplot") plt.show(block=False) plt.pause(4) plt.close("all") #================ single variable scatter plots as part of univariate analysis ================ # setting up a setosa_df, virginica_df and a versicolor_df. setosa_df = df[df["species"] == "setosa"] countset = setosa_df["Count"] sepalwidthset = setosa_df["sepal_width"] sepallengthset = setosa_df["sepal_length"] petalwidthset = setosa_df["petal_width"] petallengthset = setosa_df["petal_length"] virginica_df = df[df["species"] == "virginica"] countvir = virginica_df["Count"] sepalwidthvir = virginica_df["sepal_width"] sepallengthvir = virginica_df["sepal_length"] petalwidthvir = virginica_df["petal_width"] petallengthvir = virginica_df["petal_length"] versicolor_df = df[df["species"] == "versicolor"] countver = versicolor_df["Count"] sepalwidthver = versicolor_df["sepal_width"] sepallengthver = versicolor_df["sepal_length"] petalwidthver = versicolor_df["petal_width"] petallengthver = versicolor_df["petal_length"] # Plotting scatter plots, with each only having one of the four variables of interest. # Using "Count" as the second variable. This is why count is included in the dataset. # Part of univariate analysis is to compare one variable at a time for the three species. plt.figure(figsize=(12,8)) plt.scatter(countset,sepalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(countvir,sepalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(countver,sepalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_width_scatter") plt.xlabel("") plt.ylabel("Sepal_Width") plt.legend() plt.savefig("sepal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(countset,sepallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(countvir,sepallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(countver,sepallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_length_scatter") plt.xlabel("") plt.ylabel("Sepal_Length") plt.legend() plt.savefig("sepal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(countset,petalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(countvir,petalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(countver,petalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_width_scatter") plt.xlabel("") plt.ylabel("Petal_Width") plt.legend() plt.savefig("petal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(countset,petallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(countvir,petallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(countver,petallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_length_scatter") plt.xlabel("") plt.ylabel("Petal_Length") plt.legend() plt.savefig("petal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) #================ scatter plots as part of multivariate analysis ================ plt.figure(figsize=(12,8)) plt.scatter(sepalwidthset,sepallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepalwidthvir,sepallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepalwidthver,sepallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_width_sepal_length_scatter") plt.xlabel("Sepal_Width") plt.ylabel("Sepal_Length") plt.legend() plt.savefig("sepal_width_sepal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(sepalwidthset,petallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepalwidthvir,petallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepalwidthver,petallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_width_petal_length_scatter") plt.xlabel("Sepal_Width") plt.ylabel("Petal_Length") plt.legend() plt.savefig("sepal_width_petal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(sepalwidthset,petalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepalwidthvir,petalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepalwidthver,petalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_width_petal_width_scatter") plt.xlabel("Sepal_Width") plt.ylabel("Petal_Width") plt.legend() plt.savefig("sepal_width_petal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(sepallengthset,sepalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepallengthvir,sepalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepallengthver,sepalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_length_sepal_width_scatter") plt.xlabel("Sepal_Length") plt.ylabel("Sepal_Width") plt.legend() plt.savefig("sepal_length_sepal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(sepallengthset,petalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepallengthvir,petalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepallengthver,petalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_length_petal_width_scatter") plt.xlabel("Sepal_Length") plt.ylabel("Petal_Width") plt.legend() plt.savefig("sepal_length_petal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(sepallengthset,petallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(sepallengthvir,petallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(sepallengthver,petallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("sepal_length_petal_length_scatter") plt.xlabel("Sepal_Width") plt.ylabel("Petal_Length") plt.legend() plt.savefig("sepal_length_petal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petalwidthset,petallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petalwidthvir,petallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petalwidthver,petallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_width_petal_length_scatter") plt.xlabel("Petal_Width") plt.ylabel("Petal_Length") plt.legend() plt.savefig("petal_width_petal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petalwidthset,sepallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petalwidthvir,sepallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petalwidthver,sepallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_width_sepal_length_scatter") plt.xlabel("Petal_Width") plt.ylabel("Sepal_Length") plt.legend() plt.savefig("petal_width_sepal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petalwidthset,sepalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petalwidthvir,sepalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petalwidthver,sepalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_width_sepal_width_scatter") plt.xlabel("Petal_Width") plt.ylabel("Sepal_Width") plt.legend() plt.savefig("petal_width_sepal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petallengthset,petalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petallengthvir,petalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petallengthver,petalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_length_petal_width_scatter") plt.xlabel("Petal_Length") plt.ylabel("Petal_Width") plt.legend() plt.savefig("petal_length_petal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petallengthset,sepalwidthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petallengthvir,sepalwidthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petallengthver,sepalwidthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("petal_length_sepal_width") plt.xlabel("Petal_Length") plt.ylabel("Sepal_Width") plt.legend() plt.savefig("petal_length_sepal_width_scatter") plt.show(block=False) plt.pause(4) plt.close("all") plt.figure(figsize=(12,8)) plt.scatter(petallengthset,sepallengthset, s=12, color=["red"], marker="*", label = "setosa") plt.scatter(petallengthvir,sepallengthvir, s=12, color=["blue"], marker="x", label = "virginica") plt.scatter(petallengthver,sepallengthver, s=12, color=["green"], marker="o", label = "versicolor") plt.title("IRIS Data Set") plt.xlabel("Petal_Length") plt.ylabel("Sepal_Length") plt.legend() plt.savefig("petal_length_sepal_length_scatter") plt.show(block=False) plt.pause(4) plt.close("all") #================ Seaborn pairplot scatter plots as part of univariate analysis ================ sns.pairplot(df2, hue = "species") plt.savefig("pairplot") plt.show(block=False) plt.pause(14) plt.close("all")
4732e17e6f91fc5f0f7d8affee379ae136e72f47
zachMitchell/pythonClass
/classes/answer.py
1,839
3.921875
4
#This is one possible answer to this mission. Get creative and build your own! :D #If you still want to solve this for yourself; look away!! class house(object): def __init__(self,name,price): self.name="" #Search through the string and find the name: for word in name.split(" "): if not word == "The" and not word == "house": self.name=word break self.price=price self.total=0 self.items=[] self.bedrooms = [] def getMaterials(self,materialList): if len(self.items) > 0: self.items = [] tempPrice = self.price #The Priciest item you can buy; this is the key for the materialList while not tempPrice == 0: mostExpensiveItem = "" #Let's figure out the most expensive item we can purchase, then buy from there for material in materialList: # print(material) if ( mostExpensiveItem=="" or materialList[material] > materialList[mostExpensiveItem]) and tempPrice >= materialList[material]: mostExpensiveItem = material #If we can't purchase anything, we can't just run this again, it will be an error! if mostExpensiveItem == "" or materialList[mostExpensiveItem] > tempPrice: break else: tempPrice-=materialList[mostExpensiveItem] self.total+=materialList[mostExpensiveItem] self.items.append(mostExpensiveItem) #Fill in our list of bedrooms with True for boys, and False for girls: def makeBedrooms(self,boys,girls): boyOrGirl = True for bg in [boys,girls]: for i in range(bg): self.bedrooms.append(boyOrGirl) boyOrGirl = False
9dd2477c3cae31639bbcb72c81653f0d70e5772e
mahatmaWM/leetcode
/leetcode/editor/cn/703.数据流中的第K大元素.py
2,208
3.640625
4
# # @lc app=leetcode.cn id=703 lang=python3 # # [703] 数据流中的第K大元素 # # https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/description/ # # algorithms # Easy (43.92%) # Likes: 135 # Dislikes: 0 # Total Accepted: 22.5K # Total Submissions: 50.6K # Testcase Example: '["KthLargest","add","add","add","add","add"]\n' + '[[3,[4,5,8,2]],[3],[5],[10],[9],[4]]' # # 设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。 # # 你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 # KthLargest.add,返回当前数据流中第K大的元素。 # # 示例: # # # int k = 3; # int[] arr = [4,5,8,2]; # KthLargest kthLargest = new KthLargest(3, arr); # kthLargest.add(3);   // returns 4 # kthLargest.add(5);   // returns 5 # kthLargest.add(10);  // returns 5 # kthLargest.add(9);   // returns 8 # kthLargest.add(4);   // returns 8 # # # 说明: # 你可以假设 nums 的长度≥ k-1 且k ≥ 1。 # # # @lc code=start import heapq class KthLargest: # 使用Python的堆是小根堆,不需要对其进行转换。 # 如果一个堆的大小是k的话,那么最小的数字就在其最前面(即为第k大的数字),只要维护当新来的数字和最前面的这个数字比较即可。 # 所以我们的工作就是维护一个小根堆,这个小根堆保存的是从第K大的数字到最大的数字。 # 堆的大小即为K。 def __init__(self, k: int, nums: List[int]): self.pool = nums self.size = len(self.pool) self.k = k heapq.heapify(self.pool) while self.size > k: heapq.heappop(self.pool) self.size -= 1 def add(self, val: int) -> int: if self.size < self.k: heapq.heappush(self.pool, val) self.size += 1 elif val > self.pool[0]: heapq.heapreplace(self.pool, val) return self.pool[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val) # @lc code=end
4a5ab7196046ee86a307596673b4b15aea94fffa
sknaht/algorithm
/python/sort/merge-k-sorted-lists.py
1,352
3.921875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class Solution: # @param {ListNode[]} lists # @return {ListNode} def mergeKLists(self, lists): return self.merge(0, len(lists) - 1, lists) def merge(self, start, end, lists): if start > end: return None if start == end: return lists[start] mid = (start + end) / 2 left = self.merge(start, mid, lists) right = self.merge(mid + 1, end, lists) tmp = ListNode(-1) curr = tmp while left and right: if left.val < right.val: curr.next = left left = left.next curr = curr.next else: curr.next = right right = right.next curr = curr.next if left: curr.next = left if right: curr.next = right return tmp.next x = ListNode(0) x.next = ListNode(5) a = [ ListNode(1), ListNode(4), ListNode(3), x ] print Solution().mergeKLists(a)
57a30f76ddd2e67df43e1ff11314a3772b7813d8
mifusuzuki/decision-tree
/classification.py
8,826
4.0625
4
############################################################################# # 60012: Introduction to Machine Learning # Coursework 1 Skeleton code # Prepared by: Josiah Wang # # Your tasks: Complete the fit(), predict() and prune() methods of # DecisionTreeClassifier. You are free to add any other methods as needed. ############################################################################## import numpy as np import math class Split(): def __init__(self, col, val): self.col = col self.val = val class Node(): def __init__(self, left, right, split): self.is_leaf = False self.split = split self.left_child = left # less than val self.right_child = right # greater or equal to val def get_next_node(self, single_row): if single_row[self.split.col] < self.split.val: return self.left_child return self.right_child class Leaf(): def __init__(self, label): self.is_leaf = True self.label = label class DecisionTreeClassifier(object): """ Basic decision tree classifier Attributes: is_trained (bool): Keeps track of whether the classifier has been trained Methods: fit(x, y): Constructs a decision tree from data X and label y predict(x): Predicts the class label of samples X prune(x_val, y_val): Post-prunes the decision tree """ def __init__(self): self.is_trained = False self.tree_root = None def calc_entropy(self, y): entropy = 0 unique_label, freq = np.unique(y, return_counts=True) total = sum(freq) #print(unique_label, freq) #print(freq, total) for i, (label, freq) in enumerate(zip(unique_label, freq)): entropy += -(freq/total)*math.log(freq/total, 2) return entropy def partition(self, x, y, split): col = split.col val = split.val # partition #left_x = x[x[:, col] < val, :] # using masking #print(left_x) #right_x = x[x[:, col] >= val, :] #print(right_x) # left indices = np.where(x[:,col] < val) left_x = x[indices] left_y = y[indices] # right indices = np.where(x[:,col] >= val) right_x = x[indices] right_y = y[indices] return left_x,left_y, right_x, right_y def calc_info_gain(self, x, y, split): left_x,left_y, right_x, right_y = self.partition(x, y, split) # calc entropy left_entropy = self.calc_entropy(left_y) #print('left entropy = ', left_entropy) right_entropy = self.calc_entropy(right_y) #print('right entropy = ', right_entropy) original_entropy = self.calc_entropy(y) #print('original entropy = ', original_entropy) # calc information gain average_of_left_and_right_entropy = len(left_y)/len(y)*left_entropy + len(right_y)/len(y)*right_entropy info_gain = original_entropy - average_of_left_and_right_entropy return info_gain def find_optimal_split(self, x, y): optimal_split = None max_info_gain = 0 seen = {} for row in range(len(x)): for col in range(len(x[0])): val = x[row][col] if col in seen and val in seen[col]: continue if col not in seen: seen[col] = [] seen[col].append(val) # mark as seen split = Split(col, val) # create split info_gain = self.calc_info_gain(x, y, split) #print('info gain = ', info_gain, ' col = ', col, ' val = ', val) if info_gain > max_info_gain: max_info_gain = info_gain optimal_split = split return max_info_gain, optimal_split def build_tree(self, x, y): info_gain, split = self.find_optimal_split(x, y) if info_gain == 0: #print('Leaf reached') return Leaf(y[0]) # Returns the first element since they are all the same - IS THIS TRUE THO?? #print('optimal info gain = ', info_gain, ' col = ', split.col, ' val = ', split.val) left_x,left_y, right_x, right_y = self.partition(x, y, split) left_child = self.build_tree(left_x, left_y) right_child = self.build_tree(right_x, right_y) return Node(left_child, right_child, split) def fit(self, x, y): """ Constructs a decision tree classifier from data Args: x (numpy.ndarray): Instances, numpy array of shape (N, K) N is the number of instances K is the number of attributes y (numpy.ndarray): Class labels, numpy array of shape (N, ) Each element in y is a str """ # Make sure that x and y have the same number of instances assert x.shape[0] == len(y), \ "Training failed. x and y must have the same number of instances." ####################################################################### # ** TASK 2.1: COMPLETE THIS METHOD ** ####################################################################### # build a tree and assign the returned root to self.tree_root self.tree_root = self.build_tree(x, y) # set a flag so that we know that the classifier has been trained self.is_trained = True def find_label(self, instance, cur_node): if cur_node.is_leaf: return cur_node.label next_node = cur_node.get_next_node(instance) return self.find_label(instance, next_node) def predict(self, x): """ Predicts a set of samples using the trained DecisionTreeClassifier. Assumes that the DecisionTreeClassifier has already been trained. Args: x (numpy.ndarray): Instances, numpy array of shape (M, K) M is the number of test instances K is the number of attributes Returns: numpy.ndarray: A numpy array of shape (M, ) containing the predicted class label for each instance in x """ # make sure that the classifier has been trained before predicting if not self.is_trained: raise Exception("DecisionTreeClassifier has not yet been trained.") # set up an empty (M, ) numpy array to store the predicted labels # feel free to change this if needed predictions = np.zeros((x.shape[0],), dtype=np.object) ####################################################################### # ** TASK 2.2: COMPLETE THIS METHOD ** ####################################################################### # Investigate one row at a time for i, row in enumerate(x): predictions[i] = self.find_label(row, self.tree_root) # remember to change this if you rename the variable return predictions def prediction_accuracy(self, y_gold, y_prediction): assert len(y_gold) == len(y_prediction) try: return np.sum(y_gold == y_prediction) / len(y_gold) except ZeroDivisionError: return 0 return correct/total def prune(self, x_val, y_val): """ Post-prune your DecisionTreeClassifier given some optional validation dataset. You can ignore x_val and y_val if you do not need a validation dataset for pruning. Args: x_val (numpy.ndarray): Instances of validation dataset, numpy array of shape (L, K). L is the number of validation instances K is the number of attributes y_val (numpy.ndarray): Class labels for validation dataset, numpy array of shape (L, ) Each element in y is a str """ # make sure that the classifier has been trained before predicting if not self.is_trained: raise Exception("DecisionTreeClassifier has not yet been trained.") ####################################################################### # ** TASK 4.1: COMPLETE THIS METHOD ** #######################################################################
dd217b7cdd858e5cc24ca39a2e3a02241259366d
anjanibox/myPythonProjects
/ML-OpenLearning01.py
2,448
3.5625
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 8 16:03:10 2020 @author: Tomatobox """ #Import Libraries # Import Python libraries for data manipuation and visualization import pandas as pd import numpy as np import matplotlib.pyplot as pyplot # Import the Python machine learning libraries we need from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score import sklearn.tree as tree import pydotplus from sklearn.externals.six import StringIO from IPython.display import Image from functions import boxPlotAll from functions import histPlotAll from functions import viewDecisionTree from functions import classComparePlot #1. Define the Task #Remember the task:Use life expectancy and long-term unemployment rate to predict the perceived happiness (low or high) of inhabitants of a country. #2. Load the data set dataset = pd.read_csv("C:\\Tomato-BS\\DevOps\\python-scripts\\world_data_really_tiny.csv") #3. Understand the Data #3.1 Inspect the Data #3.1.1 Inspect first few rows print(dataset.head(12)) #3.1.2 Inspect data shape dataset.shape print(dataset.shape) #3.1.3 Inspect descriptive stats print(dataset.describe()) #3.2 Visualize the Data #3.2.1 View univariate histgram plots histPlotAll(dataset) #3.2.2 View univariate box plots boxPlotAll(dataset) #3.2.3 View class split classComparePlot(dataset[["happiness","lifeexp","unemployment"]], 'happiness', plotType='hist') #4. Prepare the Data for Supervised Machine Learning #4.1 Select Features and Split Into Input and Target Features y = dataset["happiness"] X = dataset[["lifeexp","unemployment"]] print(X.head()) print(y.head()) #5. Build a Model #5.1 Split Into Training and Test Sets test_size = 0.33 seed = 7 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed) print(X_train) print(X_test) print(y_train) #5.2 Select an Algorithm model = DecisionTreeClassifier() #5.3 Fit the Model to the Data model.fit(X_train, y_train) #print(model.fit) #5.4 Check the Model predictions = model.predict(X_train) #print(predictions) #print(accuracy_score(y_train, predictions)) #6. Evaluate the Model #6.1 Compute Accuracy Score predictions = model.predict(X_test) #print(predictions) #print(accuracy_score(y_test, predictions)) #df = X_test.copy() #df['Actual'] = y_test #df['Prediction'] = predictions print(viewDecisionTree(model, X.columns))
ce38c009a605b1da57c5f43c49af247e902e6c47
PiMastah/aoc_2020
/02/index.py
645
3.5625
4
import sys my_file = open("input.txt", "r") content_list = my_file.read().split('\n') def is_valid_1(s, l, low, high): c = sum([1 for x in s if x == l]) return low <= c and c <= high def is_valid_2(s, l, low, high): return (s[low-1] == l) != (s[high-1] == l) def validate(s, mode=1): val, st = s.split(': ') lims, letter = val.split(' ') low, high = lims.split('-') low = int(low) high = int(high) fn = is_valid_1 if mode == 1 else is_valid_2 return fn(st, letter, low, high) print("PART 1: {}".format(sum([1 for x in content_list if validate(x)]))) print("PART 2: {}".format(sum([1 for x in content_list if validate(x, 2)])))
b11ca5bbffe18bc61fb1ab37531f6e54372606a4
pankajjha85/Python
/FactorialRecursion.py
447
4.5625
5
# An example of a recursive function to # find the factorial of a number def CalculateFactorial(prm_input): """This is a recursive function to find the factorial of an integer""" if prm_input == 1: return 1 else: return (prm_input * CalculateFactorial(prm_input-1)) num = int(input('Please enter the number to calculate the Factorial.')) print("The Factorial of", num, "is", CalculateFactorial(num))
541c7f9932ce3cd3d53880cca39f8fe143cc825b
dagasheva01/py
/string_functions.py
619
3.5
4
# palindrome # anagram s = "Hello, my name is Dauren 12425." s = s.upper() s = s.lower() l = s.split() first_word = l[0] last_word = l[-1] print(first_word) print(last_word) s = s.replace(",", "") ll = [] for c in s: if c.isalpha() or c == ' ': ll.append(c) s = "".join(ll) print(s) s1 = 'Dauren' s2 = 'Neruad' s1 = s1.lower() s2 = s2.lower() if len(s1) == len(s2): l1 = [] l2 = [] for c in s1: l1.append(c) for c in s2: l2.append(c) l1 = sorted(l1) l2 = sorted(l2) ok = True for i in range(0, len(l1), 1): if l1[i] != l2[i]: ok = False break print(ok)
6411c1fabc63423099533164942d32a848cfdf8a
rasfivtay/zoo_booking
/src/webapp/helpers/geo_helper.py
449
3.578125
4
import math from dataclasses import dataclass @dataclass class Point: lat: float lon: float def distance(point1: Point, point2: Point): lon1, lat1, lon2, lat2 = map( math.radians, [point1.lon, point1.lat, point2.lon, point2.lat] ) return 6371 * ( math.acos( math.sin(lat1) * math.sin(lat2) + math.cos(lat1) * math.cos(lat2) * math.cos(lon1 - lon2), ) )
4344768b3251f7eac9fa76f92224f002ea875991
wuruthie/CodingExercises
/counting_inversions.py
1,125
4.34375
4
count = 0 def merging(first_array, second_array): i = 0 j = 0 global count sorted_array = [] # while both arrays are non-empty while i < len(first_array) and j < len(second_array): if first_array[i] < second_array[j]: sorted_array.append(first_array[i]) i = i + 1 else: sorted_array.append(second_array[j]) count += len(first_array[i:]) j = j + 1 # when one array becomes empty if i == len(first_array): sorted_array.extend(second_array[j:]) else: sorted_array.extend(first_array[i:]) return sorted_array, count """ Here you can define functions you want to use within function counting_inversions(array). """ def counting_inversions(array): """ Please put your code here. """ if len(array) is 1: return array, 0 #because no inversions #else...resursively sort middle = len(array) / 2 left = counting_inversions(array[:middle])[0] #there's a lot of mess here. make it zero to ignore the inversions in between right = counting_inversions(array[middle:])[0] sortedlist = merging(left,right) return sortedlist A = [2,1,5,3] # print the num print counting_inversions(A)
7ca6010205f7245c3880ad58488e7e41e90540ed
yankunsam/learning
/python/function/oop.py
774
3.96875
4
#!/usr/bin/python class Employee: 'Common base class for all employee' empCount = 0 #bahavior def __init__(self,name,salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name :",self.name, ",Salary: ",self.salary emp1 = Employee("god",1) emp2 = Employee("wade",10000000000) emp3 = Employee("kobe",3); setattr(emp3,'age',41) print "emp3 age:",getattr(emp3,'age') print "emp2 age:" ,hasattr(emp2,'age') print "emp3 age:",hasattr(emp3,'age') delattr(emp3, 'age') print "emp3 age:",hasattr(emp3,'age') emp1.displayEmployee() emp2.displayEmployee() print "Employee.__doc__",Employee.__doc__
70c79e8f65ba210eafd230c1099227032bc53c0f
Abhishek1004/Binary-Search-2
/peak_element.py
478
3.796875
4
class Solution: def findPeakElement(self, nums: List[int]) -> int: def binarySearch(nums, start, end): mid = (start + end)//2 if start == end or nums[mid] > max(nums[mid-1], nums[mid+1]): return mid if nums[mid+1] > nums[mid]: return binarySearch(nums, mid+1, end) else: return binarySearch(nums, start, mid-1) return binarySearch(nums, 0, len(nums)-1) #time complexity - O(logn) for binary search #space complexity - O(1) #all testcases passed
2d32cee67f73d590a6f0e5842a745601246edbd4
venkatesh799/python
/List to list tuple with cubes.py
119
3.671875
4
# list to list of tuple with cubes l=[1,2,3] l2=[(val,pow(val,3)) for val in l] print(l2) #[(1, 1), (2, 8), (3, 27)]
56ea78503229a3d80a9ac17b8e0d6f1f77a7f8df
i0Ek3/PythonCrashCourse
/code/part1/35_car_class.py
1,236
3.953125
4
#!/usr/bin/env python # coding=utf-8 class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self,mileage): #2 if mileage >= self.odometer_reading: self.odometer_reading = mileage else: self.odometer_reading = mileage def increment_odometer(self,miles): #3 self.odometer_reading += miles my_new_car = Car('audi','a6',2017) print(my_new_car.get_descriptive_name()) my_new_car.read_odometer() # way1 to modified value of property my_new_car.odometer_reading = 23 my_new_car.read_odometer() # way2 my_new_car.update_odometer(23) my_new_car.read_odometer() # way3 my_used_car = Car('subaru','outback',2013) print(my_used_car.get_descriptive_name()) my_used_car.update_odometer(222000) print(my_used_car.read_odometer()) my_used_car.increment_odometer(100) print(my_used_car.read_odometer())
6cc06568c7cf0dd0b2a90c45afe2b72ab4d5b73b
ijaniszewski/esports
/run_from_file.py
958
3.75
4
"""Get movie id from passed argument.""" import argparse from src.main import GetInfo class GetArgument: """Get passed movie ID and get info about it via GetInfo instance.""" @staticmethod def get_argument(): """Get the movie id from argument if it is integer. Return ---------- movie_id: int Movie ID as an integer """ parser = argparse.ArgumentParser() parser.add_argument( '-m', '--movie_id', help="Please provide movie id as an integer", type=int, required=True) movie_id = parser.parse_args().movie_id return movie_id def from_file(self): """Get the movie_id as passed argument and create GetInfo object.""" movie_id = self.get_argument() get_info = GetInfo() get_info.main(movie_id) if __name__ == "__main__": ga = GetArgument() ga.from_file()
9a8373c70c01ca115d10097d054bb2c0f97a012d
deven367/Automated-Face-Recognition
/excel.py
435
3.546875
4
import xlwt from xlwt import Workbook import datetime # Workbook is created wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Sheet 1') sheet1.write(1, 0, 'ISBT DEHRADUN') sheet1.write(2, 0, 'SHASTRADHARA') sheet1.write(3, 0, 'CLEMEN TOWN') sheet1.write(4, 0, 'RAJPUR ROAD') sheet1.write(5, 0, 'CLOCK TOWER') time = datetime.datetime.now() print(time) sheet1.write(6,0, str(time)) wb.save('xlwt example.xls')
c0c7be120dc164b4d143a69f6e0b64fe7ff4a17c
salernodan/curso-python-fundamentals
/try_except/ex_convidados.py
269
3.765625
4
#!/usr/bin/python3 nomes = ['daniel', 'pedro', 'julia'] try: index = int(input("Digite um index para encontrar o convidado na lista: ")) print(nomes[index]) except IndexError as ie: print("Nao foi encontrado o convidado na lista.\nErro: {}.".format(ie))
4b24cd808a49ce6d71401a59934e93e29ce8dadf
ovravna/tdt4136
/colors/colors.py
1,151
4.09375
4
# Python program to print # colored text and background class colors: '''Colors class:reset all colors with colors.reset; two sub classes fg for foreground and bg for background; use as colors.subclass.colorname. i.e. colors.fg.red or colors.bg.greenalso, the generic bold, disable, underline, reverse, strike through, and invisible work with the main class i.e. colors.bold''' reset = '\033[0m' bold = '\033[01m' disable = '\033[02m' underline = '\033[04m' reverse = '\033[07m' strikethrough = '\033[09m' invisible = '\033[08m' class fg: black = '\033[30m' red = '\033[31m' green = '\033[32m' orange = '\033[33m' blue = '\033[34m' purple = '\033[35m' cyan = '\033[36m' lightgrey = '\033[37m' darkgrey = '\033[90m' lightred = '\033[91m' lightgreen = '\033[92m' yellow = '\033[93m' lightblue = '\033[94m' pink = '\033[95m' lightcyan = '\033[96m' class bg: black = '\033[40m' red = '\033[41m' green = '\033[42m' orange = '\033[43m' blue = '\033[44m' purple = '\033[45m' cyan = '\033[46m' lightgrey = '\033[47m' def colored(msg:str, *color): return "".join(color) + msg + colors.reset
738d52c3bd34940eea82e4a46aac40dc09aa2dea
ch2ohch2oh/leetcode233
/2.py
1,762
3.84375
4
# 2 add-two-numbers # Keywords: # linked lists # # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode() cur = head carry = 0 while l1 and l2: val = l1.val + l2.val + carry carry = val // 10 val %= 10 cur.next = ListNode(val) cur = cur.next l1 = l1.next l2 = l2.next if l2: l1 = l2 while l1: val = l1.val + carry carry = val // 10 val %= 10 cur.next = ListNode(val) cur = cur.next l1 = l1.next if carry > 0: cur.next = ListNode(carry) return head.next # A slightly better version # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # The first node is not used head = ListNode() cur = head carry = 0 while l1 or l2: val1 = 0 val2 = 0 if l1: val1 = l1.val l1 = l1.next if l2: val2 = l2.val l2 = l2.next val = val1 + val2 + carry carry = val // 10 val %= 10 cur.next = ListNode(val) cur = cur.next # Do not forget the carry bit if carry: cur.next = ListNode(carry) return head.next
8fc10d35f9fa5cced3f4939ab0d2ca50d42ab5cb
Beks667/2.7Hw
/2.7.py
1,341
4.15625
4
# class Phone : # def __init__ (self,brand,model,color): # self.brand = brand # self.model = model # self.color = color # def show (self): # print(f"{self.brand},{self.model},{self.color}") # phone = Phone("Apple", "XS", "black") # phone.show() # class Monkey: # max_age = 12 # loves_bananas = True # def climb(self): # print('I am climbing the tree') # abc = Monkey() # abc.climb() # print(abc.max_age) # abc.climb() # print(abc.loves_bananas) # Это через input---------------------------------------------------------------- # class Person: # def __init__(self,name,age,gender): # self.name = name # self.age = age # self.gender = gender # def calculate_age(self): # self.number = int(input('enter year:')) # print(self.age + self.number) # p = Person('John', 23, 'male') # p.calculate_age() # #Это через self----------------------------------------------------------------------- # class Person: # def __init__(self,name,age,gender): # self.name = name # self.age = age # self.gender = gender # def calculate_age(self,year): # self.year = year # print(self.age + self.year) # p = Person('John', 23, 'male') # p.calculate_age(10) #
28aae8cfe5a73c77d850db2f4ed93bb4b166b252
ronnie7z7z/Autumn-of-Automation-Ronit-Shukla
/Python/test1.py
1,873
3.84375
4
#Python Object-Oriented Programming class Employee: numofemps = 0 raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first +'.' + last + '@company.com' Employee.numofemps += 1 def fullname(self): return self.first +' '+ self.last def apply_raise(self): self.pay = int(self.pay*self.raise_amt) def __repr__(self): return "Employee('{}', '{}', {})".format(self.first, self.last, self.pay) def __str__(self): return '{} - {}'.format(self.fullname(), self.email) def __add__(self,other): return self.pay + other.pay @classmethod def set_raise_amt(cls,amount): cls.raise_amt = amount class Developer(Employee): raise_amt = 1.10 def __init__(self, first, last, pay, prog_lang): super().__init__(first, last, pay) self.prog_lang = prog_lang class Manager(Employee): def __init__(self, first, last, pay, employees = None): super().__init__(first, last, pay) if employees is None: self.employees = [] else : self.employees = employees def add_emp(self, emp): if emp not in self.employees: self.employees.append(emp) def remove_emp(self,emp): if emp in self.employees: self.employees.remove(emp) def print_emps(self): for emp in self.employees: print('-->', emp.fullname()) dev1 = Developer('Ronit', 'Shukla', 90000, 'Python') dev2 = Developer('Shivani', 'Shukla', 125000, 'Java') mgr1 = Manager('Ulrich', ' Nielsen', 3000000, [dev1]) # print(dev1) print(dev1+dev2) # print(repr(dev1)) # print(str(dev1)) # print(dev1.pay) # dev1.apply_raise() # print(dev1.pay) # print(emp1.email) # print(emp2.email)
366ebb1a44028050ee1044922abcff7ff7ee369d
MSquared88/Intro-Python-I
/src/13_file_io.py
926
4.21875
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # YOUR CODE HERE # assign a variable to the file and open it with r to # read only text_file = open("foo.txt", "r") # print the file contents with the read method print(text_file.read()) #always close the file so there is no unused memory text_file.close() # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain # YOUR CODE HERE f = open("bar.txt", "w+") for i in range(3): f.write(f"this is a line {i+1}\n") f.close()
d5123d2438c8bfbc0d67dc857fe8fef99f2599ac
DPNT-Sourcecode/FIZ-lsfx01
/lib/solutions/FIZ/fizz_buzz_solution.py
812
3.828125
4
# noinspection PyUnusedLocal import re def fizz_buzz(number): #conver to string to use find str_num = str(number) #find 3 in string three = re.findall('3', str_num) #find 5 in string five = re.findall('5', str_num) message = "" #fizz buzz logic if (number % 3 == 0) or (three): message = "fizz " if (number % 5 == 0) or (five): message += "buzz " #deluxe logic if ((number % 3 == 0) and (three)) or ((number % 5 == 0) and (five)): #if even then deluxe else fake deluxe if (number % 2 == 0): message += "deluxe" else: message += "fake deluxe" #None of the above then is a plain number if message == "": message = str_num return message.strip()
e638264a26508580180a40f8af5c41218b7b5c1f
AndrewMiranda/holbertonschool-machine_learning-1
/supervised_learning/0x06-keras/8-train.py
1,855
3.71875
4
#!/usr/bin/env python3 """File that contains the function train_model""" import tensorflow.keras as K def train_model(network, data, labels, batch_size, epochs, validation_data=None, early_stopping=False, patience=0, learning_rate_decay=False, alpha=0.1, decay_rate=1, save_best=False, filepath=None, verbose=True, shuffle=False): """ Function That trains a model using mini-batch gradient descent Args: network is the model to train data is a numpy.ndarray of shape (m, nx) containing the input data labels is a one-hot numpy.ndarray of shape (m, classes) containing the labels of data batch_size is the size of the batch used for mini-batch gradient descent epochs is the number of passes through data for mini-batch gradient descent validation_data is the data to validate the model with, if not None """ def learning_rate_decay(epoch): """Function tha uses the learning rate""" alpha_0 = alpha / (1 + (decay_rate * epoch)) return alpha_0 callbacks = [] if validation_data: if early_stopping: early_stop = K.callbacks.EarlyStopping(patience=patience) callbacks.append(early_stop) if learning_rate_decay: decay = K.callbacks.LearningRateScheduler(learning_rate_decay, verbose=1) callbacks.append(decay) if save_best: save = K.callbacks.ModelCheckpoint(filepath, save_best_only=True) callbacks.append(save) train = network.fit(x=data, y=labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, callbacks=callbacks, verbose=verbose, shuffle=shuffle) return train