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
ecdf1624163912b3901c912e17528ebed0301a8b
lanhybrid/Python_Basics
/CursoEmVideo/064_sumStop.py
507
4.03125
4
num = 0 sum = 0 cont = 0 flag = 'S' maior = 0 menor = 0 while flag in 'Ss': num = int(input('Digite um número para somar: ')) if cont == 0: maior = num menor = num elif num > maior: maior = num elif num < menor: menor = num sum += num cont += 1 flag = input('Continuar? [S/N]') print(f'Você entrou entrou {cont} números, com soma de {sum}\n' f'O maior númereo foi {maior} e o menor foi {menor}\n' f'A média foi {sum/cont:.2f}')
e5c0f355f6a14af884363c0d2b057a87b3a21183
andywu1998/A-Byte-of-Python
/str_format.py
614
4.21875
4
#print("hello world")#注意到print是一个函数 age=20 name='Swaroop' country='America' print('{0} was {1} years old when he wrote this book in {2}'.format(name,age,country)) print('why is {0} playing with that python?'.format(name)) #对于浮点数'0.333'保留小数点(.)后三位 print('{0:.3f}'.format(1.0/3)) #使用下标填充文本,并保持文字处于中间位置 #使用(^)定义'__hello___'字符串长度为11 print('{0:_^11}'.format('hello')) print('{name} wrote {book}'.format(name='Swaroop',book='A byte of Python')) print('what\'s your name?') print(r"Newlines are indicated by \n")
4a14ce8576ec62731716d6251d06bb32d8b59d02
lareniar/Curso2018-2019DAW
/1er Trimestre/Ejercicios/estrellasNumeros.py
161
4.09375
4
x = int(input("Inserta un número")) while 0 < x: cont = x while 0 < cont: print("x", end="") cont = cont - 1 x = x - 1 print("")
e350b244a3f299380dbd774866bd3540e2ae05b1
wardmike/Rapid-Problem-Solving
/Codeforces/602B/codeforces602b.py
1,714
4
4
number = int(raw_input()) line = map(int, raw_input().split()) def find_largest_range(size, numbers): longestRange = 0 #longest range so far beginRange1 = 0 #begin of current number - 1 beginRange2 = 0 #begin of current number - 2 for x in range(1, size): if numbers[x] > numbers[x - 1] + 1: #next number is at least 2 bigger if x - beginRange2 > longestRange: longestRange = x - beginRange2 #print "longest range now " + str(longestRange) + " at position " + str(x) beginRange2 = numbers[x - 1] beginRange1 = beginRange2 elif numbers[x] > numbers[x - 1]: #next number is bigger if x - beginRange2 + 1 > longestRange: longestRange = x - beginRange2 + 1 #print "longest range now " + str(longestRange) + " at position " + str(x) beginRange2 = beginRange1 beginRange1 = numbers[x - 1] if numbers[x] < numbers[x - 1] -1: #next number is at least 2 smaller if x - beginRange2 > longestRange: longestRange = x - beginRange2 #print "longest range now " + str(longestRange) + " at position " + str(x) beginRange2 = numbers[x - 1] beginRange1 = beginRange2 elif numbers[x] < numbers[x - 1]: #next number is smaller if x - beginRange2 + 1 > longestRange: longestRange = x - beginRange2 + 1 #print "longest range now " + str(longestRange) + " at position " + str(x) beginRange2 = beginRange1 beginRange1 = numbers[x - 1] return longestRange print find_largest_range(number, line)
55fdf04aafbbd871f1afecf1f4dd55931faa66a0
bkmgit/megamol
/plugins/pbs/utils/knapsack.py
2,478
3.8125
4
# SOURCES: # https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize # https://codereview.stackexchange.com/questions/20569/dynamic-programming-solution-to-knapsack-problem import collections import functools class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if not isinstance(args, collections.Hashable): # uncacheable. a list, for instance. # better to not cache than blow up. return self.func(*args) if args in self.cache: return self.cache[args] else: value = self.func(*args) self.cache[args] = value return value def __repr__(self): '''Return the function's docstring.''' return self.func.__doc__ def __get__(self, obj, objtype): '''Support instance methods.''' return functools.partial(self.__call__, obj) def knapsack(items, maxweight): """ Solve the knapsack problem by finding the most valuable subsequence of `items` subject that weighs no more than `maxweight`. `items` is a sequence of pairs `(value, weight)`, where `value` is a number and `weight` is a non-negative integer. `maxweight` is a non-negative integer. Return a pair whose first element is the sum of values in the most valuable subsequence, and whose second element is the subsequence. >>> items = [(4, 12), (2, 1), (6, 4), (1, 1), (2, 2)] >>> knapsack(items, 15) (11, [(2, 1), (6, 4), (1, 1), (2, 2)]) """ # Return the value of the most valuable subsequence of the first i # elements in items whose weights sum to no more than j. @memoized def bestvalue(i, j): if i == 0: return 0 value, weight = items[i - 1] if weight > j: return bestvalue(i - 1, j) else: return max(bestvalue(i - 1, j), bestvalue(i - 1, j - weight) + value) j = maxweight result = [] for i in xrange(len(items), 0, -1): if bestvalue(i, j) != bestvalue(i - 1, j): result.append(items[i - 1]) j -= items[i - 1][1] result.reverse() return bestvalue(len(items), maxweight), result
991292bceb0efe007dfea8eda48afa8a9e7edbf4
shiran1992s/HW2_AI
/intro_to_AI_hw2_2020-provided-code/SearchAlgos.py
6,233
3.515625
4
""" Search Algos: MiniMax, AlphaBeta """ from utils import ALPHA_VALUE_INIT, BETA_VALUE_INIT # TODO: you can import more modules, if needed import numpy as np import copy from players import MinimaxPlayer from players import AlphabetaPlayer class SearchAlgos: def __init__(self, utility, succ, perform_move, goal): """The constructor for all the search algos. You can code these functions as you like to, and use them in MiniMax and AlphaBeta algos as learned in class :param utility: The utility function. :param succ: The succesor function. :param perform_move: The perform move function. :param goal: function that check if you are in a goal state. """ self.utility = utility self.succ = succ self.perform_move = perform_move self.goal = goal def search(self, state, depth, maximizing_player): pass class MiniMax(SearchAlgos): def search(self, state, depth, maximizing_player): """Start the MiniMax algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is a max node (True) or a min node (False). :return: A tuple: (The min max algorithm value, The direction in case of max node or None in min mode) """ # TODO: erase the following line and implement this function. # if MinimaxPlayer.Player.check_time(): # MinimaxPlayer.Player.time_ended = True # if MinimaxPlayer.Player.time_ended: # return -1 if self.goal(state, maximizing_player): val = self.utility(state), None # print(f'In Goal State ,maximizing_player={maximizing_player}, Utility value is:{val}\n') return val if depth == 0: val = MinimaxPlayer.heuristic(state), None # print(f'In Depth 0 ,maximizing_player={maximizing_player}, Heuristic value is:{val}\n') return val available_moves = MinimaxPlayer.get_moves_from_location(state, maximizing_player) max_result = float("-inf") min_result = float("inf") selected_move = None # print(f'In Depth = {depth} ,maximizing_player={maximizing_player}, available_moves:{available_moves}\n') for move in available_moves: # print(f'In Depth = {depth} ,maximizing_player={maximizing_player}, player making move:{move}\n') state.make_move(move, maximizing_player) move_value = self.search(copy.deepcopy(state), depth - 1, not maximizing_player) state.undo_move(move, maximizing_player) # print(f'In Depth = {depth} ,maximizing_player={maximizing_player}, player undoing move:{move}\n') if maximizing_player and max_result < move_value[0]: # print(f'In Depth = {depth} ,maximizing_player={maximizing_player},\n' # f'new max value is:{move_value[0]} and selected move is:{move}\n') max_result = move_value[0] selected_move = move elif not maximizing_player and min_result > move_value[0]: # print(f'In Depth = {depth} ,maximizing_player={maximizing_player},\n' # f'new min value is:{move_value[0]} and selected move is None\n') min_result = move_value[0] if maximizing_player: # print(f'In Depth = {depth} ,maximizing_player={maximizing_player},\n' # f'The selected max value is:{max_result} and selected move is:{selected_move}\n') return max_result, selected_move else: # print(f'In Depth = {depth} ,maximizing_player={maximizing_player},\n' # f'The selected min value is:{min_result} and selected move is None\n') return min_result, None class AlphaBeta(SearchAlgos): def search(self, state, depth, maximizing_player, alpha=ALPHA_VALUE_INIT, beta=BETA_VALUE_INIT): """Start the AlphaBeta algorithm. :param state: The state to start from. :param depth: The maximum allowed depth for the algorithm. :param maximizing_player: Whether this is a max node (True) or a min node (False). :param alpha: alpha value :param: beta: beta value :return: A tuple: (The min max algorithm value, The direction in case of max node or None in min mode) """ # TODO: erase the following line and implement this function. # raise NotImplementedError if self.goal(state, maximizing_player): val = self.utility(state), None # print(f'In Goal State ,maximizing_player={maximizing_player}, Utility value is:{val}\n') return val if depth == 0: val = MinimaxPlayer.heuristic(state), None # print(f'In Depth 0 ,maximizing_player={maximizing_player}, Heuristic value is:{val}\n') return val available_moves = MinimaxPlayer.get_moves_from_location(state, maximizing_player) max_result = float("-inf") min_result = float("inf") selected_move = None for move in available_moves: state.make_move(move, maximizing_player) move_value = self.search(copy.deepcopy(state), depth - 1, not maximizing_player, alpha, beta) state.undo_move(move, maximizing_player) # if move_value[0] == np.inf or move_value[0] == -np.inf: # break if maximizing_player and max_result < move_value[0]: max_result = move_value[0] selected_move = move alpha = max(move_value[0], alpha) if alpha >= beta: break # return np.inf, None elif (not maximizing_player) and (min_result > move_value[0]): min_result = move_value[0] beta = min(move_value[0], beta) if alpha >= beta: break # return -np.inf, None if maximizing_player: return max_result, selected_move else: return min_result, None
075531c2c448b0af31ef066ad1146266be850bc1
Portia-Lin/caesar-code
/RSA/rsa_decrypt.py
909
3.71875
4
import binascii def modinv(a, m): for x in range(1, m): if (a * x) % m == 1: return x return None def decrypt_block(c): m = modinv(c**d, n) if m == None: print("Немає оберненого за модулем числа для: " + str(c) + ".") return m def decrypt_string(s): return ''.join([chr(decrypt_block(ord(x))) for x in list(s)]) def hex2str(h): return binascii.unhexlify(h) result = "" s = (hex2str(input("Введіть повідомлення для розшифрування: ")).decode('utf-8')) d = int(input("Введіть закритий ключ d: ")) n = int(input("Введіть модуль n: ")) print("Зачекайте, йде процес розшифрування повідомлення . . .") for i in s: result += decrypt_string(str(i)) print("Розшифроване повідомлення: " + result)
55b77471f4e65d2baef128f5d4041c079ebaff0b
BashvitzBen/Final-Project-Ben-Bashvitz
/class_model.py
6,423
4.09375
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 16 10:13:33 2021 @author: bashv """ from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Dense, Conv2D, Activation, Flatten, MaxPooling2D class model(): #this class handles all functions that relate to creating, training and saving the models used in the program. model = None #variable model will contain the finished keras sequential model. def __init__(self): #initializes the model vaiable of the class as a keras sequential model. self.model = Sequential() def initialize_face_detection_model(self,X,y): #this function checks if the face detection model has already been trained. if it has been, it loads it into variable model. #if it has not, it adds layers to the model variable and saves it so it can later be loaded in. #input: two arrays which contain the processed images and their labels. more information in Variables Explained below. #output: adds all the layers needed for the model and saves it. also prompts the user with a few messages to make sure # he understands what is currently happening. try: self.model = load_model("ft_model") print("The face detection model has already been trained, you may proceed.") except Exception as e: print("The data is now loaded and the face detection model will start it's training process.") print("The progress of this procedure will be shown in the console.") self.add_convolutional_Layer(64, (3,3), input_shape = X.shape[1:]) self.add_convolutional_Layer(64, (3,3), input_shape = X.shape[1:]) self.add_densing_layers(64) self.train_model(X, y, 32, 10, 0.1) self.model.save("ft_model") print("The face detection model has finished it's training.") def initialize_recognition_model(self,X,y,name): #this function checks if a face recognition model for 'name' has already been trained. it it has, it loads it into variable model. #if it has not, it adds layers to the model variable and saves it so it can later be loaded in. #input: two arrays which contain the processed images and their labels # and a string name that corresopnds to the person the user wanted the model to recognise more information in Variables Explained below. #output: adds all the layers needed for the model and saves it. also prompts the user with a few messages to make sure he understands # what is currently happening. try: self.model = load_model("fr_model_"+name) print("The face recognition model for ",name," has already been trained, you may proceed.") except Exception as e: if(len(X) != 0): print("The data is now loaded and the face recognition model will start it's training process.") print("The progress of this procedure will be shown in the console.") self.add_convolutional_Layer(32,(3,3),input_shape=X.shape[1:]) self.add_convolutional_Layer(64,(3,3),input_shape=X.shape[1:]) self.add_convolutional_Layer(128,(3,3),input_shape=X.shape[1:]) self.add_densing_layers(128) self.train_model(X, y, 32, 5, 0.1) self.model.save("fr_model_"+name) print("The face recognition model has finished it's training.") else: self.model = None print("a model for this person does not exist, the program will end now.") print("make sure you train a model for this person before you test it.") def add_convolutional_Layer(self,num_filters,shape_filters,input_shape): #this function adds the following layer to the model variable: a 2d convolutional layer, #an activation function for that convolutional layer and a 2d max pooling layer. #input: integer num_filters which corresponds to the number of weights added in the convolutional layer. # tuple shape_filters which corresponds to the shape of the weights used by the convolutional layer. # tuple input_shape which tells the convolutional layer what is the size of the images it will work on. #output: adds a convolutional layer to the model self.model.add(Conv2D(num_filters,shape_filters,input_shape = input_shape)) self.model.add(Activation("relu")) self.model.add(MaxPooling2D(pool_size=(2,2))) def add_densing_layers(self,channels): #this function adds a flattening layer to the model and two densing layers and a sigmoid activation function. this will make it so the output #of the model is a single number between 0 and 1. where 1 is a positive result and 0 is a negative result. #input: an integer that describes the number of channels of the output of the last convolutional layer. it is used in the densing function to dense the output # into size 'channels'. #output: adds a flattening layer, two densing layers and a sigmoid activation function to the model. self.model.add(Flatten()) self.model.add(Dense(channels)) self.model.add(Dense(1)) self.model.add(Activation("sigmoid")) def train_model(self, X, y, batch_size, epochs, validation_split): #this function compiles the model with the right loss function, #optimizers and metrics in order to increase the accuracy of the model's predictions. #then, it trains the model using the inputed variables. #input: two arrays which contain the processed images and their labels. # two integers batch_size and epochs which tells the training function # how many images to fit per batch and how many times it need to repeat that process. #output: compiles and trains the model variable. self.model.compile(loss="binary_crossentropy", optimizer = "adam", metrics=["accuracy"]) self.model.fit(X,y,batch_size = batch_size,epochs = epochs, validation_split = validation_split)
4b0f80d03f934d585dcd64923371744211730874
iakonk/MyHomeRepos
/python/examples/leetcode/easy/reverse-words-in-a-string-iii.py
785
3.734375
4
# Runtime: 48 ms, faster than 31.54% of Python online submissions for Reverse Words in a String III. # Memory Usage: 13.9 MB, less than 9.09% of Python online submissions for Reverse Words in a String III. class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ' '.join([w[::-1] for w in s.split()]) # words = s.split() # seen = {} # for ind, w in enumerate(words): # if w not in seen: # r = ''.join([char for char in reversed(w)]) # seen[w] = r # words[ind] = seen[w] # return ' '.join(words) # ans = Solution().reverseWords("Let's take LeetCode contest") ans = Solution().reverseWords("s'a a's s'x") print(ans)
3dd355d63fed3cb8e5fec5de075958e299d17947
kanoaellis/Kattis
/jackpot.py
714
3.546875
4
def GCD(g, s): if (s == 0): return g return GCD(s, g % s) def LCM(x, y): return (x * y) // GCD(x, y) i = 0 a = int(input()) while(i < a): b = int(input()) z = [int(w) for w in input().split()] if(b == 1): t = z[0] elif(b == 2): t = LCM(z[0], z[1]) elif(b == 3): t = LCM(z[0], z[1]) t = LCM(z[2], t) elif(b == 4): t = LCM(z[0], z[1]) t = LCM(z[2], t) t = LCM(z[3], t) elif(b == 5): t = LCM(z[0], z[1]) t = LCM(z[2], t) t = LCM(z[3], t) t = LCM(z[4], t) else: break if(t > 1000000000): print('More than a billion.') else: print(t) i += 1
04b6e4ec53dee91ba5ccf370fffbd8fe03f1bd0b
harut0111/ACA
/Homework/homework_03/task2.py
283
3.515625
4
def get_frequency(li): l = len(li) res = [] for x in list(set(li)): k = 0 for y in li: if x == y: k += 1 res.append({x: k/l}) return res print(get_frequency([1,1,2,2,3])) print(get_frequency([4,4])) print(get_frequency([1,2,3]))
2b992ca8bbd413bb71769515caa5f8de7cbc0ffe
snowcloak/PYTHON
/shortestDistance.py
790
3.859375
4
data = [(1, 1), (-1, -1), (3, 4), (6, 1), (-1, -6), (-4, -3)] #simple distance formula def euclideanDistance(point1, point2): return ((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2) ** 0.5 #shortest distance algorithm #double loops, use range with len #conditional check for minDistance #update the new minDistance with the distance #preserve the points that return that distance def returnShortestDistance(points): minDistance = 99999 for i in range(len(points)-1): for j in range(i+1, len(points)): dist = euclideanDistance(points[i],points[j]) if dist < minDistance: minDistance = dist point1 = points[i] point2 = points[j] return [point1, point2] print(returnShortestDistance(data))
6cacc94b4629a8168a251016a2a7eefb269c7304
hedgehoCrow/Python_study
/language_processing/00/09.py
694
3.765625
4
#!/usr/bin/env python3 # coding: UTF-8 import random def typoglycmia(target): result = [] shuffle_list = target[1:-1] random.shuffle(shuffle_list) result.append(target[0]) result.extend(shuffle_list) result.append(target[-1]) return result def main(): sentence = "I couldn't believe that I could actually understand what I was reading : the phenomenal power of the human mind ." split_sentence = sentence.split(' ') if len(split_sentence) > 4: split_sentence = typoglycmia(split_sentence) print (split_sentence) #print (' '.join(split_sentence)) else: print (sentence) if __name__ == '__main__': main()
bfc3d14edfa7cf18aeb6e704d0a51f6c7f2fcca7
mymindhungry/python_works
/intro.py
7,328
4.3125
4
# # # print('Hello Python') # # # # x = 10 # # print('the number',format(x)) # # # ---------------------------------------- # # name = 'admin' # # age = 20 # # # # # print ('your name is : ' + (name)) # # print('your age is', format(age)) # # # # print(type(age)) # # print(type(name)) # # # ----------------------------------------- # # # # # # is is not in not in (new special operator) # # + _ * % aithmetic data types # # # # print(x + y) # # print(x - y) # # print(x * y) # # print(x % y) # # print(x ** y) # exponetial # # name = "ram karki" # # print(name.upper()) # print(dir(name)) # # -------------------------------------- # -------python data types ---------- # integer int float complex # string # boolean # sequence type list tuple dic set # # """input value of x and y to use airthmetic operators""" # x = input('enter the value of X : ') # y = input('enter the value of Y : ') # # print(x + y) # print(x - y) # print(x * y) # print(x % y) # print(x ** y) """using 3 variables in one line""" # x, y, z = "orange", "banana", "apple" # print(x) # print(y) # print(z) # as, and , break, class, continue, def, del , if, else, elif,except, global, # in , import, pass, or, not, yield, with, while,for, from, finally, # return, try, True, False, none, assert, lambda, nonlocal, raise # # ------------------------------------------------------------------ # """ Type casting for interger """ # x = int(input("Enter the value of X : ")) # y = int(input("enter the value of Y : ")) # # print("The total sum is", (x + y)) # print("Total multiplication of x adn y is :", (x * y)) # # #------------------------------------------------------------ # x = 10 # y = 20 # # if x > y: # print("x is large") # else: # print("y is large") # == > < >= <= != # # # x = input("Enter X ") # y = input("Enter Y ") # # username = x # password = y # # x = "admin" # y = "admin002" # # if x == y: # print("welcome admin") # else: # print("access denied") # username="admin" # password="admin123" # # if username=="admin" and password == "admin123": # print (f'wlecome {username}') # # else: # print ('invalid acess') # # # # """ 3 number checking """ # x = 10 # y = 20 # z = 30 # # if x > y and x > z: # print("x") # elif y > x and y > z: # print("y") # # else: # print("z") # # """ subject marks""" # # total, percentage, division,pass, or fail - HOMEWORK -1 # englis = input(" English Mark ") # # dell = int(input("Enter Dell Qty 10000")) # mac = int(input('enter mac Qty 50000')) # toshiba = int(input("enter toshiba Qty 30000")) # # delivery = input("select home/pickup") # if delivery ='home': # price = 1000 # # else # # """ Marksheet Program using conditional statements""" # # english = int(input('insert english mark : ')) # a = english # nepali = int(input('insert nepali mark : ')) # b = nepali # math = int(input('insert math mark : ')) # c = math # science = int(input('insert science mark : ')) # d = science # social = int(input('insert social mark : ')) # e = social # computer = int(input('insert computer mark : ')) # f = computer # health = int(input('insert health mark : ')) # g = health # physics = int(input('insert physics mark : ')) # h = physics # # """ for total Marks""" # t = a + b + c + d + e + f + g + h # print('Your Total Marks is : ', t) # # """ for Total percentage """ # print('Your Total percentage is ', t * 12.5 / 100, '%') # p = t * 12.5 / 100 # # """ for Division """ # # if t < 360 and t > 280: # print('Your Result is : Third Division') # if t < 480 and t > 360: # print('Your Result is : Second Division') # if t < 600 and t > 480: # print('Your Result is : First Division') # if t < 720 and t > 600: # print('Your Result is : Dictintion') # if t < 801 and t > 720: # print('Your Result is : Board Topper') # else: # print('') # # """ for Pass or Fail """ # # if print(a < 35 and b < 35): # print(" Fail in Subject") # else: # print('Pass in all subject') """----------------------------------------------""" # dellrs = 50000 # d = dellrs # macrs = 90000 # m = macrs # toshibars = 65000 # tb = toshibars # dellqty = int(input("Enter Dell Qty Rs.50000 : ")) # dq = dellqty # macqty = int(input('enter mac Qty Rs.90000 : ')) # mq = macqty # toshibaqty = int(input("enter toshiba Qty Rs.65000 : ")) # tbq = toshibaqty # # t = (d * dq) + (m * mq) + (tb * tbq) # delivery = input("select home/pick-up : ") # if delivery == 'home': # dprice = 1000 # print(t + dprice, ('with home delivery')) # else: # print(t, ' Free Pick-up from Shop') # # """ Packaging Charge """ # # packaging = input('plastic/bag/gift-box: ') # if packaging == 'plastic': # plastic = 500 # if packaging == 'bag': # bag = 1000 # if packaging == 'gift-box': # Gift = 500 # else: # print('no charge for packaging') # print(t + dprice, ('with home delivery')) # # """ Location """ # # location = input('Kathmandu/birgunj/pokhara: ') # if location == 'kathmandu': # kathmandu = 500 # if location == 'birgunj': # birgunj = 1000 # if location == 'pokhara': # pokhara = 1500 # else: # print('City is not selected') # # print('VAT AMOUNT : ', t*13 / 100) # vat=(t*13/100) # print('Gtotal :',t+vat) """ python data types""" # Number = int, floadt, complex # string # list -- array() # tuple # set # dic # data = 2 + 5j # print(data.real) # print(data.imag) # # data = 5 + 4j # print(data) """ List - array""" # data = ['ram', 'shyam', 'hari', 'sita', 'gita', 8787] # print(type(data)) # print(data) # data[3] = 'madan' # print(data[3]) # # Tuple # data = ('hari', 'gita', 'sophia', 'hari') """ duplication data can entry""" # print(data) # # #set # data = {('hari', 'gita', 'sophia', 'hari'} """ no duplication data can entry""" # # print(data) # # data = { # 'name': 'ram', # 'age': 20, # 'phone': 984854 # # } # # print = (f"your name is {data['name']}") # # # data = [ # ['ram', 'hari'], # ['sita', 'gira'], # ['madan', 'raj'], # {'name': 'bimala', 'age': 20}, # {'address':['ktm', # 'bkt' # ]} # ] # # # # # print(type(data)) # # # print(data[2][1]) # # # print(data[3]['name']) # print(data[4]['address'][1]) # # # #is is not # #in not in # name ='ram' # print('b' not in name) # # """ loop = for, while, yield""" Homework # is ----- identity # == ----- comparision # # x = [1, 2, 3, 4, 5] # y = [1, 2, 3, 4, 5] # y = x # print(id(x)) # print(id(y)) # # if x is y: # print(True) # else: # print(False) # data = [1, 3, 4, 5, 6, 7] # # for x in data: # print(x) # data = [ # ['ram', 'hari', 'sita', 'gita'], # ['gopal', 'madan', 'binita', 'sunita'], # ['nadira', 'mandira', 'laxmi', 'kabita'], # ] # for x in data: # for y in x: # print(y) # for x in range(1,11): # print(x) # # # x = 1 # # while x < 10: # print(x) # x += 1 # x = 1 # while x < 10: # print(input("Enter the Numnber of Employee"), (x)) # x += 1 # # stu_num = int(input('Enter the number if student')) # x = 0 # student_list = [1] # while x < stu_num: # name = input('Enter name') # student_list.append(name) # x += 1 # for s in student_list: # print(f'Your Nwme is {s}') # data = [1, 2, 3, 4, 5, 6, 7, 8] # # for x in data: # if x == 3 and 7: # continue # # # print(x)
ea84c2259c54caa7b67fb8eb1824141497c04b3f
Opsy1169/locationbot
/prime.py
351
3.65625
4
import math import random def inventing(comp): comp = int(comp) que = random.randint(3, 10 ** (comp + 1)) if (que % 2 == 0): que += 1; return que def isprime(que): limit = int(math.sqrt((que))) i = 3 while (i <= limit): if (que % i == 0): return 'False' i += 1 return 'True'
a293d6cc7ba26430676024acdc6794e82ce3463b
MichaelArslangul/python_Sandbox
/DP/CuttingRods.py
1,316
3.75
4
class CuttingRods: """ Given a rod of length N and prices p[0], ..., p[N], where p[i] is the price of a length i of the rod. Find the max revenue we can get from the rod by cutting and selling it """ def highest_revenue_recursive(self, rod_length, prices): _max_revenue = float("-inf") if rod_length == 0: return 0 for i in range(rod_length): _temp_revenue = prices[i] + self.highest_revenue( rod_length -i -1, prices) _max_revenue = max(_temp_revenue, _max_revenue) return _max_revenue def highest_revenue_dp(self, rod_length, prices): _revenue = [0]*(rod_length +1) for i in range(1, rod_length+1): _max_revenue = float("-inf") for j in range(i): _max_revenue = max(_max_revenue, prices[j] + _revenue[i-j-1]) _revenue[i] = _max_revenue return _revenue[rod_length] cr = CuttingRods() rod_length = 8 prices = [1, 5, 8, 9, 10, 17, 17, 20] print("most cost effective to cut a rod of length {} using recursion is: {}".format( rod_length, cr.highest_revenue_recursive(rod_length, prices))) print("most cost effective to cut a rod of length {} using DP is: {}".format( rod_length, cr.highest_revenue_dp(rod_length, prices)))
e7ceaf1411b28676e55afc5acfb4b4312f405ead
santosclaudinei/Entra21_Claudinei
/exercicioa05e06.py
311
4.09375
4
# Exercicio 6 # Escreva um programa que peça 2 números e mostre eles em ordem crescente num1 = int(input('Digite um numero: ')) num2 = int(input('Digite outro numero: ')) if num1 > num2: menor = num2 if num2 > num1: menor = num1 print('O menor numero entre {} e {} é {}' .format(num1, num2, menor))
acef33b2785335b4ba52169cc0b4fd0767bbf0b4
mantues/Medical-temp-check-sheet
/temp-check-sheet-en.py
3,485
4.125
4
# web ↓ # https://office54.net/python/tkinter/textbox-get-insert import tkinter as tk from tkinter import * import csv import os # Processing when a button is pressed. def memo_temp(): #Read IDs from taion.csv index=int(textID.get())#ID value judgment if(index<1 or 1001<index): s="Make sure ID is correct.(Range:1~1000)" labelResult['text']=s return else: #Body temperature value judgment temp=float(texttemp.get()) #Body temperature value judgment if(temp<35 or 40<temp): s="Please re-enter your body temperature. Range: 35~40℃" labelResult['text']=s return else: if(37.5<temp): s="High fever." elif(temp<35.5): s="Body temperature is low." else: s="Let's do our best today!" #taion.csv file read filename="taion.csv" #Check if there is a csv file. If not, create one. if (os.path.exists(filename)): with open(filename, "r") as f: read_csv=csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONNUMERIC) #val=f.read() temp_files=[row for row in read_csv] #print(temp_files) else: temp_files=[] #Determine if the ID (index) is larger than the list, and if so, add a line. if(index<len(temp_files)): id_temp=temp_files[index-1] else: for i in range(0, index-len(temp_files)): temp_files.append([]) id_temp=temp_files[index-1] #Add body temperature to the list id_temp.append(float(temp)) #Calculation of average body temperature (must be in str format to be displayed) average=str(sum(id_temp)/len(id_temp)) #print(average) print(temp_files) labelResult['text']=s+"\n Average: "+ average + "℃" #Writing Files with open(filename, 'w', newline="") as f: writer = csv.writer(f) writer.writerows(temp_files) # Create a window win = tk.Tk() # Empty window. This is where you put the information. win.title("Medical record sheet") # Specify the window title win.geometry("250x250") # Specify size #Loading image(optional)png, pgm, ppm, gif image_file = "pic.png" image = tk.PhotoImage(file=image_file) if (os.path.exists(image_file)): img=tk.Label(image=image) img.pack() # Create the parts labelID = tk.Label(win, text='ID:') # Labels to place in the window labelID.pack() # Commands to be placed in the window from top to bottom textID = tk.Entry(win) # Create a text box textID.insert(tk.END, '1') # Default characters textID.pack() # deployment labeltemp = tk.Label(win, text='Body temperature(℃):') # Same as ID labeltemp.pack() texttemp = tk.Entry(win) texttemp.insert(tk.END, '36.5') texttemp.pack() labelResult = tk.Label(win, text='---') # Same as ID labelResult.pack() # This is the part that is specified as labelResult['text'] = s in the memo_temp function. It overwrites the text part of text='---' created in line 86. calcButton = tk.Button(win, text='Record') # In Button widget, you can specify the command. calcButton["command"] = memo_temp # Calling the function memo_temp # The above two lines can be summarized as calcButton = tk.Button(win, text='record',command=memo_temp) calcButton.pack() # Work the window win.mainloop()
9770ae221755016022ae8888406f6604ca6f13b2
CurryMentos/algorithm
/exercise/数学题/2.1.py
537
3.53125
4
# !/usr/bin/env python # -*-coding:utf-8 -*- """ # File : 2.1.py # Time :2021/7/16 10:22 # Author :zyz # version :python 3.7 """ """ 如果一个 3 位数等于其各位数字的立方和,则称这个数为水仙花数。 例如:153 = 1^3 + 5^3 + 3^3,因此 153 就是一个水仙花数 那么问题来了,求1000以内的水仙花数(3位数) """ for i in range(100, 1000): a = i % 10 b = int(i / 100) c = int((i - b * 100) / 10) if i == a ** 3 + b ** 3 + c ** 3: print(i)
72a78852a61f104f2d112cc620f29ad252073103
git-mih/Learning
/python/01_functional/06modules_packages_namespaces/01modules/exemple1/module1.py
2,039
3.796875
4
print(f'--------------- Running: {__name__} ---------------') def func(file_name, namespace): print(f'\n\t---------- {file_name} ----------') for k, v in namespace.items(): print(f'{k}: {v}') print(f'\t-------------------------------------\n') func('module1 namespace', globals()) print(f'--------------- End of: {__name__} ---------------') #_________________________________________________________________________________________________ # the __name__ attribute: # whenever we execute this module directly, the __name__ attribute will be set to __main__. # therefore, if we execute this code indirectly, for exemple, from inside another module, # the __name__ attribute value will be the file name itself. in this case, `module1`. # we can see that, if we execute the `main.py` module, that module is loading and executing # this `module1` module object in there. therefore, the __name__ attribute value in there will # be set to "module1". # it happens because whenever we import an module object, Python automatically loads and execute # that module. by using the __name__ attribute, we can prevent that automatically execution. # we can specify if we do want or not want and what to execute based on the __name__ attribute # value. # maybe we want to execute the module in certain way if we execute the module direclty. and # maybe we dont want to run any code at all when we import some module. #_________________________________________________________________________________________________ # --------------- Running: __main__ --------------- # ---------- module1 namespace ---------- # __name__: __main__ # __doc__: None # __package__: None # __loader__: <_frozen_importlib_external.SourceFileLoader object at 0x000002> # __spec__: None # __annotations__: {} # __builtins__: <module 'builtins' (built-in)> # __file__: module1.py # __cached__: None # func: <function func at 0x000001> # ------------------------------------- # --------------- End of: __main__ ----------------
fa2c80eba7483d452261d1864a936f13c9c39c7e
stOracle/Migrate
/Programming/CS313E/Turtle/Train.py
2,004
3.75
4
# File: Train.py # Description: A turtle graphics attempt of drawing a choo-choo train # Student Name: Stephen Rauner # Student UT EID: STR428 # Course Name: CS 313E # Unique Number: 50945 # Date Created: 2/28/16 # Date Last Modified: 2/29/16 import turtle import math def drawLine (ttl, x1, y1, x2, y2): ttl.penup() ttl.goto(x1, y1) ttl.pendown() ttl.goto(x2, y2) ttl.penup() def tracks(ttl, start_x, num): ttl.penup() ttl.goto(start_x, -310) y = -310 w = 23 h = 5 for i in range(num): ttl.goto(start_x + (i*45), y) ttl.pendown() drawLine(ttl, start_x + (i * 45), y, start_x + (i * 45), y - h) drawLine(ttl, start_x + (i * 45), y - h, start_x + w + (i * 45), y - h) drawLine(ttl, start_x + w + (i * 45), y - h, start_x + w +(i * 45), y) ttl.penup() def spokes(ttl, cen_x, cen_y, r): for i in range(8): ttl.penup() ttl.goto(cen_x, cen_y) ttl.tilt(45) ttl.pendown() ttl.forward(r - 10) def wheels(ttl): # big wheel ttl.color("red") ttl.penup() ttl.goto(-200, -300) ttl.pendown() ttl.circle(50) ttl.penup() ttl.goto(-200, -290) ttl.pendown() ttl.circle(40) spokes(ttl, -200, -250, 50) ttl.penup() ttl.goto(-200, -260) ttl.pendown() ttl.circle(10) # small wheel 1 ttl.penup() ttl.goto(-30, -300) ttl.pendown() ttl.circle(40) ttl.penup() ttl.goto(-30, -290) ttl.pendown() ttl.circle(30) spokes(ttl, -30, -260, 40) ttl.penup() ttl.goto(-30, -265) ttl.pendown() ttl.circle(5) # small wheel 2 ttl.penup() ttl.goto(100, -300) ttl.pendown() ttl.circle(40) ttl.penup() ttl.goto(100, -290) ttl.pendown() ttl.circle(30) spokes(ttl, 100, -260, 40) ttl.penup() ttl.goto(100, -265) ttl.pendown() ttl.circle(5) def main(): turtle.title("Choo-Choo") turtle.setup(800, 800, 0, 0) turtle.speed(0) turtle.ht() ttl = turtle.Turtle() ttl.ht() drawLine(ttl, -300, -300, 300, -300) drawLine(ttl, -300, -310, 300, -310) count = 10 tracks(ttl, -290, 13) wheels(ttl) turtle.done() main()
8c8cd78dcc454d5d08fc7b3abb0863987b4f56fd
Jackthebighead/recruiment-2022
/algo_probs/jzoffer/jz32_3.py
1,555
3.90625
4
# 题意:从上到下打印二叉树3: 奇数层从左到右,偶数层从右到左 # 题解1: 辅助双端队列 # 题解2: 对奇偶不同处理,若该层的res_temp的len为奇数则正序加入res,若为偶数则倒序加入res。 # 题解3: 对单数双数层不同处理,这个最笨。if 即可。 # res.append(tmp[::-1] if len(res) % 2 else tmp) # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root): import collections if not root: return [] res,queue,cnt = [], collections.deque(),1 queue.append(root) while queue: res_temp = collections.deque() for _ in range(len(queue)): # 对于 python ,range() 的工作机制是在开启循环时建立一个列表,然后循环按照这个列表进行,因此“只会在进入循环前执行一次 len(queue) temp = queue.popleft() # 将res_temp也设置为双端队列,偶数层就插入到左边 if cnt % 2: res_temp.append(temp.val) else: res_temp.appendleft(temp.val) # 双端队列左边出右边进 if temp.left: queue.append(temp.left) if temp.right: queue.append(temp.right) res.append(list(res_temp)) cnt += 1 return res
f1c915e9774887422bb2c7405d0e99e8320c5d85
uzusun/tf
/python/set_op.py
260
3.921875
4
data1 = set(["cola","water","sprite"]) data2 = set(["coffee","milk"]) print(data1 & data2) print(data1.intersection(data2)) print(data1 | data2) print(data1.union(data2)) print(data1 - data2) print(data1.difference(data2)) """ print(data1) print(data2) """
cdd90bd93b18c55d46cd974c31eb9a1a56862b5e
AmbientOne/FlaskBarCodeScanner
/BarcodeScanner/digitGenerator.py
261
3.8125
4
import random def randomDigitGenerator(name, price): barcode = name[0:2].upper() for i in range(15): barcode += str(random.randrange(1, 10)) return barcode print(randomDigitGenerator(input("Enter a name: "), input("Enter a price: ")))
a6deb79c757e25b3f43adc6ec30323286ec33fee
omitogunjesufemi/gits
/PythonBootcamp/day2/Assignment Two/Question1.py
201
4.25
4
# Coverting Celsius to Fahrenheit celsius = int(input("Enter the temperature degree in celsius: ")) fahrenheit = (9/5) * celsius + 32 print(str(celsius), "Celsius is " +str(fahrenheit), "Fahrenheit" )
b8575f4f45140cac291a60f7b82f0f2168330361
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/134_7.py
2,835
4.375
4
Python | Type conversion of dictionary items The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let’s discuss certain ways in which this task can be performed. **Method #1 : Using loop** This problem can be solved using naive method by the use of loops. In this, we loop for each key and value and then typecast keys and value’s separately and returning the desired integral container. __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Type conversion of dictionary items # Using loop # Initialize dictionary test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Using loop # Type conversion of dictionary items res = {} for key, value in test_dict.items(): res[int(key)] = [int(item) for item in value] # printing result print("Dictionary after type conversion : " + str(res)) --- __ __ **Output :** > The original dictionary : {’10’: [‘8’], ‘4’: [‘6’, ‘7’], ‘1’: [‘4’, ‘5’]} > Dictionary after type conversion : {1: [4, 5], 10: [8], 4: [6, 7]} **Method #2 : Using dictionary comprehension** This task can be easily performed using single line shorthand using dictionary comprehension. This offers a shorter alternative to the loop method discussed above and hence recommended. __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Type conversion of dictionary items # Using dictionary comprehension # Initialize dictionary test_dict = {'1' : ['4', '5'], '4' : ['6', '7'], '10' : ['8']} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Using dictionary comprehension # Type conversion of dictionary items res = {int(key):[int(i) for i in val] for key, val in test_dict.items()} # printing result print("Dictionary after type conversion : " + str(res)) --- __ __ **Output :** > The original dictionary : {’10’: [‘8’], ‘4’: [‘6’, ‘7’], ‘1’: [‘4’, ‘5’]} > Dictionary after type conversion : {1: [4, 5], 10: [8], 4: [6, 7]} Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
9d334671995beeb247af5ff2b5c3c983413d9e9d
wfeng1991/learnpy
/py/leetcode/114.py
1,541
3.921875
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def flatten1(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ def help(root): if root: left=help(root.left) right=help(root.right) if left: root.right=left root.left=None while left.right: left=left.right left.right=right return root else: return None help(root) def flatten(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ def dfs(root): if not root.right and not root.left: return root right = root.right right_last, left_last = None, None if root.right: right_last = dfs(root.right) if root.left: left_last = dfs(root.left) root.right = root.left root.left = None left_last.right = right right = root.right return right_last or left_last if root:dfs(root) t=TreeNode(1) t.right=TreeNode(2) Solution().flatten(t)
2e98629efd3cc149d75f23b02cc6af8b4b0954e1
abs-tudelft/vhsnunzip
/tests/emu/utils.py
2,924
3.9375
4
def safe_chr(data, oneline=False): """Returns a byte or iterable of bytes as ASCII, using ANSI color codes to represent non-printables. If oneline is set, \n is treated as a special character, otherwise it is passed through unchanged. The following color codes are used: - green 'n': newline - green 'r': carriage return - green 't': horizontal tab - red number: control codes 0 through 9 - red uppercase up to V: control code 10 through 31 - dark gray dot: code 32 (space) - bright character: code 33 through 126 (printables) - red 'Y': control code 127 - red '^': code 128 through 255 """ if not hasattr(data, '__iter__'): data = [data] s = ['\033[1m'] for value in data: if value == ord('\n'): if oneline: s.append('\033[32mn') else: s.append('\n') elif value == ord('\r'): s.append('\033[32mr') elif value == ord('\t'): s.append('\033[32mt') elif value < 10: s.append('\033[31m%d' % value) elif value < 32: s.append('\033[31m%s' % chr(ord('A') + value)) elif value == 32: s.append('\033[30m·') elif value < 127: s.append('\033[37m%s' % chr(value)) elif value == 127: s.append('\033[31mY') else: s.append('\033[31m^') return ''.join(s) + '\033[0m' def binary(data, bits, valid=True): """Returns a python integer or list of integers as a (concatenated) std_logic_vector string of the given bitcount per element. If valid is specified and false, don't-cares are returned instead.""" if not hasattr(data, '__iter__'): data = [data] s = [] for value in data: if valid: s.append(('{:0%db}' % bits).format(value & (2**bits-1))) else: s.append('-' * bits) return ''.join(s) def is_std_logic(value): """Returns whether the given value is the Python equivalent of an std_logic.""" return value is True or value is False def is_unsigned(value, bits): """Returns whether the given value is the Python equivalent of an unsigned with the given length.""" return not (value & ~(2**bits-1)) def is_signed(value, bits): """Returns whether the given value is the Python equivalent of an signed with the given length.""" return value >= -2**(bits-1) and value < 2**(bits-1) def is_std_logic_vector(value, bits): """Returns whether the given value is the Python equivalent of an std_logic_vector with the given length.""" return value & ~(2**bits-1) in [0, -1] def is_byte_array(value, count): """Returns whether the given value is the Python equivalent of a byte array.""" return isinstance(value, tuple) and len(value) == count and all(map(lambda x: x >= 0 and x <= 255, value))
8e37b06a20173b889da316e61ecf3990bc220877
prachijain07/Prachi-programs
/src/Exercise_32.py
661
3.5
4
#PF-Exer-32 def human_pyramid(no_of_people): if(no_of_people==1): return 1*(50) else: return no_of_people*(50)+human_pyramid(no_of_people-2) def find_maximum_people(max_weight): no_of_people=0 m=max_weight//50 sum1=0 for i in range(1,m+1,2): sum1+=i if(sum1>m): sum1=sum1-i break row=0 for i in range(1,sum1+1): if(sum1//i==i): row=i break j=1 for i in range(row): j+=2 j-=2 no_of_people=j return no_of_people max_people=find_maximum_people(1000) print(max_people)
94a41636496c8e16d5b401aa41d229e3aba1190f
dipikakhullar/Data-Structures-Algorithms
/trie.py
4,725
4.03125
4
from collections import deque class TrieNode: def __init__(self, v): self.val = v self.children = {} self.is_end = False class Trie: """ 1. insert 2. contains word 3. return all words with prefix 4. num entries with that prefix? 5. delete word 6. return all words in trie """ def __init__(self): self.root = TrieNode(None) def insert(self, word): """ inserts word in trie """ if not word: return word = self.normalize_word(word) trav = self.root for i, char in enumerate(word): if char not in trav.children: trav.children[char] = TrieNode(char) trav = trav.children[char] trav.is_end = True def contains(self, word): trav = self.root for char in word: if char not in trav.children: return False trav = trav.children[char] return trav.is_end def get_all_words(self): word_list = [] for letter in self.root.children: word_list.extend(self.get_possible_words(letter)) return word_list def longest_prefix(self, word): """ Finds the word in the trie rooted at root with the longest matching prefix with word. In the case of a tie in longest prefix, one word is chosen arbitrarily. """ current_node = self.root current_prefix = "" for char in word: if char not in current_node.children: break else: current_node = current_node.children[char] current_prefix += char strings = [] self.find_strings(current_prefix, current_node, strings) return strings[0] def find_strings(self, prefix, node, results): """ Recursively traverses the sub-trie rooted at node and adds all strings of the sub-tree into results. """ if node.is_end: results.append(prefix) for char in node.children: self.find_strings(prefix + char, node.children[char], results) # return results def normalize_word(self, word): return word.strip().lower() def _get_possible_words(self, word, word_node, word_list=None): if word_list is None: word_list = [] else: word_list if word_node.is_end: word_list.append(word) for letter in word_node.children: if not word_node.children[letter]: word_list.append(word + letter) else: self._get_possible_words(word + letter, word_node.children[letter], word_list) return word_list def get_possible_words(self, word): found_prefix = self.found_prefix(word) if found_prefix: word_node = self._contains(word, self.root) if word_node is None: return [] else: return self._get_possible_words(word, word_node) else: return [] def found_prefix(self, prefix): # found_prefix = True current_node = self.root found_prefix = True for symbol in prefix.strip().lower(): if symbol in current_node.children: current_node = current_node.children[symbol] else: found_prefix = False break return found_prefix def _contains(self, word, node): if not word: return node if word[0] and node.children.keys(): return self._contains(word[1:], node.children[word[0]]) else: return None def _contains_word(self, item): current_node = self.root contained = True for symbol in self.normalize_word(item): if symbol in current_node.children: current_node = current_node.children[symbol] else: contained = False break return contained and current_node.is_end def delete_word(self, word): print("DELETING WORD: ", word) if self.contains(word): word_node = self._contains(word, self.root) word_node.is_end = False trie = Trie() a = trie.insert("fun") b = trie.insert("funny") c = trie.insert("funcakes") # d = trie.contains("funn") # print(a) # print(d) # trie.longest_prefix("a") # trie.find_strings("", trie.root, []) # print("FINDING ALL WORDS") # words = trie.get_all_words() # print(words) all_possible_words = trie.get_possible_words("fu") print("ALL POSSIBLE WORDS WITH PREFIX FU: ", all_possible_words) # # trie.insert("a") # # trie.insert("add") # # trie.insert("an") # # trie.insert("and") # # trie.insert("any") # # trie.insert("bagel") # # trie.insert("bag") # # trie.insert("bags") # # trie.insert("bat") # # trie.insert("bath") # # trie.insert("bay") # # prefix = 'z' # # actual_words = trie.get_possible_words(prefix) # # print(actual_words) # t = Trie() # t.insert("e-mail") # t.insert("above-said") # t.insert("above-water") # t.insert("above-written") # t.insert("above") # t.insert("abode") # t.insert("exit") # all_words = t.get_all_words() # # print(all_words) # # print(all_words) # # print(len(all_words)) # print(all_words) # print(t.contains("abode")) # print(t.contains("above")) # print(t.contains("above-said")) # t.delete_word("abode") # print(t.get_all_words())
9d7696b6673420e9c88e271593f0cc41a8e7935f
rraj29/Sequences
/spliting_things.py
920
3.9375
4
panagram = "The quick brown fox jumps over the lazy dog" words = panagram.split() print(words) numbers = "4,566,4523,8895,445,5656,55,4226,45" print(numbers.split(",")) # **JOIN will create a STRING from a list. SPLIT will create a LIST from a string. #values = "".join(char if char not in separators else " " for numbers in numbers).split() generated_list = ['9',' ', '2', '2', '3', ' ', '3', '7', '2', ' ', '0', '3', '6', ' ', '8', '5', '4', ' ', '7', '7', '5', ' ', '8', '0', '7', ] values = "".join(generated_list) print(values) values_list = values.split() print(values_list) item_list_int = [] for item in values_list: item_list_int.append(int(item)) print(item_list_int) for index in range(len(values_list)): values_list[index]= int(values_list[index]) print(values_list)
894ac296306c253b9c32ac11d49fbde2d97d1ae8
Rishiraj122/Python_programs
/ForLoop.py
179
4.15625
4
fruits=["Apple","Pineapple","Mango","Grapes","Oranges"] for x in fruits: print(x); if x=="Apple": print("Well, there's Apple, so there must be Applepie :) ");
28e3113c08178de77a32b8427346880f8479536e
huginngri/TitleTraveler
/V2.py
1,563
3.921875
4
def possiblem(x , y): attir = "(S)outh (N)orth (W)est (E)ast" s, n, w, e = attir.split() if y == 1: return n + "." elif x == 1: if y == 2: return n + " or " + e + " or " + s + "." if y == 3: return e + " or " + s + "." elif x == 2: if y == 2: return s + " or " + w + "." if y == 3: return e + " or " + w + "." elif x == 3: if y == 2: return n + " or " + s + "." if y == 3: return s + " or " + w + "." else: return "" def movementx(char): if char == "e" or char == "E": x = 1 elif char == "w" or char == "W": x = -1 else: x = 0 return x def movementy(char): if char == "n" or char == "N": y = 1 elif char == "s" or char =="S": y = -1 else: y = 0 return y x = 1 y = 1 n = "(N)orth" s = "(S)outh" e = "(E)ast" w = "(W)est" while (x != 3) | (y != 1): a ="" b="" c = "" d ="" print("You can travel: " + possiblem(x, y)) move = input("Direction: ") if n in possiblem(x,y): a = n if s in possiblem(x,y): b = s if e in possiblem(x,y): c = e if w in possiblem(x,y): d = w while (move.upper() != a[1:2]) and (move.upper() != b[1:2]) and (move.upper() != c[1:2]) and (move.upper() != d[1:2]): print("Not a valid direction!") move = input("Direction: ") x += movementx(move) y += movementy(move) print("Victory!")
6c655044a49f27e0d4d8766df68cd6bf2da18cf6
Tri-x/exercise
/5/chars_count.py
620
3.578125
4
from string import *#引入字符模块 from random import * #统计字符数 str_dict={} strings='' for x in range(randint(0,200)):#随机字符随机长度 strings+=printable[randint(0,len(printable)-6)] #string.printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' print(strings) for x in range(len(set(strings))):#计数每个字符出现的次数储存在字典中一一对应 str_dict[list(set(strings))[x]]=strings.count(list(set(strings))[x]) for strss,nums in str_dict.items():#格式化输出 print('{0}:{1}'.format(strss,nums),end='|')
08744af1aae261def618dd478a0fdd54224fe32a
JeferyLee/smpAlgorithms
/K_calibre.py
510
3.5
4
""" -*- coding:utf-8 -*- @author : jerry @time : 2019/10/28 9:24 """ import pandas as pd import numpy as np data=pd.read_excel("c:/users/dell/desktop/test.xlsx") print(data) # data=pd.DataFrame(data=ws2,index=[[1,2],[1,2,3,4]],columns=[[1,2],[1,2,3,4]]) # data=pd.DataFrame(data=ws2,index=['2','3','4','5']) # print(data) # frame=pd.DataFrame(np.arange(12).reshape((4,3)), index=[['a','a','b','b'],[1,2,1,2]], # columns=[['Ohio','Ohio','Colorado'], # ['Green','Red','Green']])
0b455d583dbfd9a3935dd860d8bce940105bb562
SteveImmanuel/multimedia-stegano
/crypto/engine/key.py
435
3.546875
4
from enum import Enum from typing import List, Union class KeyType(Enum): NUMBER = 'number' STRING = 'string' class Key: def __init__(self, key_type: KeyType, data: List[Union[str, int]]): self.key_type = key_type if key_type == KeyType.NUMBER: self.data = list(map(int, data)) elif key_type == KeyType.STRING: self.data = list(map(lambda x: x.lower(), map(str, data)))
b2cf3d07c9a77b8a5b25fe2673ca30c0c49ff291
atkins126/sample_nullpobug
/python/csv1/reader.py
382
3.65625
4
# coding: utf-8 import csv def main(): with open('data.csv') as csvfile: reader = csv.reader(csvfile) # readerのシーケンスはリストを返す for row in reader: for idx, value in enumerate(row): print u"{}: {}".format(idx + 1, value.decode('cp932')) print "-" * 10 if __name__ == '__main__': main()
375a0f3634cc9b9bcea50ce0c5dc05cfbd088770
JerryTom121/COREL
/code/Models/pi_pj_model_with_no_th_cat.py
1,670
3.6875
4
import csv import sys from itertools import product import operator from sets import Set readfile=csv.reader(open('./../dataset/preprocess_data_new.csv','rt')) true_count=0 #no of time successfuly predicted total_count=0 #total number of prediction made n=int(input("Enter N: ")) def frequency(products,item): #this will caculate the frequency of item in products list count=0 for x in products: if x==item: count+=1 return count for row in readfile: total_count+=1 section_A=row[1].split(',') #section A products of any user section_B=row[2].split(',') #section B products of any user section_C=Set([]) #set of section C products of any user for x in row[3].split(','): try: section_C.add(x) except KeyError: continue products=section_A+section_B pi=section_B[0] #item purchased by user #pi_count=frequency(products,pi) item_counter={} # print pi #this section calculates the frequency of each item in products list for item in products: try: if item in item_counter: item_counter[item]+=1 else: item_counter[item]=1 except KeyError: continue #this will sort the items according to their frequency item_counter=sorted(item_counter.items(),key=operator.itemgetter(1),reverse=True) # print item_counter #this will create a set of top n products counter=0 top_item=Set([]) for item,value in item_counter: if counter==n: break if item!=pi: top_item.add(item) counter+=1 #print section_C #print 'hello2' #this will check whether pridicted output is correct or not if len(section_C.intersection(top_item))>0: true_count+=1 #print true_count print float(true_count)/total_count
1ad2a2beb0d679cc6963254194e98737c7097cb5
samuVG/Tarea1_Samuel_Vasco_Gonz-lez
/Tarea1.py
975
4.0625
4
#!/usr/bin/env python # coding: utf-8 # In[3]: import funciones #se invocan las funciones creadas en el módulo funciones #Ejercicio 4: se lanza una moneda n veces # a). la probabilidad de que si se hace este experimento 100 veces, el resultado sean 10 veces cara. def Probabilidad(n,k): #funcion que calcula la probabilidad de que cuando se lanza una moneda n veces prob=funciones.Binomial(n,k)/2**n # y resulte un numero k de veces cara (sello) return prob print("Punto a).") print("La probabilidad de lanzar 100 veces una moneda y caiga 10 veces cara es: ",Probabilidad(100,10)) print("La probabilidad de que suceda es del orden de 10^(-15)% \n") suma=0 for i in range(31,101): # se suman las probabilidades desde 31 hasta 100 suma=suma+Probabilidad(100,i) print("Punto b).") print("La probabilidad de lanzar 100 veces una moneda y caiga más de 30 veces cara es: ",suma) print("La probabilidad de que suceda es del orden de 99.996%") # In[ ]:
9dfea52358d6c3d7511f9d05b6afccd2d2d906f3
Rproc/sim_agent
/monteCarlo.py
1,380
4.3125
4
import numpy as np import math import random e = math.e pi = math.pi def get_rand_number(min_value, max_value): """ This functions gets a random number from a uniform distribution between the two input values [min_value, max_value] inclusively Args: - min_value (float) - max_value (float) Return: - Random number between this range (float) """ range = max_value - min_value choice = random.uniform(0,1) return min_value + range*choice def f_of_x(x): """ This is the main function we want to integrate over. Args: - x (float) : input to function; must be in radians Return: - output of function f(x) (float) """ return (e**(-1*x))/(1+(x-1)**2) def crude_monte_carlo(num_samples=5000): """ This function performs the Crude Monte Carlo for our specific function f(x) on the range x=0 to x=5. Notice that this bound is sufficient because f(x) approaches 0 at around PI. Args: - num_samples (float) : number of samples Return: - Crude Monte Carlo estimation (float) """ lower_bound = 0 upper_bound = 1000 sum_of_samples = 0 for i in range(num_samples): x = get_rand_number(lower_bound, upper_bound) sum_of_samples += f_of_x(x) return (upper_bound - lower_bound) * float(sum_of_samples/num_samples) # crude_monte_carlo()
dd17d8251a661225c4ab68ac6c61b3eb3a818be4
vapawar/vpz_pycodes
/vpz/vpz_linklist.py
1,020
3.890625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def add(self, data): temp = Node(data) temp.next = self.head self.head = temp def remove(self, key): temp = self.head if temp and temp.data == key: self.head = temp.next return while temp: if temp.data == key: break prev = temp temp = temp.next if temp == None: return prev.next = temp.next def show(self): temp = self.head while temp: print(temp.data) temp = temp.next llist = LinkedList() llist.add(7) llist.add(1) llist.add(3) llist.add(2) print("show") llist.show() llist.remove(1) print("delete 1") llist.show() llist.remove(7) print("delete 7") llist.show() llist.remove(4) print("delete 4") llist.show() llist.remove(2) print("delete 2") llist.show()
9c59ff7d03ba56c52523a22530c4559e0aa6a53c
Tahmid79/ud120-projects
/outliers/outlier_cleaner.py
885
3.796875
4
#!/usr/bin/python import math def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] ### your code goes here #predictions, ages, net_worths #(age, net_worth, error) for i in range(len(predictions)): error = predictions[i] - net_worths[i] error = abs(error) lst = [] lst.extend([ ages[i] , net_worths[i] , error ]) lst = tuple(lst) cleaned_data.append(lst) cleaned_data.sort(key= lambda tup : tup[2]) remn = int( 0.9 * len(ages)) cleaned_data = cleaned_data[:remn] return cleaned_data
4107bd220d010a882f92807299c1b07e529c358d
Flibielt/mlbasics-ex6
/ex6/src/ex6_spam.py
5,776
3.515625
4
from scipy.io import loadmat import numpy as np import os from .utils import process_email, email_features, svm_train, linear_kernel, svm_predict, get_vocab_list def ex6_spam(): """ Exercise 6 | Spam Classification with SVMs Instructions ------------ This file contains code that helps you get started on the exercise. You will need to complete the following functions: gaussian_kernel.py dataset3_params.py process_email.py email_features.py For this exercise, you will not need to change any code in this file, or any other files other than those mentioned above. """ """ ==================== Part 1: Email Preprocessing ==================== To use an SVM to classify emails into Spam v.s. Non-Spam, you first need to convert each email into a vector of features. In this part, you will implement the preprocessing steps for each email. You should complete the code in processEmail.m to produce a word indices vector for a given email. """ print('\nPreprocessing sample email (emailSample1.txt)\n') # Extract Features sample1_path = os.path.dirname(os.path.realpath(__file__)) + '/data/emailSample1.txt' sample1_path = sample1_path.replace('\\', '/') with open(sample1_path) as fid: file_contents = fid.read() word_indices = process_email(file_contents) # Print stats print('Word Indicies: %d' % len(word_indices)) input('Program paused. Press enter to continue.\n') """ ==================== Part 2: Feature Extraction ==================== Now, you will convert each email into a vector of features in R^n. You should complete the code in email_features.py to produce a feature vector for a given email. """ print('\nExtracting features from sample email (emailSample1.txt)\n') features = email_features(word_indices) # Print Stats print('\nLength of feature vector: %d' % len(features)) print('Number of non-zero entries: %d' % sum(features > 0)) input('Program paused. Press enter to continue.\n') """ =========== Part 3: Train Linear SVM for Spam Classification ======== In this section, you will train a linear classifier to determine if an email is Spam or Not-Spam. """ # Load the Spam Email dataset # You will have X, y in your environment spam_train_path = os.path.dirname(os.path.realpath(__file__)) + '/data/spamTrain.mat' spam_train_path = spam_train_path.replace('\\', '/') data = loadmat(spam_train_path) X, y = data['X'].astype(float), data['y'][:, 0] print('Training Linear SVM (Spam Classification)') print('This may take 1 to 2 minutes ...\n') C = 0.1 model = svm_train(X, y, C, linear_kernel) # Compute the training accuracy p = svm_predict(model, X) print('Training Accuracy: %.2f' % (np.mean(p == y) * 100)) """ =================== Part 4: Test Spam Classification ================ After training the classifier, we can evaluate it on a test set. We have included a test set in spamTest.mat """ # Load the test dataset # You will have Xtest, ytest in your environment spam_test_path = os.path.dirname(os.path.realpath(__file__)) + '/data/spamTest.mat' spam_test_path = spam_test_path.replace('\\', '/') data = loadmat(spam_test_path) Xtest, ytest = data['Xtest'].astype(float), data['ytest'][:, 0] print('Evaluating the trained Linear SVM on a test set ...') p = svm_predict(model, Xtest) print('Test Accuracy: %.2f' % (np.mean(p == ytest) * 100)) input('\nProgram paused. Press enter to continue.\n') """ ================= Part 5: Top Predictors of Spam ==================== Since the model we are training is a linear SVM, we can inspect the weights learned by the model to understand better how it is determining whether an email is spam or not. The following code finds the words with the highest weights in the classifier. Informally, the classifier 'thinks' that these words are the most likely indicators of spam. """ # Sort the weights and obtain the vocabulary list idx = np.argsort(model['w']) top_idx = idx[-15:][::-1] vocab_list = get_vocab_list() print('Top predictors of spam:') print('%-15s %-15s' % ('word', 'weight')) print('----' + ' ' * 12 + '------') for word, w in zip(np.array(vocab_list)[top_idx], model['w'][top_idx]): print('%-15s %0.2f' % (word, w)) input('\nProgram paused. Press enter to continue.\n') """ =================== Part 6: Try Your Own Emails ===================== Now that you've trained the spam classifier, you can use it on your own emails! In the starter code, we have included spamSample1.txt, spamSample2.txt, emailSample1.txt and emailSample2.txt as examples. The following code reads in one of these emails and then uses your learned SVM classifier to determine whether the email is Spam or Not Spam """ # Set the file to be read in (change this to spamSample2.txt, # emailSample1.txt or emailSample2.txt to see different predictions on # different emails types). Try your own emails as well! email_sample_path = os.path.dirname(os.path.realpath(__file__)) + '/data/emailSample1.txt' email_sample_path = email_sample_path.replace('\\', '/') with open(email_sample_path) as fid: file_contents = fid.read() word_indices = process_email(file_contents, verbose=False) x = email_features(word_indices) p = svm_predict(model, x) print('\nProcessed %s\nSpam Classification: %s' % (email_sample_path, 'spam' if p else 'not spam')) print('(1 indicates spam, 0 indicates not spam)\n\n')
5236f90479fe988fda5f8692db1b01c77f17aa51
4597veronica/Projectos_python
/calculadora/Ejercicio_17-3/menu_calc_if.py
405
3.984375
4
#coding:utf-8 # Haremos un menu de una calculadora print "¿Que desea hacer amo?" print "S.-salir" print "1.-Sumar" print "2.-Restar" print "3.-Multiplicar" print "4.-Dividir" obcion=raw_input ("Introduce una obcion: ") #if not obcion>=1 and obcion<=4: if obcion == "s" : print "Introduce una S mayuscula" else : if not obcion>="1" and obcion<="4" : print "Esa opción no existe"
437b1f52ee4f0293f9d03aab34330b80b619b7c4
orloffanya/python
/advanced_loops_80.py
1,066
4.375
4
# The prime factorization of an integer, n, can be determined using the following steps: # Initialize factor to 2 # While factor is less than or equal to n do # If n is evenly divisible by factor then # Conclude that factor is a factor of n # Divide n by factor using floor division # Else # Increase factor by 1 # Write a program that reads an integer from the user. If the value entered by the # user is less than 2 then your program should display an appropriate error message. # Otherwise your program should display the prime numbers that can be multiplied # together to compute n, with one factor appearing on each line. For example: # Enter an integer (2 or greater): 72 # The prime factors of 72 are: # 2 # 2 # 2 # 3 # 3 factor = 2 n = int(input("Please enter a number greater than 2: ")) while n < 2: print("The number should be greater than 2") n = int(input("Please enter a number: ")) print(f"The prime factors of {n} are:") while factor <= n: if n % factor == 0: n = n // factor print(factor) else: factor += 1
a164fc90702c0192a9aa71cad6e65b0a8e198de2
CrookedY/AirPollutionBot
/buildreplytweet.py
350
3.625
4
from replybot import listofstationsdata if pollutant == 'NOX': #if function on data to sort which high or low function append high of low to list for pollutionlevel function to sort though Then add the pollutant name and a space to a string. Start of string should be 'The pollution level in (location) is high or low. NOX is , P10 is, p2.5 is'
a331a6b6820a72375f6d8b355c1a4344b1d761a1
Ohforcute/learn-arcade-work
/Lab 12 - Final Lab/part_12.py
61,898
3.75
4
import arcade import os SPRITE_SCALING = 0.1 SPRITE_NATIVE_SIZE = 128 SPRITE_SIZE = int(SPRITE_NATIVE_SIZE * SPRITE_SCALING) SCREEN_WIDTH = 600 SCREEN_HEIGHT = 400 SCREEN_TITLE = "Atari Adventure Knockoff Edition" MOVEMENT_SPEED = 5 class Room: """ This class holds all the information about the different rooms. """ def __init__(self): # You may want many lists. Lists for coins, monsters, etc. self.wall_list = None # This holds the background images. If you don't want changing # background images, you can delete this part. self.background = None self.lock_list = arcade.SpriteList() self.dragon_list = arcade.SpriteList() self.sword_list = arcade.SpriteList() self.key_list = arcade.SpriteList() self.trophy_list = arcade.SpriteList() def setup_room_1(): """ Create and return room 1. If your program gets large, you may want to separate this into different files. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.lock_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26: # http://www.i2clipart.com/clipart-custom-color-round-square-button-c82a wall = arcade.Sprite("blue wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): # Skip making a block 4 and 5 blocks up on the right side if y != SPRITE_SIZE * 4 and y != SPRITE_SIZE * 5 and y != SPRITE_SIZE * 6: wall = arcade.Sprite("blue wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create castle for x in range(80, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 380 room.wall_list.append(wall) for x in range(415, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 380 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 355 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 355 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 330 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 330 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 305 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 280 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 255 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) lock = arcade.Sprite("lockBlue.png", 0.2) lock.center_y = 210 lock.center_x = 297 lock.color_match = "blue" lock.open = False room.lock_list.append(lock) # Load the background image for this level. # https://www.iconsdb.com/gray-icons/rectangle-icon.html room.background = arcade.load_texture("background.png") return room def setup_room_2(): """ Create and return room 2. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.dragon_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 12 and x != SPRITE_SIZE * 13 and x != SPRITE_SIZE * 14) or y != 0: # https://www.iconsdb.com/custom-color/square-icon.html wall = arcade.Sprite("actual_red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): # Skip making a block 4 and 5 blocks up if (y != SPRITE_SIZE * 4 and y != SPRITE_SIZE * 5 and y != SPRITE_SIZE * 6) or x != 0: wall = arcade.Sprite("actual_red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # https://icon-library.com/icon/dragon-png-icon-17.html dragon = Dragon("dragon.png", SPRITE_SCALING * 2) dragon.center_x = 0 dragon.center_y = 400 dragon.dead = False room.dragon_list.append(dragon) room.background = arcade.load_texture("background.png") return room def setup_room_3(): """ Create and return room 3. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 12 and x != SPRITE_SIZE * 13 and x != SPRITE_SIZE * 14) or y == 0: # https: // www.iconsdb.com / yellow - icons / square - icon.html wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): if (y != SPRITE_SIZE * 2 and y != SPRITE_SIZE * 3 and y != SPRITE_SIZE * 4) or x != 0: wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Creates maze for x in range(23, 525, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 315 room.wall_list.append(wall) for x in range(63, 300, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 265 room.wall_list.append(wall) for x in range(360, 580, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 265 room.wall_list.append(wall) for x in range(23, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 215 room.wall_list.append(wall) for x in range(260, 580, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 215 room.wall_list.append(wall) for x in range(53, 110, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(160, 280, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(320, 400, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(460, 580, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(23, 50, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 115 room.wall_list.append(wall) for x in range(100, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 115 room.wall_list.append(wall) for x in range(23, 230, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 65 room.wall_list.append(wall) for x in range(280, 580, SPRITE_SIZE * 2): wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = 65 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 260 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 160 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 100 wall.bottom = 140 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 363 wall.bottom = 140 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 304 wall.bottom = 90 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 288 wall.bottom = 25 room.wall_list.append(wall) wall = arcade.Sprite("yellow_wall.png", SPRITE_SCALING) wall.left = 288 wall.bottom = 38 room.wall_list.append(wall) room.background = arcade.load_texture("background.png") # https://www.vexels.com/png-svg/preview/209809/hand-drawn-sword-historical-weapon object = arcade.Sprite("sword.png", .16) object.left = 335 object.bottom = 95 object.type = "sword" object.color_match = "none" room.object_list.append(object) return room def setup_room_4(): """ Create and return room 4. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26) or y != 0: # https://www.iconsdb.com/custom-color/square-icon.html wall = arcade.Sprite("purple_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) for x in range(30, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 65 room.wall_list.append(wall) for x in range(60, 135, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 115 room.wall_list.append(wall) for x in range(245, 375, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 115 room.wall_list.append(wall) for x in range(425, 570, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 115 room.wall_list.append(wall) for x in range(30, 80, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(132, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(320, 470, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 165 room.wall_list.append(wall) for x in range(60, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 215 room.wall_list.append(wall) for x in range(245, 320, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 215 room.wall_list.append(wall) for x in range(520, 580, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 215 room.wall_list.append(wall) for x in range(60, 110, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 265 room.wall_list.append(wall) for x in range(220, 275, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 265 room.wall_list.append(wall) for x in range(385, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 265 room.wall_list.append(wall) for x in range(60, 110, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 315 room.wall_list.append(wall) for x in range(158, 230, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 315 room.wall_list.append(wall) for x in range(315, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("purple_wall.png", .08) wall.left = x wall.bottom = 315 room.wall_list.append(wall) room.background = arcade.load_texture("background.png") wall = arcade.Sprite("purple_wall.png", .08) wall.left = 190 wall.bottom = 90 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 190 wall.bottom = 115 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 310 wall.bottom = 90 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 132 wall.bottom = 140 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 245 wall.bottom = 140 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 245 wall.bottom = 165 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 365 wall.bottom = 140 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 83 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 180 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 320 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 463 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 463 wall.bottom = 215 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 463 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 520 wall.bottom = 190 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 520 wall.bottom = 165 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 385 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 385 wall.bottom = 215 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 60 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 245 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 158 wall.bottom = 240 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 315 wall.bottom = 290 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 315 wall.bottom = 265 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 108 wall.bottom = 290 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 158 wall.bottom = 290 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 390 wall.bottom = 345 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 255 wall.bottom = 345 room.wall_list.append(wall) wall = arcade.Sprite("purple_wall.png", .08) wall.left = 255 wall.bottom = 320 room.wall_list.append(wall) object = arcade.Sprite("keyGreen.png", .2) object.left = 60 object.bottom = 195 object.color_match = "green" object.type = "key" room.object_list.append(object) return room def setup_room_5(): """ Create and return room 5. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.lock_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26) or y == 0: # https://www.iconsdb.com/custom-color/square-icon.html wall = arcade.Sprite("red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): if (y != SPRITE_SIZE * 4 and y != SPRITE_SIZE * 5 and y != SPRITE_SIZE * 6) or x == 0: wall = arcade.Sprite("red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create castle for x in range(80, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 380 room.wall_list.append(wall) for x in range(415, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 380 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 355 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 355 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 330 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 330 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 305 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 280 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 255 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) lock = arcade.Sprite("lockRed.png", 0.2) lock.center_y = 210 lock.center_x = 297 lock.color_match = "red" lock.open = False room.lock_list.append(lock) room.background = arcade.load_texture("background.png") return room def setup_room_6(): """ Create and return room 6. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26: # https://www.iconsdb.com/white-icons/square-icon.html wall = arcade.Sprite("white_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): if y != SPRITE_SIZE * 2 and y != SPRITE_SIZE * 3 and y != SPRITE_SIZE * 4: wall = arcade.Sprite("white_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) room.background = arcade.load_texture("background.png") return room def setup_room_7(): """ Create and return room 7. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.dragon_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): # https://www.iconsdb.com/black-icons/square-icon.html wall = arcade.Sprite("black_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): if (y != SPRITE_SIZE * 2 and y != SPRITE_SIZE * 3 and y != SPRITE_SIZE * 4) or x == 0: wall = arcade.Sprite("black_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) object = arcade.Sprite("keyRed.png", .2) object.left = 50 object.bottom = 50 object.color_match = "red" object.type = "key" room.object_list.append(object) dragon = Dragon("dragon.png", SPRITE_SCALING * 2) dragon.center_x = 0 dragon.center_y = 400 dragon.dead = False room.dragon_list.append(dragon) room.background = arcade.load_texture("background.png") return room def setup_room_8(): """ Create and return room 8. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.dragon_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26) or y != 0: # https://www.iconsdb.com/custom-color/square-icon.html wall = arcade.Sprite("actual_red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): wall = arcade.Sprite("actual_red_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) object = arcade.Sprite("keyBlue.png", .2) object.left = 350 object.bottom = 350 object.color_match = "blue" object.type = "key" room.object_list.append(object) dragon = Dragon("dragon.png", SPRITE_SCALING * 2) dragon.center_x = 0 dragon.center_y = 400 dragon.dead = False room.dragon_list.append(dragon) room.background = arcade.load_texture("background.png") return room def setup_room_9(): """ Create and return room 9. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.lock_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26: # https://www.iconsdb.com/green-icons/square-rounded-icon.html wall = arcade.Sprite("green wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): wall = arcade.Sprite("green wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create castle for x in range(80, 200, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 30 room.wall_list.append(wall) for x in range(415, 520, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 30 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 55 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 55 room.wall_list.append(wall) for x in range(92, 185, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 80 room.wall_list.append(wall) for x in range(427, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 80 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 105 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 130 room.wall_list.append(wall) for x in range(92, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 155 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 180 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 205 room.wall_list.append(wall) for x in range(92, 250, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) for x in range(357, 505, SPRITE_SIZE * 2): wall = arcade.Sprite("brickGrey.png", 0.2) wall.center_x = x wall.center_y = 230 room.wall_list.append(wall) lock = arcade.Sprite("lockGreen.png", .2) lock.center_y = 205 lock.center_x = 297 lock.angle = 180 lock.color_match = "green" lock.open = False room.lock_list.append(lock) room.background = arcade.load_texture("background.png") return room def setup_room_10(): """ Create and return room 10. """ room = Room() """ Set up the game and initialize the variables. """ # Sprite lists room.wall_list = arcade.SpriteList() room.object_list = arcade.SpriteList() # -- Set up the walls # Create bottom and top row of boxes # This y loops a list of two, the coordinate 0, and just under the top of window for y in (0, SCREEN_HEIGHT - SPRITE_SIZE * 2): # Loop for each box going across for x in range(0, SCREEN_WIDTH, SPRITE_SIZE * 2): if (x != SPRITE_SIZE * 22 and x != SPRITE_SIZE * 24 and x != SPRITE_SIZE * 26) or y == 0: # https://www.walpaperlist.com/2020/01/rainbow-wallpaper-png.html wall = arcade.Sprite("rainbow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # Create left and right column of boxes for x in (0, SCREEN_WIDTH - SPRITE_SIZE * 2): # Loop for each box going across for y in range(SPRITE_SIZE * 2, SCREEN_HEIGHT - SPRITE_SIZE, SPRITE_SIZE * 2): wall = arcade.Sprite("rainbow_wall.png", SPRITE_SCALING) wall.left = x wall.bottom = y room.wall_list.append(wall) # https://findicons.com/icon/456447/trophy object = arcade.Sprite("trophy.png", .2) object.left = 275 object.bottom = 190 object.type = "trophy" object.color_match = "none" room.object_list.append(object) room.background = arcade.load_texture("background.png") return room class Player(arcade.Sprite): def __init__(self, image, scale): super().__init__(image, scale) self.carry = None class Dragon(arcade.Sprite): def __init__(self, image, scale): super().__init__(image, scale) def follow_sprite(self, player_sprite): if self.center_y < player_sprite.center_y: self.center_y += min(MOVEMENT_SPEED - 3, player_sprite.center_y - self.center_y) elif self.center_y > player_sprite.center_y: self.center_y -= min(MOVEMENT_SPEED - 3, self.center_y - player_sprite.center_y) if self.center_x < player_sprite.center_x: self.center_x += min(MOVEMENT_SPEED - 3, player_sprite.center_x - self.center_x) elif self.center_x > player_sprite.center_x: self.center_x -= min(MOVEMENT_SPEED - 3, self.center_x - player_sprite.center_x) class InstructionView(arcade.View): def on_show(self): """ This is run once when we switch to this view """ arcade.set_background_color(arcade.csscolor.DARK_SLATE_BLUE) # Reset the viewport, necessary if we have a scrolling game and we need # to reset the viewport back to the start so we can see what we draw. arcade.set_viewport(0, SCREEN_WIDTH - 1, 0, SCREEN_HEIGHT - 1) def on_draw(self): """ Draw this view """ arcade.start_render() arcade.draw_text("Instructions:", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 90, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text(" Find the hidden chalice that \n has been stolen from the kingdom,\n " "but beware that danger lurks!", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, arcade.color.WHITE, font_size=20, anchor_x="center") arcade.draw_text("Click to advance", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 75, arcade.color.WHITE, font_size=20, anchor_x="center") def on_mouse_press(self, _x, _y, _button, _modifiers): """ If the user presses the mouse button, start the game. """ game_view = MyGame() game_view.setup() self.window.show_view(game_view) class GameOverView(arcade.View): """ View to show when game is over """ def __init__(self): """ This is run once when we switch to this view """ super().__init__() # http://pngimg.com/download/83375 self.texture = arcade.load_texture("game_over_PNG57.png") # Reset the viewport, necessary if we have a scrolling game and we need # to reset the viewport back to the start so we can see what we draw. arcade.set_viewport(0, SCREEN_WIDTH - 1, 0, SCREEN_HEIGHT - 1) def on_draw(self): """ Draw this view """ arcade.start_render() self.texture.draw_sized(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, SCREEN_WIDTH, SCREEN_HEIGHT) arcade.draw_text("Click anywhere to restart!", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 - 150, arcade.color.WHITE, font_size=20, anchor_x="center") def on_mouse_press(self, _x, _y, _button, _modifiers): """ If the user presses the mouse button, re-start the game. """ game_view = MyGame() game_view.setup() self.window.show_view(game_view) class MyGame(arcade.View): """ Main application class. """ def __init__(self): """ Initializer """ super().__init__() # Set the working directory (where we expect to find files) to the same # directory this .py file is in. You can leave this out of your own # code, but it is needed to easily run the examples using "python -m" # as mentioned at the top of this program. file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) # Sprite lists self.current_room = 0 self.object_list = None self.dragon_list = None self.lock_list = None # Set up the player self.rooms = None self.player_sprite = None self.player_list = None self.physics_engine = None # Track the current state of what key is pressed self.left_pressed = False self.right_pressed = False self.up_pressed = False self.down_pressed = False def setup(self): """ Set up the game and initialize the variables. """ # Set up the player # http://www.i2clipart.com/colorwheel-24-football-flower-12-color-f5ce self.player_sprite = Player("player.png", 0.08) self.player_sprite.center_x = 100 self.player_sprite.center_y = 100 self.player_sprite.dead = False self.player_sprite.winner = False self.player_list = arcade.SpriteList() self.player_list.append(self.player_sprite) self.object_list = arcade.SpriteList() self.dragon_list = arcade.SpriteList() self.lock_list = arcade.SpriteList() # Our list of rooms self.rooms = [] # Create the rooms. Extend the pattern for each room. room = setup_room_1() self.rooms.append(room) room = setup_room_2() self.rooms.append(room) room = setup_room_3() self.rooms.append(room) room = setup_room_4() self.rooms.append(room) room = setup_room_5() self.rooms.append(room) room = setup_room_6() self.rooms.append(room) room = setup_room_7() self.rooms.append(room) room = setup_room_8() self.rooms.append(room) room = setup_room_9() self.rooms.append(room) room = setup_room_10() self.rooms.append(room) # Our starting room number self.current_room = 0 # Create a physics engine for this room self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) def on_draw(self): """ Render the screen. """ # This command has to happen before we start drawing arcade.start_render() # Draw the background texture arcade.draw_lrwh_rectangle_textured(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, self.rooms[self.current_room].background) # Draw all the walls in this room self.rooms[self.current_room].wall_list.draw() if self.rooms[self.current_room].lock_list: self.rooms[self.current_room].lock_list.draw() if self.rooms[self.current_room].dragon_list: self.rooms[self.current_room].dragon_list.draw() if self.rooms[self.current_room].object_list: self.rooms[self.current_room].object_list.draw() # If you have coins or monsters, then copy and modify the line # above for each list. self.player_list.draw() if self.player_sprite.carry: self.player_sprite.carry.draw() if self.player_sprite.winner: self.rooms[9].wall_list.draw() arcade.draw_text("CONGRATULATIONS!!", SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2 + 100, arcade.color.WHITE, font_size=30, anchor_x="center") def on_key_press(self, key, modifiers): """Called whenever a key is pressed. """ if key == arcade.key.UP: self.up_pressed = True elif key == arcade.key.DOWN: self.down_pressed = True elif key == arcade.key.LEFT: self.left_pressed = True elif key == arcade.key.RIGHT: self.right_pressed = True elif key == arcade.key.SPACE: if self.player_sprite.carry: self.rooms[self.current_room].object_list.append(self.player_sprite.carry) self.player_sprite.carry = None def on_key_release(self, key, modifiers): """Called when the user releases a key. """ if key == arcade.key.UP: self.up_pressed = False elif key == arcade.key.DOWN: self.down_pressed = False elif key == arcade.key.LEFT: self.left_pressed = False elif key == arcade.key.RIGHT: self.right_pressed = False def on_update(self, delta_time): """ Movement and game logic """ if not self.player_sprite.dead and not self.player_sprite.winner: if self.player_sprite.carry: self.player_sprite.carry.center_x = self.player_sprite.center_x + 30 self.player_sprite.carry.center_y = self.player_sprite.center_y if self.rooms[self.current_room].object_list: object_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.rooms[self.current_room].object_list) if self.player_sprite.carry and self.player_sprite.carry not in \ self.rooms[self.current_room].object_list: self.rooms[self.current_room].object_list.append(self.player_sprite.carry) for object in object_hit_list: self.player_sprite.carry = object self.rooms[self.current_room].object_list.remove(object) if self.rooms[self.current_room].dragon_list: for dragon in self.rooms[self.current_room].dragon_list: if not dragon.dead: dragon.follow_sprite(self.player_sprite) hit = arcade.check_for_collision(self.player_sprite, dragon) if hit: if not dragon.dead and self.player_sprite.carry: if self.player_sprite.carry.type != "sword": self.player_sprite.dead = True view = GameOverView() self.window.show_view(view) else: dragon.dead = True elif not dragon.dead: self.player_sprite.dead = True view = GameOverView() self.window.show_view(view) if self.player_sprite.carry: object_hit_list = arcade.check_for_collision_with_list(self.player_sprite.carry, self.rooms[self.current_room].lock_list) if self.player_sprite.carry.type == "trophy" and self.current_room == 5: self.player_sprite.winner = True self.player_sprite.center_y = 200 self.player_sprite.center_x = 300 self.player_sprite.carry.center_y = 100 self.player_sprite.carry.center_x = 300 self.player_sprite.carry.scale = .5 for object in object_hit_list: if object.color_match == self.player_sprite.carry.color_match and self.current_room == 4 and not object.open: self.rooms[self.current_room].wall_list[150].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[149].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[148].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[147].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[146].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[145].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[132].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[131].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[130].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[129].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[128].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[127].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[114].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[113].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[112].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[111].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[110].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[109].remove_from_sprite_lists() object.open = True self.rooms[self.current_room].lock_list[0].remove_from_sprite_lists() self.rooms[self.current_room].object_list.append(self.player_sprite.carry) self.player_sprite.carry = None elif object.color_match == self.player_sprite.carry.color_match and self.current_room == 0 and not object.open: self.rooms[self.current_room].wall_list[145].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[144].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[143].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[142].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[141].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[140].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[127].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[126].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[125].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[124].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[123].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[122].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[109].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[108].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[106].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[105].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[104].remove_from_sprite_lists() object.open = True self.rooms[self.current_room].lock_list[0].remove_from_sprite_lists() self.rooms[self.current_room].object_list.append(self.player_sprite.carry) self.player_sprite.carry = None elif object.color_match == self.player_sprite.carry.color_match and self.current_room == 8 and not object.open: self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[107].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[118].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[131].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[131].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[131].remove_from_sprite_lists() self.rooms[self.current_room].wall_list[131].remove_from_sprite_lists() object.open = True self.rooms[self.current_room].lock_list[0].remove_from_sprite_lists() self.rooms[self.current_room].object_list.append(self.player_sprite.carry) self.player_sprite.carry = None # Do some logic here to figure out what room we are in, and if we need to go # to a different room. if self.player_sprite.center_x > SCREEN_WIDTH and self.current_room == 0: self.current_room = 1 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = 0 elif self.player_sprite.center_x < 0 and self.current_room == 1: self.current_room = 0 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = SCREEN_WIDTH elif self.player_sprite.center_y < 0 and self.current_room == 1: self.current_room = 2 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 2: self.current_room = 1 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 0: self.current_room = 3 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 elif self.player_sprite.center_y < 0 and self.current_room == 3: self.current_room = 0 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_x < 0 and self.current_room == 0: self.current_room = 4 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = SCREEN_WIDTH elif self.player_sprite.center_x > SCREEN_WIDTH and self.current_room == 4: self.current_room = 0 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = 0 elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 4: self.current_room = 7 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 elif self.player_sprite.center_y < 0 and self.current_room == 7: self.current_room = 4 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_x < 0 and self.current_room == 2: self.current_room = 5 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = SCREEN_WIDTH elif self.player_sprite.center_x > SCREEN_WIDTH and self.current_room == 5: self.current_room = 2 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = 0 elif self.player_sprite.center_x < 0 and self.current_room == 5: self.current_room = 6 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = SCREEN_WIDTH elif self.player_sprite.center_x > SCREEN_WIDTH and self.current_room == 6: self.current_room = 5 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_x = 0 elif self.player_sprite.center_y < 0 and self.current_room == 5: self.current_room = 8 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 8: self.current_room = 5 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 5: self.current_room = 0 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 elif self.player_sprite.center_y < 0 and self.current_room == 0: self.current_room = 5 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_y < 0 and self.current_room == 8: self.current_room = 9 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = SCREEN_HEIGHT elif self.player_sprite.center_y > SCREEN_HEIGHT and self.current_room == 9: self.current_room = 8 self.physics_engine = arcade.PhysicsEngineSimple(self.player_sprite, self.rooms[self.current_room].wall_list) self.player_sprite.center_y = 0 self.player_sprite.change_x = 0 self.player_sprite.change_y = 0 if self.up_pressed and not self.down_pressed: self.player_sprite.change_y = MOVEMENT_SPEED - 2 elif self.down_pressed and not self.up_pressed: self.player_sprite.change_y = -MOVEMENT_SPEED + 2 if self.left_pressed and not self.right_pressed: self.player_sprite.change_x = -MOVEMENT_SPEED + 2 elif self.right_pressed and not self.left_pressed: self.player_sprite.change_x = MOVEMENT_SPEED - 2 # Call update on all sprites self.player_list.update() self.physics_engine.update() def main(): """ Main method """ window = arcade.Window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) start_view = InstructionView() window.show_view(start_view) arcade.run() if __name__ == "__main__": main()
caa4abed4158bc9c4ed4289e1564db76a676dfd7
Jimboni-tech/python-exercise
/first_python/first.py
508
4.15625
4
def main(): while True: try: num = input('what is your favorite number? ') square = int(num)**2 print('The square of', num, 'is', square) break except: print('Please enter a valid number') if __name__ == "__main__": main() ''' I learned how to use a while True loop in order to continously repeat until a certain statement was found, in this case, a number. I then learned how to use break to stop a loop. I also learned how to use try and except. '''
246d8c45ead653cd3df51643eadedee7b2fd9f2f
sydul-fahim-pantha/python-practice
/tutorials-point/list.py
1,522
4.46875
4
#!/usr/bin/python3 num_list = list(range(5)) str_list = ["a", "b", "c"] print() print("str_list: ", str_list ) hetero_list = ["a", 10, list(range(5))] print() print("hetero_list: ", hetero_list ) print() print("num_list: ", num_list ) print("accessing value") print("list[2]: ", num_list[2]) print("delete item 3: del list[2]") del num_list[2] print("num_list", num_list) print() print() print("basic operation") num_list = list(range(5)) print("len(num_list): ", len(num_list)) print("num_list + num_list: ", num_list + num_list) print("num_list * 4: ", num_list * 4) print("3 in num_list: ", 3 in num_list) print() print("iteration: for item in num_list: print('item') ") for item in num_list: print("item: ", item) print() print("slicing") print("num_list[:]", num_list[:]) print("num_list[1:2]", num_list[1:2]) print("num_list[:-1]", num_list[:-1]) print() print("built-in function") print(num_list, " len(num_list)", len(num_list)) print(num_list, " max(num_list)", max(num_list)) print(str_list, " max(str_list)", max(str_list)) print(tuple(range(5)), " list(tuple(range(5))): ", list(tuple(range(5)))) print("list('String'): ", list("String")) print() print("list function") print("list:", num_list) num_list.extend(range(11,15)) print("list.extend(range(11,15)): ", num_list) num_list.append(1) print("list.append(1): ", num_list) print(num_list, ".count(1): ", num_list.count(1)) print(num_list, ".index(1): ", num_list.index(1)) num_list.insert(5, 100) print("list.insert(5, 100): ", num_list)
cc8c22f3b950db022a53d844f185381978fe2eab
ahephner/pythonUdemy
/Python basics/list_methods.py
946
4.21875
4
#list methods add #append #cant add more than 1 item scores = [3,4,12,4] scores.append(3) scores.append('string') #extend can pass in a list that adds to the end of that list #if you did .append([]) you would nest a list in a list scores.extend([2, 3]) print(scores) #insert #first pass where you want the item placed in the index scores.insert(2, 'HEY') #based off last count scores.insert(-2, 'neg') print(scores) teachers = [] teachers.extend(['Colt', 'Blue', 'Lisa']) print(teachers) #List Methods- Delet build = [1,3,4,5] #delete all build.clear() item1 = [1,3,4,5] #returns last item and removes from list question = item1.pop() print(question) print(item1) #removes the index and returns it #can use to grab specific var or just simple remove it sel = item1.pop(1) print(sel) print(item1) #remove #will remove first item from a list of value you give pets = ['dog', 'cat', 'fish', 'fish'] pets.remove('fish') print(pets)
7a2726d05fe906643f70842453af94bdfa01f77c
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/blmjac004/question1.py
956
3.8125
4
message="no message yet" while True: print("Welcome to UCT BBS\nMENU") print("(E)nter a message\n(V)iew message\n(L)ist files\n(D)isplay file\ne(X)it") selection=input("Enter your selection:\n") if selection== "E" or selection=="e": message=input("Enter the message:\n") elif selection=="V" or selection=="v": print("The message is:", message) elif selection=="L" or selection=="l": print("List of files: 42.txt, 1015.txt") elif selection=="D" or selection=="d": filename=input("Enter the filename:\n") if filename== "1015.txt": print("Computer Science class notes ... simplified\nDo all work\nPass course\nBe happy") elif filename== "42.txt": print("The meaning of life is blah blah blah ...") else: print("File not found") elif selection=="X" or selection=="x": print("Goodbye!") break
92749a358c54765e38e8f841fb67be6b7425ee78
yz9527-1/1YZ
/pycharm/Practice/python 3自学/9-函数.py
582
3.75
4
""" def maxTwo(a, b): if a > b: print(a) else: print(b) def maxThree(x, y, z): if x > y: maxTwo(x, z) else: maxTwo(y, z) maxThree(12, 8, 45) import random def custom_str(length, type): if type == 'number': s = '1234567890' elif type == 'letter': s = 'abcdrfg' else: s = '123456789asdfghjklzxcvbnm' return random.sample(s,length) #测试代码 print(custom_str(6,'number')) print(custom_str(7,'letter')) """ #import string,random #user=''.join(random.sample(string.digits,8)) #print(user)
03cf84510129ef9ecc2a33ecf9ea1d7022d7a345
gabriellaec/desoft-analise-exercicios
/backup/user_112/ch16_2020_05_04_19_58_13_049880.py
100
3.59375
4
x = input('valor da conta do restaurante') n = x * 1.01 print("Valor da conta com 10%: R$%2f" % n)
6f6c149d54c7dd0fef7ec9dd0defa5b24f6e9b48
KylanThomson/Polynomial-Regression-Neuron
/main.py
1,106
3.78125
4
# John Bachman Kelley, 10/19/2020, Artificial Intelligence # The purpose of this code is to predict energy consumption using three different architectures of linear regression # neurons. We have been given 3 days of data, from 8:00 to 5:00 pm with 1-hour intervals. import pandas as pd import numpy as np import matplotlib as plt class Neuron1D: # In this method, you need to import, normalize, and set object variables def __init__(self, csv_path): raw_data = pd.read_csv(csv_path) return def train(self): return def test(self): return class Neuron2D: # In this method, you need to import, normalize, and set object variables def __init__(self, csv_path): raw_data = pd.read_csv(csv_path) return def train(self): return def test(self): return class Neuron3D: # In this method, you need to import, normalize, and set object variables def __init__(self, csv_path): raw_data = pd.read_csv(csv_path) return def train(self): return def test(self): return
276c0719a609ba213d60d3c4b75c110a8c34409a
Archenemy-666/Edureka-Python-Training-for-Data-Science
/assignments/case_study/siddharth.c_casestudy1.py
1,543
4.25
4
#Write a program which will find factors of given number and find whether the factor is even or odd. def fatorization_of(x): print("list : ") for i in range(1, x+1): if x % i == 0: print(i," : is a factor") else: print(i," : is not the factor\n\n") num = 10 fatorization_of(num) #case2 Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. list = [] no_of_inputs = int(input("no of inputs: ")) for i in range(0,no_of_inputs): list.append(input("give strings: ")) list.sort() print(list,"\n\n") #Write a program, whichwill find all the numbers between 1000 and 3000 (both included) #such that each digit of a number is an even number. The numbers obtained should be printed #in a comma separated sequence on a single line. i = 1000 for i in range(1000,3001): v = str(i) a = v[0] b = v[1] c = v[2] d = v[3] l = int(a) m = int(b) n = int(c) o = int(d) if((l%2==0) and (m%2==0) and (n%2==0) and (o%2==0) ): print(i) #Write a program that accepts a sentence and calculate the number of letters and digits. x = input() counta = 0 counti = 0 for i in x: if i.isalpha(): counta = counta + 1 elif i.isdigit(): counti = counti + 1 else: print("not recognized") print("number : ",counti, "alphabets",counta) def pallindrome(x): if (x == x[::-1]): print("pallindrome") else : (" not ") pallindrome("dud")
1c1cd18465c3a0232cf863fc8f9a21e6f4a7130b
ektorasgr/ABS
/tablePrinter.py
1,157
4.25
4
''' this function takes a list of lists of strings and displays it in a well-organized table with each column right-justified ABS Ch. 6 Practice Project ''' tableData = [['apples', 'oranges', 'cherries', 'banana'], ['Alice', 'Bob', 'Carol', 'David'], ['dogs', 'cats', 'moose', 'goose']] def printTable(Data): #find the longest string of each list and store in colWidths colWidths = [0] * len(Data) for i in range(len(Data)): for k in range(len(Data[i])): if len(Data[i][k]) > colWidths[i]: colWidths[i] = len(Data[i][k]) #else: #continue #find the longest string of the sublists and store in longest longest = 0 for i in range(len(colWidths)): if colWidths[i] > longest: longest = colWidths[i] #else: #continue for i in range(len(Data[i])): for k in range(len(Data)): if k < (len(Data)-1): print(Data[k][i].rjust(longest), end = '') else: print(Data[k][i].rjust(longest)) printTable(tableData)
ac2504902390a810ed29cb659fe722d2d97d88b8
NikolaosPanagiotopoulos/PythonLab
/labs/source/lab_02/lab_02_exercise_1.py
964
3.640625
4
# Ζητάμε από το φοιτητή να δώσει το όνομα του onoma = input("Δώσε όνομα φοιτητή: ") # Ζητάμε από το φοιτητ΄τη να δώσει το βαθμό προόδου proodos = input("Δώσε βαθμό προόδου: ") # Ζητάμε από το φοιτητ΄τη να δώσει το βαθμό γραπτού grapto = input("Δώσε βαθμό γραπτού: ") # Μετρατρέπουμε την πρόοδο από αλφαριθμητική τιμή σε ακέραια proodos = int(proodos) # Μετρατρέπουμε το γραπτό από αλφαριθμητική τιμή σε ακέραια grapto = int(grapto) # Υπολογίζουμε τον τελικό βαθμό του φοιτητή telikosVathmos = proodos * 0.2 + grapto * 0.8 # Εμφανίζουμε το όνομα του φοιτητή και τον τελικό βαθμό του print(onoma, telikosVathmos)
5e7bc2b2ea7e1eb2faf45710cad46bc82b2703a8
colinpannikkat/pythonexercises
/exercise6.py
344
3.84375
4
string = input("Input String:\n") string = string.replace(" ", "") list = list(string) a = int(len(list)) x = a-1 c = [] while x > -1: b = string[x] c.append(b) x = x-1 b = int(len(c)) z = list[0:a] y = c[0:b] print (z,y) if z == y: print("The string is a palendrome!\n") else: print("The string is not a palendrome.\n")
d12108b43170575efc1fc8647998be68db478eb4
tuanphandeveloper/practicepython.org
/cowsAndBulls.py
1,524
4.125
4
# Create a program that will play the “cows and bulls” game with the user. The game works like this: # Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the # user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly # in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” # they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses # the user makes throughout teh game and tell the user at the end. # Say the number generated by the computer is 1038. An example interaction could look like this: # Welcome to the Cows and Bulls Game! # Enter a number: # >>> 1234 # 2 cows, 0 bulls # >>> 1256 # 1 cow, 1 bull # ... # Until the user guesses the number. import random randNum = ''.join(random.sample('0123456789', 4)) cow = 0 bull = 0 def cowsAndBull(n): cow = 0 bull = 0 randNumList = [int(d) for d in str(randNum)] guessNumList = [int(d) for d in str(n)] for indexA, a in enumerate(randNumList): for indexB, b in enumerate(guessNumList): if a == b: cow = cow + 1 if indexA == indexB: bull = bull + 1 break print(str(cow) + " cows, " + str(bull) + " bulls") return(bull) if __name__=="__main__": print(randNum) while(bull != 4): user_num = int(input("Give me a number: ")) bull = cowsAndBull(user_num)
c88cf2191baf0f40f37b54f70fd57093e6da4c8d
SuzanneRioue/programmering1python
/Arbetsbok/kap 16/övn 16.1, sid. 40 - register.py
2,074
3.53125
4
#!/usr/local/bin/python3.9 # Filnamn: övn 16.1, sid. 40 - register.py # Mer om listor samt dictionarier # Programmeringsövningar till kapitel 16 # Programmet låter användaren mata in uppgifer till register över e-postadresser, vilka lagras i et dictionary. # Nycklarna ska vara namn och e-postadresserna värden. Vi låter användaren välja vad som ska göras genom ett menyval # Import av modul # Funktionsdefinitioner def meny(): print('Vad vill du göra?') print('===================================') print('1. lägga till eller ändra en adress') print('2. söka en adress') print('3. ta bort en adress ur listan') print('4. visa hela registret') print('0. avsluta\n') def avsluta(): exit() def laggTill(): print() nyckel = input('Ange namn: ') värde = input('Ange e-postadress: ') nyckel = nyckel.capitalize() värde = värde.lower() adresser[nyckel] = värde print() def sok(): print() nyckel = input('Ange namn på den adress du vill söka efter: ') nyckel = nyckel.capitalize() if nyckel in adresser: print('Namnet', nyckel, 'finns.') else: print('Ingen med namn', nyckel,'finns.') print() def tabort(): print() nyckel = input('Ange namn på den adress du vill ta bort: ') nyckel = nyckel.capitalize() print('Tar bort addressen', adresser[nyckel]) del(adresser[nyckel]) print() def visa(): print() for nyckel, värde in adresser.items(): print('Namn:', nyckel,'e-post:', värde) print() # Huvudprogram def main(): # Skriv ut meny meny() # Fråga vad användaren vill while True: val = input('Välj 1 - 4 eller 0: ') if val == '0': avsluta() elif val == '1': laggTill() meny() elif val == '2': sok() meny() elif val == '3': tabort() meny() elif val == '4': visa() meny() # Huvudprogram anropas adresser = {} main()
0b7ced82cb26c14214facfb3a1ee5c53d6e593a0
jeffreyalvr/python-sistema-mercado-simples
/main.py
1,329
3.59375
4
import math import sys # variável para determinar em qual menu o usuário estará comando = 0 # mensagem inicial de boas vindas print('Bem-vindo ao Sistema de Mercadinho!\n') # função para exibir o menu inicial def mostrar_menu(): print('1. Inciar uma nova compra') print('2. Adicionar produto ao catálogo') print('3. Remover produto do catálogo') print('4. Sair do programa') # pega o input do usuário com o valor desejado comando = int(input('\nSelecione uma opção digitando um número: ')) # envia o valor para a função valida_input valida_input(comando) # função para terminar a aplicação def sair(): print('\nDeseja sair da aplicação?') comando = int(input("Digite '0' para sair ou '1' para cancelar e voltar ao menu: ")) if (comando == 0): sys.exit() # termina a aplicação else: mostrar_menu() # função que verifica qual o input dado pelo usuário e exibe o menu correspondente def valida_input(valor): import compra import catalogo if (valor == 0): mostrar_menu() elif (valor == 1): compra.compra() elif (valor == 2): catalogo.adicionar_produto() elif (valor == 3): catalogo.remover_produto() elif (valor == 4): sair() # exibe inicialmente o menu mostrar_menu()
22c29914fc208fbbee7042e3cbb2e3c3ffec255e
milohiggo/PythonSQL
/database3.py
602
3.875
4
# -*- coding: utf-8 -*- """ Video https://www.youtube.com/watch?v=byHcYRpMgI4 Created on Sat May 29 20:17:56 2021 @author: ssaghi """ import sqlite3 # conn = sqlite3.connect(':memory:') conn = sqlite3.connect('customer.db') #Create cursor curs = conn.cursor() #Insert many records many_customers = [('M1', 'Brown','M1.Brownn@me.com'), ('M2', 'Brown','M2.Brownn@me.com'), ('M3', 'Brown','M3.Brownn@me.com')] curs.executemany("INSERT INTO customers VALUES (?,?,?)",many_customers) print("Insert many executed successfully") #commit our command conn.commit() # Close connection conn.close()
56073b87d9972d41eb7823b4befa31b7df1f899e
Fahofah/Python-Week1
/Phyton Exs.py
2,619
3.890625
4
#Task1 print('#Task1') print('Hello World!') #Task2 print('#Task2') hi='Hello World' print(hi) #Task3 print('#Task3') def printThis(text): print(text) printThis('Hello Mama') #Task4 print('#Task4') def add(x,y): print(x+y) add(4,5) #Task5 print('#Task5') def sumORmult(x,y,sumIt): if (sumIt): result=x+y else: result=x*y print(result) sumORmult(2,3,False) #Task6 print('#Task6') def sumORmult2(x,y,sumIt): if (x==0): result=y elif (y==0): result=x else: if (sumIt): result=x+y else: result=x*y print(result) sumORmult2(0,7,True) #Task7 print('#Task7') for x in range(0,10): sumORmult2(x,3,True) #Task8 print('#Task8') numList= [6,2,7,4,3,6,7,8,9,10] for x in range(0,10): sumORmult2(numList[x],numList[-(x+1)],True) #Task9 print('#Task9') for x in numList: print(x) #Task10 print('#Task10') nums=[None]*10 for x in range(0,10): nums[x]=x print(x) for x in nums: print(x*10) #Task11 print('#Task11') size=int(input('How many numbers you want to enter?')) numSet=[None]*size print('OK, now please enter the first number') for x in range(0,size): numSet[x]=int(input()) print('Now please enter number %d' %(x+2)) for x in numSet: print(x) for x in numSet: print(x*10) #Task12 print('#Task12') from functools import partial def mult(x,y): return x*y num=int(input('Enter a number:')) double = partial(mult,2) triple = partial(mult,3) print("Double is", str(double(num)) ,"and triple is " ,str(triple(num))) #Task13 print('#Task13') def blackjack(x,y): if(x<0 or y<0): print('Invalid cards') else: if(x>21 and y>21): return 0 elif(x>21 and y<22): print('was here') return y elif(y>21 and x<22): return x else: if(x>y): return x elif(y>x): return y elif(x==y): print('Tie') print(blackjack(23,23)) #Task14 print('#Task14') def uniqSum(x,y,z): if(x==y==z): return 0 elif(x==y): return y+z elif(y==z): return x+y elif(x==z): return x+y else: return x+y+z print(uniqSum(2,2,1)) #Task15 print('#Task15') def tooHot(temp,isSummer): upLim=90 if(isSummer): upLim=100 if(temp>=60 and temp<=upLim): return True else: return False print(tooHot(95,True)) #Task16 print('#Task16') def isLeap(year): if(year%4==0): return True else: return False print(isLeap(2001))
e870a8e0ff6adaa32e2722aa4e9622839bd0e07d
rafaelblira/python-progressivo
/exibir_laber_vertical.py
841
4
4
import tkinter class MinhaGUI: def __init__(self): # Criando a janela principal self.main_window = tkinter.Tk() # Criando a label Ceará e exibindo self.label = tkinter.Label(self.main_window, text="Ceará", bg="black", fg="white") self.label.pack(fill = tkinter.Y, side='left') # Criando a label Flamengo e exibindo self.label = tkinter.Label(self.main_window, text="Flamengo", bg="red", fg="black") self.label.pack(fill = tkinter.Y, side='left') # Criando a label Palmeiras e exibindo self.label = tkinter.Label(self.main_window, text="Palmeiras", bg="green", fg="black") self.label.pack(fill = tkinter.Y, side='left') # Fazer o Tkinter exibir o looping da janela tkinter.mainloop() minha_gui = MinhaGUI()
7a881b449e348d21f5174a30384f6f5cac16b2b4
arnoldtaveras/ICC_102
/dividendos.py
343
4.03125
4
dividendo = -1 divisor = -1 while (dividendo <= 0 or divisor <= 0): dividendo = int(input("Digite el dividendo: ")) divisor = int(input("Digite el divisor: ")) if (dividendo <= 0 or divisor <= 0): print ("Error. solo numeros positivos") while(dividendo >= divisor): dividendo = dividendo - divisor print(dividendo)
458b1e6f951f4f53aaa625b3d8c09e7a69703257
aechen10/redtrackedit
/Test/Pandas+NumPy/pandasTest.py
2,017
3.546875
4
import numpy import pandas import random #Creating series (similar to arrays?) s = pandas.Series([1, 3, 5, numpy.nan, 6, 8]) print(s) #Creating Date Range dates = pandas.date_range('20190602', '20190604',3) print(dates) numpyData = numpy.random.randn(3, 4) for i in range(0, len(numpyData)): for j in range(0, len(numpyData[i])): print(numpyData[i][j], end=" ") print() dataFrame = pandas.DataFrame(numpyData, index = dates, columns=list('ABCD')) print(dataFrame) #None is python's equivalent of null (HOWEVER, python CAN print None values) variable = None print(variable) arr = [[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]] dataFrame2 = pandas.DataFrame(arr, index = ["1-4","5-8", "9-12","13-16"], columns=["1*4", "2*4", "3*4", "4*4"]) print(dataFrame2) #Print out dataframe index as index object print(dataFrame2.index) print(dataFrame.describe()) dataFrame.at['20190602', 'A'] = None print(dataFrame) dataFrame3 = dataFrame2.sort_values(by = "1*4", ascending = False) print(dataFrame3) randomArray = [] for i in range(0, 7): randomArray.append([]) for j in range(0,50): randomArray[i].append(random.randint(0,25)) randomData = pandas.DataFrame(randomArray, index = ["A","B","C","D","E","F","G"]).T randomData = randomData.sort_values(by = "A", ascending = True) print(randomData) sortData = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'], 'age': [20, 19, 19, 21], 'favorite_color': ['blue', 'red', 'yellow', "green"], 'grade': [88, 92, 95, 70]} dataFrame4 = pandas.DataFrame(sortData, index = sortData['name']) print(dataFrame4) dataFrame4 = dataFrame4.sort_values(by = ['age', 'grade'], ascending= [True, False]) print(dataFrame4) data5 = {'Title': ['Article 1', 'Article 2' , 'Article 3', 'MEMEZ'], 'Upvotes': [5,104,104,38910], 'Downvotes': [0, 104, 1, 0], 'Comments': [2, 50, 23, 1045]} dataFrame5 = pandas.DataFrame(data5, index = data5['Title']) dataFrame5 = dataFrame5.sort_values(by = ['Upvotes', 'Downvotes'], ascending= [False, True]) print(dataFrame5)
3a8f91d5e43af07ad555619162a25a3c548a7c1b
nuraanNinah/ANIMALS-PART-1.-OOP-BASICS
/Animal.py
326
3.796875
4
class Animal: def __init__ (self, name, sounds): self.name= name self.sounds =sounds def food(self): print("{0} eats".format (self.name)) def sound(self): print("{0} barks".format(self.sounds)) dog = Animal("Rex", "Dog") cat = Animal("Stormy", "Cat") dog.food() dog.sound()
7ded493fa87d022fe474133db99a6ba62b241292
ShimnaA/Turtle
/Hexagon.py
119
3.78125
4
# Draw a Hexagon using turtle import turtle t = turtle.Turtle() for i in range(6): t.forward(50) t.right(60)
5c31af2cf537031b0d22d7d1471a64e6774dff58
PedroDNBR/ossu-pyton-for-everybody
/6. Loops and Iterations/worked-exercise-5.1.py
582
4.03125
4
numberQtd = 0 total = 0 #loop that users insert the numbers, if write done, the loop stops while True numberInput = input("Insira um numero:") if numberInput == "done" : break try: numberFloat = float(numberInput) except: print("Valor invalido") continue #calculate the number quantity and the total of sum numberQtd = numberQtd + 1 total = total + numberFloat #print total, number quantity and the average print("O total é:"+total,", o a quantidade de numeros inseridos é:"+numberQtd,"e a média é:"total/numberQtd)
23ba4a0f80643f85ca5b64af6aca504034249d52
ZoranPandovski/al-go-rithms
/data_structures/b_tree/Python/sum_root_leaf.py
1,270
4.125
4
""" To find whether a tree has a sum of tree from root to leaf is equal to the given number. If true, return the path which produces the sum. Else, return False """ from __future__ import print_function import binary_search_tree class SumRootLeaf(): def root_leaf(self,root, given_sum, val, path_list): if root == None: return if root.left == None and root.right == None: if (val + root.val) == given_sum: path.append(root.val) return True else: return False if(self.root_leaf(root.left,given_sum,(val + root.val),path_list)): path.append(root.val) return True if(self.root_leaf(root.right,given_sum,(val + root.val),path_list)): path.append(root.val) return True return False ### Testcases ### root = None tree = binary_search_tree.Tree() root = tree.insert(root, 4) root = tree.insert(root, 2) root = tree.insert(root, 1) root = tree.insert(root, 3) root = tree.insert(root, 5) #tree.preorder(root) obj = SumRootLeaf() path = [] if(obj.root_leaf(root,9,0,path)): print(path) else: print(None)
d55a2966408ec30b2ee98097bf520cb399c1c43f
favour-22/holbertonschool-higher_level_programming
/0x03-python-data_structures/2-main.py
803
3.953125
4
#!/usr/bin/python3 replace_in_list = __import__('2-replace_in_list').replace_in_list my_list = [1, 2, 3, 4, 5] idx = 3 new_element = 9 new_list = replace_in_list(my_list, idx, new_element) print("Valid index") print(new_list) print(my_list) idx = -1 new_element = 19 new_list = replace_in_list(my_list, idx, new_element) print("Negative index") print(new_list) print(my_list) idx = 10 new_element = 29 new_list = replace_in_list(my_list, idx, new_element) print("Out of range index") print(new_list) print(my_list) idx = 4 new_element = 39 new_list = replace_in_list(my_list, idx, new_element) print("Last index") print(new_list) print(my_list) idx = 5 new_element = 49 new_list = replace_in_list(my_list, idx, new_element) print("One greater than last index") print(new_list) print(my_list)
ce55d1121ac3ea0d4ec4c4dc722f24ab7fe0b3e0
dhanashreesshetty/Project-Euler
/Problem 19 Counting Sundays/pyprog.py
161
3.84375
4
from datetime import date count=0 for year in range(1901,2001): for month in range(1,13): if date(year,month,1).weekday()==6: count+=1 print(count)
6f07c8fa8f7bf8f0a945613e48c5a76aadc028b3
nodicora/planarity
/planarity/planarity_functions.py
780
3.671875
4
"""Functional interface to planarity.""" import planarity __all__ = ['is_planar', 'kuratowski_edges', 'ascii', 'write', 'mapping'] def is_planar(graph): """Test planarity of graph.""" return planarity.PGraph(graph).is_planar() def kuratowski_edges(graph): """Return edges of forbidden subgraph of non-planar graph.""" return planarity.PGraph(graph).kuratowski_edges() def ascii(graph): """Draw text representation of a planar graph.""" return planarity.PGraph(graph).ascii() def write(graph, path='stdout'): """Write an adjacency list representation of graph to path.""" planarity.PGraph(graph).write(path) def mapping(graph): """Return dictionary of internal mapping of nodes to integers.""" return planarity.PGraph(graph).mapping()
6a9882c304ac032524e615e45c9e80c2301ea69a
pnugues/ilppp
/programs/ch05/python/count_bigrams.py
737
3.875
4
""" Bigram counting Usage: python count_bigrams.py < corpus.txt """ __author__ = "Pierre Nugues" import sys import regex def tokenize(text): words = regex.findall(r'\p{L}+', text) return words def count_bigrams(words): bigrams = [tuple(words[idx:idx + 2]) for idx in range(len(words) - 1)] frequencies = {} for bigram in bigrams: if bigram in frequencies: frequencies[bigram] += 1 else: frequencies[bigram] = 1 return frequencies if __name__ == '__main__': text = sys.stdin.read().lower() words = tokenize(text) frequency_bigrams = count_bigrams(words) for bigram in frequency_bigrams: print(frequency_bigrams[bigram], "\t", bigram)
d2e3b144af63fee8009b8dacd4e83b35503d46f7
ashud06/algorithms_dataStructures
/Code_development/Recursion_Backtracking/Hackerank_Problems/problem1/problem1.py
2,785
3.5625
4
#!/bin/python3 import math import os import random import re import sys ''' def check(X,val): global combos if val == X: print('success') combos+=1 return 1 else: return 0 def getCombos(X, N,prev_total=0,start_index=0): print('previous total: {}'.format(prev_total)) if start_index == X - 1 or prev_total > X: return global combos total = 0 print("SI: {}".format(start_index)) possibleList = [i for i in range(1, X)] print(possibleList) ptr_val = possibleList[start_index] print("PTR val: {}".format(ptr_val)) status=check(X, pow(ptr_val, N)) if status: return 1 total += pow(ptr_val, N) print('total updated to at start: {0}'.format(total)) for j in range(start_index+1,X): print('checking now with {} against {}'.format(ptr_val,possibleList[j])) print('total is : {}'.format(total)) for i in range(j, X): print("current iter: {0} , {1}".format(i, possibleList[i])) if pow(possibleList[i], N) > X or i == X - 1 or total > X: print('flag 1') return 2 if possibleList[i] == ptr_val or possibleList[i] == 0: print('flag 2') # total+=pow(possibleList[i],N) # print('total updated to: {0}'.format(total)) # check(X,total) continue total += pow(possibleList[i], N) status=check(X, total) if status: return 1 print('total updated to: {0}'.format(total)) if total > X: total -= pow(possibleList[i], N) print('total updated to after return 2: {0}'.format(total)) return total #series-> 6,7, #trigger 6, 36 check, +next iter ie. 7, total=36+49=85, into iter 8 where +8>X, back to iter 7, total back to 85. total= total + prev_total status=check(X, total) result = getCombos(X, N, total, i) if result == 2: total-=pow(possibleList[i],N) print('total updated to after return: {0}'.format(total)) break # Complete the powerSum function below. def powerSum(X, N): possibleList=[i for i in range(1,X)] for i in possibleList: if pow(i,N)<=X: print("Next Triggered: {}".format(i)) getCombos(X,N,0,0) combos = 0 ptr = 0 print(powerSum(100, 3)) print(combos) ''' def totnum(X,N,num=1): print('func called with params: {} , {} , {}'.format(X,N,num)) if(pow(num,N)<X): return (totnum(X,N,num+1)+totnum(X-pow(num,N),N,num+1)) elif(pow(num,N)==X): return 1 else: return 0 print(totnum(100,2))
2a02f0ef86a56792fa2bbb15778d45325e6071d1
EunhyeKIMM/python
/ch09/ex13.py
262
3.546875
4
import time def gettime(): now = time.localtime() return now.tm_hour, now.tm_min result = gettime() print("지금은 %d시 %d분 입니다. " %(result[0], result[1])) hour, minute = gettime() print("지금은 %d시 %d분 입니다. " %(hour, minute))
7242e88b50610a0481937714bf2dc40dfb69f138
sknielsen/shopping_list
/shopping_list_program.py
1,823
4.3125
4
shopping_list = { "Target": ["socks" , "soap", "detergent", "sponges"], "Bi-Rite" : [ "butter", "cake", "cookies", "bread"] } #Function to display main Menu def show_main_menu(): return """ 0 - Main Menu 1 - Show all lists. 2 - Show a specific list. 3 - Add a new shopping list. 4 - Add an item to a shopping list. 5 - Remove an item from a shopping list. 6 - Remove a list by nickname. 7 - Exit when you are done. """ #Function that shows all lists def show_all_lists(): # print shopping_list for nickname in shopping_list: print nickname + ': ' + ", ".join(shopping_list[nickname]) #for nickname in shopping.list: #Function to show a specific list def show_specific_list(list): print list + ': ' + ", ".join(shopping_list[list]) # def add_new_list(item, list): shopping_list[list] = item def add_item_to_list(item, list): shopping_list[list].append(item) return shopping_list def remove_item_from_list(item, list): shopping_list[list].remove(item) return shopping_list def remove_list(list): del shopping_list[list] return shopping_list def exit_program(): exit() def main(): #show_main_menu() user_input = int(raw_input(show_main_menu())) if user_input == 0: print show_main_menu() elif user_input== 1: show_all_lists() elif user_input == 2: list = raw_input("Enter list to be displayed") show_specific_list(list) elif user_input == 3: list = raw_input("Enter new list name") item = raw_input("Enter items for new list") #show_main_menu() #show_all_lists() #show_specific_list('Target') #print add_item_to_list('brush', 'Target') #print remove_item_from_list('soap', 'Target') #print remove_list('Target') if __name__ == '__main__': main()
e27ce8911a2851969ed189bc7d326d9f3a6307f3
Infinity7878/SimpleLogin
/main.py
937
3.671875
4
import tkinter as tk from tkinter import messagebox app = tk.Tk() app.geometry("300x50") box1 = tk.Entry(app) box1.grid(row=1, column=1) box2 = tk.Entry(app) box2.grid(row=2, column=1) def signup(): user = box1.get() passw = box2.get() file1 = open("users.txt", "a") info = user + passw file1.write("\n" + info) def login(): user = box1.get() passw = box2.get() file1 = open("users.txt", "r") info = user + passw if info in file1: tk.messagebox.showinfo("Success", "Success") else: tk.messagebox.showinfo("Error", "Incorrect Username or Password") tk.Label(app, text="Username:").grid(row=1, column=0) tk.Label(app, text="Password:").grid(row=2, column=0) button1 = tk.Button(app, command=login, text="Login") button1.place(x=200, y=10) button2 = tk.Button(app, command=signup, text="SignUp") button2.place(x=245, y=10) app.mainloop()
353843608bede50f52ff8bf3662c3bb1ca048bf8
sharondsza26/python-Technology
/objectOriented/PiggyBank/objectOrientation.py
2,111
3.921875
4
# Stage 1 class PiggyBank: pass print("Hello") pg1 = PiggyBank() print(pg1) print(id(pg1)) print(hex(id(pg1))) print(type(pg1)) print(pg1.__class__) # Stage 2 -Extensible class PiggyBank: pass pg1 = PiggyBank() print(pg1) print(id(pg1)) print(pg1.__class__) pg1.balance = 10 # It creates a variable balance i.e Object pg1 got extended pg1.lt = 10 # It creates a variable lt print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(pg2) print(id(pg2)) print(pg2.__class__) pg2.balance = 200 # It creates a variable balance i.e Object pg2 got extended pg2.lt = 200 # It creates a variable lt print(pg2.balance) print(pg2.lt) print(isinstance(pg1,PiggyBank)) print(isinstance(pg2,PiggyBank)) # Stage 3 - __init__ class PiggyBank: def __init__(self): print("Entering Init") print(id(self)) print("Leaving Init") pg1 = PiggyBank() print(id(pg1)) pg1.balance = 10 pg1.lt = 10 print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(id(pg2)) pg2.balance = 200 pg2.lt = 200 print(pg2.balance) print(pg2.lt) # Stage 4 - self class PiggyBank: def __init__(self): #Constructor print("Entering Init") self.balance = 0 self.lt = 0 print("Leaving Init") pg1 = PiggyBank() print(pg1.balance) print(pg1.lt) pg2 = PiggyBank() print(pg2.balance) print(pg2.lt) # Stage 5 - Object Oriented Piggy print("Welcome to Object Oriented PiggyBank") class PiggyBank: def __init__(self): self.balance = 0 self.lt = 0 def deposit(self,amount): self.balance = self.balance + amount self.lt = amount def withdraw(self,amount): if(self.balance >= amount): self.balance -= amount self.lt = -amount def statement(self): print("Balance =",self.balance) print("Last Transaction =",self.lt) pg1 = PiggyBank() pg1.deposit(100) pg1.deposit(100) pg1.statement() pg1.withdraw(50) pg1.statement() pg2 = PiggyBank() pg2.deposit(1000) pg2.deposit(1000) pg2.statement() pg2.withdraw(500) pg2.statement()
45aa0f6b6b032f5f31a392efb73131de994fa4ce
Edvinauskas/Project-Euler
/nr_014_python.py
1,178
3.875
4
######################################### # Problem Nr. 14 # The following iterative sequence is defined # for the set of positive integers: # # n n/2 (n is even) # n 3n + 1 (n is odd) # # Using the rule above and starting with 13, we # generate the following sequence: # # 13 40 20 10 5 16 8 4 2 1 # It can be seen that this sequence (starting at # 13 and finishing at 1) contains 10 terms. # Although it has not been proved yet (Collatz Problem), # it is thought that all starting numbers finish at 1. # # Which starting number, under one million, # produces the longest chain? # # NOTE: Once the chain starts the terms are # allowed to go above one million. ######################################### largest_sequence = 0 most_seq = 1 cache = [0 for i in range(1000000)] for i in range(1000000): length = 1 sequence = i while sequence > 1 and sequence >= i: if sequence % 2 == 0: sequence = (sequence/2) else: sequence = (3 * sequence) + 1 length += 1 cache[i] = length + cache[sequence] if cache[i] > largest_sequence: largest_sequence = cache[i] most_seq = i print most_seq
d11b87211b857167e090cd315ac093554403ba66
MakeSchool-17/twitter-bot-python-samlee405
/5. HerokuServer/sample.py
1,287
3.890625
4
import wordFrequency import sys import random # Get a random word from a file def sample(): textFile = sys.argv[1] histogram = wordFrequency.histogramFile(textFile) # print(histogram) # Get total count of words wordCount = 0 for item in histogram: wordCount += item[1] # Generate a random number from 1 - wordCount randomValue = random.randint(1, wordCount) # print(randomValue) # Iterate to find the chosen word sumTotal = 0 for item in histogram: sumTotal += item[1] if randomValue <= sumTotal: return item[0] # Test accuracy of sample() def sampleTest(count): oneCount = 0 twoCount = 0 threeCount = 0 fourCount = 0 fishCount = 0 for _ in range(count): word = sample() if word == "one": oneCount += 1 elif word == "two": twoCount += 1 elif word == "three": threeCount += 1 elif word == "four": fourCount += 1 elif word == "fish": fishCount += 1 print("one: " + str(oneCount) + "\n" + "two: " + str(twoCount) + "\n" + "three: " + str(threeCount) + "\n" + "four: " + str(fourCount) + "\n" + "fish: " + str(fishCount)) # print(sample()) # sampleTest(8000)
576585854e1f93c004ffa0da9549d387a515b8e2
sreesindhusruthiyadavalli/MLsnippets
/numpybasics.py
1,031
4
4
import numpy as np #1d array a = np.array([0,1, 2, 3,4,5]) print a print a.ndim #dimension is 1 print a.shape #(6,) is 6 rows print a.dtype #type of the array #For 2d array b = a.reshape((3,2)) # 3 rows and 2 columns print b print b.ndim #2 dimensional print b.shape #Shape of the array #Here b and a refers same object ,to have independent objects use .copy() c = a.reshape((3,2)).copy() #Operations on numpy array d = np.array([1,2,3,4,5]) print d * 2 print d ** 2 #To filter the data with some conditions print a > 4 print a[a > 4] #To trim outliers of any data a[a > 4] = 5 print a print a.clip(0, 4) #To clip the values at both ends of an interval #Non existing values k = np.array([1, 2, np.NAN, 3, 4]) print k print np.isnan(k) #Array that results True for Nan print k[~np.isnan(k)] #Array results only valid numbers print np.mean(k[~np.isnan(k)]) #Find the mean of all valid numbers #For different datatypes in np array print np.array([1, "Test"]).dtype print np.array([1, "Test", set([1,2,3])]).dtype
f114dbea25ff21bc529989c4fee1a19cac287f87
frankolson/PythonProjectEuler
/problem8.py
611
3.8125
4
### Project Euler Problem 8 ### Will Olson ### 01 July 2013 ### Python 2.7.5 def iterate_through_file( file_name ): fout = open(file_name, 'r') file_line = fout.readline() file_list = list(file_line) count = 0 highest = 0 while count < len(file_list)-5: product = int(file_list[count])*int(file_list[count+1])*int(file_list[count+2])*int(file_list[count+3])*int(file_list[count+4]) if product > highest: highest = product count += 1 fout.close() return highest user_file = raw_input("enter a file name: ") print iterate_through_file(user_file)
b4be1ec472c62ad0c15b1028527729248c6671ea
costadazur/g_code_sample_python
/src/video_playlist.py
1,124
3.78125
4
"""A video playlist class.""" from .video_library import VideoLibrary from .video import Video class Playlist: """A class used to represent a Playlist.""" def __init__(self): self._video_library = VideoLibrary() self._videos = [] self._current_video = Video("","","") def add_video_to_playlist(self, video_id): found_video = False for vid in self._video_library.get_all_videos(): if(vid.video_id)==video_id: self._videos.append(vid) found_video = True if found_video == False: raise ValueError("Video is not in library") def delete_video_from_playlist(self, video_id): found_video = False video_found = [] for vid in self._video_library.get_all_videos(): if(vid.video_id)==video_id: video_found = vid found_video = True if found_video == False: raise ValueError("Video is not in playlist") else: self._videos.remove(video_found) def clear_videos_from_playlist(self): self._videos = []
0b3f5a7174a434763041c921188ee74e1023551e
guveni/RandomExerciseQuestions
/distance.py
978
4
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ """ __author__ = 'guven' def get_min_of_three(o1,o2,o3): first = o1 if o1 < o2 else o2 result = first if first < o3 else o3 return result def calculate_dist(str1, str2): if not str1 or not str2: return -1 len1 = len(str1)+1 len2 = len(str2)+1 matrix = [[0 for x in xrange(len1)] for y in xrange(len2)] for i in xrange(1,len1): matrix[0][i] = i for i in xrange(1,len2): matrix[i][0] = i for y in xrange(1, len1): for x in xrange(1, len2): c1 = str1[y-1] c2 = str2[x-1] if c1 == c2: matrix[x][y] = matrix[x-1][y-1] else: opt1 = matrix[x-1][y] opt2 = matrix[x][y-1] opt3 = matrix[x-1][y-1] matrix[x][y] = get_min_of_three(opt1, opt2, opt3) +1 return matrix[len2-1][len1-1] print calculate_dist('saturday','sunday')
56df065da26975a245a8bdd365ca7b46afadc281
MichaelYoungGo/Practice
/输入限制I的双向队列.py
1,714
3.96875
4
# -*- coding: utf-8 -*- # @Time : 2018/11/1 0001 下午 1:23 # @Author : 杨宏兵 # @File : 输入限制I的双向队列.py # @Software: PyCharm class Node: def __init__(self): self.data = 0 self.next = None front = Node() rear = Node() front = None rear = None def enquenue(value): global front global rear node = Node() node.data = value node.next = None if rear == None: front == node else: rear.next = node rear = node def dequeue(action): global front global rear if (front != None) and action == 1: if front == rear: rear= None value = front.data front = front.next return value elif front != None and action ==2: startNode = front value = rear.data tempNode = front while front.next != rear and front != None: front = front.next tempNode = front front = startNode rear = tempNode if front.next == None or rear.next == None: front = None rear = None return value else: return -1 print('用链表来实现双向队列') print('===============================================') ch = 'a' while True: ch = input('加入请按a, 取出请按d, 结束请按e') if ch == 'e': break elif ch == 'a': item = int(input('加入的元素值:')) enquenue(item) elif ch == 'd': temp = dequeue(1) print('从双向队列前端按序取出的元素值为:%d' %temp) temp = dequeue(2) print('从双向队列后端按序取出的元素值为:%d' % temp) else: break
a0cd4e87f470509d4b764b4b379575fb843ec153
Glitch-is/CP
/cp.py
2,414
4.15625
4
""" Competitive Programming Library for Python Functions: #Primes: isPrime(n) sieve(n) #Fibonacci: fib(n) Authors: Glitch https://github.com/RuNnNy/CP """ import math """Primality check that iterates through all integers below the square root of the number being checked and makes sure it's not divisable by any of them""" def isPrime(n): if n <= 1: return False if n is 2: return True if n % 2 is 0: return False for i in range(3, math.sqrt(n) + 1, 2): if n % i is 0: return False return True """Returns a Sieve of Eratosthenes. Generates all prime numbers below n""" def sieve(n): prime = [True] * n + 1 prime[0], prime[1] = False, False for i in range(2, math.sqrt(n) + 1): if prime[i]: for k in range(i * i, n + 1, i): prime[k] = False return prime # Fast doubling Fibonacci algorithm # # Copyright (c) 2013 Nayuki Minase # All rights reserved. Contact Nayuki for licensing. # http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms # Returns F(n) def fib(n): if n < 0: raise ValueError("Negative arguments not implemented") return _fib(n)[0] # Returns a tuple (F(n), F(n+1)) def _fib(n): if n == 0: return (0, 1) else: a, b = _fib(n // 2) c = a * (2 * b - a) d = b * b + a * a if n % 2 == 0: return (c, d) else: return (d, c + d) """Returns all prime factors of number""" def PrimeFactors(n): #Returns factors of n primeList = [] d = 2 while n != 0: if n % d == 0: primeList.append(d) n /= d else: d += 1 if d*d > n: if n > 1: primeList.append(n) break return primeList """Returns number of divisors""" def NumberOfDivisors(n): #Returns the number of divisors of n factors = PrimeFactors(n) tmp = factors[0] res,count = 1, 0 for x in range(len(factors)): if factors[x] != tmp: tmp = factors[x] res *= (count+1) count = 1 if x == len(factors): res *= 2 else: count += 1 if count > 0: res *= (count+1) return res """Checks if number is palindrome""" def isPalindrome(n): return str(n) == str(n)[::-1]
fdfc923ad3020be38d6dbbc059bfd944877ff7af
ppinko/python_exercises
/algorithms/hard_algoritm_sorting_time.py
570
3.703125
4
""" https://edabit.com/challenge/kjJWvK9XtdbEJ2EKe """ def sort_array(L: list) -> list: for i in range(len(L)): for j in range(len(L) - 1): if L[j+1] < L[j]: temp = L[j+1] L[j+1] = L[j] L[j] = temp return L assert sort_array([2, -5, 1, 4, 7, 8]) == [-5, 1, 2, 4, 7, 8] assert sort_array([23, 15, 34, 17, -28]) == [-28, 15, 17, 23, 34] assert sort_array([38, 57, 45, 18, 47, 39]) == [18, 38, 39, 45, 47, 57] assert sort_array([26, -1, -45, 74, 20]) == [-45, -1, 20, 26, 74] print("Success")
08f4b21b8da0de351ac2b69bf1926dfa9cafbf1d
GlennRC/Algorithms
/Labs/Lab13/Horspools.py
2,103
3.53125
4
import string import random import time ''' This lab was worked on by Glenn Contreras, Neha Tammana, and Ben Liu ''' def shiftTable(pattern, isBit): if isBit: var = ['0', '1'] else: var = string.ascii_lowercase + ' ' table = {} for i in range(len(var)): table.update({var[i]: len(pattern)}) for j in range(len(pattern)-1): table[pattern[j]] = len(pattern) - 1 - j return table def horspool(pattern, text, isBit): table = shiftTable(pattern, isBit) m = len(pattern) i = m-1 while i <= len(text)-1: k = 0 while k <= m-1 and pattern[m-1-k] == text[i-k]: k += 1 if k == m: return i-m+1 else: i += table[str(text[i])] return -1 def bruteForceStringMatch(Text, Pattern): n = len(Text) m = len(Pattern) for i in range(n - m + 1): j = 0 while j < m and Pattern[j] == Text[i+j]: j += 1 if j == m: return i return -1 def genBits(): l = [] for i in range(1000000): l.append(random.randrange(0, 2)) return l def main(): pattern = "pizzazzy" bitPattern = "01110100" print("1) Part a") print(pattern) print(shiftTable(pattern.lower(), False)) print("\nPart b") print(bitPattern) print(shiftTable(bitPattern, True)) text = "I don't want to go to the party looking too pizzazzy" print("\n2)") index = horspool(pattern.lower(), text.lower(), False) if index != -1: print("Found {} at index {}".format(pattern, index)) else: print("{} not found in text".format(pattern)) bitText = genBits() bitPattern = '0000000000' print("\nPerformance comparison against Horspool's and the bruteforce algorithm") start = time.time() print(horspool(bitPattern, bitText, True)) print("Horspool's time: {}".format(time.time() - start)) start = time.time() print(bruteForceStringMatch(bitText, bitPattern)) print("Brute force time: {}".format(time.time() - start)) if __name__ == "__main__": main()
38b5aa1557881fb22c3722c5bea8cf42a9befffb
Inosonnia/ImgAna
/recog_label2txt.py
1,854
3.71875
4
#coding:utf-8 #将一种字符集产生的Text文件,转换为Label import codecs import argparse import os import sys def read_tag_file(tag_file): file_io = codecs.open(tag_file,'r','utf-8') lines = file_io.readlines() file_io.close() tag_map = {} for line in lines: line = line.strip() label,text = line.split() label = label.split(',')[0] text = text.split(',')[0] tag_map[label] = text # tag_map[label] = text.encode("ascii","ignore") return tag_map # for line in lines: # line = line.strip() # label,text = line.split() # label = label.split(',')[0] # tag_map[text] = label # return tag_map parser = argparse.ArgumentParser() parser.add_argument( "label_file", help="input label file." ) parser.add_argument( "gtlabel_file", help="label_file's tag map file" ) parser.add_argument( "output", help="output label file" ) args = parser.parse_args() label_file = args.label_file tag_file = args.gtlabel_file output = args.output # if os.path.exists(output): # print '%s is exists' % output # exit(-1) tag_map = read_tag_file(tag_file) file_io = codecs.open(label_file,'r','utf-8') lines = file_io.readlines() file_io.close() ignore_lines = [] file_io = codecs.open(output, 'w','utf-8') print tag_map for line in lines: line = line.strip() path, text = line.split() print text tag_maps = "" for ch in text.split(','): if tag_map.has_key(ch): # print ch,tag_map[ch] tag_maps = tag_maps + '%s' %(tag_map[ch]) # tag_maps = tag_maps.encode('utf-8') file_io.write('%s %s\n' %(path, tag_maps)) file_io.close() if len(ignore_lines) > 0: print 'ignore labels:' for line in ignore_lines: print line
39b2342dd306d706f8ba9cbcf383f08a55385b6a
BoZhaoUT/Teaching
/Winter_2016_CSCA48_Intro_to_Computer_Science_II/Week_2_ADTs_and_Number_Conversion/my_queues.py
5,266
4
4
class QueueA: '''A first-in , first-out (FIFO) queue of items''' def __init__(self): '''(Queue) -> NoneType Create a new, empty queue. ''' self._contents = [] def push(self, new_obj): '''(Queue, obj) -> NoneType Place new_obj at the end of this queue. ''' self._contents.append(new_obj) def pop(self): '''(Queue) -> obj Remove and return the first item in this queue. ''' return self._contents.pop(0) def is_empty(self): '''(Queue) -> bool Return True iff this queue is empty. ''' return self._contents == [] def __str__(self): '''(Queue) -> str Return a string representation of this queue. ''' # create an empty result ready to use result = '' for next_element in self._contents: result += str(next_element) + ' ' return result class QueueB: '''A first-in , first-out (FIFO) queue of items''' def __init__(self): '''(Queue) -> NoneType Create a new, empty queue. ''' self._contents = [] def push(self, new_obj): '''(Queue, obj) -> NoneType Place new_obj at the end of this queue. ''' self._contents.insert(0, new_obj) def pop(self): '''(Queue) -> obj Remove and return the first item in this queue. ''' return self._contents.pop() def is_empty(self): '''(Queue) -> bool Return True iff this queue is empty. ''' return self._contents == [] def __str__(self): '''(Queue) -> str Return a string representation of this queue. ''' # create an empty result ready to use result = '' for i in range(len(self._contents) -1, -1, -1): result += self._contents[i] + " " return result class QueueC: '''A first-in , first-out (FIFO) queue of items''' def __init__(self): '''(Queue) -> NoneType Create a new, empty queue. ''' # we're going to store the stack as a dictionary {k:v} # where k = height on stack, v = value self._contents = {} self._height = 0 self._first_item_height = 0 def push(self, new_obj): '''(Queue, obj) -> NoneType Place new_obj at the end of this queue. ''' self._contents[self._height] = new_obj self._height += 1 def pop(self): '''(Queue) -> obj Remove and return the first item in this queue. ''' # to pop, we don't actually need to remove the items from # the dictionary result = self._contents[self._first_item_height] self._first_item_height += 1 return result def is_empty(self): '''(Queue) -> bool Return True iff this queue is empty. ''' return self._height == self._first_item_height def __str__(self): '''(Queue) -> str Return a string representation of this queue. ''' # create an empty result ready to use result = '' for i in range(self._first_item_height, self._height): result += self._contents[i] + " " return result class QueueD: '''A first-in , first-out (FIFO) queue of items''' def __init__(self): '''(Queue) -> NoneType Create a new, empty queue. ''' self._contents = "" self._seperator = "->" def push(self, new_obj): '''(Queue, obj) -> NoneType Place new_obj at the end of this queue. ''' if self.is_empty(): self._contents += str(new_obj) else: # assume this queue is not empty here self._contents += self._seperator self._contents += str(new_obj) def pop(self): '''(Queue, obj) -> NoneType Remove and return the first element in this queue. ''' # case1: this queue contains more than 1 element if self._seperator in self._contents: first_seperator_beginning_index = self._contents.find(self._seperator) # record result result = self._contents[:first_seperator_beginning_index] # update this queue self._contents = self._contents[first_seperator_beginning_index + 2:] # case2: this queue contains only 1 element else: result = self._contents self._contents = "" return result def is_empty(self): '''(Queue) -> bool Return True iff this queue is empty. ''' return self._contents == '' def __str__(self): '''(Queue) -> str Return a string representation of this queue. ''' return self._contents if __name__ == "__main__": # efficiency import time start_time = time.time() queue = QueueC() for i in range(100000): queue.push(i) end_time = time.time() print(end_time - start_time) # correctness queue = QueueD() queue.push("Alice") queue.push("Bob") queue.push("Charlie") print(queue) # Alice Bob Charlie print(queue.pop()) # Alice print(queue) # Bob Charlie print(queue.pop()) # Bob print(queue.pop()) # Charlie print(queue.is_empty()) # True print(queue) # make sure an empty queue can be printed
91fa41e6c33e3082ccc1358bf2864596c9a296dc
Bavithakv/PythonLab
/CO1/colour_13.py
167
3.84375
4
color=input("Enter the list of color names seperated by commas:") print("First color entered :",color.split(",")[0]) print("Last color entered :",color.split(",")[-1])
20d0c5bb921f5ed261bb7c4e3caf918bbf772a11
michaelWGR/projectmc
/testpy/prime_test.py
1,137
4.03125
4
# -*- coding:utf-8 -*- import math import time def isPrimeNumber(num): if (num == 2): return True if (num < 2 or num % 2 == 0): return False i = 3 while i <=math.sqrt(num): if (num % i == 0): return False i +=2 return True def get_prime_list(number): prime_list = [] i = 2 while i <= number: j =2 while j <=number: if (j == i or (number-i-j == i) or (number-i-j == j)): j = j+1 continue if(isPrimeNumber(i) and isPrimeNumber(j) and isPrimeNumber(number-i-j)): prime_str = "{},{},{}".format(i,j,number-i-j) prime_list.append(prime_str) j = j+1 i = i+1 return prime_list def main(): # number = 2000 # prime_list = get_prime_list(number) # print prime_list num = 26285431 while True: if isPrimeNumber(num): print(num) num = num +2 num = num+2 if __name__ == "__main__": begin = time.time() main() end = time.time() durution = end - begin print durution
7897da4b3ccfadefd2f0142107d610fe1507325b
AzeezBello/_python
/univelcity/vowels.py
136
4
4
vowels = ['a', 'e', 'i','o','u'] name = input("Enter the your name") if a in name: print('yes', name, "contains" vowels) elif
d341c23a99d935c26557b0e66b6c162c2bd300b3
ludvikpet/denGodeGamleStatistics
/init_denGodeGamle.py
5,941
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 13:21:31 2020 @author: ludvi """ import sys import random # *** INIT - METHODS *** # #Method, that generates data: def generateData(outcomeList, k, throws): #List of results: results = [] #Switch, to indicate, whether a switch has been made: switch = 0 #Generate data - There are multiple conditions to take into account, #which can be seen throughout the following: for i in range(0,k): dice = 3 #Initiate lists, that check which dices to keep: keepList = [] # Normal keep list pressureList = [] # Pier pressure list #Boolean, for choosing dice list: pressure = False for j in range(0,throws): #Generate throw: die = random.choices(outcomeList, k=dice) #Result, with keepList: resultsKeep = sum(die) + sum(keepList) resultsPressure = sum(die) + sum(pressureList) #For lower switch: if switch % 2 != 0: if len(results) >= 3 and resultsKeep < min(maxThree(results, len(results))): results.append(resultsKeep) break else: #If a switch has occurred: if resultsKeep >= 260: switch += 1 results.append(resultsKeep) break elif resultsPressure >= 260: switch += 1 results.append(resultsPressure) break #For loop, that chooses which die to keep, due to pier pressure: for p in range(0,len(die)): if die[p] == 100: pressureList.append(die[p]) elif die[p] == 60 and not any(elem == 60 for elem in pressureList): pressureList.append(die[p]) if len(pressureList) < 2: #Reset pressureList: pressureList = [] #For loop, that chooses which die to keep: for l in range(0,len(die)): if die[l] <= 5: keepList.append(die[l]) else: pressure = True #For normal switch: else: if len(results) >= 3 and resultsKeep > max(minThree(results, len(results))): results.append(resultsKeep) break else: #If a switch has occurred: if resultsKeep == 6 or resultsKeep == 7: switch += 1 results.append(resultsKeep) break elif resultsPressure == 6 or resultsPressure == 7: switch += 1 results.append(resultsPressure) break #For loop, that chooses which die to keep, due to pier pressure: for p in range(0,len(die)): if die[p] == 2: pressureList.append(die[p]) elif die[p] == 3 and not any(elem == 3 for elem in pressureList): pressureList.append(die[p]) if len(pressureList) < 2: #Reset pressureList: pressureList = [] pressure = False #For loop, that chooses which die to keep: for l in range(0,len(die)): if die[l] >= 60: keepList.append(die[l]) else: pressure = True #If there is reasonable claim for being pier pressured: if pressure: dice = 3 - len(pressureList) #Else, throw out what you would normally throw out: else: dice = 3 - len(keepList) #Gather result: if j == (throws - 1): if pressure: results.append(resultsPressure) else: results.append(resultsKeep) return results #Method, that returns the three largest elements of a list: def maxThree(arr, arr_size): if arr_size < 3: raise Exception("Array size is not sufficient") third = second = first = -sys.maxsize for i in range(0,arr_size): if arr[i] > first: third = second second = first first = arr[i] elif arr[i] > second: third = second second = arr[i] elif arr[i] > third: third = arr[i] return [first, second, third] #Method, that returns the three smallest elements of a list: def minThree(arr, arr_size): if arr_size < 3: raise Exception("Array size is not sufficient") third = second = first = sys.maxsize for i in range(0,arr_size): if arr[i] < first: third = second second = first first = arr[i] elif arr[i] < second: third = second second = arr[i] elif arr[i] < third: third = arr[i] return [first, second, third] # *** INIT - METHODS *** #
63c2bc0c5ab1c1c042c73d9df1cc5f29e877735c
Rilst/Programming
/Practice/13/Python/Project.py
403
3.921875
4
a = int(input('Введите целое число больше 1: ')) if a == 1 or a == 0: print("Неверно введенно число") elif a == 2: print("Простое") else: i = 2 c = 0 while i < a: if (a % i == 0): c = 1 i = a i += 1; if c == 1: print("Составное") else: print("Простое")
e1958efdb19f204fa9b3e465280a9acd7bf15ad5
Nilcelso/exercicios-python
/ex018.py
773
4.15625
4
'''import math ang = float(input('Digite um angulo: ')) seno = math.sin(math.radians(ang)) cosseno = math.cos(math.radians(ang)) tangente = math.tan(math.radians(ang)) print('O angulo de {} tem seno de {:.2f}'.format(ang, seno)) print('O angulo de {} tem cosseno de {:.2f}'.format(ang, cosseno)) print('O angulo de {} tem tangente de {:.2f}'.format(ang, tangente))''' from math import radians, sin, cos, tan ang = float(input('Digite um angulo: ')) seno = sin(radians(ang)) cosseno = cos(radians(ang)) tangente = tan(radians(ang)) print('O angulo de {} tem seno de {:.2f}'.format(ang, seno)) print('O angulo de {} tem cosseno de {:.2f}'.format(ang, cosseno)) print('O angulo de {} tem tangente de {:.2f}'.format(ang, tangente)) ''' qualquer um dos dois estao rodando '''
d048167e8dac22669a8b7f757b7d9cb196f2e7c8
Bulgakoff/files_utf8_04
/lesson03/write_bytes.py
659
3.59375
4
# открываем файл для записи бфйтов with open('bytes.txt', 'wb') as f: # пишем сроку байт f.write(b'Hello bytes') # читаем как текст with open('bytes.txt', 'r', encoding='ascii') as f: # печатаем сроку байт врежиме чтения print(f.read()) # тепрь запишем(write()) и выведем на печать то что читаем(read())теперь русский техт utf -8 with open('bytes.txt', 'wb') as f: str = 'Миру мир' f.write(str.encode('utf-8')) with open('bytes.txt', 'r', encoding='utf-8') as f: print(f.read())
50bf93c73e3178db4611ccfa65841c0a5ac302f0
rjrishav5/Codes
/Sorting Algorithms/bogo_sort.py
388
3.890625
4
import random import sys def is_sorted(values): for index in range(len(values)-1): if values[index] > values[index+1]: return False return True def bogo_sort(values): count=0 while not is_sorted: print(count) random.shuffle(values) count+=1 return values numbers = 1,2,3,9,8,6,7,5 a =bogo_sort(numbers) print(a)
5a84e39022b52955f7e52d926d1f25ada26ebde7
Ivanm21/hackerrank
/Happy_Ladybugs.py
1,465
4.125
4
'''#Happy Ladybugs is a board game having the following properties: The board is represented by a string, , of length . The character of the string, , denotes the cell of the board. If is an underscore (i.e., _), it means the cell of the board is empty. If is an uppercase English alphabetic letter (i.e., A through Z), it means the cell contains a ladybug of color . String will not contain any other characters. A ladybug is happy only when its left or right adjacent cell (i.e., ) is occupied by another ladybug having the same color. In a single move, you can move a ladybug from its current position to any empty cell. Given the values of and for games of Happy Ladybugs, determine if it's possible to make all the ladybugs happy. For each game, print YES on a new line if all the ladybugs can be made happy through some number of moves; otherwise, print NO to indicate that no number of moves will result in all the ladybugs being happy. ''' #!/bin/python3 import sys def analyse(n, b): if b.count('_') == 0 and alreadyHappy(b): return "NO" for x in b: if b.count(x) == 1 and x!='_': return "NO" return "YES" def alreadyHappy(b): if len(b) == 1: return True for x in set(b): if x * b.count(x) != b[b.index(x):b.index(x) + b.count(x)]: return True return False for a0 in range(Q): n = int(input().strip()) b = input().strip() print(analyse(n,b))