blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b01e5dee91494fdc9bfe68da40b6203e2a0a8cdf
cormachogan/python-snippets
/circle-pretty.py
1,227
4.53125
5
#!/usr/bin/python3 # Demo the use of `repr` and `str` # If `__str__` is not present, python falls back to using `__repr__` # This script can be run with and without `__str__` defined to compare the differences # print uses `__str__` but python will fall back to using `__repr__` if it is not defined (useful for troubleshooting) # class circle: """ A circle object is created from a radius, default is 1 """ pi = 3.141529 def __init__(self, radius=1): "Initialise the circle from the specified radius" self.radius = radius def diameter(self): "Return twice the radius" return self.radius * 2 def area(self): "calculate the area of the circle" return circle.pi * self.radius **2 def perimeter(self): "calculate the perimeter of the circle" return self.diameter() * circle.pi def __repr__(self): "representation of a circle" return '{0}({1})'.format(self.__class__.__name__, self.radius) def __str__(self): "Pretty representation of a circle" return 'circle with radius: {r:.6f}, diameter(d:.6f) area: {a:.6f}, perimeter: {p:.6f}'.format(r=self.radius, d=self.diameter(), a=self.area(), p=self.perimeter()) c = circle() print(c) print(repr(c)) print(str(c))
392889571b3603ead5d3f0f6f0af85ee948ac404
ctc316/algorithm-python
/Lintcode/G_Practice/Tag_Hash/1103. Split Array into Subsequences Containing Continuous Elements.py
892
3.5
4
class Solution: """ @param nums: a list of integers @return: return a boolean """ def isPossible(self, nums): counts = {} tails = {} for num in nums: counts[num] = counts[num] + 1 if num in counts else 1 for num in nums: if counts[num] == 0: continue counts[num] -= 1 if num - 1 in tails and tails[num - 1] > 0: tails[num - 1] -= 1 tails[num] = tails[num] + 1 if num in tails else 1 elif num + 1 in counts and counts[num + 1] > 0 and \ num + 2 in counts and counts[num + 2] > 0: tails[num + 2] = tails[num + 2] + 1 if num + 2 in tails else 1 counts[num + 1] -= 1 counts[num + 2] -= 1 else: return False return True
41b05ca209127b0285efa0be75bff1e15de80c0d
IagoRodrigues/PythonProjects
/orientacao_objeto/conta_4.py
2,266
4
4
class Conta: def __init__(self, numero, titular, saldo, limite=1000.0): self.__numero = numero self.__titular = titular self.__saldo = saldo self.__limite = limite def extrato(self): print("Saldo R${:.2f} do titular {}".format(self.__saldo, self.__titular)) def deposita(self, valor): self.__saldo += valor """ Pode Sacar fica sendo um método privado com essa notacao """ def __pode_sacar(self, valor_a_sacar): valor_disponivel_a_sacar = self.__saldo + self.__limite return valor_a_sacar <= valor_disponivel_a_sacar def saca(self, valor): if self.__pode_sacar(valor): self.__saldo -= valor else: print("O valor {} passou o limite".format(valor)) def transfe(self, valor, destino): self.saca(valor) destino.deposita(valor) def get_saldo(self): return self.__saldo def get_titular(self): return self.__titular @property def limite(self): return self.__limite @limite.setter def limite(self, limite): self.__limite = limite """ Quando todos os objetos de uma mesma classe compartilham um mesmo metodo ou atributo, eh interessante colocar esse metodo/atributo como sendo estatico, ou seja, eh um metodo/atributo de classe. para isso samos a sintaxe abaixo: """ @staticmethod def codigo_banco(): return "001" @staticmethod def codigos_bancos(): return {'BB': '001', 'Caixa': '104', 'Bradesco': '237'} """ Já no caso de atributos podemos simplesmente declarar: Atributo = valor logo abaixo do nome da classe, sem o uso de self e fora do __init__ isso faz com que o atributo seja estático (atributo de classe), por exemplo: class Circulo: PI = 3.14 e na hora de usar: >>>Circulo.PI 3.14 """ """ Python segue uma convencao para metodos e atributos privados: Dentro da classe conta: a)o atributo __saldo se torna _Conta__saldo. b)o método __pode_sacar() se torna _Conta__pode_sacar(). """
abea49114a2a556353f2ecc4c5b206f03d6ad372
EsdrasGrau/Courses
/Codewars/8 kyu/Area or Perimeter.py
97
3.5625
4
def area_or_perimeter(l, w): if l == w: return l**2 else: return (l+w)*2
603c9fc81359f130fc6d353d8ab16342da3959bd
TTA0/Test
/ModuleRandom.py
142
3.703125
4
from random import * n = randint(0,9) x = input ("Choisir un nombre entre 0,9: ") if n == x: print("Bravo") else: print("Erreur")
2529846384f5f900fd3729c1a65b48da0aac9436
SaimunJd/even_odd_cheacking
/Even_Odd_Cheack.py
237
4.0625
4
cheack=int(input("how many times you want to cheack? : ")) for i in range (cheack): num=int(input("enter a number: ")) if(num<=1): print("its not even nor odd") elif(num%2==0): print("its even") else: print("its odd")
d5214b079b76475c7f96865ad5d24a4eeea2b2b1
twtrubiks/leetcode-python
/test_Number_of_1_Bits_191.py
1,716
4.25
4
import unittest from Number_of_1_Bits_191 import Solution, SolutionBitOperations """ Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. Example 1: Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. Example 2: Input: n = 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit. Example 3: Input: n = 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits. """ class Test_Case(unittest.TestCase): def test_answer_01(self): n = 11 # 0000 0000 0000 0000 0000 0000 0000 1011 result = 3 # self.assertEqual(Solution().hammingWeight(n), result) self.assertEqual(SolutionBitOperations().hammingWeight(n), result) def test_answer_02(self): n = 128 # 0000 0000 0000 0000 0000 0000 1000 0000 result = 1 # self.assertEqual(Solution().hammingWeight(n), result) self.assertEqual(SolutionBitOperations().hammingWeight(n), result) def test_answer_03(self): n = 4294967293 # 1111 1111 1111 1111 1111 1111 1111 1101 result = 31 # self.assertEqual(Solution().hammingWeight(n), result) self.assertEqual(SolutionBitOperations().hammingWeight(n), result) if __name__ == "__main__": unittest.main()
dbb8345d2e01b65f70561dbce484405f7b3e5937
haibinj/lecture_notes
/lecture_notes/file_operation.py
825
3.75
4
# f = open("data.txt") #print(f) ## run this file does not print. #print(f.read()) #print(f.read(3)) ## the good thing of python is that it can control the reading stream of a file. #f = open("data.txt",'w') #print(f) ## over-writing a file. 'w' open with write with open("data2.txt",'w',encoding = 'utf-8' ) as f: f.write("hello data2\n") f.write("this is a test\n") f.write("this is a test of appending") with open("data3.txt",'w',encoding = 'utf-8' ) as f: f.write("hello data2\n") f.write("this is a test\n") f.write("this is a test of appending") import csv with open('dataset.csv') as csv_file: csv_reader = csv.reader(csv_file,delimiter=',') for r in csv_reader: print(r) # this "reading csv" is relatively faster than stata. print(csv_reader) #from theano import *#
21e11c67c743ce8aadd997ab646577b41886c9f6
ReganBell/QReview
/commentsearching.py
4,348
3.53125
4
''' Matthew Beatty, Regan Bell, Akshay Saini CS51 Final Project Q Comment Summarization 4/22/15 ''' # Import modules from nltk import tokenize from nltk.tokenize import wordpunct_tokenize import nltk # Function for splitting string by specific delimiters def tsplit(string, delimiters): delimiters = tuple(delimiters) stack = [string,] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) for j, _substring in enumerate(substack): stack.insert(i+j, _substring) return stack ''' phase_for_sentence extracts the keyphrase from the target sentence using part of speech tagging. It checks for punctuation and conjunctions that signal the edges of clauses. It also accounts for edge cases in formatting the phrases. ''' def phrase_for_sentence(key_phrase, temp_list, pos_tag, max_length): for wp in temp_list: if wp.find(key_phrase) != -1: key_index = temp_list.index(wp) elif ('/' in key_phrase) or ('-' in key_phrase): key_index = temp_list.index(tsplit(key_phrase, (',', '.', '/', '-', '+'))[0]) # checks for punctuations and conjunctions to cut down tokenized word list for wp in temp_list: if wp in temp_list: wp_index = temp_list.index(wp) else: break if (wp == ',') or (wp == '.') or (wp == ':') or (wp == ';') or (wp == '!') or (wp == '?'): if wp_index < key_index: temp_list = temp_list[wp_index:] else: temp_list = temp_list[:wp_index] else: try: left = next(i for i, d in enumerate(pos_tag) if temp_list[0] in d) except StopIteration: return None right = left + len(temp_list) pos_tag = pos_tag[left:right] try: if pos_tag[wp_index][1] == 'CC': if (wp_index < key_index) and ((temp_list[wp_index-1] == ',') or (temp_list[wp_index-1] == '.') or (temp_list[wp_index-1] == ':') or (temp_list[wp_index-1] == '!') or (temp_list[wp_index-1] == '?')): temp_list = temp_list[(wp_index+1):] elif (temp_list[wp_index-1] == ',') or (temp_list[wp_index-1] == '.') or (temp_list[wp_index-1] == ':') or (temp_list[wp_index-1] == '!') or (temp_list[wp_index-1] == '?'): temp_list = temp_list[:wp_index] except IndexError: return None # final adjustments of keyphrase if (temp_list[0] == ',' or temp_list[0] == '.'): temp_list = temp_list[1:] if len(temp_list) <= max_length: joined_contracted = ' '.join(temp_list).replace(' , ',',').replace(' .','.').replace(' !','!').replace(" ' ", "'") return joined_contracted.replace(' ?','?').replace(' : ',': ').replace(' \'', '\'') else: return None ''' phrases_for_key_phrase looks through course comments for keywords and then compiles a list of the keyphrases from the comments. ''' def phrases_for_key_phrase(key_phrase, comments, max_length): sentences = [] for comment in comments: comment_sentences = tokenize.sent_tokenize(comment) for sentence in comment_sentences: tokenized = wordpunct_tokenize(unicode(sentence, errors='ignore')) if key_phrase in tokenized: phrase = phrase_for_sentence(key_phrase, tokenized, nltk.pos_tag(tokenized), max_length) if phrase is not None: sentences.append(phrase) return sentences """ finds the comment sentences containing specific keywords (used in autosummarization paragraph) """ def get_key_sentences(key_phrase, comments): sentences = [] for comment in comments: comment_sentences = tokenize.sent_tokenize(comment) for sentence in comment_sentences: tokenized = wordpunct_tokenize(unicode(sentence, errors='ignore')) if key_phrase in tokenized: sentences.append(sentence) return sentences
4d6b82136c872fa5a731ef22d6fbd10768d1320a
StuartSpiegel/BlockChain
/BlockChain/BlockChain.py
1,309
4.125
4
# Stuart Spiegel, Date: 6/17/2019 #This Python class is an implementation of a Block Chain #We must first define the class Block which is the most basic #unit of the blockchains implementation. #library to assign hashes to blocks(transactions) import hashlib as hasher class Block: def __init__(self, index, timestamp, data, previous_hash): self.index = index self.timestamp = timestamp self.data = data self.previous_hash = previous_hash self.hash = self.hash_block() def hash_block(self): sha = hasher.sha256() sha.update(str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)) return sha.hexdigest() # Create the blockchain and add the genesis block blockchain = [create_genesis_block()] previous_block = blockchain[0] #number of blocks to add to the chain + 1 (Genesis-block) num_of_blocks_to_add = 20 #small number of blocks for now (snakeCoin) # Add blocks to the chain for i in range(0, num_of_blocks_to_add): block_to_add = next_block(previous_block) blockchain.append(block_to_add) previous_block = block_to_add print "Block #{} has been added to the blockchain!".format(block_to_add.index) print "Hash: {}\n".format(block_to_add.hash)
6d06c9de15468f6c210a9119a3d077892c6ca515
srillaert/project-euler
/p055.py
377
3.546875
4
result = 0 for number in range(1, 10000): str_number = str(number) str_reverse = str_number[::-1] for iterations in range(1, 51): number += int(str_reverse) str_number = str(number) str_reverse = str_number[::-1] if str_number == str_reverse: break # palindromic if iterations == 50: result += 1 print(result)
6bcf977f840aa45037055808ea923fe46230d7db
samuellsaraiva/2-Semestre
/l07e08calculadora.py
2,182
4.65625
5
''' 8. Simule uma calculadora com as quatro operações aritméticas. Implemente uma função para cada operação aritmética. Ela recebe dois valores e não retorna nada. O usuário fornecerá a operação desejada(operador: +, -, x, / ) e os dois valores dentro do programa que chamará uma das quatro funções. O resultado do cálculo será mostrado dentro de cada função. Use variável local. Teste 1. Teste com os valores a = 45 , b = 89 e op = +. Resultado Esperado:134 Teste 2. Teste com os valores a = 67, b = 45 e op = -. Resultado Esperado:22 Teste 3. Teste com os valores a = 23, b = 8 e op = *. Resultado Esperado:184 Teste 4. Teste com os valores a = 230, b = 4 e op = /. Resultado Esperado:57.5 ---- ''' def soma(x, y): # Definição das funções. print('Soma: ', x+y) return def subtracao(x, y): print('Subtração: ', x-y) def multiplicacao(x, y): print('Multiplicação:', x*y) return def divisao(x, y): print('Divisão: ', x/y) if __name__ == '__main__': # Início da função main. valor1 = float(input("Digite primeiro valor: ")) valor2 = float(input("Digite segundo valor: ")) op = input("Digite o operador [+] [-] [x] [/]: ") if(op=="+"): soma(valor1, valor2) elif(op=="-"): subtracao(valor1, valor2) elif(op=="x"): multiplicacao(valor1, valor2) else: divisao(valor1, valor2) # ----- ALTERAÇÕES: ''' a. Inclua a mensagem de opção inválida. b. Acrescente a função soma_2, ela recebe dois valores, faz o cálculo e retorna o resultado do cálculo. Ela não imprime nada. c. Chame a função soma e soma_2, quando o usuário escolher a opção somar. --- DICAS ABAIXO: . . . # a. elif (op=="x"): multiplicacao(a, b) elif (op=="/"): divisao(a, b) else print ('Opção inválida') def soma_2 (x, y): # b. return x+y if (op=="+"): # c. Na função main soma(a, b) print (soma_2 (a, b)) # c. '''
6a4a94d806b5f2bda096505d28e3fea4fd635a69
ziGFriedman/My_programs
/Intersection_of_lists.py
762
3.9375
4
'''Пересечение списков''' # Даны два списка и необходимо найти их совпадающие элементы, то есть область # пересечения списков - элементы, которые присутствуют в обоих списках. a = [5, [1, 2], 2, 'r', 4, 'ee', 'ee'] b = [4, 'we', 'ee', 3, [1, 2]] c = [] for i in a: if i in c: continue for j in b: if i == j: c.append(i) break print(c) # Использование операций над множествами a = [5, 2, 'r', 4, 'ee'] b = [4, 1, 'we', 'ee', 2, 'r'] c = list(set(a) & set(b)) # & выполняется пересечение множеств print(c)
f8d098daf899f69b4f9454d1110970c21a314797
vemanand/pythonprograms
/general/json1.py
1,040
4.125
4
''' Python has a built-in package called json, which can be used to work with JSON data. you can parse JSON string by using the json.loads(<string>) method. This returns a Python dictionary you can convert Python object into a JSON string by using the json.dumps(<object>) method. This returns a Json string The qualified objects are list, dict, tuple, string, int, float, bool This program converts Json string to Python Object and also an object to Json string ''' import json # Declar some JSON String person = '{ "name":"Ganesh", "age":30, "city":"Hyderabad"}' # Parse the Json string using loads() method and display print("Converting JSON string to object using loads method") y = json.loads(person) # the result is a Python dictionary: print(y) print(y["age"]) # Declar a Python object (dict) pyobj = { "name": "John", "age": 30, "city": "New York" } # Convert Python object to JSON string using dumps() method and display print("Converting Python object to Json string using dumps method") y = json.dumps(pyobj) print(y)
0e9f1d9ca7153e86b5bf6635135bb755d8608474
gokou00/python_programming_challenges
/coderbyte/PrimeChecker.py
733
3.671875
4
import itertools def PrimeChecker(num): prime = [] prime.append(2) prime.append(3) isPrime = True # generate list of primes for i in range(4,1000): for j in range(2,i): if i % j == 0: isPrime = False break if isPrime: prime.append(i) else: isPrime = True #prime.append(i) #print(prime) numStr = str(num) numStrList = list(numStr) perm = list(itertools.permutations(numStrList)) for x in perm: temp = "".join(x) tempNum = int(temp) if tempNum in prime: return 1 return 0 print(PrimeChecker(598))
70057d60c837bc6df80fdba4b95e01c4d1ac8139
bimri/learning-python
/chapter_30/attributeaccess.py
1,463
3.9375
4
"Attribute Access: __getattr__ and __setattr__" """ classes can also intercept basic attribute access (a.k.a. qualification) when needed or useful. Specifically, for an object created from a class, the dot operator expression object.attribute can be implemented by your code too, for reference, assignment, and deletion contexts. """ "Attribute Reference" ''' The __getattr__ method intercepts attribute references. It’s called with the attribute name as a string whenever you try to qualify an instance with an undefined (nonexistent) attribute name. It is not called if Python can find the attribute using its inheritance tree search procedure. Because of its behavior, __getattr__ is useful as a hook for responding to attribute requests in a generic fashion. It’s commonly used to delegate calls to embedded (or “wrapped”) objects from a proxy controller object This method can also be used to adapt classes to an interface, or add accessors for data attributes after the fact—logic in a method that validates or computes an attribute after it’s already being used with simple dot notation. ''' class Empty: def __getattr__(self, attrname): # On self.undefined if attrname == 'age': return 40 else: raise AttributeError(attrname) if __name__ == '__main__': X = Empty() print(X.age) # print(X.name) # AttributeError: name
56aabdb3b5031e860f862c510d366e586c354164
sriharshadv8811/sriharsha-python-programs
/python program if file 1.py
94
3.96875
4
num=7 if num > 0: print(num,"is a positive number.") print("this is always printed.")
7525b2e4e59d4beae889c47e416d8ec9252c1ac4
Didden91/PythonCourse1
/Week 8/8_4.py
218
3.640625
4
fhand = open('romeo.txt') finallist = list() for line in fhand: words = line.split() for word in words: if word in finallist: continue finallist.append(word) finallist.sort() print(finallist)
e38595c02b857e785e18399f7e7c803e2673c49d
Jayhello/python_utils
/python_utils/numpy_operate/arr_sort.py
1,561
3.9375
4
# _*_ coding:utf-8 _*_ import numpy as np def arr_arg_sort(): arr = np.random.permutation(3 * 4).reshape(3, 4) np.random.shuffle(arr) print arr arr_sort_idx = np.argsort(arr) # default sort by row print arr_sort_idx # print np.array(arr)[arr_sort_idx] # does not apply to mul-dim array arr_sort_idx = np.argsort(arr, axis=0) # sort by column print arr_sort_idx x = np.array([0, 2, 1]) print np.argsort(x) # [0 2 1] ascending order print np.argsort(-x) # [1 2 0] descending order arr = np.array([4, 1, 3, 5]) print arr, arr[arr.argsort()] # [4 1 3 5] [1 3 4 5] print arr.argsort() # [1 2 0 3] print np.argsort(-arr), arr[np.argsort(-arr)] # [3 0 2 1], [5 4 3 1] def arr_sort(): arr = np.random.permutation(3 * 4).reshape(3, 4) print arr # [[11 4 6 1] # [10 0 2 9] # [ 8 7 5 3]] arr.sort() print 'after sort \n', arr # [[ 1 4 6 11] # [ 0 2 9 10] # [ 3 5 7 8]] print np.sort(arr) # the result is as some as arr.sort(),default sort by row print np.sort(arr, axis=0) # sort by column, axis=0 means column pass def arr_sum(): arr = np.arange(6).reshape((2, 3)) print arr # [[0 1 2] # [3 4 5]] print arr.sum(axis=0) # [3 5 7] print arr.sum(axis=1) # [ 3 12] print arr > 1 # [[False False True] # [ True True True]] print arr[::-1] # [[3 4 5] # [0 1 2]] if __name__ == '__main__': # arr_sum() arr_arg_sort() # arr_sort() pass
8ec09ec82a1bf67569dca53bdcab4d10389692c2
0ushany/learning
/python/python-crash-course/code/4_operate_list/pratice/7_3_multiple.py
161
4.1875
4
# 3的倍数 # 创建3的倍数列表,输出 multiples = list(range(3, 31, 3)) for mul in multiples: print(mul) # 很简单,每次加3就是3的倍数
0ca1bd76c5b4e2dfa7151460d92eeeacb3171cee
guruguha/Python_Exercises
/percentages.py
1,577
4
4
__author__ = 'Guruguha' # Percentages num_of_students = int(input()) if num_of_students < 2 or num_of_students > 10: print("Enter valid number of students") else: count = num_of_students student_data = [] valid_input = True while count != 0: values = input() input_list = values.split() if input_list[1].isdigit() is False or float(input_list[1]) < 0 or float(input_list[1]) > 100: print("Enter valid marks for physics") valid_input = False if input_list[2].isdigit() is False or float(input_list[2]) < 0 or float(input_list[2]) > 100: print("Enter valid marks for chemistry") valid_input = False if input_list[3].isdigit() is False or float(input_list[3]) < 0 or float(input_list[3]) > 100: print("Enter valid marks for mathematics") valid_input = False dict = {'name':input_list[0], 'physics':input_list[1], 'chemistry':input_list[2], 'mathematics':input_list[3]} student_data.append(dict) count -= 1 if valid_input: search_student = input() for i in range(0, len(student_data)): if search_student == student_data[i]['name']: total_marks = float(student_data[i]['physics']) \ + float(student_data[i]['chemistry'])\ + float(student_data[i]['mathematics']) avg = total_marks / 3 print(str("{0:.2f}".format(avg))) break else: print("Invalid input")
e69b96228c4cb48e424bf63831a18603f2cead65
BlakeLewis1/python
/QA python/grade calculator.py
580
4.125
4
#learning python #grade calculator code physics =int(input("enter your physics mark")) chemistry =int(input("enter your chemistry mark")) maths =int(input("enter your maths mark")) total = (physics + chemistry + maths) percentage =(total/300 * 100) print ("you got", percentage) if percentage < 40: print("try again") if percentage >= 40 and percentage <50: print("you got a D") if percentage >= 50 and percentage <60: print("you got a c") if percentage >= 60 and percentage <70: print("you got a b") if percentage >= 70: print ("you got an a, well done!")
7ae1514279d960fbdfb3eac64cca0fa67ab25170
sherifsoliman61/HOMEWORKS
/Homework 3.py
1,166
3.859375
4
combination = "SSNWES" stepCounter = 0 lifeCounter = 3 game = True class LostLife: if stepCounter == 10: lifeCounter - 1 stepCounter = 0 class LifeCheck: if lifeCounter == 0: game = False print("Game Over, try again") while game: print("You have entered the Maze, where would you like to go? (N,S,E,W)") if input() == "S": print("CORRECT") if input() == "S": print("CORRECT") if input() == "N": print("CORRECT") if input() == "W": print("CORRECT") if input() == "E": print("CORRECT") if input() == "S": print("YOU HAVE ESCAPED THE MAZE") game = False else: print("INCORRECT") else: print("INCORRECT") else: print("INCORRECT") else: print("INCORRECT") else: print("INCORRECT") else : print("INCORRECT")
c5c50cd3edf56792a37518e7f6ef1ec1cfaf37f7
ntravis/codeeval
/stacking.py
897
4.125
4
""" STACK IMPLEMENTATION CHALLENGE DESCRIPTION: Write a program which implements a stack interface for integers. The interface should have ‘push’ and ‘pop’ functions. Your task is to ‘push’ a series of integers and then ‘pop’ and print every alternate integer. INPUT SAMPLE: Your program should accept a file as its first argument. The file contains a series of space delimited integers, one per line. 1 2 3 4 10 -2 3 4 OUTPUT SAMPLE: Print to stdout every alternate space delimited integer, one per line. 4 2 4 -2 """ def push(toappend, x): toappend.append(x) return toappend def pop(jump): print ' '.join(jump[:2:-1]) import sys test_cases = open(sys.argv[1], 'r') for test in test_cases: overall = [] if test == "": break ints = test.split(" ") for i in ints: overall = push(overall, int(i)) pop(overall) test_cases.close()
881f247867f9c3c3f5f7c65cbe0a5fe3fc2d3c3b
poc1673/Adaptive_Flashcards
/Adaptive_Flashcard/text_manipulation_functions.py
798
3.6875
4
# Peter Caya # Function to take a corpus of words and output a list of sentences. import pandas as pd import re #os.chdir("Dropbox/Projects/Adaptive Flash Cards/") #a = pd.read_csv("Data/2019-11-24 Testing Data.csv",encoding = "ISO-8859-1",squeeze = True).x def detect_periods(string): return(string.find(".")>=0) # Function to apply filtering criteria as the first step of the data cleaning process. It omits "junk" rows which contain only a few characters # and selects for cases where the string ends with a period. def filter_corpus(string): inds = string.apply(lambda x: (detect_periods(x)&(len(x)>5 ) )) return(string[inds]) def rm_end_white(x): return( re.sub(string= x,repl = ".",pattern = "\..*$")) def detect_ngram(text,ngram):
7fe8e4a75bd449de3e1cd46502eefd2965e778d8
KGeetings/CMSC-115
/In Class/TipOnMeal.py
265
3.890625
4
costOfMeal = float(input("How much did your meal cost? (before tax) ")) amountOfTip = float(input("What percentage do you want to tip? ")) the_tip = costOfMeal * amountOfTip / 100 the_tip = int(the_tip * 100) / 100 print("Add $", the_tip, " to your meal.",sep="")
79815b2497f079613859927778355ad2744c6adb
MengLingXiao1/Python_study
/List_study2.py
177
3.859375
4
# -*- coding: utf-8 -*- # @Author : Mlx a=[1,2,3] b=a a.append(5) print a,b #result [1, 2, 3, 5] [1, 2, 3, 5] a=[1,2,3] b=a a=[4,5,6] print a,b #result [4, 5, 6] [1, 2, 3]
38f8a378e3aa0671ef3418eb652edc5d9aa7ab04
ditcraft/demo-repo
/demo.py
486
3.671875
4
# Python program to find the SHA-1 message digest of a file # importing the hashlib module import hashlib def hash_file(filename): """"This function returns the SHA-1 hash of the file passed into it""" # make a hash object h = hashlib.sha1() # open file for reading in binary mode with open(filename,'rb') as file: h.update(file.read()) # return the hex representation of digest return h.hexdigest() message = hash_file("track1.mp3") print(message)
998827538d14387636739a997e4428a460a1497f
cocoa-dev-1/--
/수업/list_1.py
398
3.59375
4
#def oddX3_evenX2(n): # return n*2 if n%2==0 else n*3 #oddX3_evenX2 = lambda n: n*2 if n%2==0 else n*3 #print(oddX3_evenX2(5)) a_list = [i for i in range(10)] print(a_list) b_list = list(map(lambda n: n*2 if n%2==0 else n*3, a_list)) print(b_list) c_list = [i for i in range(21)] turnToMinus_list = list(map(lambda n: -n if n%2 == 0 or n%5 == 0 else n/2,c_list)) print(turnToMinus_list)
1784b3a247a09ba99df831dc3144344a0eac2660
NiranjanSingh/coding-localdrive
/python/tmp.py
397
3.703125
4
"fuctions" def a(): x=0 y=3 print('hi shanoo'+ str(x) + str(y)) def b(x): print('ihello') x += 1 print(x) # c('hello') def c(name): x=98 y=97 z = 32 print(x + y + z) print(name) print(a) print(b) print(c) # print(a printm + "see yourself which is greater address ") print('a>b ' + str(a>b)) print('b>c ' + str(b>c)) a() b(int(raw_input("Enter any number : "))) c('Niranjan')
5b23b367fb31330d763a9d1f6d2fe576a9c7d38c
Hyferion/Leetcode
/recursion/frog_jump.py
273
3.828125
4
cache = {0: 1, 1: 1} def frogjump(feet): if feet < 0: return 0 if feet not in cache: cache[feet] = frogjump(feet - 1) + frogjump(feet - 3) + frogjump(feet - 5) return cache[feet] else: return cache[feet] print(frogjump(111))
3095ae90505b89d27f2c64957c9f5eb91b456fd2
kr4spy/PatchTuesday
/patchtuesday.py
935
3.671875
4
import datetime import calendar from datetime import timedelta #set first weekday c = calendar.Calendar(firstweekday=calendar.SUNDAY) #################### # Set this stuff # #################### #set the year year = 2020 #offset in days from patch Tuesday. 3 = Friday, 4 = Saturday, 5 = Sunday offsetDays = 4 #set the offset in weeks. W1 = 0, W2 = 1, W3 = 2, W4 = 3 offsetWeeks = 1 #turn it into days because we can only do math in days offsetWeeks = offsetWeeks * 7 #loop through all months month = 1 while month <= 12: monthcal = c.monthdatescalendar(year,month) #get second Tuesday secondTues = [day for week in monthcal for day in week if day.weekday() == calendar.TUESDAY and day.month == month][1] #add offset offsetDate = secondTues + datetime.timedelta(days=offsetDays) + datetime.timedelta(days=offsetWeeks) print(offsetDate) month += 1
008c74e5288baf37c73a18a3c9a864da3c19a87a
Sam-Power/033_streamlit_model_deployment
/app.py
5,943
3.546875
4
#streamlit run app.py import streamlit as st import pandas as pd import numpy as np import altair as alt # text/title st.title("Streamlit Tutorial") st.text("welcome !") # header/subheader st.header('This is a header') st.subheader('This is a subheader') #Markdownd st.markdown('### This is a markdown') st.markdown('## This is a markdown') st.markdown('# This is a markdown') st.markdown('#** This is a markdown**') st.markdown('Streamlit is **_really_ cool**.') st.markdown('`This is a markdown`') #color box st.success("this is a green box") st.info("this is info") st.warning("this is warning") st.error("this is error") st.subheader('This is a subheader') st.write('Hello, *World!* :sunglasses:') #help st.help(range) #extra st.write(1234) st.write(pd.DataFrame({'first column': [1, 2, 3, 4],'second column': [10, 20, 30, 40],})) #checkbox if st.checkbox('Show/Hide'): st.text('that shows bec you checked box') else: st.text('now its closed') #radio buttons status = st.radio('What is your status?', ('Active', 'Inactive')) if status == 'Active': st.success("You are Active") else: st.warning("You are inactive") status2 = st.radio('What is your 2nd status?', ('1','2','3')) #selectbox occupation = st.selectbox('Your occupation', ('DS','Dev','CEO')) st.write('You picked:',occupation) if occupation == "DS": st.success("wooo!") else: st.warning("damn!") #Multiselect box options = st.multiselect('What are your favorite colors', ['Green', 'Yellow', 'Red', 'Blue'], ['Yellow', 'Red']) st.write('You selected:', options) options2 = st.multiselect('Where do you live',('USA', 'GSermany', 'UK', 'Other')) st.write('You selected:', options2) if len(options2) > 1: st.write('You selected:', len(options2), 'locations') else : st.write('You selected:', len(options2), 'location') #sliders age = st.slider('How old are you?', 0, 130, 25) st.write("I'm ", age, 'years old') level = st.slider("what is your level", 0,40,20, step=5) st.write('I am ', level, 'yeah') values = st.slider('Select a range of values',0.0, 100.0, (25.0, 75.0)) st.write('Values:', values) #TimeSlider from datetime import time appointment = st.slider("Schedule your appointment:",value=(time(11, 30), time(12, 45))) st.write("You're scheduled for:", appointment) #DateTimeSlider from datetime import datetime start_time = st.slider("When do you start?",value=datetime(2020, 1, 1, 9, 30),format="MM/DD/YY - hh:mm") st.write("Start time:", start_time) #Button st.button('SImple Button') # start analysis etc.Run if st.button('About'): st.write('Streamlit is Cool') else: st.write('Hasta pronto') #text input first_name = st.text_input("Enter Your First Name") if st.button('Submit'): st.success(first_name.title()) #text area message = st.text_area("Enter your text", "Type here...") if st.button('submit'): result = message.title() st.success(result) #date input import datetime today = st.date_input('TOday is ', datetime.datetime.now()) d = st.date_input("When's your birthday", datetime.date(2019, 7, 6)) st.write('Your birthday is:', d) #time input the_time = st.time_input('Time is ', datetime.time(8,45)) #Raw Data st.text("DIsplay Text") st.code('import pandas as pd') with st.echo(): import numpy as np import pandas as pd #progress bar my_bar = st.progress(0) for p in range(10): my_bar.progress(p+1) import time my_bar = st.progress(0) for p in range(20): my_bar.progress(p+1) time.sleep(0.1) #spinner import time with st.spinner("wait for it .... "): time.sleep(3) st.success('Finished') st.balloons() #SidebAr st.sidebar.title('Churn Probabaility of a sngle CUstiner') html_temp = """ <div style="background-color:tomato;padding:1.5px"> <h1 style="color:white;text-align:center;">Richard Title </h1> </div><br>""" st.markdown(html_temp,unsafe_allow_html=True) #SidebAr align html_temp = st.sidebar.title('Churn Probabaility of a sngle CUstiner') st.markdown(html_temp,unsafe_allow_html=True) st.markdown( f''' <style> .sidebar .sidebar-content {{ width: 50px; }} </style> ''', unsafe_allow_html=True) import pickle import pandas as pd df = pickle.load(open("df_saved.pkl",'rb')) st.write(df.head()) st.text(df.head()) st.table(df.head()) st.dataframe(df.head()) tenure=st.sidebar.slider("Number of months the customer has stayed with the company (tenure)", 1, 72, step=1) MonthlyCharges=st.sidebar.slider("The amount charged to the customer monthly", 0,100, step=5) TotalCharges=st.sidebar.slider("The total amount charged to the customer", 0,5000, step=10) Contract=st.sidebar.selectbox("The contract term of the customer", ('Month-to-month', 'One year', 'Two year')) OnlineSecurity=st.sidebar.selectbox("Whether the customer has online security or not", ('No', 'Yes', 'No internet service')) InternetService=st.sidebar.selectbox("Customer’s internet service provider", ('DSL', 'Fiber optic', 'No')) TechSupport=st.sidebar.selectbox("Whether the customer has tech support or not", ('No', 'Yes', 'No internet service')) def single_customer(): my_dict = {"tenure" :tenure, "OnlineSecurity":OnlineSecurity, "Contract": Contract, "TotalCharges": TotalCharges , "InternetService": InternetService, "TechSupport": TechSupport, "MonthlyCharges":MonthlyCharges} df_sample = pd.DataFrame.from_dict([my_dict]) return df_sample df = single_customer() st.table(df) #images from PIL import Image im = Image.open('image.png') st.image(im, width=600, caption='GD') if st.checkbox('Show/Hide Picture'): st.image(im, width=600, caption='GD') #video file vid_file = open('download.mp4','rb') st.video(vid_file) import pandas as pd import numpy as np import altair as alt df = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c']) c = alt.Chart(df).mark_circle().encode(x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c']) st.write(c) st.map()
017917ce8a021ba517b04f76c6e84c2647a89905
LittleFee/python-learning-note
/day01/homework-str.py
1,677
4.40625
4
#个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息 # name_1=input("Input your name please \n") name_1="kiwi" print("Hello "+name_1.title()+",How's your day") #调整名字的大小写: 将一个人名存储到一个变量中,再以小写、大写和首字母大写的方式显示这个人名。 # name_2=input("Input your name please \n") name_2="feng Yun xiA" print(name_2.lower()) print(name_2.upper()) print(name_2.title()) #名言: 找一句你钦佩的名人说的名言,将这个名人的姓名和他的名言打印出来。输出应包括引号 words_1="宝宝说'I love you baby'" words_2='宝宝说"I love you baby"' print(words_1) print(words_1.title()) print(words_2) print(words_2.title()) #名言2: 重复练习2-5,但将名人的姓名存储在变量famous_person 中,再创建要显示的消息,并将其存储在变量message 中,然后打印这条消息。 famous_person="宝宝" message1="'I love You'" message2='"I Love you"' print(famous_person+"说:"+message1) print(famous_person+"说:"+message1.title()) print(famous_person+'say:'+message2) print(famous_person+'say:'+message2.title()) #剔除人名中的空白: 存储一个人名,并在其开头和末尾都包含一些空白字符。务必至少使用字符组合"\t" 和"\n" 各一次。 #打印这个人名,以显示其开头和末尾的空白。然后,分别使用剔除函数lstrip() 、rstrip() 和strip() 对人名进行处理,并将结果打印出来。 namestrip=" Feng\nyun\txia " print(namestrip) print(namestrip.lstrip()) print("..........") print(namestrip.rstrip()) print("..........") print(namestrip.strip())
b1e58b11ad9a741438c0e4a1f1c5551cd1e93564
crobil/project
/Reverse_or_rotate.py
1,397
3.90625
4
""" The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz). If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string. If sz is <= 0 or if str is empty return "" sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "". Examples: revrot("123456987654", 6) --> "234561876549" revrot("123456987653", 6) --> "234561356789" revrot("66443875", 4) --> "44668753" revrot("66443875", 8) --> "64438756" revrot("664438769", 8) --> "67834466" revrot("123456779", 8) --> "23456771" revrot("", 8) --> "" revrot("123456779", 0) --> "" revrot("563000655734469485", 4) --> "0365065073456944" """ def revrot(strng, sz): print (strng, sz) if len(strng) == 0 or sz == 0: return '' lst = [] res = '' for var in strng: lst.append(int(var)) if len(lst) == sz: if sum(lst) % 2 == 0: res += ''.join([str(val) for val in lst[::-1]]) else: res += ''.join([str(val) for val in lst[1:]]) res += str(lst[0]) lst = [] return res
b3ced8a1be7130c4d77deb2e7424858406c03c34
dragonesse/aoc
/2017/day19.py
2,465
3.90625
4
import sys; import re; print("Day 16 puzzle: A Series of Tubes"); #read input puzzle_file = ""; if(len(sys.argv) == 1): print ("Please provide input file as argument!"); sys.exit(); else: puzzle_file = sys.argv[1]; layout = []; #open file with open(puzzle_file, 'r') as puzzle_in: for cur_line in puzzle_in: layout.append(cur_line.strip("\n")); puzzle_in.close(); x, y = 0, 0; string = ""; def is_terminator (mark): return mark == "+" or mark == " "; def find_direction (x,y,come_from, layout): new_dir = "" if come_from == "up" or come_from == "down" : # the possible directions to search are left and right if re.match (r'[A-Z,-]', layout[y][x-1]): new_dir = "left" elif re.match (r'[A-Z,-]', layout[y][x+1]): new_dir = "right"; return new_dir; if come_from == "left" or come_from == "right": # the possible directions to search are up or down if re.match (r'[A-Z,|]', layout[y - 1][x]): new_dir = "up" elif re.match (r'[A-Z,|]', layout[y + 1][x]): new_dir = "down"; return new_dir; # try to find the entrance while x in range(len(layout[y])): if layout[y][x] != " ": break; else: x += 1; if layout[y][x] == '|': move_dir = "down"; if layout[y][x] == '-': move_dir = "left"; letters = ""; steps = 0; while True: # follow the rabit: while not is_terminator(layout[y][x]): # verify, we met letter: steps += 1; if layout[y][x].isalpha(): letters += layout[y][x]; if move_dir == "down" : y += 1; elif move_dir == "up": y -= 1; elif move_dir == "left": x -= 1; elif move_dir == "right": x += 1; # verify, we did not exceeded array if y < len(layout) and x < len(layout[0]): pass else: print ("Exceeded array dimension"); break; move_dir = find_direction(x, y, move_dir, layout) if move_dir == "down": y += 1; steps += 1 elif move_dir == "up": y -= 1; steps += 1 elif move_dir == "left": x -= 1; steps += 1 elif move_dir == "right": x += 1; steps +=1; else: print ("ended at %d %d" %(x, y)); break; print ("traceroute is: %s" %(letters)); print ("number of steps is: %d" %(steps));
7dc645b64f870784303bcbb4a0380800ab055164
damccorm/course-work
/big-data/dannymccormick3-homework-2/2_group.py
1,410
3.515625
4
from mrjob.job import MRJob import json ''' Count the screen name with the most tweets and its counts. See http://mike.teczno.com/notes/streaming-data-from-twitter.html for parsing info. Get the screen name by accessing tweet['user']['screen_name'] ''' class GroupMaxTweets(MRJob): # The _ means the field does not matter.; def mapper(self, _, line): try: tweet = json.loads(line) # yield something yield (tweet['user']['screen_name'], 1) pass except: pass def reducer(self, key, counts): # yield something -- hint you can yield a tuple of values i = 0 for count in counts: i = i+1 tup = (key,i) yield("test",tup) pass def reducer_max(self, _, counts): # yield something max = 0 name = "" for count in counts: if count[1] > max: max = count[1] name = count[0] yield (max,name) pass def steps(self): return [ self.mr(mapper=self.mapper, reducer=self.reducer), self.mr(reducer=self.reducer_max) ] def test_count(): f = open('2_group.out') lines = f.readlines() f.close() assert lines[0][:-1] in ['31890 "Jayy_LaVey"', '31890\t"Jayy_LaVey"'] if __name__ == '__main__': GroupMaxTweets.run()
99631a755ff0f83c9dc6a34204a2ee5aec68d01c
ajanes780/pythonPractice
/fibonacci.py
307
4.0625
4
def fibonacci_number(num): if num: a = 0 b = 1 for i in range(num): yield a temp = a a = b b = temp + b else: return "Please Choose a number greater then 0" my_list = [i for i in fibonacci_number(-1)] print(my_list)
1357378aa2f9c1ba6587d46c27fed666eb684ab7
unfit-raven/yolo-octo
/CST100 Object Oriented Software Development/Random Programs/distance_traveled.py
836
4.375
4
# Distance traveled calculator. # Distance = Speed * Time # Input validation - positive number for speed, and number greater than 1 for time. speed = 0 # Priming read while speed <= 0: speed = eval(input("Please enter the speed of the vehicle in MPH: ")) if speed > 0: # Speed validation print("Error. Try again.") else: print("Unknown error. Try again.") time = 0 # Priming read while time < 1: time = eval(input("Please enter the time traveled in hours: ")) if time < 1: # Time validation print("Error. Try again.") else: print("Unknown error. Try again.") # Calculate distance distance = speed * time # Display results print("The speed of the vehicle was", speed, "MPH and the time traveled was", time, "hours. The total distance traveled was", distance, "miles.")
c923dbc9fa163cbb2f653134be652bcb1637a481
AbdohDev/Pyson
/auth/signup.py
399
3.546875
4
#creating a new user from user import UserManager from util.validations import username_signup def Signup(): # is_valid = False # username = "" # password = "" # message = "" # user = None print("I am in signup.py") username = input("Please enter a username: ") password = input("Please enter a password: ") UserManager().create_user(username, password)
fa2dab39ab441908fa3cbb13412d76e32a66c350
jasdestiny0/Competitive-Coding
/Code_Asylums/dsa_bootcamp/array_questions/COUNT_PAIRS_IN_A_SORTED_ARRAY_WHOSE_SUMIS_LESS_THAN_X.py
259
3.6875
4
import math def sum_less_than_x(arr, x): n=1 for i in range(0, len(arr)-1): if arr[i]+arr[i+1]> x: break n+=1 return int(math.factorial(n)/((math.factorial(n-2))*2)) if n>1 else 0 print(sum_less_than_x([1,2,3,4,5,6],7))
0472249edf7eb708f15463f94b50698e61059588
djs1193/-w3r-esource
/exe10.py
171
3.921875
4
#finding sum of the type n + nn + nnn def my_func(n): ans = (n + (n +10*n) + (n+10*n +100*n)) print (ans) val =int(input("enter the value of n: ")) my_func(val)
9a893ef66a4cdbfff3fefa8a9ed51e918bb02c3c
zhangying123456/python_basis
/Get请求.py
209
3.796875
4
import random def fn(x): return x**2 result = [] for i in range(3): t = random.randint(1, 10) print (t) r = fn(t) result.append(r) print (result) value = eval(input()) print(value)
8c716f77b65b0d026d2d1599f4337613de4d42c4
nai7/advanced-pat-python
/1023.py
267
3.921875
4
num = raw_input() nums_before = {} for n in num: nums_before.setdefault(n, []).append(0) num = str(2 * int(num)) nums_after = {} for n in num: nums_after.setdefault(n, []).append(0) if nums_after == nums_before: print 'Yes' else: print 'No' print num
d9a9b61a5c898f8a2b8b9c458eda66752ba69375
littlebuddha16/pythonIsEasy
/Homework Assignment #7/dictionariesAndSets.py
2,614
3.875
4
""" Homework Assignment #7 Dictionaries and Sets Favourite Song Author: Kiran Kumar P V """ """ Function to clear the terminal 1. OS module has functions which can be used to interact with underlying Operating System 2. Use system function to clear the terminal 3. Use os.name and "if block" to clear either Windows terminal or Linux terminal(NT represents Windows OS) """ def clear(): import os if os.name == 'nt': os.system('cls') else: os.system('clear') """ Creating a dictionary for my favourite carnatic song 1. Dictionary elements are defined within flower brackets({}) 2. Dictionaries have keys and values 3. Key and it's value are seperated by colon(:) 4. Each "key: value" seperated by comma(,) """ favouriteSong = { 'Song': 'Nagumomu Ganaleni', 'Genre': 'Carnatic', 'Language': 'Telugu', 'Composed By': 'Tyagaraja', 'Raga': 'Abheri', 'Artist': 'Tyagaraja', 'Duration': '6 minutes', 'Release Date': '1767 - 1847', 'Best Version': 'Nagumomu Ganaleni by Kartik' } # Sets do not store duplicate values and also they don't keep the order of the elements attributes = set() # Empty Set clear() # Clears the terminal print('*'*5, 'Favourite Song', '*'*5, '\n') # Title """ Add Dictionary keys to empty set 1. Use 'for' loop to iterate through dictionary keys 2. Use add function to add the keys to the set 3. Print key and dictionary value Example: Name: Kiran Age: 28 Country: India """ for key in favouriteSong: attributes.add(key) print(key + ':', favouriteSong[key]) """ Function for Guessing Game 1. Get the attribute from the User, check in set if the key exists and print appropriate response if it does not 2. If the key does exists then take the answer 3. Check in the dictionary if the value is right and print a response 4. Return False either key is incorrect or value """ def guessGame(): key = input('Attribute you want to guess(case-sensitive): ') # Read host if key in attributes: # Key check value = input('Your answer(case-sensitive): ') # Read host if favouriteSong[key] == value: # Value check print('Correct!') # Response return True else: print('Incorrect!') # Response return False else: print('Attribute does not exist') # Response return False """ Set the game on loop: Use while to loop the game function and break it based on User's response """ while True: control = int(input('\nDo you wanna play a "Guessing Game" on my favourite song?(1- yes/0- no): ')) # Read host if control != 0: # Runs the game clear() print('*'*5, 'Guess Key and Value', '*'*5, '\n') # Title guessGame() else: # Game exit break
851680666916ebb8dc81d9c0d8f4a45aeb10e6e6
jacobcrigby/Advent-of-Code-Python
/2019/day1.py
2,294
3.734375
4
""" --- Day 1: The Tyranny of the Rocket Equation --- """ import math import unittest class SpacecraftModule: """Generic module with mass (Part 1)""" def __init__(self, mass: int): self.mass = mass def required_fuel(self, mass: int = False) -> int: if not mass: mass = self.mass return math.floor(mass / 3) - 2 class SpacecraftModule2(SpacecraftModule): """Module that has to carry its own fuel weight (Part 2)""" def __init__(self, mass: int): super().__init__(mass) def required_fuel(self) -> int: total = 0 req_fuel = super().required_fuel(self.mass) while req_fuel > 0: total += req_fuel req_fuel = super().required_fuel(req_fuel) return total class Spacecraft: """Collection of modules""" def __init__(self): self.modules = [] def add_module(self, module: SpacecraftModule): self.modules.append(module) def total_fuel(self) -> int: return sum(mod.required_fuel() for mod in self.modules) class TestSpacecraftModule(unittest.TestCase): def test_modules(self): mod1 = SpacecraftModule(12) mod2 = SpacecraftModule(14) mod3 = SpacecraftModule(1969) mod4 = SpacecraftModule(100756) modules = [mod1, mod2, mod3, mod4] self.assertEqual(mod1.required_fuel(), 2) self.assertEqual(mod2.required_fuel(), 2) self.assertEqual(mod3.required_fuel(), 654) self.assertEqual(mod4.required_fuel(), 33583) total = sum(mod.required_fuel() for mod in modules) self.assertEqual(total, 34241) class TestSpacecraft(unittest.TestCase): def test_spacecraft(self): craft = Spacecraft() mod1 = SpacecraftModule2(14) mod2 = SpacecraftModule2(1969) mod3 = SpacecraftModule2(100756) craft.add_module(mod1) craft.add_module(mod2) craft.add_module(mod3) self.assertEqual(craft.total_fuel(), 51314) if __name__ == "__main__": # unittest.main() craft = Spacecraft() with open('./2019/input_day1.txt', 'r') as inp: for item in inp: craft.add_module(SpacecraftModule2(int(item))) total = craft.total_fuel() print(total)
4249826c93f6d12b0c6a669ffecc6f7aef1b7568
BorisovDima/_ex
/algoritms/Merge_sort.py
1,480
3.546875
4
from test_sort import test_sort import random # def merge_sort1(iterable): # if len(iterable) <= 1: # return iterable # slice_ = len(iterable) // 2 # left = iterable[:slice_] # right = iterable[slice_:] # return merge(merge_sort(left), merge_sort(right)) # # def merge(i1, i2): # result = [] # n1 = n2 = 0 # for i in i1: # for j in i2[n2:]: # if not i > j: # result.append(i) # n1 += 1 # break # else: # n2 += 1 # result.append(j) # result.extend(i1[n1:] or i2[n2:]) # return result def merge_sort(iterable): if len(iterable) > 1: slice_ = len(iterable) // 2 left = iterable[:slice_] right = iterable[slice_:] merge_sort(left) merge_sort(right) l1 = r2 = k = 0 while l1 < len(left) and r2 < len(right): if not left[l1] > right[r2]: iterable[k] = left[l1] l1 += 1 else: iterable[k] = right[r2] r2 += 1 k += 1 ost, n = (right, r2) if len(right) > r2 else (left, l1) while len(ost) > n: iterable[k] = ost[n] k += 1 n += 1 return iterable import time t = time.time() for i in range(1000): iterable = random.choices(range(-1000, 1000), k=i) test_sort(iterable, merge_sort) print(time.time() - t)
529214716f22291fbf2ce63b56f969ab846e4693
Baistan/FirstProject
/while_tasks/Задача2.py
208
3.75
4
num = int(input()) i = 2 while num % i != 0: i += 1 print(i) print("Конец Цикла") # num = int(input()) # i = 0 # while i < num: # i += 1 # print(i) # print("Конец цикла")
75cdef0cf035e8cae59855bc8119e664d9313b74
WokasWokas/UserRegistation
/test.py
4,869
3.640625
4
import os os.system("cls") class Data: users = [] class User(object): def __init__(self, user: dict): self.name = user.get("name") self.exp = user.get("exp") self.lvl = user.get("lvl") self.maxExp = user.get("maxExp") self.password = user.get("password") def info(self): print(f"-Information about {self.name}") print(f"-Level: {self.lvl}") print(f"-Expierence: {self.exp} / {self.maxExp}") def add_exp(self, exp: int): add_exp(user=self, exp=exp) add_lvl(user=self) def exit_user(self): result = exit_user(user=self) if result == False: return result else: print("-User can't exit") def delete_user(self): delete_user(user=self) result = exit_user(user=self) if result == False: return result else: print("-User can't exit") def format_user(**kwargs): return {"name": kwargs.get("name"), "exp": kwargs.get("exp"), "lvl": kwargs.get("lvl"), "maxExp": kwargs.get("maxExp"), "password": kwargs.get("password")} def add_exp(user: User, exp: int): try: user.exp += exp return 0 except: return 1 def add_lvl(user: User): try: while True: if user.lvl == 10 or user.lvl == "max": user.lvl = "max" user.exp = user.maxExp user.maxExp = "Infinity" return 0 if user.exp >= user.maxExp: user.lvl += 1 user.maxExp *= 2 else: user.exp = 0 return 0 except: return 1 def create_user(name: str, password: str): try: user = format_user(name=name, lvl=0, exp=0, maxExp=10, password=password) Data.users.append(user) return User(user) except: return 1 def connect_user(name: str, password: str): try: for user in Data.users: if user["name"] == name: if user["password"] == password: return User(user) print("[Warn] User not found") return False except: return False def exit_user(user: User): try: del(user) return False except: print("[Error] User not deleted") return 1 def delete_user(user: User): try: for userList in Data.users: if userList["name"] == user.name: Data.users.remove(userList) return 0 print("-User not found") return 1 except: return 1 def save_user(user): if type(user) == User: for name in Data.users: if name.get("name") == user.name: user = format_user(name=user.name, exp=user.exp, lvl=user.lvl, maxExp=user.maxExp, password=user.password) Data.users[Data.users.index(name)] = user def check_menu(user): if user == False: return start_menu() def start_menu(): commands = ["help", "create_user", "connect_user"] while True: option = input("start_menu:") if option == commands[0]: for command in commands: print(f"-{command}") if option == commands[1]: name = input("Name:") password = input("Password:") user = create_user(name=name, password=password) return user if option == commands[2]: name = input("Name:") password = input("Password:") user = connect_user(name=name, password=password) return user def user_menu(user: User): commands = ["help", "info", "exit_user", "add_exp","delete_user", "exit"] while True: option = input(f"{user.name}:") if option == commands[0]: for command in commands: print(f"-{command}") if option == commands[1]: user.info() if option == commands[2]: return user.exit_user() if option == commands[3]: exp = input("Exp:") try: user.add_exp(int(exp)) except ValueError: print("-Wrong value") if option == commands[4]: return user.exit_user() if option == commands[5]: print("Program closing") exit() user = False while True: try: user = check_menu(user) if user != False: user = user_menu(user) save_user(user) except KeyboardInterrupt: save_user(user) exit("\n-User close program")
af8a6d8d777cfe57f4c603eec56de1b7663f4959
freeland120/Algorithm_Practice
/CodingTest_Python/Programmers_MaxNumber.py
243
3.640625
4
## 정렬 "가장 큰 수" def solution(numbers): numbers = list(map(str,numbers)) numbers.sort(key = lambda x : x*3, reverse=True) return str(int(''.join(numbers))) list1 = [6,10,2] print(solution(list1))
ea0a780daa3aeeb758a20851b6071fffa336253e
itsarcanedave/Python-UDP-Chat
/Client.py
1,445
3.8125
4
import socket import ipaddress name = input ("Please enter your name: ") print ("Hello", name, "!") local = socket.gethostbyname(socket.gethostname()) print ("Your client IP address is", local) ip = input ("Please enter server IP address: ") ipaddress.ip_address(ip) port = int(input ("Please enter port: ")) counter = 1 while (counter <= 3): if counter <=2: messageString = input("Enter a message: ") separator = str(": ") username = str.encode(name) separatorSend = str.encode(separator) message = str.encode(messageString) sendMessage = username + separatorSend + message clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) clientSocket.sendto(sendMessage, (ip, port)) data, server = clientSocket.recvfrom(4096) dataString = data.decode() print (dataString) counter = counter + 1 elif counter == 3: messageString = input("Enter a message: ") separator = str(": ") username = str.encode(name) separatorSend = str.encode(separator) message = str.encode(messageString) sendMessage = username + separatorSend + message clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) clientSocket.sendto(sendMessage, (ip, port)) break print ("Connection closed!") done = input("Press any key to exit!")
636daccf700b752020c49b5c89ca5d4b5f8f020c
janam111/datastructures
/Matrix/Rotate Matrix Anti-clockwise.py
396
3.546875
4
from Common import inputMatrix def rotateMatrix(arr): m = len(arr) n = len(arr[0]) res = [[0 for i in range(m)] for j in range(n)] for i in range(n): for j in range(m): res[n-i-1][j] = arr[j][i] return res arr = inputMatrix() res = rotateMatrix(arr) for i in range(len(res)): for j in range(len(res[0])): print(res[i][j], end=' ') print()
a139ba27746f9ba0771345ca2fae800ead384390
yogesh1234567890/insight_python_assignment
/completed/Data40.py
285
4.40625
4
#40.​ Write a Python program to add an item in a tuple. tups=(1,2,3,4,5,6,7,8) lst=list(tups) num=int(input("Enter the number of values you want to add in the tuple: ")) for i in range(num): value=int(input('Enter the value: ')) lst.append(value) out=tuple(lst) print(out)
d9b543efa56518a98fc46e9e1562c6e6a9250856
ericdweise/quantum
/qiskit/myqiskit/circuits.py
503
3.578125
4
from qiskit import QuantumCircuit def encode_int(number, bit_depth=8): '''Encode an integer into a quantum circuit.''' assert(isinstance(number, int)) assert(isinstance(bit_depth, int)) assert(bit_depth > 0) assert(number >= 0) assert(number <= 2**bit_depth - 1) circuit = QuantumCircuit(bit_depth) for i in range(bit_depth, -1, -1): bit_power = 2**i if number >= bit_power: circuit.x(i) number -= bit_power return circuit
83fc67e0b07a518da20886c2fb6bb1b8778529e2
DamienOConnell/MIT-600.1x
/Week_1/str_involve.py
373
3.984375
4
#!/usr/bin/env python3 # 1 "string involved:" varA = 4 varB = "adieu" # 2 "string involved" varA = hola, varB = hola if (type(varA) == str) or (type(varB) == str): print("string involved") elif (type(varA) == int) and (type(varB) == int): if varA > varB: print("bigger") elif varA == varB: print("equal") else: print("smaller")
353ef4c65295bda8a9ce55640b251f2795e7e43c
cfspoway/python101
/Homework12/Sarah_Homework_12.py
400
3.8125
4
sentence = input('Please input a sentence') length = len(sentence) #print(length) fc = 0 #first character pos = 0 #position print('The word list is:') while pos < length: if sentence[pos] == ' ': if pos != fc: print(sentence[fc:pos]) pos = pos + 1 fc = pos else: pos = pos + 1 if pos != fc: print(sentence[fc:pos])
cecc607c1374477df7c1f302ffadd5072decaf14
kevinhan29/python_fundamentals
/10_testing/10_01_unittest.py
585
4.3125
4
''' Demonstrate your knowledge of unittest by first creating a function with input parameters and a return value. Once you have a function, write at least two tests for the function that use various assertions. The test should pass. Also include a test that does not pass. ''' def Triple(val): try: temp = val float(temp) except ValueError: print("That's not a number") return None else: return val*3 def test_Triple_Multiply(): assert Triple(2) == 6 def test_Triple_IncorrectTypeCatch(): assert Triple("hello") == None
e878b96101b3e4108246aa1d7a89c3cbe484f493
isnakie/CMPS115
/scatter.py
5,573
3.671875
4
""" Created on April 13, 2016 Reads a csv file containing stock market data and shows and saves a plot of the trend line, given optional starting and ending date information. Call makeChart() with return value of readFile() and a list of prices, e.g., ['Open','Close']. @author: Johnnie Chang """ import argparse import numpy as np import pandas as pd import sklearn as sk import matplotlib.pyplot as plt import time from datetime import datetime # Months with 30 days. shortMonths = [4, 6, 9, 11] def readFile(inFile=None, startY=None, startM=None, startD=None,\ endY=None, endM=None, endD=None, dateFormat=None): """ Read the input csv file and return a pandas.DataFrame containing the data. :param file: The file name of the csv containing the market data. :param startY, startM, startD, endY, endM, endD: Optional parameters specifying the timeframe; defaults to the begining and end of the current year. :type startY, startM, startD, endY, endM, endD: int """ # Default to reading "StockDataFixed.csv" as input file. file = "StockDataFixed.csv" if inFile: file = inFile # Read in the file and parse the date strings. try: market = pd.read_csv(file, header = 0) except OSError as ose: print("Please reconsider your input file:", ose) return parsedDates = [] # Yahoo Finance data date format: mm/dd/yy. format = '%m/%d/%y' # Use user format if given. if dateFormat: format = dateFormat # Parse date information into a new column. try: for d in market['Date']: parsedDates.append(datetime.strptime(d, format)) except ValueError as ve: print("Please reconsider your date format:",ve) print() return market['parsed'] = parsedDates # latestDate = market['parsed'][0] earliestDate = market['parsed'][len(market['parsed'])-1] thisY = datetime.today().year defaultStartDate = datetime(thisY, 1, 1) #defaultEndDate = datetime(thisY, 12, 31) defaultEndDate = latestDate print('The data used starts on', earliestDate.strftime("%B %d, %Y"),\ 'and ends on', latestDate.strftime("%B %d, %Y.")) print() # Start date defaults to the beginning of the current year. startDate = defaultStartDate if startY: try: startDate = datetime(startY, startDate.month, startDate.day) except ValueError as ve: print("Please reconsider your starting year.") print() if startM: try: startDate = datetime(startDate.year, startM, startDate.day) except ValueError as ve: print("Please reconsider your starting month.") print() if startD: try: startDate = datetime(startDate.year, startDate.month, startD) except ValueError as ve: print("Please reconsider your starting day.") print() # Start date should not be earlier than the earliest date in the data. if startDate < earliestDate: print("Your starting date is earlier than the earliest date in the data.") print("Adjusting starting date to earliest date.") print() startDate = earliestDate # End date defaults to the end of the current year. endDate = defaultEndDate #endDate = latestDate if endY: try: endDate = datetime(endY, endDate.month, endDate.day) except ValueError as ve: print("Please reconsider your ending year.") print() if endM: y,m,d = endDate.year, endM, endDate.day # Last day of Feb and other shorter months is not 31st. if endM == 2: d = 28 elif endM in shortMonths: d = 30 try: endDate = datetime(y, m, d) except ValueError as ve: print("Please reconsider your ending month.") print() if endD: try: endDate = datetime(endDate.year, endDate.month, endD) except ValueError as ve: print("Please reconsider your ending year.") print() # End date should not be later than the latest date. if endDate > latestDate: print("Your ending date is later than the latest date in the data.") print("Adjusting ending date to latest date.") print() endDate = latestDate # Start date should not be later than end date. if startDate > endDate: print("The ending date is earlier than the starting date.") print("Adjusting ending date to the latest date.") endDate = latestDate #print('start:',startDate, 'end:',endDate) # if startDate < earliestDate: # print("Weird input:") # if endDate > latestDate: # print("Weird input:") # Update the contents: only keep data after start date and before end date. market = market[market.parsed > startDate] market = market[market.parsed < endDate] return market def makeChart(market, prices): """ Generates connected scatter plot, shows and saves to png. :param market: :param prices: list of strings specifying the prices to be in the plot. """ # The readFile() call was not done successfully. # TODO other data types given? #print(type(market)) if market == None: print("Please fix errors in input first.") print() return # Empty list of prices to plot. if len(prices) == 0: print("Please input the prices to plot.") print() return plt.figure() colors = ['b','g','r','c','m','y','k'] plt.xticks(rotation=30) for i in range(len(prices)): price = prices[i] color = colors[i] plt.plot(market['parsed'], market[price], c=color, label=price) plt.xlabel('Date') plt.ylabel('USD') plt.title(' '.join(prices) + ' Price Trend') plt.legend(loc="best") plt.savefig('day_'+'_'.join(prices)+'.png') plt.show()
1ae5e2dfa9b8416c0dab0a7eceacb82840210886
grozhnev/yaal_examples
/Python+/Python3/src/module/builtins/exception/try_except_finally.py
181
3.578125
4
x = 0 try: x = 1 / 0 except ZeroDivisionError as error: print(error) x = 2 except ValueError as error: print(error) x = -1 finally: x = x * 3 assert x == 6
e6b6c32158aec03d8df1f4d4c33907b60151cf02
famaf/Modelos_Simulacion_2016
/Practico_04/ejercicio03.py
2,044
3.84375
4
# -*- coding: utf-8 -*- import random import math def esperanza(n): """ Calcula la esperanza con la Ley de los Grandes Numeros. """ N = 0 # Total de lanzamientos en los n experimentos for _ in xrange(n): RESULTADOS = range(2, 13) # Lista de resultados [2...12] lanzamientos = 0 # Lanzamientos necesarios # Mientras no se hayan obtenido todos los resultados tirar los dados while len(RESULTADOS) != 0: dado1 = random.randint(1, 6) # Dado 1 dado2 = random.randint(1, 6) # Dado 2 suma_dados = dado1 + dado2 lanzamientos += 1 # Si la suma de los dados esta en los resultados posibles # remover dicho resultado de los posibles (xq ya se obtuvo) if suma_dados in RESULTADOS: RESULTADOS.remove(suma_dados) N += lanzamientos return float(N)/n def varianza(n): """ Calcula la varianza en base a la esperanza. """ N1 = 0 N2 = 0 for _ in xrange(n): RESULTADOS = range(2, 13) # Lista de resultados [2...12] lanzamientos = 0 # Lanzamientos necesarios # Mientras no se hayan obtenido todos los resultados tirar los dados while len(RESULTADOS) != 0: dado1 = random.randint(1, 6) # Dado 1 dado2 = random.randint(1, 6) # Dado 2 suma_dados = dado1 + dado2 lanzamientos += 1 # Si la suma de los dados esta en los resultados posibles # remover dicho resultado de los posibles (xq ya se obtuvo) if suma_dados in RESULTADOS: RESULTADOS.remove(suma_dados) N1 += lanzamientos # x N2 += lanzamientos**2 # x^2 varianza = N2/float(n) - (N1/float(n))**2 # V(x) = E(x^2) - E(x)^2 return varianza for n in [100, 1000, 10000, 100000]: print("n =", n, "--> E(X) =", esperanza(n)) print("--------------------------------") for n in [100, 1000, 10000, 100000]: print("n =", n, "--> V(X) =", varianza(n))
34307b20bc490adc5353c9dec5b6f611754e20e3
AhmedRaafat14/Solutions-Of-Cracking-the-Coding-Interview-Gayle-5th-Edition
/Chapter 1/1-2.py
383
3.96875
4
""" Implement a function void reverse(char* str) in C or C++ which reverses a null- terminated string """ # Using python benefits =xD def reverse_s(s): return s[::-1] # Using Naive solution def reverse_s_naive(s): new_s = "" for ch in s: new_s = ch + new_s return new_s if __name__ == "__main__": print(reverse_s("test")) print(reverse_s("car"))
72ae950582dac0f0257ab91a8b0462b66c844e6a
asiasumo/pp3
/python/zadanie23.py
246
3.984375
4
for x in range(1,51): if x % 3 == 0 and x % 5 == 0: print("BINGO") elif x % 5 == 0 or x % 3 == 0: if x % 5 == 0: print("BAM") elif x % 3 == 0 : print("BIM") else: print(x)
7b82699ed776f635d4458105c0a222271dd0eeae
fabiano-palharini/python_codes
/2021_couting_valleys.py
950
4.15625
4
test_case_1 = 'UDUDDU' expected_result_1 = 1 test_case_2 = 'UDDDUU' expected_result_2 = 1 test_case_3 = 'UDUDUDDU' expected_result_3 = 1 test_case_4 = 'UDUDDUDU' expected_result_4 = 2 test_case_5 = 'DUDUDDUU' expected_result_5 = 3 def count_valleys(sequence): sea_level = 0 previous_sea_level = 0 number_of_valleys = 0 for char in sequence: if char == 'U': sea_level += 1 else: sea_level -= 1 if previous_sea_level < 0 and sea_level == 0: number_of_valleys += 1 previous_sea_level = sea_level return number_of_valleys if __name__ == "__main__": print(count_valleys(test_case_1) == expected_result_1) print(count_valleys(test_case_2) == expected_result_2) print(count_valleys(test_case_3) == expected_result_3) print(count_valleys(test_case_4) == expected_result_4) print(count_valleys(test_case_5) == expected_result_5)
7cb5661cecccbfddc4491173e4a469774757ab4e
jackeown/PythonIsNotSlow
/naiveBenchmark.py
655
3.5
4
import sys import random def squareMatrixBenchmark(n): m1 = [None] * (n**2) m2 = [None] * (n**2) m3 = [None] * (n**2) for i in range(n): for j in range(n): m1[i*n + j] = random.random() m2[i*n + j] = random.random() for i in range(n): for j in range(n): s = 0 for k in range(n): s += m1[i*n + k]*m2[k*n + j] m3[i*n+j] = s if __name__ == "__main__": if(len(sys.argv) != 2): print("usage: python naiveBenchmark.py n") exit() n = int(sys.argv[1]) random.seed(0) squareMatrixBenchmark(n)
e82be1c26a35e93b00c19e29175439e4589671ca
Wbeaching/Cryptanalysis-and-security-assessment-of-the-modern-symmetric-key-algorithms-using-neural-networks
/DataGen/Debug/Bits.py
786
3.75
4
def to_bits(s): """ Supports only string on input: 'Hi :D' """ result = [] for c in s: bits = bin(ord(c))[2:] bits = '00000000'[len(bits):] + bits result.extend([int(b) for b in bits]) return result def from_bits(bits): """ Supports only bits on input: [1, 0, 1, 1, 0, 0, 1, 0] """ chars = [] for b in range(int(len(bits) / 8)): byte = bits[b * 8:(b + 1) * 8] chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(chars) def access_hex_bit(data, num): """ Supports only hex format as input: b'\xff' """ base = int(num / 8) shift = num % 8 return (data[base] & (1 << shift)) >> shift def hex_to_bits(data): """ Supports only hex format as input: b'\xff' """ return [access_hex_bit(data, i) for i in range(len(data) * 8)]
8e019b2578512bb97305c2f3a8171eb645730701
dkaisers/Project-Euler
/015/15.py
362
3.96875
4
import math print("x by y") x = int(input("Enter a value for x: ")) y = int(input("Enter a value for y: ")) def bico(x, y): if y == x: return 1 elif y == 1: return x elif y > x: return 0 else: a = math.factorial(x) b = math.factorial(y) c = math.factorial(x - y) return (a // (b * c)) print("Number of lattice paths:") print(bico(x + y, x))
4ed12b5e973290a4694eb684a323007ff898dbd0
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/66_12.py
2,497
3.671875
4
Python – Mutiple Keys Grouped Summation Sometimes, while working with Python records, we can have a problem in which, we need to perform elements grouping based on multiple key equality, and also summation of the grouped result of particular key. This kind of problem can occur in application in data domains. Let’s discuss certain way in which this task can be performed. > **Input** : > test_list = [(12, ‘M’, ‘Gfg’), (23, ‘H’, ‘Gfg’), (13, ‘M’, ‘Best’)] > grp_indx = [1, 2] [ Indices to group ] > sum_idx = [0] [ Index to sum ] > **Output** : [(‘M’, ‘Gfg’, 12), (‘H’, ‘Gfg’, 23), (‘M’, ‘Best’, 13)] > > **Input** : > test_list = [(12, ‘M’, ‘Gfg’), (23, ‘M’, ‘Gfg’), (13, ‘M’, ‘Best’)] > grp_indx = [1, 2] [ Indices to group ] > sum_idx = [0] [ Index to sum ] > **Output** : [(‘M’, ‘Gfg’, 35), (‘M’, ‘Best’, 13)] **Method : Using loop +defaultdict() \+ list comprehension** The combination of above functionalities can be used to solve this problem. In this, we perform grouping using loop and the task of performing summation of key is done using list comprehension. __ __ __ __ __ __ __ # Python3 code to demonstrate working of # Mutiple Keys Grouped Summation # Using loop + defaultdict() + list comprehension from collections import defaultdict # initializing list test_list = [(12, 'M', 'Gfg'), (23, 'H', 'Gfg'), (13, 'M', 'Best'), (18, 'M', 'Gfg'), (2, 'H', 'Gfg'), (23, 'M', 'Best')] # printing original list print("The original list is : " + str(test_list)) # initializing grouping indices grp_indx = [1, 2] # initializing sum index sum_idx = [0] # Mutiple Keys Grouped Summation # Using loop + defaultdict() + list comprehension temp = defaultdict(int) for sub in test_list: temp[(sub[grp_indx[0]], sub[grp_indx[1]])] += sub[sum_idx[0]] res = [key + (val, ) for key, val in temp.items()] # printing result print("The grouped summation : " + str(res)) --- __ __ **Output :** > The original list is : [(12, ‘M’, ‘Gfg’), (23, ‘H’, ‘Gfg’), (13, ‘M’, > ‘Best’), (18, ‘M’, ‘Gfg’), (2, ‘H’, ‘Gfg’), (23, ‘M’, ‘Best’)] > The grouped summation : [(‘M’, ‘Gfg’, 30), (‘H’, ‘Gfg’, 25), (‘M’, ‘Best’, > 36)]
20a0da08d9cfd3c8175b704b35aeae2314494bce
mjpmorse/CMU_ML
/HW/HW4/LR_PredictLabels.py
757
3.59375
4
# The matlab code translated is originally authored by Tom Mitchell # Translated to python 3 by Michael J. P. Morse Sept. 2019 # Predict the labels for a test set using logistic regression def predict_labels(x_test,y_test,w_hat): import numpy as np #get dimensions num_row,num_col = np.shape(x_test) #add a feature of 1's to x_test x_test = np.append(np.ones([num_row,1]),x_test,axis=1); #precompute x.w and exp(x,w) xw = np.dot(x_test,w_hat); exw = np.exp(xw); # calculate p(Y=0) py0 = 1./(1+ exw); # calculate p(Y=1) py1 = exw/(1+ exw); #choose best label prob = np.append(py0,py1,axis=1); y_hat = np.argmax(prob,axis=1).reshape(-1,1); num_error = sum(y_hat != y_test); return y_hat, num_error
50cce03d831a18a36ebd15a20482412b9674fb54
chaofan-zheng/python_learning_code
/leetcode/huawei/跳台阶.py
668
3.640625
4
""" 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 只考虑最后一次的情况 """ class Solution: def jumpFloor(self, number): # write code here if number == 2: return 2 if number == 1: return 1 return self.jumpFloor(number - 1) + self.jumpFloor(number - 2) class Solution2: def jumpFloor(self, number): # write code here a, b = 0, 1 for i in range(number + 1): a, b = b, a + b return a s = Solution2() print(s.jumpFloor(5))
bef8a58794b247476f87218047a776c187b1fc53
BinceAlocious/python
/oops/inheritance/firstpgm.py
194
3.59375
4
class One: def m1(self): print("Inside Parent Method M1") class Two(One): #Inheritence def m2(self): print("Inside Child Method M2 ") obj=Two() obj.m1() obj.m2()
38651a76d936008a7c44cd46e42b0c837d86ca64
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/rbnben002/question2.py
668
3.625
4
import math userA = input(("Enter vector A:\n")) listA = userA.split(" ") userB = input(("Enter vector B:\n")) listB = userB.split(" ") Addition = [eval(listA[0]) + eval(listB[0]),eval(listA[1]) + eval(listB[1]),eval(listA[2]) + eval(listB[2])] Sum = ((eval(listA[0])*eval(listB[0]))+(eval(listA[1])*eval(listB[1]))+(eval(listA[2])*eval(listB[2]))) NormA = round(math.sqrt(eval(listA[0])**2 + eval(listA[1])**2+ eval(listA[2])**2),2) NormB = round(math.sqrt(eval(listB[0])**2+ eval(listB[1])**2+ eval(listB[2])**2),2) print("A+B =",Addition) print("A.B =",Sum) print("|A| =","{0:.2f}".format(NormA)) print("|B| =","{0:.2f}".format(NormB))
e06a159b33d1572ba4ef78ede2cbb0c8bbe37830
mihirkelkar/EPI
/Tree/Next_Node_Preorder/preOrderNext.py
1,024
4.0625
4
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None self.parent = None def preOrderNext(node): if node.left != None: return node.left elif node.right != None: return node.right if node.parent == None: return None else: while node.parent != None: if node == node.parent.left: node = node.parent if node.right != None: return node.right else: node = node.parent elif node == node.parent.right: node = node.parent return None """ 1 / \ 2 5 \ 3 / 4 We will check for 4 and 2, 5 """ one = Node(1) one.left = Node(2) one.left.parent = one one.left.right = Node(3) one.left.right.parent = one.left one.left.right.left = Node(4) one.left.right.left.parent = one.left.right one.right = Node(5) one.right.parent = one print preOrderNext(one.left.right.left).value print preOrderNext(one.left).value print preOrderNext(one.right)
94e9792a5ea96e1e893943f32d5a67dc3a4da53d
cityguy3156/Text-Fantasy-RPG
/TEXT-BASED RPG.py
20,130
3.53125
4
import random # DAMAGE GIVEN TO ANY ENEMY WITH WEAPON def weaponDamage(W): crit = random.randint(1, 5) #CHANCE OF A CRITICAL STRIKE if (W == "Sword"): Damage = random.randint(80, 95) elif (W == "Bow"): Damage = random.randint(65, 80) elif (W == "Axe"): Damage = random.randint(95, 120) if (crit == 3): print "CRITICAL HIT!" return (int)(Damage * 1.25) else: return Damage # DAMAGE GIVEN TO ANY ENEMY WITH MAGIC def magicDamage(M): if (M == 'Ice'): Damage = random.randint(73, 77) elif (M == 'Lightning'): Damage = random.randint(82, 89) elif (M == 'Fire'): Damage = random.randint(95, 120) return Damage # ENEMY STATUS def status(M): mCrit = random.randint(1,3) #CHANCE OF INFLICTING A STATUS ON AN ENEMY if (mCrit == 2): print "CRITICAL STRIKE" if (M == 'Ice'): print "You have cast a Freeze curse onto the creature" return 'FREEZE' elif (M == 'Lightning'): print "You have cast a stun curse onto the creature" return 'STUN' elif (M == 'Fire'): print "You have cast a burn curse onto the creature" return 'BURN' else: return "Normal" def bossReturns(bossStatus): if (bossStatus != 'FREEZE'): return 'Normal' # FIGHT WITH ANYTHING def bossFight(BossHealth, PlayerHealth, Mana, W, M, DR, bossName, a, b, c, d): bossStatus = 'Normal' pStatus = 'Normal' heal = True while (PlayerHealth > 0 and BossHealth > 0): question = raw_input("How will you attack the creature (W M HEAL): ") dodge = random.randint(1,DR) if (pStatus == 'STUN'): print "You are under a stun curse. You cannot do anything." else: while (question != 30202012): if (question == 'W' or question == 'w'): break elif (question == 'M' or question == 'm'): if (Mana > 0): break else: print "\nYou do not have enough mana to cast any magic spells" question = raw_input("How will you attack the creature (W HEAL): ") elif (question == 'HEAL'): if (heal == True): break else: print "\nI've already healed you once this battle. I cannot do it again" question = raw_input("How will you attack the creature (W M): ") else: print "\nI'm afraid you do not have that option" question = raw_input("How will you attack the creature (W M HEAL): ") if (question == 'W' or question == 'w'): if (bossStatus == 'FREEZE'): Damage = weaponDamage(W) * 1.5 else: Damage = weaponDamage(W) print "The enemy takes",Damage,"damage!" BossHealth = BossHealth - Damage elif (question == 'M' or question == 'm'): Mana = Mana - 1 Damage = magicDamage(M) bossStatus = status(M) print "The enemy takes",Damage,"damage!" BossHealth = BossHealth - Damage else: PlayerHealth = 500 print "I have fully restored your health" print "You have",PlayerHealth,"health left" pStatus = 'Normal' heal = False if (bossName == 'CATIPILLAR'): break if (pStatus == 'STUN'): pStatus = 'Normal' if (bossStatus == 'STUN'): print "The creature is stunned and does nothing" elif (dodge == 1): print "You dodged the enemy's attack." else: #THE GATKEEPER FIGHT if (bossName == 'KNIGHT'): print print "The Knight attacks you." PDamage = random.randint(a,b) #THE SPIDER FIGHT elif (bossName == 'SPIDER'): attackChoice = random.randint(1,2) if (attackChoice == 1): if (pStatus != 'POISON'): print print "The spider bites you!" print "You are poisoned by it" pStatus = 'POISON' PDamage = random.randint(a,b) elif (attackChoice == 2): print print "The spider spits a ball of web at you" PDamage = random.randint(c,d) #THE DRAGON FIGHT elif (bossName == 'DRAGON'): attackChoice = random.randint(1,2) if (attackChoice == 1): print print "The dragon envelops you in a fire blast" PDamage = random.randint(a,b) if (pStatus == 'Normal'): pFire = random.randint(1,2) if (pFire == 2): print "CURSE" print "You have been inflicted with a burn curse" pStatus = 'BURN' elif (attackChoice == 2): print print "The dragon hits you with it's tail" PDamage = random.randint(c,d) if (pStatus == 'Normal'): pStun = random.randint(1,3) if (pStun == 2): print "CURSE!" print "You have been inflicted with a stun curse" pStatus = 'STUN' if (bossStatus == 'FREEZE'): PDamage = (int)(PDamage/2) print "You take",PDamage,"damage!" PlayerHealth = PlayerHealth - PDamage #POST BATTLE DAMAGES ##FOR BOSS if (bossStatus == 'BURN'): burnDamage = random.randint(81,88) print "The",bossName,"takes",burnDamage,"damage." BossHealth = BossHealth - random.randint(81,88) if (bossStatus != 'FREEZE'): bossStatus = 'Normal' ##FOR PLAYER if (pStatus == 'POISON'): poison = random.randint(27,39) print "You take",poison,"damage from the poison curse." PlayerHealth = PlayerHealth - poison if (pStatus == 'BURN'): burn = random.randint(41,47) print "You take",burn,"damage from the burn curse." PlayerHealth = PlayerHealth - burn pStatus = 'Normal' if (PlayerHealth > 0): print "You have",PlayerHealth,"life left" else: print "You have no life left" break print "You have",Mana,"Mana left" print return PlayerHealth # PART 1 def sectionOne(PlayerHealth, Mana, W, M, DR): play = True while (play == True): print "CHAPTER 1" move = raw_input("You find yourself in an old village.") print ("Before you move any further, a man steps in your way.") print "\nMAN: I know what yer after, kid. And you ain't never gonna get it unless you can get past that knight in the way. Not even a strong man like you got a chance against him in a one on one. Fortunately for you, I know the secret password that'll make sure you never hafta. All it'll cost ya are two outta five a dem mana points a yers. You in?" getPassword = raw_input("\nGive this man 2 mana points? (Y N): ") #CHOICE: SACRIFICE MANA TO KNOW THE PASSWORD while (getPassword != -2393321345): if (getPassword == 'Y' or getPassword == 'y'): Mana = Mana - 2 print "\nYou have",Mana,"mana left" print "\nMAN: The password is 'Gilgamesh,' but ya gotta say it loudly. Say it strong, say it proud, and he just might let ya through." move = raw_input("The man runs off, and you continue to make your way to the forest.") break elif (getPassword == 'N' or getPassword == 'n'): print "\nMAN: Then I wish you the best of luck" move = raw_input("\nThe man runs off, and you continue to make your way to the forest.") break else: print "\nI'm sorry, I don't understand what you mean." getPassword = raw_input("Give this man 2 mana points? (Y N): ") move = raw_input("\nYou see a pathway leading into the forest. There is a tall, clocked figure blocking the path.") password = raw_input("\nGATEKEEPER: What is the password? (Enter Password):") move = raw_input("\nGATEKEEPER: Password...") if (password == 'GILGAMESH'): print "\nGATEKEEPER: Acceptable" print "\n The gatekeeper steps aside, and allows you to journey into the forest" move = raw_input("\nGUIDE: That was easy. Let's keep moving.") break else: print "\n GATEKEEPER: Unacceptable!" print "(The gatekeeper pulls out his tremendous sword, and challenges you to a duel!)" PlayerHealth = bossFight(500, PlayerHealth, Mana, W, M, DR, 'KNIGHT', 50, 57, 0, 0) if (PlayerHealth > 0): print "\nThe gatekeeper declares you worthy as he falls to the ground." move = raw_input("\nGUIDE: With that out of the way, let's move on.") break else: print "You failed to complete your journey." CONT = raw_input("Would you like to try again?(Y/N): ") while (CONT != 2342432): if (CONT == 'Y' or CONT == 'y'): PlayerHealth = 500 Mana = 5 break elif (CONT == 'N' or CONT == 'n'): print "GAME OVER" PlayerHealth = "GAME OVER" break else: print "I don't understand that answer." CONT = raw_input("Would you like to try again?(Y/N): ") if (CONT == 'N' or CONT == 'n'): return 'GAME OVER' # PART 2: The Spider Fight def sectionTwo(name, PlayerHealth, Mana, W, M, DR): play = True while (play == True): CONT = "THING" print "\n\nCHAPTER 2" move = raw_input("\nAs you proceed through the forest, your finding that it truly lives up to it's macabre legacy. Ther air reeks of feces and foul gasses and the stench of rotting corpses of many ugly things.") print "\nGUIDE: Hey,",name+"! Look what I found!" move = raw_input("You walk over to where the guide is.") print "\nGUIDE: This body looks like it's human: a treasure hunter much like you. Or...at least he used to be. He's clearly been dead for a long time." getMap = raw_input("\nGUIDE: It also looks like he's holding something. Do you think we should pick it up? (Y,N): ") while (getMap != -2393321345): if (getMap == 'Y' or getMap == 'y'): raw_input("\nGUIDE: Well talk about luck! This man was holding a map to navigate through the forest. In fact, it leads us directly to the ancient temple filled with riches! Let's not waste any more time, and go!") break elif (getMap == 'N' or getMap == 'n'): raw_input("\nGUIDE: You're right. It's really not polite to loot people's corpse. Besides, the less time we stay in this forest the better. Let's just go.") break else: print "I'm sorry, I don't understand what you mean." getMap = raw_input("Do you think we should pick up the map? (Y,N): ") move = raw_input("\nGUIDE: I said come on. Let's go.") move = raw_input("\nGUIDE: Hey, what's the matter? Don't you want to find this treasure?") move = raw_input("\nGUIDE: Oh, wait a minute! You're stuck! Looks like while we were looking at that corpse, you accidentally got your feet entangled in some kind of white glop. I'm sorry! Here. Let me try and get you out") print "\nGUIDE: Wow, this stuf is sticky. I'm not exactly what you'd call an expert, but this stuff kind of feels like..." move = raw_input("You then hear a soft, monstrous hissing from behind you.)") move = raw_input("\nGUIDE: Um...I...: ") move = raw_input("\nGUIDE: I'd recommend getting your " + W +" ready: ") print("(You turn around, and realize that you are entangled in the web of a tremendous mother spider. By intruding on its home, you have awakened it's slumber, and it is very angry. But also very hungry. It impatiently lurches towards you, ready to sink it's teeth into your flesh!") print "\nFIGHT\n" PlayerHealth = bossFight(500, PlayerHealth, Mana, W, M, DR, 'SPIDER', 61, 69, 42, 47) #INITIATE FIGHT WITH THE SPIDER if (PlayerHealth > 0): print "The vile arachnid falls over dead." if (getMap == 'Y' or getMap == 'y'): move = raw_input("\nGUIDE: Now let's see where this map leads us: ") return 501 break else: move = raw_input("\nGUIDE: Legends say that there is a temple in the east. Let's go that way: ") return 500 else: #GAME OVER/RETRY print "You failed to complete your journey." CONT = raw_input("Would you like to try again?(Y/N): ") while (CONT != 2342432): if (CONT == 'Y' or CONT == 'y'): #ALLOWS USER TO RETRY SECTION FROM BEGINNING PlayerHealth = 500 Mana = 5 break elif (CONT == 'N' or CONT == 'n'): #ALLOWS USER TO QUIT WHOLE GAME print "GAME OVER" break else: print "I don't understand that answer." CONT = raw_input("Would you like to try again?(Y/N): ") if (CONT == 'N' or CONT == 'n'): return 'GAME OVER' # THE FAKE TEMPLE (You come here if you DON'T get the map) def fakeTemple(name, PlayerHealth, Mana, W, M, DR): print "\n\nCHAPTER 3" print ("\n(Venturing through the forest, you find a stone temple)") move = raw_input("\nGUIDE: Looks like we found it. It took a bit to get here, but now it's time to get our reward.") move = raw_input ("\nInside the temple, you find a dusty open book sitting upon a stone pillar.)") move = raw_input ("\nAs you approach the book, you notice that there is a small catipillar sitting on it") print "\nFIGHT" PlayerHealth = bossFight(3, PlayerHealth, Mana, W, M, DR, 'CATIPILLAR', 0, 0, 0, 0) print "The harmless creature dies instantly" move = raw_input ("\nGUIDE: Now let's close the book, and see what we have") print "(You close the book, and read the words engraved on the cover)" move = raw_input ("\nGUIDE: Webster's Dictionary. For there is no treasure greater than knowledge") print print "\nYOU HAVE COMPLETED YOUR TREASURE QUEST. THANK YOU FOR PLAYING!" print "For a more satisfying ending, play again" # PART 3: THE REAL TEMPLE (You come here if you get the map) def sectionThree(name, PlayerHealth, Mana, W, M, DR): play = True while (play == True): print "C\n\nHAPTER 3" print ("\n(Venturing through the forest, you find a stone temple)") move = raw_input("\nGUIDE: Looks like we found it. It took a bit to get here, but now it's time to get our reward.") move = raw_input("\n(You enter the temple, and find that the walls are engraved in precious gemstones. They lead towards a tremendous, golden doorway") move = raw_input("\nGUIDE: Oh my god! We did it! We found the precious temple!") print "(The ground then starts shaking below your feet)" move = raw_input("\nVOICE: WHO DARES DISTURB MY PRECIOUS SLUMBER!") print "(The golden doors suddenly fly open, and a tremendous dragon emerges from them)" move = raw_input("\nGUIDE: Come on, "+ name + "! Let's fight this dragon, and get the reward we deserve!") print "\nFIGHT" PlayerHealth = bossFight(700, PlayerHealth, Mana, W, M, DR, 'DRAGON', 57, 64, 44, 52) if (PlayerHealth > 0): move = raw_input("DRAGON: NOOOOOOOOO!") print "\n(The dragon's body bursts into flames and swiftly crumble to ash)" move = raw_input("GUIDE: We did it! Now let's see what's on the other side!") print "You enter through the golden doorway, and find gold coins and gemstones from father than the eye can see!" print "Enjoy",name+". For you have earned ever piece of it." print print "\nYOU HAVE COMPLETED YOUR TREASURE QUEST. THANK YOU FOR PLAYING!" break else: print "You failed to complete your journey." CONT = raw_input("Would you like to try again?(Y/N): ") while (CONT != 2342432): if (CONT == 'Y' or CONT == 'y'): PlayerHealth = 500 Mana = 5 break elif (CONT == 'N' or CONT == 'n'): print "GAME OVER" PlayerHealth = "GAME OVER" break else: print "I don't understand that answer." CONT = raw_input("Would you like to try again?(Y/N): ") if (CONT == 'N' or CONT == 'n'): return 'GAME OVER' Health = 500 Mana = 5 #NAME INPUT name = raw_input("Hello, friend. I am your spiritual guide. What is your name: ") print "Well",name + ", you are about to embark on the journy of a lifetime." print "There will be danger, of course, but should make it through, you shall walk away very, very rich!" print "As your spiritual guide, I going to help through this journey. And I shall start by giving you a weapon." #WEAPON SELECT Weapon = raw_input("Tell me, would you like to take a sword, a bow, or an axe? (S B A): ") while (Weapon != 34782): if (Weapon == 'B' or Weapon == 'b'): W = 'Bow' DR = 3 #RATE OF AVOIDING ATTACKS break elif (Weapon == 'S' or Weapon == 's'): W = 'Sword' DR = 7 #RATE OF AVOIDING ATTACKS break elif(Weapon == 'A' or Weapon == 'a'): W = 'Axe' DR = 10 #RATE OF AVOIDING ATTACKS break else: print "I'm afraid you do not have that option" Weapon = raw_input("Tell me, would you like to take a sword, a bow, or an axe? (S B A): ") print "Excellent." print "It also looks like you'll be able to take one spellbook with you." print "I can give you a book that channels the power of ice, lightning or fire." #MAGIC SELECT Magic = raw_input("What spellbook would you like to bring? (F I L): ") while (Magic != 34782): if (Magic == 'L' or Magic == 'l'): #Lightning can stun an enemy and prevent them from attacking M = 'Lightning' break elif (Magic == 'F' or Magic == 'f'): #Fire can do extra damage M = 'Fire' break elif (Magic == 'I' or Magic == 'i'): #Ice can make an enemy weeker and your attacks stronger M = 'Ice' break else: print "I'm afraid you do not have that option" Magic = raw_input("What spellbook would you like to bring? (F I L): ") print "A very fine choice!" print "Now, you are ready to begin your adventure" print Play = True Health = sectionOne(Health, Mana, W, M, DR) if (Health != 'GAME OVER'): Health = sectionTwo(name, 500, Mana, W, M, DR) if (Health != 'GAME OVER'): if (Health == 501): sectionThree(name, Health, Mana, W, M, DR) else: fakeTemple(name, Health, Mana, W, M, DR)
00915a5edbe4582846b0ec23c74ff4d348b56360
tnakaicode/jburkardt-python
/counterfeit_detection/counterfeit_detection.py
14,317
3.6875
4
#! /usr/bin/env python3 # def counterfeit_detection_brute(n, coin, correct): # *****************************************************************************80 # # counterfeit_detection_brute detects counterfeit coins. # # Discussion: # # We are given the weights of N coins, and the correct weight of a single # coin. We are asked to identify the counterfeit coins, that is, those # with incorrect weight. We don't know how many such coins there are. # # We simply use brute force. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 22 March 2019 # # Author: # # John Burkardt # # Reference: # # Kurt Bryan, Tanya Leise, # Making do with less: an introduction to compressed sensing, # SIAM Review, # Volume 55, Number 3, September 2013, pages 547-566. # # Parameters: # # Input, integer n, the number of coins. # # Input, real coin(n), the weights of the coins. # # Input, real correct, the correct weight of a single coin. # # Output, integer suspect(*), the indices of the suspected counterfeit coins. # import numpy as np suspect = np.nonzero(coin != correct) suspect = np.ravel(suspect) return suspect def counterfeit_detection_brute_test(): # *****************************************************************************80 # # counterfeit_detection_brute_test tests counterfeit_detection_brute. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 22 March 2019 # # Author: # # John Burkardt # import numpy as np import platform print('') print('counterfeit_detection_brute_test') print(' Python version: %s' % (platform.python_version())) print(' Test counterfeit_detection_brute,') print(' which seeks to identify multiple counterfeit coins among n coins') print(' using brute force.') # # Generate the problem. # n = 100 correct = 17.0 coin = correct * np.ones(n) fake_num = np.random.randint(3, 11) fake_index = np.random.choice(n, fake_num, replace=False) fake_index.sort() coin[fake_index] = correct + 3.0 * np.random.normal(fake_num) # # Report the fakes. # print('') print(' There were %d fakes' % (fake_num)) print('') print(' Indices of fakes:') print('') for i in range(0, fake_num): print(' %d: %d %g' % (i, fake_index[i], coin[fake_index[i]])) # # Detect and report the fakes. # suspect = counterfeit_detection_brute(n, coin, correct) suspect_num = len(suspect) print('') print(' The function found %d suspects.' % (suspect_num)) print('') print(' Indices of suspects:') print('') for i in range(0, suspect_num): print(' %d: %d %g' % (i, suspect[i], coin[suspect[i]])) return def counterfeit_detection_combinatorial(logn, coin, correct): # *****************************************************************************80 # # counterfeit_detection_combinatorial detects a counterfeit coin. # # Discussion: # # N = 2^(logn) - 1 coins are given. All but one have the correct weight. # Identify the fake coin in logn weighings. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 22 March 2019 # # Author: # # John Burkardt # # Reference: # # Kurt Bryan, Tanya Leise, # Making do with less: an introduction to compressed sensing, # SIAM Review, # Volume 55, Number 3, September 2013, pages 547-566. # # Parameters: # # Input, integer logn, the number of coins is 2^logn - 1. # # Input, real coin(2^logn-1), the weights of the coins. # # Input, real correct, the correct weight of a single coin. # # Output, integer suspect, the index of the suspected counterfeit coin. # import numpy as np n = 2 ** logn - 1 # # The PHI matrix encodes the binary representations of 1 through n. # For n = 7: # # 1 0 1 0 1 0 1 # 0 1 1 0 0 1 1 # 0 0 0 1 1 1 1 # # We compute column J of the PHI matrix, and multiply by COIN(J), # and add that to W. W = PHI * COIN. # w = np.zeros(logn) phi = np.zeros(logn) for j in range(0, n): for i in range(0, logn): if (phi[i] == 0): phi[i] = 1 break phi[i] = 0 w[0:logn] = w[0:logn] + phi[0:logn] * coin[j] # # The suspected coin is found because the incorrect entries in W # form the binary representation of the index. # suspect = 0 good = correct * 2 ** (logn - 1) factor = 1 for i in range(0, logn): if (w[i] != good): suspect = suspect + factor factor = factor * 2 # # Subtract 1 for Python base 0 indexing... # suspect = suspect - 1 return suspect def counterfeit_detection_combinatorial_test(logn): # *****************************************************************************80 # # counterfeit_detection_combinatorial_test tests counterfeit_detection_combinatorial. # # Discussion: # # N = 2^(logn) - 1 coins are given. All but one have the correct weight. # Identify the fake coin in logn weighings. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 22 March 2019 # # Author: # # John Burkardt # # Reference: # # Kurt Bryan, Tanya Leise, # Making do with less: an introduction to compressed sensing, # SIAM Review, # Volume 55, Number 3, September 2013, pages 547-566. # # Parameters: # # Input, integer logn, the number of coins is 2^logn - 1. # A value of 3 is typical. # import numpy as np import platform print('') print('counterfeit_detection_combinatorial_test') print(' Python version: %s' % (platform.python_version())) print(' Test counterfeit_detection_combinatorial,') print(' which can identify one counterfeit coin among 2^logn-1 coins') print(' using just logn comparisons.') n = 2 ** logn - 1 # # Set the data. # correct = 17.0 coin = correct * np.ones(n) # # Select one coin at random to have the wrong weight. # fake = np.random.randint(0, n) coin[fake] = coin[fake] + 0.5 * np.random.normal(1) suspect = counterfeit_detection_combinatorial(logn, coin, correct) # # Compare actual fake to your suspect. # print('') print(' %d coins were checked' % (n)) print(' The fake coin was number %d' % (fake)) print(' %d comparisons were made' % (logn)) print(' The suspected coin is number %d' % (suspect)) return def counterfeit_detection_compressed(n, coin, correct, k): # *****************************************************************************80 # # counterfeit_detection_compressed detects counterfeit coins. # # Discussion: # # We are given the weights of N coins, and the correct weight of a single # coin. We are asked to identify the counterfeit coins, that is, those # with incorrect weight. We don't know how many such coins there are. # # We use techniques from compressed sensing. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 23 March 2019 # # Author: # # John Burkardt # # Reference: # # Kurt Bryan, Tanya Leise, # Making do with less: an introduction to compressed sensing, # SIAM Review, # Volume 55, Number 3, September 2013, pages 547-566. # # Parameters: # # Input, integer n, the number of coins. # # Input, real coin(n), the weights of the coins. # # Input, real correct, the correct weight of a single coin. # # Input, integer k, the number of rows to use in the sensing matrix. # # Output, integer suspect, the index of the suspected counterfeit coin. # import numpy as np from scipy.optimize import linprog from scipy.optimize import OptimizeWarning import warnings phi = np.random.randint(0, 2, size=(k, n)) b1 = np.matmul(phi, coin) b2 = correct * np.sum(phi, axis=1) b2 = np.reshape(b2, (k)) b = b1 - b2 # # Find x which minimizes ||x||_1 subject to phi*x=b. # f = np.ones(n) # # Without this, linprog will warn that the Phi matrix does not have # full row rank. We don't care! # with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=OptimizeWarning) result = linprog(f, A_ub=None, b_ub=None, A_eq=phi, b_eq=b, bounds=(0, None)) # result = linprog ( f, A_ub=None, b_ub=None, A_eq=phi, b_eq=b, bounds = (0,None), options={'tol':1.0e-8} ) suspect = np.nonzero(result.x) suspect = np.ravel(suspect) return suspect def counterfeit_detection_compressed_test(k): # *****************************************************************************80 # # counterfeit_detection_compressed_test tests counterfeit_detection_compressed. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 10 March 2019 # # Author: # # John Burkardt # # Reference: # # Kurt Bryan, Tanya Leise, # Making do with less: an introduction to compressed sensing, # SIAM Review, # Volume 55, Number 3, September 2013, pages 547-566. # # Parameters: # # Input, integer k, the number of random subsets to test. # If n = 100, k = 20 is reasonable. # import numpy as np import platform print('') print('counterfeit_detection_compressed_test') print(' Python version: %s' % (platform.python_version())) print(' Test counterfeit_detection_compressed,') print(' which seeks to identify multiple counterfeit coins among n coins') print(' using compressed sensing techniques.') problem = 2 if (problem == 1): n = 7 correct = 17.0 coin = correct * np.ones(n) fake = np.array([2]) fake_num = len(fake) coin[fake[0]] = correct + 0.5 * np.random.random(fake_num) else: # # Very strange! Setting all counterfeits to 17.5 improves chances of # getting a solution... # n = 100 correct = 17.0 coin = correct * np.ones(n) fake_num = 3 fake = np.random.choice(n, fake_num, replace=False) fake.sort() for i in range(0, fake_num): # coin[fake[i]] = correct + 0.5 * np.random.random ( 1 ) coin[fake[i]] = correct + 0.5 print(' There are %d coins to check.' % (n)) print(' The correct coin weight is %g' % (correct)) # # Report the fakes. # print('') print(' There were %d fakes' % (fake_num)) print('') print(' Fake Index Weight::') print('') for i in range(0, fake_num): print(' %7d: %4d %g' % (i, fake[i], coin[fake[i]])) # # Detect and report the suspected fakes. # suspect = counterfeit_detection_compressed(n, coin, correct, k) suspect_num = len(suspect) print('') print(' %d random subsets were weighed.' % (k)) print(' The function found %d suspects.' % (suspect_num)) print('') print(' Suspect Index Weight:') print('') for i in range(0, suspect_num): print(' %7d: %4d %g' % (i, suspect[i], coin[suspect[i]])) # # Declare success or failure. # if (suspect_num != fake_num): success = False elif (np.array_equal(fake, suspect)): success = True else: success = False print('') if (success): print(' The test succeeded') else: print(' The test failed.') return def counterfeit_detection_test(): # *****************************************************************************80 # # counterfeit_detection_test tests counterfeit_detection. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 23 March 2019 # # Author: # # John Burkardt # import platform print('') print('counterfeit_detection_test') print(' Python version: %s' % (platform.python_version())) print(' Test counterfeit_detection.') counterfeit_detection_brute_test() logn = 3 counterfeit_detection_combinatorial_test(logn) k = 20 counterfeit_detection_compressed_test(k) # # Terminate. # print('') print('counterfeit_detection_test:') print(' Normal end of execution.') return def timestamp(): # *****************************************************************************80 # # TIMESTAMP prints the date as a timestamp. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 06 April 2013 # # Author: # # John Burkardt # # Parameters: # # None # import time t = time.time() print(time.ctime(t)) return None def timestamp_test(): # *****************************************************************************80 # # TIMESTAMP_TEST tests TIMESTAMP. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 03 December 2014 # # Author: # # John Burkardt # # Parameters: # # None # import platform print('') print('TIMESTAMP_TEST:') print(' Python version: %s' % (platform.python_version())) print(' TIMESTAMP prints a timestamp of the current date and time.') print('') timestamp() # # Terminate. # print('') print('TIMESTAMP_TEST:') print(' Normal end of execution.') return if (__name__ == '__main__'): timestamp() counterfeit_detection_test() timestamp()
70f34adabee503cba4e41471b4863c1d91f3c496
MZoltan79/Python_Idomar
/p0031_mutable_immutable.py
737
4.09375
4
#!/usr/bin/env python3 # mutable variable a1 = [1, 2] b1 = a1 a1[0] = 'abc' print(a1, b1) # a list mutable, azaz ha ugyanarra a referenciára 2 # hivatkozás mutat, és az egyiket változtatom, mind # a 2 megváltozik. # ezért 'másolni' kell! a2 = [1, 2] b2 = a2[:] # vagy list(a2) a2[0] = 'abc' print(a2, b2) # immutable variables a = 3 b = a print(a, b, a == b, a is b) a = 4 print(a, b) # érdekesség, hogy a python optimalizációs okok # miatt eleve betölt bizonyos objektumokat a # memóriába (a számokat pl. -5 - 256-ig). # az alábbi pár sor ezt hivatott szemléltetni: a = -5 b = -5 while a is b: a += 1 b += 1 print('a = ', a, ', b = ', b, ', a == b: ', a == b, ', a is b: '\ , a is b, sep = '')
2654a0b8ef12501cc4437b37f48c835487962dcd
Python-lab-cycle/Najmalfawaz
/concatenate elemts in list.py
177
3.96875
4
lis=input("enter a list(apace seperated):") s1=lis.split() print(s1) result='' for element in s1: result += str(element) print("concatenate in the list:",result)
9b9a78a66044f37b0b9a812f6dadfb2b70ce01e5
Izardo/my-work
/Topic_2_statements/numGreaterThan.py
302
4.09375
4
# This program calculates whether one number is greater than another # Author: Isabella Doyle num1 = input("Enter the first number:") # requests input of integer num2 = input("Enter the second number:") # requests input of integer # prints output of whether one number greater than second print(num1 > num2)
c5ec87058ba18923323669c3f71625bb5e080c79
ezequielhenrique/exercicios-python
/modulos/ex115/lib/interface/__init__.py
666
3.609375
4
def linha(tam=40): print('~' * tam) def cabecalho(txt): linha() print(f'{txt}'.center(40)) linha() def leiaInt(txt): while True: try: n = int(input(txt)) except (ValueError, TypeError): print('\033[031m[ERRO] por favor, digite um número inteiro válido\033[m') except KeyboardInterrupt: print('Programa interrompido pelo usuário') else: return n def menu(lista): cabecalho('MENU PRINCIPAL') c = 1 for i in lista: print(f'\033[34m{c} - {i}\033[m') c += 1 linha() opc = leiaInt('\033[36mSua opção: \033[m') return opc
334df13577dbcab2bb01631da6ec7f2beec065c3
harshareddy832/amfoss-tasks
/Task-2 Programming/amfoss9.py
130
3.859375
4
x=int(input()) s=str(x) team1="0000000" team2="1111111" if team1 in s or team2 in s: print("YES") else: print("NO")
b4609735102e24d87670a461f23647a0b2face8d
kaunta/IONs
/src/Level4/w.py
175
3.5625
4
## w.py # Welcome to Level 4. We begin by reviewing our notation # for ω, the smallest infinite ordinal. X="" while True: output(X) X = "output('" + escape(X) + "')"
c409e3822df40a681aec5bc8ee1d069d05110cbf
NorthcoteHS/10MCOD-Jason-VU
/modules/u3_organisationAndReources/naming/New folder/temp/completeMe.py
573
4.0625
4
""" Prog: rectCalc.py Name: Student Name Date: 12/03/18 Desc: Calculates the area and perimeter of a rectangle. """ # Display welcome message. print('Welcome to the Rectangle Calculator!') # Use input to get the rectangle's length and width (2 lines). # - Remember to provide a prompt message for each input. # Convert length and width to integers. length = int(length) width = int(width) # Calculate the area (1 line: length times width). # Display the area. print('The area is', area) # Calculate and display the perimeter (2 lines: P = 2*length + 2*width).
be6d99da4403b6b9a5993988c7a6fdab13ae7cbe
Mustafamado/Quran_Module
/Quran_Module.py
4,195
3.515625
4
import os import csv class Project_Quran: def __init__(self): Quran_English = [] with open('./Quran_English.csv', 'rt') as f: for rows in f: Quran_English.append(rows) self.Quran_English = Quran_English Quran_Arabic = [] with open('./Quran_Arabic.csv') as v: for rows in v: Quran_Arabic.append(rows) self.Quran_Arabic = Quran_Arabic def Check_Ayah(self, Ayah_Number): self.Check_Ayah_Results = False for enteries in self.Quran_English: if Ayah_Number in enteries: self.Check_Ayah_Results = True def Get_Ayah_English(self, Ayah_Number): for enteries in self.Quran_English: if Ayah_Number in enteries: self.Ayah_English = enteries return self.Ayah_English def Get_Ayah_Arabic(self, Ayah_Number): for enteries in self.Quran_Arabic: if Ayah_Number in enteries: self.Ayah_Arabic = enteries return self.Ayah_Arabic def Get_Quran(self): self.All_Quran_English = self.Quran_English self.All_Quran_Arabic = self.Quran_Arabic return self.All_Quran_Arabic, self.All_Quran_English def Get_Custom_Quran_text(self, Ayah_List, filename = 'Quran_text.txt'): f = open(filename, 'a+') for Ayah_Number in Ayah_List: Arabic_Num = '1,' + Ayah_Number self.Get_Ayah_Arabic(Arabic_Num) f.write(self.Ayah_Arabic) English_Num = '59,' + Ayah_Number self.Get_Ayah_English(English_Num) f.write(self.Ayah_English) f.close() def Find_Text_English(self, Text_to_Find): self.Search_Results_English = [] for enteries in self.Quran_English: if Text_to_Find in enteries: print(enteries) self.Search_Results_English.append(enteries) print(str(len(self.Search_Results_English)) + ' Ayahs found! ;)') return self.Search_Results_English def Find_Text_Arabic(self, Text_to_Find): self.Search_Results_Arabic = [] for enteries in self.Quran_Arabic: if Text_to_Find in enteries: print(enteries) self.Search_Results_Arabic.append(enteries) print(str(len(self.Search_Results_Arabic)) + ' Ayahs found! ;)') if len(self.Search_Results_Arabic) == 0: print("Try Searching the same word in English, or If you want it in Arabic Add Proper (َ ِ ُ ّ )") return self.Search_Results_Arabic if __name__ == '__main__': print("Module has no Errors and it works just fine I suppose, If you have any Questions Related to Project_Quran.\n Contact: Muneebkhurram9@gmail.com \n Note: \n We are AnonymousPAK we are a Legion, We do Forgive, but We do not Forget, Expect us!") os.system('pip install pyfiglet') os.system('pyfiglet AnonymousPAK shall Rise') print('[+] Death is upon Iluminati and New World Order, Insha-Allah!') print('[+] Islam shall rise as it a religon of Peace, and those who try to mock Islam, fear the wrath of God, the Almighty, the All Merciful.') print('[+] Fear Death as Death will also come to Death on the Day of Judgement') print('[+] We follow Hadrat Muhammad (PBUH), We are Only Muslims, we are the Religion of Peace, But when try to take over our homelands, we would retaliate!') print('[+] You try to mock Islam, have you ever thought, Ilumninati, in your country USA when a Black man does a firing he is a Terrorist, but when a white man does it, that is Mental Ilness!') print('[+] لا الہ الا اللّٰہ محمد الرسول اللّٰہ ﷺ') print("We are Peaceful, and we have no racial injustice like you since the beginning of Islam, As our Prophet (PBUH) said; \n We all are the children of Adam (A.S), thus no Arabian has any superiority over Non-Arabian and no Non-Arabian has superiority on Arabian, \n No Black is superior on white and No white is superior on Black!") os.system("pyfiglet '/----PAK----/'")
68593ade992c345cc82c4659f7113ce16310b9c0
riishij/Land-of-the-Pirates
/Choose Your Story.py
78,191
3.8125
4
#------------------------------------------------------------------------------- # Name: Riishi Jeevakumar # Program Name: Lost in the land of Pirates: A choose your story adventure game #------------------------------------------------------------------------------- #start of game #outputs introduction to game print"--------------------------------------------------------------------------------------------------" print"Welcome to the Land of the Pirates!" print" " import time time.sleep(3) print"During the game, you will receive points by selecting the most suitable option!" print" " import time time.sleep(3) print"You must be alive by the end of the game. " print " " import time time.sleep(3) print"Once you complete the game, you will be ranked based on the total amount of points you've earned!" print " " import time time.sleep(3) print"Good luck and break a leg! ARGHHH!" print"--------------------------------------------------------------------------------------------------" x=1 while x==1: #variables set for user's name, total points and health name=raw_input("Enter Your Name") totalPoints=0 health=100 health=int(health) #location of user's starting point print "Location: Jeevan Industries " print "Year: 2100" print "" #Delay and display storyline import time time.sleep(4) print name +", you are a famous scientist who has invented the first ever Time Machine!" print" " maleFriend=raw_input("Enter the name of your male friend") #Delay and display storyline import time time.sleep(4) print "One day, you and " + maleFriend + " arrive at Jeevan Laboratories to see your wonderful invention." print"" #Delay and display storyline import time time.sleep(4) print "However, when you try to test the time machine, it doesn't turn on. " print"" #Delay and display storyline import time time.sleep(4) print name +", you decide to go inside the time machine to see what is wrong. " print"" #Delay and display storyline import time time.sleep(4) print "Once you go inside, you hear the door behind you close! " print"" #Delay and display storyline import time time.sleep(4) print"BEEP! BEEP! BEEP!" print"" #Delay and display storyline import time time.sleep(4) print name + ", you turn around to see how the door got closed and once you do, you see your friend tampering with the time machine's controls. " print"" #Delay and display storyline import time time.sleep(4) print "You ask " + maleFriend + " to help you, but suddenly he takes off his mask!" print"" #Delay and display storyline import time time.sleep(4) print "You realize that he's your arch-nemesis, Kuta Raja, but's it's too late as the time machine activates!" print"" #Delay and display storyline import time time.sleep(4) print"BOOM!" print"" #Delay and display storyline import time time.sleep(2) print"You go unconscious..." #Delay and display storyline import time time.sleep(2) print"(Loses 20 health)" #user loses 20 health health= health-20 #Delay and display storyline import time time.sleep(2) #Display remaining health print"Total health remaining= " + str(health) print"" #Delay and display storyline import time time.sleep(3) #new user location print "Location: Isle of Blood" print "Year: 1679" #Delay and display storyline import time time.sleep(3) print "Splash! Woosh! Chrip! " print name + ", after going unconscious, you go back 421 years in time and wake up the Isle of Blood, a land full of pirates!" #Delay and display storyline import time time.sleep(4) print" " print "You cannot believe how hot it is as you decide to take off your lab coat." #Delay and display storyline import time time.sleep(4) print" " print"Once you do, you try to open the time machine, but it doesn't budge!" #Delay and display storyline import time time.sleep(4) #FIRST PART (ASKING USER TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Take a break to find some food" print"2. Try to break open the time machine using a rock" print"3. Go into the town to get some help" #Asks user question, uses try and except to safeguard the program from crashing question1=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question1 = int(question1) if question1 >=1 and question1 <=3: break else: print "Invalid input!" question1=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question1=raw_input("Enter which option you would like to pick(1, 2, or 3)") #If user chooses option 1, display storyline if (question1==1): print" " print name + ", you go into the nearby forest." print" " #Delay and display storyline import time time.sleep(4) print "When you do, a lion comes out from a bush and jumps towards you!" print" " #Delay and display storyline import time time.sleep(4) print "You try to scream for help but no can hear you!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you have nothing to protect yourself from the lion as you took off your lab coat before entering the forest!" print" " #Delay and display storyline import time time.sleep(4) print"ROAR! CRUNCH!" print" " #Delay and display storyline import time time.sleep(2) #User is dead print name.upper() + ", YOU ARE DEAD!" print" " time.sleep(2) #health variable set to 0 print"(Loses 80 health)" health=0 time.sleep(2) #Outputs health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if(question1==2): #If user chooses option 2, display storyline print" " print name + ", when you try to open the machine, it breaks as the rock damages it greatly." print" " #Delay and display storyline import time time.sleep(4) print "You then lie in the sand and find a mysterious letter." print" " #Delay and display storyline import time time.sleep(2) totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if(question1==3): #If user chooses option 3, display storyline import time time.sleep(4) print name + ", you decide to walk to the nearby town, Cooksville." print" " import time time.sleep(4) print "Once you arrive at Cooksville, you try to enter the town, but the inlanders think that you are an enemy." print " " #Delay and display storyline import time time.sleep(4) print "You then decide to run back to the time machine." print" " #RANDOM EVENT NUMBER 1 #Random generator determines outcome of user print"While running, you suddenly see a flash of lighting strike a tree as it comes crashing down towards you!" from random import randint num = randint (1,10) if num !=1 or num!=3 or num!=5 or num!=7 or num!=9: print "However, you were able to successfully dodge the tree as you went back to the time machine where you found a letter in the sand." totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points import time time.sleep(4) print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break else: print name + ", you have no time to react as the tree crushes your body!" #Delay and display storyline import time time.sleep(2) #User is dead print name.upper() + ", YOU ARE DEAD!" print" " time.sleep(2) #health variable set to 0 health=0 time.sleep(2) #Outputs health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print"Invalid Input" while x==1: #Delay and display storyline import time time.sleep(4) print name + ", after finding the letter, you decide to take a rest and open it tomorrow." print " " #Delay and display storyline import time time.sleep(4) print "The next day, you open the letter." print " " #Delay and display storyline import time time.sleep(4) print "Inside the letter, it contains a message that says 'If you want to return home, head north to Banterville for your next clue.' " print " " #Delay and display storyline import time time.sleep(4) print "However, you have no idea where Banterville is, but suddenly you see a small house." print " " #Delay and display storyline import time time.sleep(4) print name + ", you aren't sure what's in the house." print " " #Delay and display storyline import time time.sleep(4) #SECOND PART (ASKING USER TO SELECT AN OPTION) #Display options print "What do you want to do?" print" " print"1. Head to the house" print"2. Ignore the house" print"3. Take a break and head into the ocean" #Asks user question, uses try and except to safeguard the program from crashing question2=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question2 = int(question2) if question2 >=1 and question2 <=3: break else: print "Invalid input!" question2=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question2=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question2==1): #if user selects option 1, display storyline print" " print name + ", you head to the house." print" " #Delay and display storyline import time time.sleep(4) print "When you enter the house, you notice a old man on the ground." print" " #Delay and display storyline import time time.sleep(4) print name + ", you try to not disturb him, but suddenly he wakes up!" print" " #Delay and display storyline import time time.sleep(4) print "When he sees you, he notices your injuries and heals you with a Pecha Berry, a berry that heals your health!" print" " time.sleep(4) health=health+10 #Display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print "He then introduces himself as a priest." print" " #variable created to allow user to enter the name of the priest priest=raw_input("Enter the name of the priest") #Delay and display storyline import time time.sleep(4) print name + ", you show your letter to " + priest + "." print" " #Delay and display storyline import time time.sleep(4) print "Once the priest reads the letter, he tells you that you are the chosen one and hands you a map!" print" " #Delay and display storyline import time time.sleep(4) print "You then thank " + priest + " and begin your journey to Banterville." print" " break totalPoints=int(totalPoints) totalPoints=totalPoints+2 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " if(question2==2): #if user selects option 2, display storyline print" " print name + ", you ignore the house and begin your journey." print" " #Delay and display storyline import time time.sleep(4) print "While you are walking, a inlander comes to you and hits you with a whip!" print"" print"(Loses 20 health)" health= health-20 #Display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print "While the inlander hits you, you notice a map hanging from the inlander's pocket!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you then hear something coming from the house!" print" " #Delay and display storyline import time time.sleep(4) print "Priest: ARGHHHHH! WHO WOKE ME UP!" print" " #Delay and display storyline import time time.sleep(4) print name + ", the inlander gets distracted from this as you are able to push him onto the ground and snatch the map!" print" " #Delay and display storyline import time time.sleep(4) print "The inlander then runs away." print" " #Delay and display storyline import time time.sleep(4) print "The man who was at the house comes towards you and introduces himself as a priest." print" " priest=raw_input("Enter the name of the priest") #Delay and display storyline import time time.sleep(4) print name + ", you show your letter to " + priest + "." print" " #Delay and display storyline import time time.sleep(4) print "Once the priest reads the letter, he tells you that you are the chosen one!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you then thank " + priest + " and continue your journey to Banterville." print" " break totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " if(question2==3): #if user selects option 3, display storyline print" " print name + ", you go into the ocean to swim and relax." print" " #Delay and display storyline import time time.sleep(4) print "When you do, you notice something shiny and swim to it." print" " #Delay and display storyline import time time.sleep(4) print "Once you get close to the object, you notice a Great White Shark coming towards you!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you try to swim away, but the shark crunches you into bits!" print" " #Delay and display storyline import time time.sleep(2) print"CRUNCH!" print" " #Delay and display storyline import time time.sleep(2) #user has died print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #Display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" while x==1: #Delay and display storyline import time time.sleep(4) print name + ", while walking to Banterville, you fall into a hole." #Delay and display storyline import time time.sleep(2) print "One of these options will randomly select your outcome." #Delay and display storyline import time time.sleep(4) #RANDOM EVENT NUMBER 2 #Random generator determines user's outcome #Display options print"1. You jump over the hole and proceed with your journey." print"2. You fall into the hole." print"3. The priest saves you and gives you a potion which revives your health." from random import randint random2 = randint (1,4) if (random2==1): #If random option 1 is selected , delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that you will jump over the hole without sustaining any injuries and proceed with your journey! " print" " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (random2==2): #if random option 2 is selected , delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that you will fall in the hole and injure your foot greatly! " print" " print"(Loses 20 health)" health= health-20 #Display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print"However, you are able to get out of the hole using all of your strength as you continue your journey." print" " break if (random2==3): #if random option 3 is selected, delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that " + priest+ " saves you from falling in the hole and gives you a potion which revives your health!" print" " print" " print"(Gains 5 health)" health= health+5 #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print name + ", you thank " + priest + " and continue your journey." print" " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break while x==1: #Delay and display storyline import time time.sleep(4) print name + ", once you get to Banterville, you ask the townsfolk about the next clue. " print " " #Delay and display storyline import time time.sleep(4) print "No one knows what you are talking about and you think of leaving the town. " print " " #Delay and display storyline import time time.sleep(4) print "However, a little girl comes to you as she tries to communicate with you. " print " " #Delay and display storyline import time time.sleep(4) print name + ", you realize that she is deaf, but you notice something unusual with the girl. " print " " #Delay and display storyline import time time.sleep(4) #THIRD PART (ASKING USER TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Ignore the girl and leave the town" print"2. Run away" print"3. Show her the letter" #Asks user question, uses try and except to safeguard the program from crashing question3=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question3 = int(question3) if question3 >=1 and question3 <=3: break else: print "Invalid input!" question3=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question3=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question3==1): #If option 1 is selected, display storyline print" " print name + ", when you leave the town, you encounter a wildfire and burn to death! " print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question3==2): #If option 2 is selected, display storyline print" " print name + ", you decide to run away from Banterville after you notice something unusual about the girl." print" " #Delay and display storyline import time time.sleep(4) print print "While you are running away, the girl gets mad at you and slams you on the ground using her mind control skills! " print" " #user loses health print"(Loses 30 health)" health= health-30 #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print print name + ", you try to apologize, but the girl isn't having it as she kills you instantly by tossing you in the sky and smashing your head onto the ground! " print" " #Delay and display storyline import time time.sleep(4) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(4) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question3==3): #if option 3 is selected, display storyline print" " print name + ", you decide to show the letter to the girl." print" " #Delay and display storyline import time time.sleep(4) print "After you show the letter, you communicate with her in sign language!" print " " #user enters name of girl for new variable girl=raw_input("Enter the name of the girl") #Delay and display storyline import time time.sleep(4) print "The girl introduces herself as " + girl + " and hands you the next clue." print " " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " #Delay and display storyline import time time.sleep(4) print girl + " then asks you if she can join you on your adventure. " print " " #Delay and display storyline import time time.sleep(4) #FOURTH PART (ASKING USER TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Allow her to join you" print"2. Tell her to stay in the town" print"3. Tell her to run off and get help" #Asks user question, uses try and except to safeguard the program from crashing question4=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question4 = int(question4) if question4 >=1 and question4 <=3: break else: print "Invalid input!" question4=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question4=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question4==1): #if user selects option 1, display storyline print" " print name + ", you decide to let " + girl + " join you" print" " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (question4==2): #if user selects option 2, display storyline print" " print name + ", you tell " + girl + " to stay in town because she is pretty young." #Delay and display storyline import time time.sleep(4) print girl + " cries because she can't come with you and runs behind a bush. " print " " #Delay and display storyline import time time.sleep(4) print "You run to the bush to apologize to " + girl + ",but suddenly, a vine from the ground grabs your foot and throws you onto the ground!" print " " print" " print"(Loses 10 health)" health= health-10 #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(4) print "" print name + ", after you get up from the ground, more vines grab you and suffocate you." #Delay and display storyline import time time.sleep(4) print "" print girl + " then comes out of the bush as her eyes are pitch black" print girl + " is using her mind control tactics to control the vines" #Delay and display storyline import time time.sleep(4) print "" print name + ", after you realize what's going on, you apologize to " + girl + " and tell her that she can come with you in sign language." #Delay and display storyline import time time.sleep(4) print "" print girl + "'s eyes return to normal as the vines disappear. " print girl + " then tells you that she is sorry for what she did. " #Delay and display storyline import time time.sleep(4) print "" print name + ", you forgive " + girl + " as you continue your journey with your new accomplice." print "" totalPoints=int(totalPoints) totalPoints=totalPoints+2 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (question4==3): #if option 3 is selected, display storyline print" " print name + ", you tell " + girl + " to run off and get help." print" " #Delay and display storyline import time time.sleep(4) print "" print "After " + girl + " runs off, you decide to ditch her and continue your journey." #Delay and display storyline import time time.sleep(4) print "" print "However, the " + girl + " sees you and uses her mind control tactics to block the gates of the town." #Delay and display storyline import time time.sleep(2) print "" print "BOOM!" print name.upper() + ", YOU ARE TRAPPED!" #Delay and display storyline import time time.sleep(3) print "" print "You try to apologize to " + girl + ",but she doesn't care as you lied to her!" #Delay and display storyline import time time.sleep(4) print "" print girl + "'s eyes go pitch black as she uses her mind control tactics once again to throw a huge rock at you!" #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" while x==1: #Delay and display storyline import time time.sleep(4) print name + ", after you allow " + girl + " to join you, you head onto the Picanugan Forest. " print " " #Delay and display storyline import time time.sleep(4) print "As you come to the edge of the forest, there is a fork in the pathway. " print " " #Delay and display storyline import time time.sleep(4) print name + ", to the right of the pathway, you see a strange looking house and to the left of the forest, you see the pathway disappear over a tall hill. " print " " #Delay and display storyline import time time.sleep(4) print "You aren't sure which pathway to take." print " " #Delay and display storyline import time time.sleep(4) #FIFTH PART (ASKING USER TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Stay in the forest and camp out for the night" print"2. Head onto the left pathway" print"3. Head onto the right pathway" #Asks user question, uses try and except to safeguard the program from crashing question5=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question5 = int(question5) if question5 >=1 and question5 <=3: break else: print "Invalid input!" question5=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question5=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question5==1): #if user selects option 1, display storyline print" " print name + ", you and " + girl + " decide to stay in the forest and camp out for the night." print" " #Delay and display storyline import time time.sleep(4) print "The next day, when you wake up, you noticed that " + girl + " has disappeared!" print" " #Delay and display storyline import time time.sleep(4) print "However, you finally notice her on the fork of the pathway as she is in combat with someone." print" " #Delay and display storyline import time time.sleep(4) print "When you get closer, you couldn't believe your eyes!" print" " #Delay and display storyline import time time.sleep(4) print "IT WAS YOUR ARCH-NEMESIS, KUTA RAJA!" print" " #Delay and display storyline import time time.sleep(4) print "Once you realize Kuta Raja is here, you try to join the fight." print" " #Delay and display storyline import time time.sleep(4) print "However, Kuta Raja is able to kill " + girl + " in a couple of seconds and soon he notices you!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you do not have anything to protect yourself with as he fires a bullet at you!" print" " #Delay and display storyline import time time.sleep(2) print "BOOM!" print" " #Delay and display storyline import time time.sleep(2) print "The bullet goes through your head and pierces your skull!" print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question5==2): #if user selects option 2, display storyline print" " print name + ", you and " + girl + " decide to go onto the left pathway." print" " #Delay and display storyline import time time.sleep(4) print "While walking to the strange house, you hear dreadfull sounds." print" " #Delay and display storyline import time time.sleep(4) print "BOO! SQUEAK! CAW! AH!" print" " #Delay and display storyline import time time.sleep(4) print name + ", once you arrive at the house, " + girl + " tells you that she wants to go inside first." print" " #Delay and display storyline import time time.sleep(4) print "You let " + girl + " inside the home, but after 10 minutes, she doesn't come outside!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you get scared so you decide to go inside the house." print" " #Delay and display storyline import time time.sleep(4) print "The first thing you see is " + girl + "'s body on the ground drenched by blood!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you become traumatized by what you saw and suddenly, someone hits you from behind!" print" " #Delay and display storyline import time time.sleep(4) print "You check to see who hit you and you couldn't believe your eyes!" print" " #Delay and display storyline import time time.sleep(4) print "IT WAS YOUR ARCH-NEMESIS, KUTA RAJA!" print" " #Delay and display storyline import time time.sleep(4) print "You get up and ask Kuta Raja what he is doing here." print" " #Delay and display storyline import time time.sleep(4) print "Kuta Raja: I'm finishing you right here and now! ARGHH!" print" " #Delay and display storyline import time time.sleep(2) print "BOOM!" print" " #Delay and display storyline import time time.sleep(2) print name + ", a bullet goes through your head and pierces your skull!" print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question5==3): #if user selects option 3, display storyline print" " print name + ", you and " + girl + " decide to go onto the right pathway." print" " #Delay and display storyline import time time.sleep(4) print "After going over the hill, you notice " + priest + " standing at the bottom of the hill." print " " #Delay and display storyline import time time.sleep(4) print name + ", he comes up to you and gives you one of three things:" print " " import time time.sleep(4) #RANDOM EVENT NUMBER 3 #Random generator determines user's outcome #Display options print"1. A suit of armor" print"2. A Mersa Berry" print"3. A guide dog" #Asks user question, uses try and except to safeguard the program from crashing from random import randint random3 = randint (1,4) if (random3==1): #If random option 1 is selected , delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that you will receive a suit of armor! " print" " #Delay and display storyline import time time.sleep(2) print" " print"(Gains 50 health)" health= health+50 #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" print"" #Delay and display storyline import time time.sleep(2) print name + ",in addition, " + priest + " gives you the next clue!" print" " #Delay and display storyline import time time.sleep(2) totalPoints=int(totalPoints) totalPoints=totalPoints+3 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " #Delay and display storyline import time time.sleep(3) print "You thank " + priest + " for his help and continue your journey." print" " break if (random3==2): #If random option 2 is selected , delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that you will receive a Mersa Berry! " print" " #Delay and display storyline import time time.sleep(2) print name + ", however, " + priest + " accidentally gives you the wrong berry as you get really sick!" print" " print"(Loses 10 health)" health= health-10 #display health print"------------------------------------------------------------------------------------" print"You have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Delay and display storyline import time time.sleep(2) print priest + " apologizes for giving you the wrong berry and hands you the next clue!" print" " #Delay and display storyline import time time.sleep(2) print name + ", you forgive him and thank him for the clue as you continue your journey." print" " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (random3==3): #If random option 3 is selected , delay and display storyline import time time.sleep(4) print"The Pirate Gods are determining the outcome..." print" " #Delay and display storyline import time time.sleep(4) print"The Pirate Gods decided that " + priest + " gives you a guide dog!" print" " #new variable created for user to enter name for dog dog=raw_input("Enter the name of the dog") #Delay and display storyline import time time.sleep(2) print name + ", you ask " + priest + " why you received a dog." print" " #Delay and display storyline import time time.sleep(2) print priest + " tells you that a dog is a man's best friend and hands you the next clue." print" " #Delay and display storyline import time time.sleep(2) print "Afterwards, " + priest + " disappears into thin air!" print" " totalPoints=int(totalPoints) totalPoints=totalPoints+1 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break while x==1: #Delay and display storyline import time time.sleep(4) print name + ", after exiting the Picanugan Forest, you head to Pirate Cove." print" " #Delay and display storyline import time time.sleep(4) print "Once you arrive at Pirate Cove, you encounter a group of Pirates!" print" " #Delay and display storyline import time time.sleep(4) print "When the pirates try to attack you, you hear something that is very familar." print" " #Delay and display storyline import time time.sleep(4) print "STOP!" print" " #Delay and display storyline import time time.sleep(4) print "The pirates stop their attack and you see your arch-nemesis Kuta Raja at the top of the cove!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you then have a long conversation with Kuta Raja..." print" " #Delay and display storyline #Dialogue between you and Kuta Raja import time time.sleep(3) print "Kuta Raja: Well, well, well. What do we have here?" #Delay and display storyline import time time.sleep(3) print name + ": You bastard! Why are you here!" #Delay and display storyline import time time.sleep(3) print "Kuta Raja: Bro, such harsh words." #Delay and display storyline import time time.sleep(3) print name + ": Stop calling me bro!" #Delay and display storyline import time time.sleep(3) print "Kuta Raja: Ok bro." #based on the random option user got in random event #3, user will get a different storyline unique to that option if (random3==1 or random3==2): #Delay and display storyline import time time.sleep(3) print "While you are talking, you notice " + girl + " sneak in Pirate Cove." print" " break if (random3==3): #Delay and display storyline import time time.sleep(3) print "While you are talking, you notice " + girl + " and " + dog + " sneak in Pirate Cove." print" " break while x==1: #Delay and display storyline import time time.sleep(3) print name + ", you then continue your conversation with Kuta Raja..." print" " #Delay and display storyline import time time.sleep(3) print name + ": What the heck man!" #Delay and display storyline import time time.sleep(3) print "Kuta Raja: I'm only here for one reason...and you know why!" #Delay and display storyline import time time.sleep(3) print name + ": Huh, what." #Delay and display storyline import time time.sleep(3) print "Kuta Raja: Ugh, I came here to finish you off once in for all!" #Delay and display storyline import time time.sleep(3) print name + ": But why did you transport me here." #Delay and display storyline import time time.sleep(3) print "Kuta Raja: I want to kill you here so that I will be known as the creator of the time machine in 2100!" #Delay and display storyline import time time.sleep(3) print name + ": Shut up! Tell me how I can get out of here!" #Delay and display storyline import time time.sleep(3) print "Kuta Raja: There's only one way how you can get out of here, but I have it in my hand right now!" #Delay and display storyline import time time.sleep(3) print "(Shows golden key to " + name + ")" #Delay and display storyline import time time.sleep(3) print name + ": Give it to me!" #Delay and display storyline import time time.sleep(3) print "Kuta Raja: Are you ok? You took my idea of creating the time machine and now I will annihilate you with my pirate army!" #Delay and display storyline import time time.sleep(3) print name + ", after the conversation..." print" " #Delay and display storyline import time time.sleep(3) print "You realize that this is your only chance to get back to the year 2100." print" " #Delay and display storyline import time time.sleep(3) print "However, you are very nervous as you could lose your life right now." print" " #Delay and display storyline import time time.sleep(3) #SIXTH PART (ASKING USER TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Run away" print"2. Use your brains to find a strategic way to get the key" print"3. Fight the pirates head on" #Asks user question, uses try and except to safeguard the program from crashing question6=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question6 = int(question6) if question6 >=1 and question6 <=3: break else: print "Invalid input!" question6=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question6=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question6==1): #if user selects option 1, display storyline print"" print name + ", you decide to run away from Pirate Cove!" print"" #Delay and display storyline import time time.sleep(4) print "Kuta Raja: HA HA HA! SUCH A COWARD!" print" " #Delay and display storyline import time time.sleep(4) print "Kuta Raja then fires a bullet at you!" print" " #Delay and display storyline import time time.sleep(2) print name + ", the bullet goes through your head and pierces your skull" print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question6==2): #if option 2 is selected, display storyline print"" print name + ", you decide to use your brains to find a strategic way to get the key." print"" #Delay and display storyline import time time.sleep(4) print "However, it's literally impossible for you to get the key as Kuta Raja is at the top of the cove!" print" " #Delay and display storyline import time time.sleep(4) print name + ", while you are thinking, the pirates charge and trample you with ease!" print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD!" print" " #health variable is set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" if (question6==3): #if option 3 is selected, display storyline print"" print name + ", you decide to fight the pirates head on!" print"" #Delay and display storyline import time time.sleep(4) print "You pull out a sword and a gun that you stole from Banterville and injure each pirate member one by one." print" " #Delay and display storyline import time time.sleep(4) print "Finally, all that is remaining is you and Kuta Raja!" print" " import time time.sleep(4) print "Kuta Raja: How in the world did you do that!" import time time.sleep(4) print name + ": Shut up coward! Let's fight!" #Delay and display storyline import time time.sleep(4) print "You and Kuta Raja fight for a very long time..." print" " #Delay and display storyline import time time.sleep(3) print "Suddenly, you are on the ground and Kuta Raja is about to shoot his gun towards you!" print" " import time time.sleep(3) print "Kuta Raja: THIS IS THE END OF YOU! ARGHHH!" #Delay and display storyline import time time.sleep(4) print name + ", you close your eyes knowing that fact that you are going to die..." print" " #Delay and display storyline import time time.sleep(4) print "The trigger is pulled!" print" " #Delay and display storyline import time time.sleep(4) print "CRACK! BOOM!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you think you are dead, but once you open your eyes, you see Kuta Raja wailing on the ground holding his arm." print" " #Delay and display storyline import time time.sleep(4) print "You are shocked by the outcome, but you notice your accomplices and a big bulky man at the front of Pirate Cove." print" " import time time.sleep(4) print "Captain Cook: HA HA HA. It's about time I got revenge!" #Delay and display storyline import time time.sleep(3) print name + ", you take the golden key from Kuta Raja's pocket and kill him afterwards using your gun!" print" " totalPoints=int(totalPoints) totalPoints=totalPoints+2 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break while x==1: #based on the random option user got in random event #3, user will get a different storyline unique to that option if (random3==1 or random3==2): #Delay and display storyline import time time.sleep(4) print "Captain Cook comes towards you and introduces himself as the leader of the pirates." print" " #Delay and display storyline import time time.sleep(4) print "He tells you that Kuta Raja caged him inside Pirate Cove, but thanks to " + girl + ", he was able to be set free!" print" " #Delay and display storyline import time time.sleep(4) print "Captain Cook then transports both of you back to Cooksville due to your heroic efforts..." print" " totalPoints=int(totalPoints) totalPoints=totalPoints+5 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " #Delay and display storyline import time time.sleep(4) print name + ", once you get back to Cooksville, you thank " + girl + " for her services as you hug her tightly." print" " #Delay and display storyline import time time.sleep(4) print "Afterwards, " + girl + " goes into " + priest + "'s home and once " + priest + " comes out of his home, you also thank him for his help." print" " break if (random3==3): #Delay and display storyline import time time.sleep(4) print "Captain Cook comes towards you and introduces himself as the leader of the pirates." print" " #Delay and display storyline import time time.sleep(4) print "He tells you that Kuta Raja caged him inside Pirate Cove, but thanks to " + girl + " and " + dog + ", he was able to be set free!" print" " #Delay and display storyline import time time.sleep(4) print "Captain Cook then transports all of you back to Cooksville due to your heroic efforts..." print" " totalPoints=int(totalPoints) totalPoints=totalPoints+5 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " #Delay and display storyline import time time.sleep(4) print name + ", once you get back to Cooksville, you thank " + girl + " and " + dog + " for their services as you hug them tightly." print" " #Delay and display storyline import time time.sleep(4) print "Afterwards, " + girl + " and " + dog + " both go into " + priest + "'s home and once " + priest + " comes out of his home, you thank him for his help." print" " break while x==1: #Delay and display storyline import time time.sleep(3) print "However, for some reason, the atmosphere starts to get really hot and you notice a meteor heading towards Cooksville." print" " import time time.sleep(3) #SEVENTH PART (ASKING USERS TO SELECT AN OPTION) #Display options print name + ", what do you want to do?" print" " print"1. Head inside the time machine" print"2. Face the meteor head on" print"3. Create a plan to stop the meteor" #Asks user question, uses try and except to safeguard the program from crashing question7=raw_input("Enter which option you would like to pick(1, 2, or 3)") while x==1: try : question7 = int(question7) if question7 >=1 and question7 <=3: break else: print "Invalid input!" question7=raw_input("Enter which option you would like to pick(1, 2, or 3)") except: print "Invalid input!" question7=raw_input("Enter which option you would like to pick(1, 2, or 3)") if (question7==1): #if option 1 is selected, display storyline print"" print name + ", you decide to head inside the time machine because you don't want to die." print"" #Delay and display storyline import time time.sleep(4) print name + ", you then go ahead 421 years to return to the present..." print" " #user returns to original location print "Location: Jeevan Industries " print "Year: 2100" totalPoints=int(totalPoints) totalPoints=totalPoints+2 #Displays points print"-----------------------------------------------------------------------------------------" print"You have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (question7==2): #if option 2 is selected, display storyline print "" print name + ", you decide to face the meteor head on!" print "" #Delay and display storyline import time time.sleep(4) print name + ", you then levitate in the sky and suddenly, you are able to redirect the meteor away from Cooksville!" print" " totalPoints=int(totalPoints) totalPoints=totalPoints+5 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " #Delay and display storyline import time time.sleep(4) print priest + ": THE CHOSEN ONE HAS SAVED US! PRAISE " + name + "!" print" " #Delay and display storyline import time time.sleep(4) print name + ": How did I do that just now!" print" " #Delay and display storyline import time time.sleep(4) print priest + ": You are the chosen one!" print" " #Delay and display storyline import time time.sleep(4) print name + " Um, thank you! I appreciate the opportunity to experience this, but now I must return home!" print" " #Delay and display storyline import time time.sleep(4) print priest + ": Bye! Come again soon THE CHOSEN ONE!" print" " #Delay and display storyline import time time.sleep(4) print name + ", you then go inside the time machine and go ahead 421 years to return to the present..." print" " #user returns to original location print "Location: Jeevan Industries " print "Year: 2100" totalPoints=int(totalPoints) totalPoints=totalPoints+2 #Displays points print"-----------------------------------------------------------------------------------------" print name + ", you have "+str(totalPoints)+" point(s) right now" print"-----------------------------------------------------------------------------------------" print" " break if (question7==3): #if option 3 is selected, display storyline print"" print name + ", you decide to make a plan to stop the meteor." print"" #Delay and display storyline import time time.sleep(3) print "However, it's too late as the meteor hits Cooksville within seconds!" print" " #Delay and display storyline import time time.sleep(2) #user is dead print name.upper() + ", YOU ARE DEAD" print" " #health variable set to 0 health=0 time.sleep(2) #display health print"------------------------------------------------------------------------------------" print name + ", you have "+ str(health)+" health right now" print"------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print"Game Over" print str(name)+" ,you ended with "+str(health)+" health" +" and with "+str(totalPoints)+" points" print"Make better decisions next time!" x=0 #game is done else: print "Invalid Input" endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") while x==1: #delay and display conclusion of game import time time.sleep(4) print" CONGRATULATIONS, " + name + "! YOU HAVE FINISHED THE GAME! WOO HOO!" print" " time.sleep(4) #display total health and points print"--------------------------------------------------------------------------------------" print"You ended the game with "+ str(health)+" health and with " + str(totalPoints)+ " points!" #based on how many points user received in the game, the user will receive a unique message if totalPoints >=18: print name.upper() + ", YOU ARE A MIGHTY PIRATE! ARGHHHH!" elif totalPoints >=12 and totalPoints <=17: print name.upper() + ", YOU ARE A SHIP COOK! ARGHHHH!" else: print name.upper() + ", YOU ARE A PEASANT WATER BOY! ARGHHH!" print"--------------------------------------------------------------------------------------" #Asks the user if they want to restart the game or end the game while x==1: endGameOption=raw_input("Enter R to restart the game or Enter E to Exit the game") if (endGameOption=="R" or endGameOption=="r"): print"You have restarted the game" print" " print"-------------------------------------------------------------------------------" break elif(endGameOption=="E" or endGameOption=="e"): print "Thanks for playing!" print "See you soon!" x=0 #game is done else: print "Invalid Input"
ee435a89a5d765f50f4b2b9e40bdb2d4fc64bff8
vijayvardhan94/pychilis
/pyprac/1.py
474
4.3125
4
#Create a program that asks the user to enter their name and their age. #Print out a message addressed to them that tells them the year that they will turn 100 years old. UserName = str(input("Enter your Name:")) UserAge = int(input("Enter your age:")) AgeToHundred = 100 - UserAge CurrentYear = 2018 YearOfHundred = CurrentYear + AgeToHundred print(AgeToHundred,"years for you to reach age 100") print(YearOfHundred, "is the year in which you will turn 100 years old")
3c49cd8556b168585313028e00b338b2d32a98ad
rbassett3/ProverbGenerator
/Generator1.py
1,292
4.09375
4
import random class Proverb: """A proverb generator, which takes a text corpus W at initialization. W is an array of words with '!' as a starting token and '.' as an end token. Generate a proverb with Proverb.Generate(). This method is a Markov chain model. The state is the current word. To proceed to the next state (word), we sample from all of the possible words which occur after the current word in the corpus. Example: P = Proverb(Words) P.Generate() >>> "A fish is always greener on the boat" """ def __init__(self, Words): self.Words = Words def Generate(self): flag = True generated = "" curWord = '!' while flag: PossibleWords = [self.Words[i+1] for i in range(len(self.Words)) if self.Words[i] == curWord] curWord = random.sample(PossibleWords, 1)[0] if curWord == ".": flag = False else: generated += " " + curWord print(generated) if __name__=='__main__': with open("ProverbList.txt", 'r') as f: Lines = f.readlines() Words = [] list(map(Words.extend, [("! " + line[:-1] + " . \n").split() for line in Lines if line != "\n"])) P = Proverb(Words) P.Generate()
85511ab633cd67594edf5836211906ef3ca363fd
madeibao/PythonAlgorithm
/PartB/Py华为的重复的字符串来进行排序.py
454
3.59375
4
# 重复字符排序 # 题目描述:找出输入字符串中的重复字符,再根据ASCII码把重复的字符从小到大排序。 # 例如:输入ABCABCdd,输出ABCd。 # 找出字符串中的重复的字符,来进行排序 from collections import Counter str2 = input() dict2 = dict(Counter(str2)) res = [] for i in list(str2): if dict2.get(i)>1: res.append(i) else: continue res.sort() print("".join(res))
4c69c1b9be3ae7d23d4601a5e7501c6905fca722
NataliaDiaz/BrainGym
/detect-feature-kernel.py
2,387
4.03125
4
""" # Feature detection in a image with: - a convolution kernel, - a threshold and - image as input. The convolution kernel is a square K x K real matrix denoted by k(i,j), the threshold is a real number, and the image is given as an RxC real matrix with elements between 0 and 1, with the pixel in row r and column c given by p(r,c) where r in [0,R) and c in [0,C). We say theat there is a feature at position (r,c) if SUM (k(i,j) p(r+i, c+j)) > T However, the kernel is only valid if it is not overflowing the image, therefore, if the kernel is overflowing the image, we do not want to detect a feature. Input: 2 0.65 3 4 # K, T, R and C where all are integers except T which is a real number -1.0 1.0 # kernel values (KxK) 1.0 0.0 0.0 0.1 0.2 0.3 # image values (RxC) 0.4 0.5 0.6 0.7 0.8 0.9 0.0 0.1 Output: 0 2 # the positions of the detected features (r, c), one per line 1 0 1 1 """ def detect_features_with_convolution_kernel_and_threshold():#kernel, T, R, C): K,T,R,C = str(raw_input()).strip().split() K = int(K) T = float(T) R = int(R) C = int(C) #print "K,T,R,C : ",K,T,R,C kernel = [] # read kernel for kernel_row in range(K): kernel_row = [] for value in (raw_input()).split():#strip().split() kernel_row.append(float(value)) kernel.append(kernel_row) #print "Kernel: \n",kernel # read image img = [] for image_row in range(R): image_row = [] for value in (raw_input()).split():#strip().split() image_row.append(float(value)) img.append(image_row) #print "Image: \n",img features = [] for r in range(R): for c in range(C): #while kernel_start_r < (R-K) and kernel_start_c < (C-K): if feature_is_present_in_pos(kernel, img, r, c, K, T, R, C): features.append((r, c)) print_features(features) def feature_is_present_in_pos(kernel, img, r, c, K, T, R, C): suma = 0 if not kernel_overflows_img(r, c, K, R, C): for i in range(K): for j in range(K): partial_sum = kernel[i][j] * img[r+i][c+j] suma += partial_sum if suma > T: #print "feature_is_present in (r,c): ", r,c return True return False def kernel_overflows_img(r, c, K, R, C): if (r+K) > R or (c+K)> C: return True return False def print_features(features): for (r,c) in features: print r, " ", c detect_features_with_convolution_kernel_and_threshold()
28345162d98c78903cf20acb459ccc1a87d210ed
pisfer/cin-in-python
/__init__.py
1,060
3.59375
4
import re class ArgumentError(Exception): def __init__(self, message): super().__init__(message) class cin: """cin func in python""" def __init__(self, *args, text): self.args = args self.n = text self.pora = "(?P<" + self.args[0] + ">[\w\d\S]*)" self.index = "" self.vbn = {} for self.g in self.args[1:]: self.pora = self.pora + "\s+(?P<" + self.g + ">[\w\d\S]*)" self.i = input(self.n) self.hpo = re.match(self.pora, self.i) if self.hpo: for self.k in self.args: self.vbn[self.k] = self.hpo.group(self.k) else: raise ArgumentError("You inserted false arguments") def get(self, index): self.index = index return self.vbn[self.index] if __name__ == '__main__': cin_python = cin("first1", "second2", text = "input two or more words like 'hello everyone' - ") print("first word - " + cin_python.get("first1")) print("second word - " + cin_python.get("second2"))
e649a77bc83700744f29a5d53bbd1d31c8036940
tx991020/MyLeetcode
/数组/两数之和.py
668
3.796875
4
''' 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] ''' class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ d = {} for i, num in enumerate(nums): if target - num in d: return [d[target - num], i] d[num] = i
93321b44a8996bd2e2432532e905753ec918db06
AlokRanjanBhoi/HackerRank_Python_Solutions
/1. Introduction/Loops.py
239
3.546875
4
''' Title : Loops Subdomain : Introduction Domain : Python3 Author : Alok Ranjan Bhoi Created : 14 January 2019 ''' # Enter your code here. Read input from STDIN. Print output to STDOUT a=int(input()) for i in range(0,a): print(i*i)
9755b0787b01481be6b76bb1c8d0eb8e14cc1dd7
hengzeforever/165A-M1
/template/page.py
2,438
3.671875
4
from template.config import * '''The Page class provides low-level physical storage capabilities. In the provided skeleton, each page has a fixed size of 4096KB. This should provide optimal performance when persisting to disk as most hard drives have blocks of the same size. You can experiment with different sizes. This class is mostly used internally by the Table class to store and retrieve records. While working with this class keep in mind that tail and base pages should be identical from the hardware’s point of view. If your table has 3 columns, you would have a set of base pages containing 3 pages, 1 for each column. Each column has a physical page, and a base page is a set of such physical pages each column could have multiple page objects Within the same page range ''' class Page: def __init__(self): self.num_records = 0 self.data = bytearray(PAGE_SIZE) # Creates an array of that size and initialized with 0 def has_capacity(self): if self.num_records < MAX_NUM_RECORD: return True else: return False def write(self, value): start = self.num_records * INT_SIZE end = (self.num_records + 1) * INT_SIZE if value != None: self.data[start:end] = value.to_bytes(INT_SIZE,'big') self.num_records += 1 def len(self): return self.num_records class BasePage: def __init__(self, num_columns): self.colPages = [] self.num_columns = num_columns for i in range(INTERNAL_COL_NUM + self.num_columns): self.colPages.append(Page()) def has_capacity(self): return self.colPages[0].has_capacity() class PageRange: def __init__(self, num_columns): self.num_columns = num_columns self.basePageList = [BasePage(self.num_columns)] self.tailPageList = [BasePage(self.num_columns)] # Tail page is essentially the same as base page def has_capacity(self): return len(self.basePageList) < BASE_PAGE_PER_PAGE_RANGE | self.basePageList[-1].has_capacity() def create_NewBasePage(self): self.basePageList.append(BasePage(self.num_columns)) return True def create_NewTailPage(self): self.tailPageList.append(BasePage(self.num_columns)) return True
d092c8e959e361606e94b6048da90981316d2ca5
LearningSteps/Learn-Python-The-Hard-Way-Test-Driven-Learning
/LearnPythonTheHardWay/ex31.py
765
4
4
#Making Decisions print("Door 1 or 2?") door = input("> ") if door == "1": print("There's a bear and a cake.") print("What do you do?") print("1. the cake") print("2. The bear") bear = input("> ") if bear == "1": print("You died. GG") elif bear == "2": print("The bear eats your legs off. GG") else: print(f"Well, doing {bear} is probably better.") print("Bears run away.") elif door == "2": print("You stare into an eyeball") print("meh1") print("blue2") print("meh3") insanity = input("> ") if insanity == "1" or insanity == "2": print("Jello!") print("gg!") else: print("You died.") print("gg!") else: print("Yeeeeepeeeedoooo!")
54d6f4765a2e50bcebaf22245653527c4b5452e2
Max143/Python_programs
/reversing the number.py
438
4.15625
4
# write python to reverse a given number # using loop # using recursion # using function # 1. By using loop method number = int(input("Enter number: ")) Reverse = 0 while (number > 0): Remainder = number % 10 Reverse = (Reverse*10) + Remainder number = number // 10 print("In reverse of entered no. is %d ", Reverse) ,,,,, ,,,, ,, ,,,,
2887d929b4540fd38a89398292571c1d91d5af42
macio-matheus/algorithms-and-data-structure-practices
/leetcode_merged_k_sorted_lists.py
1,612
4.28125
4
""" Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input:[1->4->5, 1->3->4, 2->6] Output: 1->1->2->3->4->4->5->6 Approach 1: Brute Force Intuition & Algorithm Traverse all the linked lists and collect the values of the nodes into an array. Sort and iterate over this array to get the proper value of nodes. Create a new sorted linked list and extend it with the new nodes. As for sorting, you can refer here for more about sorting algorithms. Complexity Analysis Time complexity : O(N log N)O(NlogN) where NN is the total number of nodes. Collecting all the values costs O(N)O(N) time. A stable sorting algorithm costs O(N log N)O(NlogN) time. Iterating for creating the linked list costs O(N)O(N) time. Space complexity : O(N)O(N). Sorting cost O(N)O(N) space (depends on the algorithm you choose). Creating a new linked list costs O(N)O(N) space. """ import heapq class ListNode: """ Definition for singly-linked list. """ def __init__(self, x): self.val = x self.next = None class Solution: def merge_klists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ h = [(l.val, idx) for idx, l in enumerate(lists) if l] heapq.heapify(h) head = cur = ListNode(None) while h: val, idx = heapq.heappop(h) cur.next = ListNode(val) cur = cur.next node = lists[idx] = lists[idx].next if node: heapq.heappush(h, (node.val, idx)) return head.next
bbf411463736a030a68272e3687a63fbbf3ac7b9
Alarical/Interview
/LintCode/lint_solution/664CountingBits.py
390
3.546875
4
class Solution: """ @param num: a non negative integer number @return: an array represent the number of 1's in their binary """ def countBits(self, num): # write your code here if num == 0 : return [0] dp = [0 for i in range(num+1)] for i in range(1,num+1): dp[i] = dp[i >> 1] + (i & 1) return dp
4bddf8bed9c0dd249fbb03be82a5a8349a3e3dd7
OlgaShevtsova1/Python
/HW_2_5.py
297
4.03125
4
# Задача 5 Reiting= [7,5,3,3,2] #начало print() print("Рейтинг:",Reiting) r=-1 while r!=0: r=int(input("Введите целое число от 0 до 10")) Reiting.append(r) Reiting.sort () Reiting.reverse() print("Рейтинг: ",Reiting) print()
640dcff5d587eb8b14ef5bb3b12774b8d2bc5366
iftitutul/Using-Python-to-Interact-with-the-Operating-System
/Week-3/3.3.10-regex-sub.py
222
3.609375
4
#!/usr/bin/env python3.6 import re result = re.sub(r"[\w.%+-]+@[\w.-]+", "[REDACTED]", "Received an email for go_nuts95@my.example.com") print(result) result = re.sub(r"^([\w .-]*), ([\w .-]*)$", r"\2 \1", "lovelace, Ada") print(result)
6cdc57e90461a3140aa31d9beb4b5d7669c59f18
ideven85/Machine_Learning_Algorithms
/Algorithms/HundredDaysOfCode/GraphProblems.py
6,321
3.8125
4
from collections import deque from functools import lru_cache from typing import List class Node: def __init__(self, name): self.children = [] self.name = name def addChild(self, name): self.children.append(Node(name)) return self def depthFirstSearch(self, array): # Write your code here. array.append(self.name) for child in self.children: child.depthFirstSearch(array=array) return array def breadthFirstSearch(self, array): # Write your code here. pass class Graph: adj = [] def addEdge(self, u, v, isDirected): self.adj[u].append(v) if not isDirected: self.adj[v].append(u) def dfsUtil(self, source, destination, count): if source == destination: return count else: for u in self.adj[source]: count += 1 self.dfsUtil(u, destination=destination, count=count) return count def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: W = len(edges) a = [1] for _ in range(n): self.adj.append([]) count = 0 for i in range(n): self.addEdge(edges[i][0], edges[i][1], True) count = self.dfsUtil(source, destination, count) return count == 0 def allPathsSourceTarget( graph: List[List[int]]) -> List[List[int]]: target = len(graph) - 1 results = [] def backtrack(currNode, path): # if we reach the target, no need to explore further. if currNode == target: results.append(list(path)) return # explore the neighbor nodes one after another. for nextNode in graph[currNode]: path.append(nextNode) backtrack(nextNode, path) path.pop() # kick of the backtracking, starting from the source node (0). path = deque([0]) backtrack(0, path) return results """ For DP Solution nextNode∈neighbors(currNode),allPathsToTarget(currNode)={currNode+allPathsToTarget(nextNode)} """ def allPathsSourceTargetV2( graph: List[List[int]]) -> List[List[int]]: target = len(graph) - 1 # apply the memoization @lru_cache(maxsize=None) def allPathsToTarget(currNode): if currNode == target: return [[target]] results = [] for nextNode in graph[currNode]: for path in allPathsToTarget(nextNode): results.append([currNode] + path) return results return allPathsToTarget(0) def dfsUtil(array,source,visited): visited[source]=True i = 0 target = 0 while i!=source: print(visited) target+=array[i] visited[i]=True i+=1 print() return False def hasSingleCycle(array): jumps = 0 position = 0 while True: position += array[position] position %= len(array) print(position,end=' ') jumps += 1 if position == 0 or array[position] == 0 or jumps > len(array): break print() return jumps == len(array) def hasSingleCycleV2(array): # Write your code here. visited = [False for _ in range(len(array))] n = len(array) for i in range(n): visited = [False for _ in range(len(array))] if not dfsUtil(array,i,visited): return False return True def hasSingleCycleV4(array): n = len(array) jumps = 0 current_position=0 while True: current_position+=array[current_position] current_position=current_position%n jumps+=1 if current_position == 0 or array[current_position] == 0 or jumps > len(array): break return jumps == n def hasSingleCycleV5(array): correct_cycles = 0 jumps = 0 n = len(array) for i in range(n): vertex = i jumps=0 for j in range(n): jumps+= array[j] jumps = jumps % n if jumps == i: print(jumps) correct_cycles+=1 break print(correct_cycles) return correct_cycles == n-1 def maximumScore(nums: List[int], multipliers: List[int]) -> int: pointer1 = 0 n = len(nums) pointer2 = len(nums)-1 m = len(multipliers) dp = [[0]*(m+1) for _ in range(m+1)] for i in range(m-1,-1,-1): for left in range(i,-1,-1): mult = multipliers[i] right = n-1-(i-left) dp[i][left]=max(mult*nums[left]+dp[i+1][left+1],mult*nums[right]+dp[i+1][left]) print(dp) return dp[0][0] #!/bin/python3 # # Complete the 'maximumSum' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts following parameters: # 1. LONG_INTEGER_ARRAY a # 2. LONG_INTEGER m # def maximumSum(a, m): max_so_far=0;total=0 current = 0;left=0 for i in range(len(a)): if a[i]%m==m-1: return m-1 if max_so_far==m-1: return max_so_far max_so_far+=a[i] if total<=max_so_far: total=max_so_far if total%m==m-1: print("Foo",total) return m-1 if max_so_far>m: left = i while max_so_far>m and left>=0: max_so_far-=a[left] left-=1 print(left) i=left print("Max",max_so_far,end=' ') print(total) return total%m def maximumScoreV2( nums: List[int], multipliers: List[int]) -> int: # lru_cache from functools automatically memoizes the function @lru_cache(2000) def dp(i, left): # Base case if i == m: return 0 mult = multipliers[i] right = n - 1 - (i - left) # Recurrence relation return max(mult * nums[left] + dp(i + 1, left + 1), mult * nums[right] + dp(i + 1, left)) n, m = len(nums), len(multipliers) return dp(0, 0) if __name__ == '__main__': a = [2,3,1,-4,-4,2] print(hasSingleCycleV5(a)) nums1 = [1,2,3] multipliers = [3,2,1] print(maximumScore(nums1,multipliers)) a = [1,5,3,22,30,2,5] print(maximumSum(a,2))
5f3a299afd1f42c9c50551178812a5ca3cc49152
MohamedAwad9k8/Travian-Manager
/Functions.py
1,045
3.859375
4
def read_from_file(file_name, task_list): try: input_file = open("text_files\\" + file_name + ".txt", "r") except: print(file_name + ".txt couldn't be found, please make sure it exists in text_files directorty") else: for line in input_file: task_list.append(line.strip()) #print("read line successfully") input_file.close() def write_to_file(file_name, task_list): try: output_file = open("text_files\\" + file_name + ".txt", "w") except: print(file_name + ".txt couldn't be found, please make sure it exists in text_files directorty") else: for task in task_list: print(task, file = output_file) #print("wrote line successfully") output_file.close() def add_to_list(task ,task_list): task_list.append(task) print("added task successfully") def remove_from_list(task, task_list): if task in task_list: task_list.remove(task) print("removed task successfully")
c4a40d13b36babfd2f986215d5f2791c5b8ecdf5
alexbaltman/ctci
/ch8-RecursionDynamicProgramming/questions/paintfill.py
489
3.84375
4
''' Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color. Hints: 364, 382 ''' def paintfill(s): pass if __name__ == '__main__': assert paintfill('') == assert paintfill('') == assert paintfill('') == assert paintfill('') == assert paintfill('') ==