blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
efc585c7a65c638ad40e2b2999a08b5514a67daf
ramostitoyostin-unprg/t6_ramos_tito_yostin
/ramos/condicionales_multiples/ejercicio5.py
982
3.890625
4
import os # INPUT velocidad_01=int(os.sys.argv[1]) velocidad_02=int(os.sys.argv[2]) distancia=int(os.sys.argv[3]) # PROCESSING Tiempo_de_encuentro=(distancia)/(velocidad_01+velocidad_02) # VERIFICADOR validar_tiempo_encuentro=(Tiempo_de_encuentro==20) # OUTPUT print("##################################") print(("# BOLETA DE FISICA ")) print("##################################") print("#") print("# velocidad 01: ",velocidad_01," ") print("# velocidad 02: ",velocidad_02," ") print("# distancia: ",distancia," ") print("# Tiempo de encuentro: ",Tiempo_de_encuentro," ") print("###########################################") # CONDICIONAL MULTIPLES # comprobando el tiempo de encuentro si es mayor a 500 if (validar_tiempo_encuentro==True): print(" el tiempo es aceptable") if (validar_tiempo_encuentro>=20 and validar_tiempo_encuentro<=50): print(" el tiempo no es aceptable") if (validar_tiempo_encuentro==False): print(" no llega a tiempo ") # fin_if
b62d7087b6c3d7f4b1a02b16262078bf988c869f
VundaRoy/NumpySamples
/collection/integerArray.py
158
3.53125
4
import numpy as np a=np.array([[1,2],[3,4],[5,6]]) print(a[[2,1,0],[0,1,1]]) print(np.array([a[0,0],a[1,1],a[2,0]])) print(a[[0,0],[1,0]]) print(a[[0,0]])
840cd2c3ba164285f7db9f867a44f7eb08cb3bd2
RishabhK88/PythonPrograms
/2. PrimitiveTypes/Numbers.py
570
4
4
x = 1 y = 1.1 z = 1 + 2j # x is integer, y is float, z is complex numbers where j reperesens iota(i) in math print(10 + 3) print(10 - 3) print(10 / 3) print(10 * 3) print(10 ** 3) # ** is used for exponent i.e. first number raised to the power second number print(10 // 3) # // is used to get an integer part from the evaluation print(10 % 3) # % is used to give remainder when the 2 operators are divided x += 3 # is same as x = x + 3, it is called augmented operator.... it can be used with # any of the above operators like x -=3 or x *= 3 and so on
0bf0853ed0581af801a76606bcac407e4c45feb9
testcg/python
/code_all/day03/demo02.py
637
3.953125
4
""" 字面值:各种写法 数据类型 int float str 10 1.2 "随便" """ # 1. int 字面值 # 十进制DEC:每位用十种状态计数,逢十进一,写法是0~9。 number01 = 10 # 二进制BIN:每位用二种状态计数,逢二进一,写法是0~1。 number02 = 0b10 # 八进制OCT:每位用八种状态计数,逢八进一,写法是0~7。 number03 = 0o10 # 十六进制HEX:每位用十六种状态计数,逢十六进一,写法是0~9 a(10)~f(15)。 number04 = 0x10 # 2. float 字面值 # 小数 number05 = 0.00001 # 科学计数法 number06 = 1e-5 print(number05)
9cbdab3c56407211104dbdc7d92524e64451bf5c
lschanne/DailyCodingProblems
/year_2019/month_02/2019_02_17__missing_positive_integer.py
1,769
3.953125
4
''' February 17, 2019 Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. My first thought was to sort the array first, but that has time complexity of O(n log n), so that doesn't fit the spec. ''' def missingPositiveInteger_take1(inputs): ''' So this was my first go. It has a few issues: - Time complexity > O(n) - Doesn't work on something like [1, 2] or [3, 2, 1] There could be more issues. I stopped determining edge cases after the aforementioned [1, 2] issue was established. ''' result = 1 first = True for x in sorted(inputs, reverse=True): if x <= 1: if first: result = 2 break if result > x - 1 or first: first = False result = x - 1 return result def missingPositiveInteger_take2(inputs): ''' This is definitely better than take1, but the sorting makes the time complexity O(n log n) > O(n). At least it actually works though. ''' result = 1 for x in sorted(inputs): if x < 1: continue if x == result: result += 1 else: break return result def missingPositiveInteger(inputs): # TODO: grow more brain cells pass if __name__ == '__main__': import sys inputs = list(map(int, sys.argv[1:])) print('inputs: {}'.format(inputs)) print('output: {}'.format(missingPositiveInteger(inputs)))
89fe8b5760c7527c4964670791da12bbb030cb7b
acmachado14/ListasCCF110
/Lista07/16.py
421
3.65625
4
#16. Dado um conjunto de 100 valores numéricos disponíveis num meio de entrada qualquer, #fazer um algoritmo para armazená-los em um vetor B, e calcular e escrever o valor do somatório dado a seguir: # S = (b1 - b100)³ + (b2 - b99)³ + ... + (b50 - b51)³ A = [] for i in range(6): A.append(int(input(f"Informe o numero da posição A[{i}]: "))) S = 0 for i in range(6): S += ((A[i] - A[5-i])**3) print(S)
1e3cb8b971d8b8cc8b387bbdcb4b32f63d4aa02a
kaseyriver11/leetcode
/euler/01.py
101
3.65625
4
total = 0 for i in range(1000): if (i % 5 == 0) | (i % 3 == 0): total += i print(total)
e838e5f1798f8dabd5cdae9f5883d317c75d652a
NatnareeChong/WeAreJack
/main.py
2,912
4.15625
4
""" Advanture into the JACK land! You might have heard of the story Jack and the magic beans. Jack accidentally get a hold of the bean yesterday and planted them in his back garden. He watered them day after day not knowing its magical property. As time passes the tiny beans grow into a giant bean sprout. Now the adventure in the giant land await him. For Jack to win and survive, we MUST to help Jack retrieves as much treasures and items to fight against the giants. Hope you enjoy the game! Authors: Natnaree Chongsiriwattana, Ziying Wu, Chollada Panbutr, Pradchayaporn Nonthavanich License: AGPLv3 or later Usage: main.py """ from utils import say from stage1 import stage1 from stage2 import stage2 import json def main(): """Start the game.""" name = input("What should we call you?: ") say("Advanture into the JACK land!") say("You might have heard of the story Jack and the magic beans" "Jack accidentally get a hold of the bean yesterday and " " planted them in his back garden.") say("He watered them day after day not knowing its magical" "property. As time passes the tiny beans grow into a giant " "bean tree") say("Now the adventure in the giant land await him." "For Jack to win and survive,we MUST to help Jack retrieves" " as much treasures and items to fight against the giants.") say("There are 5 items that you might get for each round") items = ["healing", "sword", "spear", "dagger", "bowl"] print("- ", end="") print(*items) player = {} player["hp"] = 3 player["items"] = {} questions = loadquestion() stage1_result = stage1(player, questions) if not stage1_result: return question_left = 5 say("Congrats! You have passed 10 levels") say("You have to answer 5 questions to kill the giant!") weapons = [] for k, v in player["items"].items(): if k != "healing" and k not in weapons and v > 0: weapons.append(k) if len(weapons) == 4: say("Since you have all the weapons.", "You have to answer only two questions to kill the giant!") question_left = 2 if player["hp"] <= 0: say("Game over!! You ran out of live energy") quit() special_question = loadspecialquestion() stage2_result = stage2(player, special_question, question_left) if not stage2_result: say("You can't kill the giant!!! Now you can enjoy your wealth!" " Good Bye ~O.O~") return say("Congratulations!!!!! You won the game :D") def loadquestion(): questions = None with open("question.json", "r") as question: questions = json.load(question) return questions def loadspecialquestion(): questions = None with open("special_question.json", "r") as question: questions = json.load(question) return questions if __name__ == "__main__": main()
78e5ea5684f2209252792d6b317b246c68f20039
Jungeol/algorithm
/leetcode/medium/34_find_first_and_last_position_of_element_in_sorted_array/hsh2438.py
1,555
3.640625
4
""" https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ Runtime: 100 ms, faster than 50.70% of Python3 online submissions for Find First and Last Position of Element in Sorted Array. Memory Usage: 14 MB, less than 8.93% of Python3 online submissions for Find First and Last Position of Element in Sorted Array. """ class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: if nums == []: return [-1, -1] self.position = -1 def divide_and_conquer(start, end, target): if start >= end: if nums[start] == target: self.position = start return else: mid = int((end - start) / 2) + start if nums[mid] == target: self.position = mid return else: divide_and_conquer(start, mid - 1, target) divide_and_conquer(mid + 1, end, target) divide_and_conquer(0, len(nums) - 1, target) if self.position is -1: return [-1, -1] else: result = [self.position] left = self.position - 1 while left > -1 and nums[left] is target: result.insert(0, left) left -= 1 right = self.position + 1 while right < len(nums) and nums[right] is target: result.append(right) right += 1 return [result[0], result[-1]]
e88849862d53dccc578c51b8aae03cc0d34116e1
narrasubbarao/practise
/FileHandling/Database/Demo7.py
176
3.578125
4
import sqlite3 as sql conn = sql.connect("sathya.db") curs = conn.cursor() curs.execute("select * from student") res = curs.fetchall() for x in res: print(x[0],x[1],x[2])
56fd0da6efe1562c9808d7698dcf627f4453bea3
anthonyjatoba/codewars
/7 kyu/Sum of the first nth term of Series/Sum of the first nth term of Series.py
93
3.515625
4
def series_sum(n): res = sum(1/(1+3*d) for d in range(n)) return '{:.2f}'.format(res)
a1d2f1ccf92e37fd25fd07460403a69af641cb13
andrewgrow/pyRobomix
/robomix/entries/Day.py
508
3.59375
4
import json class Day(object): def __init__(self, day_name: str, schedule: list): self.schedule = schedule self.day_name = day_name def __str__(self): return '{'+'"name":' + '"' + self.day_name + '"' + ', "schedule":' + json.dumps(self.schedule)+'}' def get_json(self): return str(self) def make_json_from_list(jsons: list) -> str: result = '[' for json in jsons: result = result + json + "," result = result[:-1] return result + ']'
fe3a3e0d8c18ce36f2aa7220569a6bd15e8edb23
arisend/epam_python_autumn_2020
/lecture_04_test/hw/task_2_mock_input.py
847
3.875
4
""" Write a function that accepts an URL as input and count how many letters `i` are present in the HTML by this URL. Write a test that check that your function works. Test should use Mock instead of real network interactions. You can use urlopen* or any other network libraries. In case of any network error raise ValueError("Unreachable {url}). Definition of done: - function is created - function is properly formatted - function has positive and negative tests - test could be run without internet connection You will learn: - how to test using mocks - how to write complex mocks - how to raise an exception form mocks - do a simple network requests >>> count_dots_on_i("https://example.com/") 59 * https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen """ def count_dots_on_i(url: str) -> int: ...
de8d7594b65e4fc3ffa5f6d482e58e0c74331d5e
aidangomez/pysched
/multi_jobs_example.py
1,754
4
4
#!/usr/bin/python """ Author: Mengye Ren ([email protected]) Example of using job scheduler of multiple jobs. This is useful for a hyper-parameter search with limited resources, and each job maybe of different length, so scheduling is crucial to keep the maximum utility of the resources. Callbacks can be used to intialize new jobs whose input is dependent on the output of the previous programs (data dependency), for example in choosing the best hyperparameters. Usage: job_request = [JobRequest({cmd line exec for param}) for param in params] job_pool = pipeline.add_job_pool(job_request, callback=None) job_pool.wait() """ from __future__ import (absolute_import, division, print_function, unicode_literals) from job import JobRequest, JobScheduler, Pipeline from slurm import SlurmJobRunnerFactory from local import LocalJobRunnerFactory def init_pipeline(max_num_jobs, scheduler): if scheduler == "slurm": sched = JobScheduler( "scheduler", SlurmJobRunnerFactory(), max_num_jobs=max_num_jobs) elif scheduler == "local": sched = JobScheduler( "scheduler", LocalJobRunnerFactory(), max_num_jobs=max_num_jobs) p = Pipeline().add_stage(sched) p.start() return p def run_multi_jobs(pipeline, callback=None): param_list = range(1, 10) job_list = [] for param in param_list: # A dummy job is to sleep from 1 to 9 seconds job = pipeline.add_job(JobRequest(["sleep", str(param)], job_id=param)) job_list.append(job) return pipeline.add_job_pool(job_list, callback=callback) def main(): pipeline = init_pipeline(max_num_jobs=3, scheduler="local") run_multi_jobs(pipeline, callback=lambda results: pipeline.finalize()) pipeline.wait() if __name__ == "__main__": main()
f65b59f9b5814c50da6f0fd15f59ef4b7e9dec29
luiziulky/Controlstructures
/Exercise 13.py
254
4.09375
4
l = ['Sunday','Monday','tuesday','Wednesday','Thursday','Friday','Saturday'] print('DAYS OF THE WEEK') while True: num = int(input('Enter a number: ')) if 0 < num < 8: print(l[num-1]) break else: print('Invalid value')
0e16f3403d0fff57d4dee8126dd2ab9e7adfc594
austinv211/Artificial-Intelligence-Assignment-1
/search/problem2.py
2,570
3.78125
4
from typing import Dict, Generator, List, Tuple from itertools import islice from queue import PriorityQueue graph = { 'S': (set(['A', 'B', 'D'])), 'A': (set(['C'])), 'B': (set(['D'])), 'C': (set(['D', 'G'])), 'D': (set(['G'])), 'G': (set()) } weights = { ('S','A'):2, ('S','B'):3, ('S','D'):5, ('A','C'):4, ('B','D'):4, ('C','D'):1, ('C','G'):2, ('D','G'):5, } def bfs_paths(graph: Dict[str, set], start: str, goal: str)-> Generator: queue = [(start, [start])] while queue: (vertex, path) = queue.pop(0) for next in graph[vertex] - set(path): if next == goal: yield path + [next] #use the + operator to yield the extended list inline else: queue.append((next, path + [next])) def dfs_paths(graph: Dict[str, set], start: str, goal: str)-> Generator: """ generator that yields the possible paths when searching the graph using depth-first-search """ stack = [(start, [start])] #stack is a list of tuples representing the vertex and the current path while stack: (vertex, path) = stack.pop() for next in graph[vertex] - set(path): if next == goal: yield path + [next] #use the + operator to yield the extended list inline else: stack.append((next, path + [next])) def ucs_weight(from_node: str, to_node: str, weights: str): return weights.get((from_node, to_node)) def ucs(graph: Dict[str, set], start: str, end: str, weights: Dict[Tuple[str, str], int])->Generator: """ generator that yeilds the possible paths when searching the graph using uniform cost search """ frontier = PriorityQueue() frontier.put((0, start, [])) # (priority, node, path) explored = [] while not frontier.empty(): ucs_w, current_node, path = frontier.get() explored.append(current_node) if current_node == end: yield (path + [current_node],ucs_w) for node in graph[current_node]: if node not in explored: frontier.put(( ucs_w + ucs_weight(current_node, node, weights), node, path + [current_node] )) if __name__ == "__main__": dfs_result = list(islice(dfs_paths(graph, 'S', 'G'), len(graph.items()))) bfs_result = list(bfs_paths(graph, 'S', 'G')) test = list(ucs(graph, 'S', 'G', weights)) print(f'DFS: {dfs_result}\nBFS: {bfs_result}\nUCS: {test}')
5dccac4e948c556065ffe020fa7eff1361723d71
remani/SRA221-PSU-Hozza
/LBD Hash Cracking/SimpleCracker.py
1,508
3.890625
4
# Simple script to crack lowercase MD5 password hashes # Brant Goings # Library needed to hash dictionary file import hashlib # Files to import hashlist = "hashes.txt" dictlist = "dictionary.txt" # Method to run def crack(): # Opens dictionary file as read-only referred to as dictreader with open(dictlist, "r") as dictreader: try: # Starts for loop in dictreader for dictline in dictreader: # Opens hash file as read-only referred to as hashreader with open(hashlist, "r") as hashreader: # Starts nested for loop in hashreader for hashline in hashreader: # -------------------- BEGIN SUPER IMPORTANT PART -------------------- # # If statement compares the hashed version of the password in dictionary.txt with the hash in hashes.txt if hashlib.md5(dictline.rstrip().encode()).hexdigest() == hashline.rstrip(): # If they match, print the hash and the line in dictionary.txt we're currently at print("MD5 hash cracked -- " + hashline.rstrip() + " : " + dictline) # If they're not the same, continue without doing anything else: pass # -------------------- END SUPER IMPORTANT PART -------------------- # except: pass # Spaces the output for readability print("\n") # Run the script crack()
94941a6411f982dcdeeda8926e5b870dd222c26f
1nF0rmed/network-manager
/security/secure.py
1,755
3.546875
4
import base64 import hashlib from Crypto import Random from Crypto.Cipher import AES class AESCipher: def __init__(self, key): self.block_size = AES.block_size # The block size for the padding data self.key = hashlib.sha256(key.encode()).digest() # Generate a hash for the key # Lambda help functions def _pad(self, s): return s + (self.block_size - len(s)%self.block_size) * chr(self.block_size - len(s)%self.block_size) def _unpad(self, s): return s[:-ord(s[len(s)-1:])] # Misc help functions def getKey(self): pass def setKey(self): pass def setBlockSize(self): pass # Main functions for AES def encrypt(self, raw): """ 1. Pad the text to the block size 2. Generate IV for the given block size using Random 3. Create a cipher using the IV and the Key in AES CBC Mode """ padded_text = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) cipher_text = iv + cipher.encrypt(padded_text) # Return the cipher text with base64 encoding return base64.b64encode( cipher_text ) def decrypt(self, r_data): """ 1. Decode the base64 encoded string 2. Extract IV from decoded string 3. Unpad the cipher text 4. Return the raw text """ enc_text = base64.b64decode(r_data) iv = enc_text[:self.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) raw_text = cipher.decrypt(enc_text[self.block_size:]) # Unpad and return the message in UTF-8 text return self._unpad(raw_text).decode("utf-8")
3b9b89f9e95200e9e4be1d74dd8a5c44f004ca9c
skafev/Python_fundamentals
/03.Third_week/05Numbers_filter.py
685
3.8125
4
num = int(input()) my_list = [] for n in range(1, num + 1): new_num = int(input()) my_list.append(new_num) command = input() new_string = [] if command == "even": for m in range(len(my_list)): if my_list[m] % 2 == 0: new_string.append(my_list[m]) if command == "odd": for m in range(len(my_list)): if my_list[m] % 2 != 0: new_string.append(my_list[m]) if command == "negative": for m in range(len(my_list)): if my_list[m] < 0: new_string.append(my_list[m]) if command == "positive": for m in range(len(my_list)): if my_list[m] >= 0: new_string.append(my_list[m]) print(new_string)
471869c5fdd3249cf6297dd0ccd412d1637e216f
tainenko/Leetcode2019
/python/34.find-first-and-last-position-of-element-in-sorted-array.py
1,737
3.8125
4
# # @lc app=leetcode id=34 lang=python # # [34] Find First and Last Position of Element in Sorted Array # # https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/ # # algorithms # Medium (33.91%) # Total Accepted: 331.2K # Total Submissions: 974.2K # Testcase Example: '[5,7,7,8,8,10]\n8' # # Given an array of integers nums sorted in ascending order, find the starting # and ending position of a given target value. # # Your algorithm's runtime complexity must be in the order of O(log n). # # If the target is not found in the array, return [-1, -1]. # # Example 1: # # # Input: nums = [5,7,7,8,8,10], target = 8 # Output: [3,4] # # Example 2: # # # Input: nums = [5,7,7,8,8,10], target = 6 # Output: [-1,-1] # # class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ right = self.findUpperbound(nums, target) if right < 0 or nums[right] != target: return [-1, -1] left = self.findLowerbound(nums, target) return [left, right] def findUpperbound(self, nums, target): right = len(nums) - 1 left = 0 while left <= right: mid = (left + right) >> 1 if nums[mid] > target: right = mid - 1 else: left = mid + 1 return right def findLowerbound(self, nums, target): right = len(nums) - 1 left = 0 while left <= right: mid = (left + right) >> 1 if nums[mid] < target: left = mid + 1 else: right = mid - 1 return left
3311f3cedfa5e8c379d4203e50c7544ef32ca354
PrasanthChettri/competitivecode
/cp/string.py
189
3.71875
4
#STRING , MASK --> _TRING for _ in range(int(input())): string = input() mask = input() for i in string: if not i in mask : print(i , end = '') print()
04e6a5a7fd3f860d62c5ec073d3cc3e51bd6bb4f
yaphet17/Kattis-Problem-Solutions
/Apaxiaaaaaaaaaaaans!.py
243
3.765625
4
string=[i for i in input()] output=[] for i in range(len(string)): if(i==len(string)-1): output.append(string[i]) break if(string[i]!=string[i+1]): output.append(string[i]) for i in output: print(i,end="")
aaf9dd76495d3bd6cf6a3ee32cc036c35641738a
TomAbrahams/Small_Tutorial_For_WordPress
/The_tutorial.py
2,551
4.78125
5
#Putting the # in front of an item is comments. #This doesn't do anything to code. #Why put comments? To let others know what you are making of course! #This program will take an input and multiply it by 2. #print prints a message. The \n is a return character. #It puts stuff on the next line. print("This prints the message I want to give\n") #this takes in an input and stores it into the variable on the left hand side. #example name = input("Enter the student's name:") #now lets store the student's major in a container known as major major = input("Enter the student's major:") #now we can create a message with the data to make an automated message! print("Welcome ", name, "\n") print("Your major is :", major) #So why is programming so powerful? #Because you can automate logical decisions. #Think of any job that has a logical decision that you have to make a decision. #This is where the automation of logical work happens #In python TABS ARE EVERYTHING #So... If you make an if statement, everything that happens if that circumstance is met #Is done one tab over. #For example #if is the first condition #elif means else if, for other conditions #else means for everything else. #if(condition): # what happens during condition. This is tabbed on purpose. #elif(condition): # what happens if the else if condition is met #else: # what happens if anything else isn't made. #Here is a GPA Calculator for a grade. print("Make a choice from the following \n") print("Convert Grade to GPA\n") print("Type one of the following A, A-, B+, B, B-, C+, C, C-, D+,D, D-, F, \n") choice = input("Type the grade here:") if(choice == "A"): print("4.0") elif(choice == "A-"): print("3.667") elif(choice == "B+"): print("3.333") elif(choice == "B"): print("3.0") elif(choice == "B-"): print("2.667") elif(choice == "C+"): print("2.333") elif(choice == "C"): print("2.0") elif(choice == "C-"): print("1.667") elif(choice == "D+"): print("1.333") elif(choice == "D"): print("1.0") elif(choice == "F"): print("0.0") else: print("Do not recognize grade") #But here is something more interesting. print("Prince is one of the greatest musicians of our time.\n") prince = input("Enter y for yes, n for no:") if (prince == "y"): print("Of course he is, may purple rain for ever.") elif(prince =="n"): print("WHAT? ARE YOU INSANE! Go purify yourself in the waters of lake Minnetonka!") else: print("You must have meant yes. OBVIOUSLY. The keys slipped.") print("\nEnding program\n")
8448017d71527315842e6f1cf6cd1ae3a0ec5ddf
OneScreenfulOfPython/screenfuls
/GeneratePassword/generate_password_v1.py
1,077
4.375
4
import os, sys import random import string try: # Make Python2 work like Python3 input = raw_input except NameError: # On Python3; already using input pass letters = string.ascii_letters numbers = string.digits punctuation = string.punctuation def generate(password_length): """Generate a password by include enough random characters to meet the password length restriction """ # # Any combination of characters is valid # valid_characters = letters + numbers + punctuation # # Start with a blank password and then go round enough # times to make a password of the required length. # password = "" for i in range(password_length): # # Each time around, add a randomly-chosen character # random.choice picks one from a list # password += random.choice(valid_characters) return password if __name__ == '__main__': password_length = int(input("How many letters? ")) password = generate(password_length) print("Your password is: {}".format(password))
91a54401b39a73e7849f74f9e70123baaa196489
shangpf1/python_study
/2017-11/2017-11-04.py
802
4.1875
4
''' 我的练习作业02 创建类,将类进行实例化 ''' # 创建一个动物类,它可以能吃能喝能睡 class animal: def __init__(self): print("创建函数时要调用构造函数") def eat(self): print("eat") def drink(self): print("drink") def sleep(self): print("sleep") elephant = animal() elephant.eat() elephant.drink() elephant.sleep() # 创建一个人类,他可以能吃能喝能爱 class human: def __init__(self,name): print("创建函数时要调用构造函数") def eat(self,name): print(name,"can eat") def drink(self,name): print(name,"can drink") def love(self,name): print(name,"can love") name = human("john") name.eat("john") name.drink("john") name.love("john")
c4532795baf369c70ceadf9555bfc103306f3636
ardentras/minesweepyr
/src/tiles.py
2,843
3.53125
4
########################################################### # Filename: tiles.py # Author: Shaun Rasmusen <[email protected]> # Last Modified: 12/31/2020 # # tile classes for numbers and mines # import pygame import colors pygame.font.init() MINE = 9 class Tile(pygame.sprite.Sprite): def __init__(self, value, pos, theme, size = 16): pygame.sprite.Sprite.__init__(self) self.borderScale = .95 self.image = pygame.Surface((size, size)) self.tile = pygame.Surface((size * self.borderScale, size * self.borderScale)) self.size = size self.theme = theme self.uncovered = False self.flagged = False self.value = value self.rect = (pos[0] * self.size, pos[1] * self.size) self.redraw() def redraw(self): return def draw(self, value, color): number = self.theme.tileFont.render(str(value), True, (255-color[0],255-color[1],255-color[2])) numMidwide = (self.size / 2) - (number.get_width() / 2) numMidhigh = (self.size / 2) - (number.get_height() / 2) tileMidwide = (self.size / 2) - ((self.size * self.borderScale) / 2) tileMidhigh = (self.size / 2) - ((self.size * self.borderScale) / 2) self.tile.fill(color) self.image.fill((abs(color[0]-32),abs(color[1]-32),abs(color[2]-32))) self.image.blit(self.tile, (tileMidwide,tileMidhigh)) self.image.blit(number, (numMidwide,numMidhigh)) def setUncovered(self, uncovered): if not self.flagged: self.uncovered = uncovered self.redraw() def isUncovered(self): return self.uncovered def setFlagged(self, flagged): if not self.uncovered: self.flagged = flagged self.redraw() def isFlagged(self): return self.flagged def getValue(self): return int(self.value) if self.value != 'X' else 9 def setTheme(self, theme): self.theme = theme class NumberTile(Tile): def __init__(self, value, pos, theme, size = 16): super().__init__(value, pos, theme, size) def redraw(self): if self.uncovered: if self.value > 0: self.draw(self.value, self.theme.tileColor) else: self.image.fill(self.theme.tileColor) elif self.flagged: self.draw("F", self.theme.tileCoverColor) else: self.draw("", self.theme.tileCoverColor) class MineTile(Tile): def __init__(self, pos, theme, size = 16): super().__init__(MINE, pos, theme, size) def redraw(self): if self.uncovered: self.draw("X", self.theme.mineColor) elif self.flagged: self.draw("F", self.theme.tileCoverColor) else: self.draw("", self.theme.tileCoverColor)
5722076ade91a65ee7551e69e4e9fba1d4a58424
jonasht/cursoIntesivoDePython
/exercisesDosCapitulos/09-classes/9.3-usuarios/usuarios.py
719
3.515625
4
class User(): def __init__(self, first_name, last_name, email, username, password): self.first_name = first_name self.last_name = last_name self.email = email self.username = username self.password = password def describe_user(self): print(f'nome: {self.first_name}') print(f'sobrenome: {self.last_name}') print(f'email: {self.email}') print(f'username: {self.username}') print(f'password: {self.password}') def greet(self): print(f'saudacoes {self.first_name} {self.last_name}') u1 = User('felipe', 'arcades', '[email protected]', 'felip123', '123') u1.describe_user() u1.greet()
6103fa116c6431b19d70a6daa3376eec35f75102
chenxu0602/LeetCode
/99.recover-binary-search-tree.py
1,690
3.71875
4
# # @lc app=leetcode id=99 lang=python3 # # [99] Recover Binary Search Tree # # https://leetcode.com/problems/recover-binary-search-tree/description/ # # algorithms # Hard (37.35%) # Likes: 1177 # Dislikes: 65 # Total Accepted: 144.6K # Total Submissions: 386.8K # Testcase Example: '[1,3,null,null,2]' # # Two elements of a binary search tree (BST) are swapped by mistake. # # Recover the tree without changing its structure. # # Example 1: # # # Input: [1,3,null,null,2] # # 1 # / # 3 # \ # 2 # # Output: [3,1,null,null,2] # # 3 # / # 1 # \ # 2 # # # Example 2: # # # Input: [3,1,4,null,null,2] # # ⁠ 3 # ⁠/ \ # 1 4 # / # 2 # # Output: [2,1,4,null,null,3] # # ⁠ 2 # ⁠/ \ # 1 4 # / # ⁠ 3 # # # Follow up: # # # A solution using O(n) space is pretty straight forward. # Could you devise a constant space solution? # # # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ stack = [] x = y = pred = None while stack or root: while root: stack.append(root) root = root.left root = stack.pop() if pred and root.val < pred.val: y = root if x is None: x = pred else: break pred = root root = root.right x.val, y.val = y.val, x.val # @lc code=end
39bde1f0ae4c9962818198d278bf4d757cfcecfa
MultiRRomero/manhattan-map
/la-data/manhattan_dist.py
1,100
3.703125
4
import math from subway_data import subway_data """ Returns: (distance in meters, subway stop data) Subway stop data has: lat, lng, stop (name), lines Lines is: string of all lines, i.e, '456' """ def get_distance_to_nearest_subway_stop(lat, lng, subway_lines = ['6','R','L']): structs = get_all_subway_structs_for_lines(subway_lines) dists = map(lambda s: manhattan_dist_meters(lat, lng, s['lat'], s['lng']), structs) zipped = zip(dists, structs) return reduce(lambda a,b: a if a[0]<b[0] else b, zipped) def get_all_subway_structs_for_lines(lines): return filter(lambda s: len(filter(lambda l: l in s['lines'], lines)), subway_data) def manhattan_dist_meters(lat1, lng1, lat2, lng2, axis_tilt_radians = 29 * math.pi/180): meters_per_lat = 111049.43673993941 # at NYC's latitude; got these from an online calc meters_per_lng = 84426.94296769376 dy = (lat1 - lat2) * meters_per_lat dx = (lng1 - lng2) * meters_per_lng dist = math.sqrt(dy*dy + dx*dx) angle = math.atan2(dy,dx) + axis_tilt_radians # rotate return dist * (abs(math.sin(angle)) + abs(math.cos(angle)))
3136556b86cc21e5a8d007b4b368d70693dca208
saurabhchris1/Algorithm-Pratice-Questions-LeetCode
/Minimum_Window_Substring.py
1,741
3.8125
4
# Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "". # # The testcases will be generated such that the answer is unique. # # A substring is a contiguous sequence of characters within the string. # # Input: s = "ADOBECODEBANC", t = "ABC" # Output: "BANC" # Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t. # # Input: s = "a", t = "a" # Output: "a" # Explanation: The entire string s is the minimum window. # # Input: s = "a", t = "aa" # Output: "" # Explanation: Both 'a's from t must be included in the window. # Since the largest window of s only has one 'a', return empty string. import collections class Solution: def minWindow(self, s, t): if not s or not t: return "" dict_t = collections.Counter(t) formed = 0 ans = float("inf"), None, None window_count = collections.defaultdict(int) l, r = 0, 0 required = len(dict_t) while r < len(s): char = s[r] window_count[char] += 1 if char in dict_t and window_count[char] == dict_t[char]: formed += 1 while l <= r and formed == required: if r - l + 1 < ans[0]: ans = (r - l + 1, l, r) char = s[l] window_count[char] -= 1 if char in dict_t and window_count[char] < dict_t[char]: formed -= 1 l += 1 r += 1 return "" if ans[0] == float("inf") else s[ans[1]: ans[2] + 1]
054543e852cdd6c77cd64766ca6dc56212619c60
grigor-stoyanov/PythonOOP
/decorators/even_numbers.py
226
3.53125
4
def even_numbers(function): def wrapper(nums): return list(filter(lambda x: x % 2 == 0, nums)) return wrapper @even_numbers def get_numbers(numbers): return numbers print(get_numbers([1, 2, 3, 4, 5]))
e844f091c5357c5bbdbd34acc5a888dd88da08c2
TIU11/Pi-Smart-Home-PSU
/relay.py
390
3.59375
4
import gpiozero # change this value based on which GPIO port the relay is connected to RELAY_PIN = 18 # create a relay object. # Triggered by the output pin going low: active_high=False. # Initially off: initial_value=False relay = gpiozero.OutputDevice(RELAY_PIN, active_high=False, initial_value=False) def toggle_relay(): print("toggling relay") relay.toggle() toggle_relay()
5c788c50f97557364bbb436dfc9688f2a730488b
Czartor/Big-Date
/Exercise4.py
248
3.578125
4
print('Wprowadź liczbę:') print('n = ') n = int(input()) if (n==0): print(1) exit() else: wprowadzona_liczba = 1 for i in range(1, n+1): wprowadzona_liczba *= i print("silnia z", n, "wynosi", wprowadzona_liczba)
fd7d3593594c6bdd867926fff268aee926ebaee8
chomimi101/system-design
/mini-twitter/mini-twitter.py
2,213
3.875
4
''' Definition of Tweet: class Tweet: @classmethod def create(cls, user_id, tweet_text): # This will create a new tweet object, # and auto fill id ''' class MiniTwitter: def __init__(self): # initialize your data structure here. self.follows = dict() self.tweets = [] # @param {int} user_id # @param {str} tweet # @return {Tweet} a tweet def postTweet(self, user_id, tweet_text): # Write your code here tweet = Tweet.create(user_id, tweet_text) self.tweets.append(tweet) return tweet # @param {int} user_id # return {Tweet[]} 10 new feeds recently # and sort by timeline def getNewsFeed(self, user_id): # Write your code here if user_id not in self.follows: return self.getTimeline(user_id) max_length = 10 ans = [] for t in self.tweets[::-1]: if t.user_id == user_id or t.user_id in self.follows[user_id]: ans.append(t) max_length -= 1 if max_length == 0: break return ans # @param {int} user_id # return {Tweet[]} 10 new posts recently # and sort by timeline def getTimeline(self, user_id): # Write your code here max_length = 10 ans = [] for t in self.tweets[::-1]: if t.user_id == user_id: ans.append(t) max_length -= 1 if max_length == 0: break return ans # @param {int} from user_id # @param {int} to_user_id # from user_id follows to_user_id def follow(self, from_user_id, to_user_id): # Write your code here if from_user_id not in self.follows: self.follows[from_user_id] = set() self.follows[from_user_id].add(to_user_id) # @param {int} from user_id # @param {int} to_user_id # from user_id unfollows to_user_id def unfollow(self, from_user_id, to_user_id): # Write your code here if from_user_id in self.follows and to_user_id in self.follows[from_user_id]: self.follows[from_user_id].remove(to_user_id)
3571b8bab993818c9c768be22e877c3193f93452
RITESH-Kapse/Python-Openpyxl-Codes
/6.2_Copying_formatting.py
1,674
3.578125
4
#!/usr/bin/env python3 """ Copying cell formatting """ from openpyxl import Workbook from copy import copy from openpyxl.styles import colors, Font def set_values(ws): ws.delete_cols(1,100) counter = 1 for row in ws.iter_rows(min_row=1, max_col=10, max_row=10): for cell in row: cell.value = counter counter += 1 def print_rows(ws): row_string = "" for row in ws.iter_rows(min_row=1, max_col=ws.max_column, max_row=ws.max_row): for cell in row: row_string += "{:<3}".format(str(cell.value) + " ") row_string += "\n" print(row_string) if __name__ == "__main__": # Create a workbook and sheets filename = "Moving_copying_ranges.xlsx" wb = Workbook() ws1 = wb["Sheet"] # Insert values from 1 to 100 into a grid of 10x10 cells set_values(ws1) print_rows(ws1) # move the whole range ten rows down ws1.move_range("A1:J10", rows=10, cols=0) print_rows(ws1) # reset values set_values(ws1) print_rows(ws1) # copy cell A1's value and formatting to cell A12 old_cell = ws1.cell(row=1, column=1) old_cell.font = Font(name='Arial', size=18, color=colors.RED) new_cell = ws1.cell(row=12, column=1, value= ws1.cell(row=1, column=1).value) new_cell.font = copy(old_cell.font) new_cell.border = copy(old_cell.border) new_cell.fill = copy(old_cell.fill) new_cell.number_format = copy(old_cell.number_format) new_cell.protection = copy(old_cell.protection) new_cell.alignment = copy(old_cell.alignment) wb.save(filename)
170734fa058609e5d528dacf2446749068940e9c
matteiluca/info1
/task1/module.py
3,784
3.640625
4
# REMARK: directory name HAD TO be changed in order to be importable # without using the __import__ function (no space; 'task1' instead of 'task 1') # because the filename is used as the identifier for imported modules and the 'import' statement doesn't support spaces! from Exercise6.task1.moduleElement import * # REMARK: import had to be changed in order to be found in PyCharm! class Module(object): module_count = 0 def __init__(self, ects, title, semester, grade=None): # constructor for class module self.ects = ects self.grade = grade self.title = title self.semester = semester self.dates = [] self.elements = [] Module.module_count += 1 def get_important_dates_overview(self): # prints all the important dates for a module print("Important dates for {0:s}:".format(self.title)) for kind,date in self.dates: print("\t{0:s} on {1:s}".format(kind, date)) def set_grade(self, grade): # set the grade to a given value self.grade = grade def add_module_element(self, other_class, date): # add a new module element to the elements list obj = other_class(self) obj.add_important_date(date) self.elements.append((obj)) def get_title(self): return self.title def get_grade(self): return self.grade ######################################################################### class Course(Module): def __str__(self): return "Course: {}".format(self.title) ######################################################################### class Seminar(Module): def __init__(self, ects, title, semester, topic): super().__init__(ects, title, semester) self.topic = topic def __str__(self): return "{} under the topic: {}".format(self.title, self.topic) def get_topic(self): return self.topic ######################################################################### class Thesis(Module): def __init__(self, ects, title, semester, topic, research_group): super().__init__(ects, title, semester) self.topic = topic self.research_group = research_group def __str__(self): return "{} on the topic: {} in the Research Group {}".format(self.title, self.topic, self.research_group) def get_topic(self): return self.topic def get_research_group(self): return self.research_group ######################################################################### ### test cases ### info1 = Course(6, "Info 1", 1) info1.add_module_element(Midterm, "31.10.2017") info1.add_module_element(FinalExam, "20.12.2017") math1 = Course(6, "Mathematik I", 1) math1.add_module_element(Midterm, "18.12.2017") info1.set_grade(6) if __name__ == '__main__': # don't execute if loaded as a module (had to be added for task 1c) info1.get_important_dates_overview() # expected output: # Important dates for Info 1: # Midterm on 31.10.2017 # Final Exam on 20.12.2017 print(info1) # expected output: # Course: Info 1 math1.get_important_dates_overview() # Important dates for Mathematik I: # Midterm on 18.12.2017 print(Module.module_count) # expected output: 2 thesis = Thesis(18,"Bachelor Thesis",6,"A promising research topic on Software Engineering","SEAL") print(thesis) # expected output: # Bachelor Thesis on the topic: A promising research topic on Software Engineering in the Research Group SEAL sem = Seminar(3,"Seminar in Software Engineering",4,"A Seminar topic") print(sem) # print(thesis) # expected output: # Seminar in Software Engineering under the topic: A Seminar topic
9d86708abd920c125b3857bcf74f90aa755ba1fb
LuisaMariaO/PhytonBasico2021
/Hojadetrabajo3.py
729
4.0625
4
#Comparacion de contraseñas print("___________________EJERCICIO 1__________________") password=input("Ingrese una contraseña: ") confirmacion=input("Confirme la contraseña: ") if password.lower()==confirmacion.lower(): print("Confirmacion exitosa") else: print("Las contraseñas no coinciden") #Grupos de personas print("___________________EJERCICIO 2__________________") nombre=input("Ingrese su nombre: ") sexo=input("Ingrese su sexo: (F si es femenino, M si es masculino ): ") if nombre[0].lower()<"m" and sexo.upper() =="F": print("Perteces al grupo A") elif nombre[0].lower()>"n" and sexo.upper()=="M": print("Perteces al grupo A") else: print("Perteneces al grupo B")
1998a5ad5655cf03c947359b9b454e67e35a4923
omrakn/randomalgorithms
/convexhull/convexhull.py
8,396
3.859375
4
""" Convex Hull with Graham Scan Algorithm @ Author: Res. Assist. Ömer Akın @ Institution: Istanbul Technical University Geomatics Engineering Departmant @ e-mail: [email protected] """ import os, sys, math, random import matplotlib.pyplot as plt def getInput(): """ Generate points randomly or from the input project files Returns ------- pointIDs : list point IDs in order points : list contains coordinate tuples """ global file while True: selection = input("Welcome to Convex Hull Finder\nPress q to exit.\n\ To find the convex hull of random points, please press 1\nTo find the convex \ hull of given point file, please press 2: \n") if selection == "q": sys.exit() elif selection == "1": pointnumber = input("How many points you want to generate: ") if pointnumber == "q": sys.exit() elif pointnumber.isdigit(): pointIDs = [i + 1 for i in range(int(pointnumber))] x = [random.uniform(20, 60) for _ in range(int(pointnumber))] y = [random.uniform(20, 60) for _ in range(int(pointnumber))] points = [(i, j) for i, j in zip(x, y)] file = "randompoints" return pointIDs, points else: print("Please enter a valid number") elif selection == "2": file = input("Please enter the file name of points without \ its extension: ") # Exit Conditions if file == "q": sys.exit() # Check file existence if os.path.exists(file + ".xyz"): print("File exists in the directory") try: # To add points pointfile = open(file + ".xyz") p_lines = pointfile.readlines()[2:] pointfile.close() pointIDs = [i.split()[0] for i in p_lines] x = [float(i.split()[1]) for i in p_lines] y = [float(i.split()[2]) for i in p_lines] points = [(i, j) for i, j in zip(x, y)] return pointIDs, points except: print("However it is not supported or properly designed") else: print("File does not exist in the directory") else: print("Please enter a valid selection") def findAnchor(IDs, points): """ Find the most southwest point to be used as initial start point for searching Parameters ---------- IDs : list point IDs in order points : list contains coordinate tuples Returns ------- anchor : tuple Most soutwestern point of given point list """ min_x = None for i, (x, y) in zip(IDs, points): if min_x is None or x < points[IDs.index(min_x)][0]: min_x = i if ( x == points[IDs.index(min_x)][0] and y < points[IDs.index(min_x)][1] ): min_x = i anchor = points[IDs.index(min_x)] return anchor def calcAzimuth(p0, p1): """ Calculate azimuthal angle between two points Parameters ---------- p0 : tuple first point p1 : tuple second point Returns ------- azimuth : float azimuthal angle between input points """ delta_y = p1[1]-p0[1] delta_x = p1[0]-p0[0] azimuth = math.atan2(delta_y, delta_x) return azimuth def sortPoints(anchor, points): """ Sort all the points based on azimuthal (polar) angle they make with the anchor to start searching in counter-clockwise rotation Parameters ---------- anchor : tuple Most soutwestern point of given point list points : list contains coordinate tuples Returns ------- sorted_points : list coordinate tuples sorted by their azimuth angles between them in ascending order """ azimuthlist = { calcAzimuth(anchor, point): (point[0], point[1]) for point in points } azimuths = list(azimuthlist.keys()) azimuths.remove(0) sort_azi = sorted(azimuths, reverse=True) sorted_points = [azimuthlist[azimuth] for azimuth in sort_azi] return sorted_points def ccw(p0, p1, p2): """ Find traversing to a point from the previous two points makes a clockwise or a counter-clockwise direction Parameters ---------- p0 : tuple first point p1 : tuple second point p3 : tuple third point Returns ------- rotation : float Difference between the slopes to identify the third point is on left or right """ rotation = (p1[0]- p0[0]) * (p2[1] - p1[1]) - (p2[0] - p1[0]) * (p1[1] - p0[1]) return rotation def convexHull(anchor, pointIDs, points, sortedPoints): """ Find convex hull of given points Parameters ---------- anchor : tuple Most soutwestern point of given point list pointIDs : list point IDs in order points : list contains coordinate tuples sortedPoints : list coordinate tuples sorted by their azimuth angles between them in ascending order Returns ------- convex_IDs : list point IDs of hull points convex_hull : list coordinates of hull points """ convex_hull = [anchor, sortedPoints[0]] for point in sortedPoints[1:]: while ccw(convex_hull[-2], convex_hull[-1], point) > 0: del convex_hull[-1] convex_hull.append(point) convex_IDs = [ pointIDs[points.index(convex_point)] for convex_point in convex_hull ] hulls = {ID: hull for ID, hull in zip(convex_IDs, convex_hull)} return convex_IDs, convex_hull def PlotConvexHull(pIDs, points, polygon): """ Plot the points and convex hull Parameters ---------- pIDs : list point IDs in order points : list contains coordinate tuples. polygon : list coordinates of hull points Returns ------- None. """ fig, ax = plt.subplots(figsize=(12, 8)) x, y = list(zip(*points))[0], list(zip(*points))[1] ax.scatter(y, x) polydraw = list(polygon) polydraw.append(polygon[0]) c_x, c_y = list(zip(*polydraw))[0], list(zip(*polydraw))[1] ax.plot(c_y, c_x, color="red") plt.title("Convex Hull with Graham Scan Algorithm") plt.xlabel("Y") plt.ylabel("X") for i, txt in enumerate(pIDs): ax.annotate(txt, (y[i], x[i]), verticalalignment="bottom", horizontalalignment="right") return def writeOutput(pointIDs, points, convexIDs): """ Write the results in output report files in the directory Parameters ---------- pointIDs : list point IDs in order points : list contains coordinate tuples. convexIDs : list point IDs of hull points Returns ------- None. """ outputfile = open(file + ".out", "w") outputfile.write("Point ID x [m] y [m]\n\ ---------------------------\n") for ID in convexIDs: outputfile.write("{} {:.3f} {:.3f}\n".format( ID, points[pointIDs.index(ID)][0], points[pointIDs.index(ID)][1] )) print("Output report is generated as {}.out in the directory".format(file)) outputfile.close() if file == "randompoints": outputfile = open("randompoints.xyz", "w") outputfile.write("{}\n".format(str(len(points)))) for ID, point in zip(pointIDs, points): outputfile.write( "{} {:.3f} {:.3f}\n".format(ID, point[0], point[1]) ) print("Generated random points' coordinates are generated as \ {}.xyz in the directory".format(file)) outputfile.close() return def main(): pointIDs, points = getInput() anchor = findAnchor(pointIDs, points) sorted_points = sortPoints(anchor, points) convex_IDs, convex_hull = convexHull(anchor, pointIDs, points, sorted_points) PlotConvexHull(pointIDs, points, convex_hull) writeOutput(pointIDs, points, convex_IDs) if __name__ == "__main__": main()
bc60f94fec9de1e835406fb49946c66ef18ff804
AyuJ01/forsk
/day17 multiple regression/Ayushi_Jain_53.py
1,317
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Jun 1 12:35:14 2018 @author: Ayushi """ import numpy as np #read csv import pandas as pd df = pd.read_csv("stats_females.csv") features = df.iloc[:,1:].values labels = df.iloc[:,0].values #splitting the dataset from sklearn.model_selection import train_test_split features_train,features_test,labels_train,labels_test = train_test_split(features,labels,test_size=0.2,random_state=0) #fitting multiple regression to training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train,labels_train) #predicting the test set result labels_pred = regressor.predict(features_test) #getting score for multiple value regressor model score = regressor.score(features_test,labels_test) #Building the optimal model using backward elimination import statsmodels.formula.api as sm features = np.append(arr = np.ones((214,1)).astype(int),values = features,axis=1) features_opt = features[:,[0,1,2]] regressor_OLS = sm.OLS(endog=labels,exog = features_opt).fit() regressor_OLS.summary() #regressor_OLS.params print('when dad height is constant then increase in avg student height is: ', regressor_OLS.params[1]) print('when Mom height is constant then increase in avg student height is: ', regressor_OLS.params[2])
bd5a71e48a60e911a816856279a2213f3fe5811d
gauravcse/Codes
/Python/Complex/ComplexNum.py
2,522
3.640625
4
class ComplexNum(object) : def __init__(self,a,b,c,d): self.x1=a; self.y1=b self.x2=c self.y2=d def add (self): self.sum=self.x1+self.x2 self.ima=self.y1+self.y2 if(self.sum==0.0) : print "%0.2fi"%(self.ima) else : if (self.ima < 0) : print "%0.2f - "%(self.sum), print "%0.2fi"%(-self.ima) elif (self.ima >0) : print "%0.2f + "%(self.sum), print "%0.2fi"%(self.ima) else : print "%0.2f"%(self.sum) def sub(self): self.sum=self.x1-self.x2 self.ima=self.y1-self.y2 if(self.sum==0.0) : print "%0.2fi"%(self.ima) else : if self.ima < 0 : print "%0.2f - "%(self.sum), print "%0.2fi"%(-self.ima) elif self.ima >0 : print "%0.2f + "%(self.sum), print "%0.2fi"%(self.ima) else : print "%0.2f"%(self.sum) def mul(self): self.sum=(self.x1*self.x2)-(self.y1*self.y2) self.ima=(self.x1*self.y2)+(self.y1*self.x2) if(self.sum==0.0) : print "%0.2fi"%(self.ima) else : if self.ima < 0 : print "%0.2f - "%(self.sum), print "%0.2fi"%(-self.ima) elif self.ima >0 : print "%0.2f + "%(self.sum), print "%0.2fi"%(self.ima) else : print "%0.2f"%(self.sum) def div(self): self.deno=(self.x2)**2-(self.y2)**2 self.sum=(self.x1*self.x2)+(self.y1*self.y2) self.ima=-(self.x1*self.y2)+(self.y1*self.x2) if(self.sum==0.0) : print "%0.2fi"%(self.ima) else : if self.ima < 0 : print "%0.2f - "%(self.sum), print "%0.2fi"%(-self.ima) elif self.ima >0 : print "%0.2f + "%(self.sum), print "%0.2fi"%(self.ima) else : print "%0.2f"%(self.sum) def mod(self): self.mod1=((self.x1**2)+(self.y1)**2)**0.5 print "%0.2f"%(self.mod1) self.mod2=((self.x2**2)+(self.y2)**2)**0.5 print "%0.2f"%(self.mod2) a,b=map(float,raw_input().split()) c,d=map(float,raw_input().split()) obj=ComplexNum(a,b,c,d) obj.add() obj.sub() obj.mul() obj.div() obj.mod()
19fdb88657e447c508b8f77134eef39cca8dd21f
asperaa/programming_problems
/dp/paint_house_linear_space.py
681
3.578125
4
"""Paint house.Time - O(n). Space - O(n)""" def paint_house(costs): if not costs: return 0 length = len(costs) dp = [[0 for _ in range(3)] for _ in range(length)] dp[0][0] = costs[0][0] dp[0][1] = costs[0][1] dp[0][2] = costs[0][2] for i in range(1, length): dp[i][0] += (min(dp[i-1][1], dp[i-1][2]) + costs[i][0]) dp[i][1] += (min(dp[i-1][0], dp[i-1][2]) + costs[i][1]) dp[i][2] += (min(dp[i-1][0], dp[i-1][1]) + costs[i][2]) return min(dp[length-1][0], dp[length-1][1], dp[length-1][2]) if __name__ == "__main__": costs = [[5,8,6],[19,14,13],[7,5,12],[14,15,17],[3,20,10]] print(paint_house(costs))
1ba73f2c1d1097603d9e9881b8b3d1aa071930b8
daveswork/pythonforeverybody
/chapter-08/excercise-06.py
1,055
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters "done". Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes. Enter a number: 6 Enter a number: 2 Enter a number: 9 Enter a number: 3 Enter a number: 5 Enter a number: done Maximum: 9.0 Minimum: 2.0 Severance, Charles. Python for Everybody: Exploring Data in Python 3 (Kindle Locations 2070-2075). Kindle Edition. """ def min_max(): numbers = [] number = "" while True: number = input("Enter a number: ") if number == "done": break try: number = float(number) numbers.append(number) except: print("Invalid input") numbers.sort() print("Maximum:", numbers[-1]) print("Minimum:", numbers[0]) min_max()
4ecc42de5bd9627996eb321e0e082993315661fe
kutakieu/AI-class
/Assignment-1-Search-master-63318a771170bfa64d905052bc0e733cfd3b576e/code/a_star_search.py
2,552
3.59375
4
""" Enter your details below: Name:Taku Ueki Student Code:u5934839 email:[email protected] """ import util from actions import Directions, Actions from search_strategies import SearchNode from frontiers import Queue, Stack, PriorityQueue import heuristics def solve(problem, heuristic) : """ *** YOUR CODE HERE *** """ # util.raise_not_defined() #Remove this line when you have implemented BrFS frontier = PriorityQueue() s0 = problem.get_initial_state() closedSet = set() # closedSet.add(s0) openSet = set() openSet.add(s0) sn_root = SearchNode(s0) frontier.push(sn_root, heuristic(s0,problem)) gScore = {} gScore[s0] = 0 check = None while not frontier.is_empty(): current_node = frontier.pop() # print(current_node.path_cost + heuristic(current_node.state,problem)) closedSet.add(current_node.state) openSet.discard(current_node.state) check = check_goal(current_node, problem) if check == None: for successor, action, cost in problem.get_successors(current_node.state): if successor not in closedSet: tentative_gScore = current_node.path_cost + cost if successor not in openSet: openSet.add(successor) #if there is a path that can be reached to this node more efficiently, discard this successor elif tentative_gScore >= gScore[successor]: continue gScore[successor] = tentative_gScore sn = SearchNode(successor, action, tentative_gScore, current_node, current_node.depth + 1) # push this node to the Queue with gScore and hScore(caluculated by heuristic function) frontier.push(sn, sn.path_cost + heuristic(successor,problem)) # total = sn.path_cost + heuristic(successor,problem) # print(str(current_node.state) + "TO" + str(successor) + " path_cost=" + str(sn.path_cost) + " heuristic=" + str(heuristic(successor,problem)) + " total=" + str(total)) else: return check def check_goal(sn, problem): if problem.goal_test(sn.state): path = [] stack = Stack() stack.push(sn.action) while sn.parent != None: stack.push(sn.parent.action) sn = sn.parent while not stack.is_empty(): path.append(stack.pop()) return path[1:] else: return None
d59839e5e25072211e7a4ee85baddc6c0cfea643
Nishi216/PYTHON-CODES
/NUMPY/numpy7.py
506
4.0625
4
''' Linear algebra in numpy ''' import numpy as np array = np.array([[6,1,1],[4,-2,5],[2,8,7]]) print("Rank of array : ",np.linalg.matrix_rank(array)) print('Trace of the matrix : ',np.trace(array)) print('Determinant of matrix : ',np.linalg.det(array)) print('Inverse of matrix : ',np.linalg.inv(array)) print('Matrix raised to the power of 2 : ',np.linalg.matrix_power(array,2)) #For more matrix and linear algebra opeartions - follow https://www.geeksforgeeks.org/numpy-linear-algebra/
a862e69f1a765276f9b96e4b4e86757263dffb0d
itzketan/3rd-day
/3rd day.py
2,945
4.46875
4
#simple GUI registration form. #importing tkinter module for GUI application from tkinter import * #Creating object 'root' of Tk() root = Tk() #Providing Geometry to the form root.geometry("800x700") #Providing title to the form root.title('Registration form') #this creates 'Label' widget for Registration Form and uses place() method. label_0 =Label(root,text="Registration Form", width=20,font=("bold",20)) #place method in tkinter is geometry manager it is used to organize widgets by placing them in specific position label_0.place(x=90,y=60) #this creates 'Label' widget for Fullname and uses place() method. label_1 =Label(root,text="Employee ID", width=20,font=("bold",10)) label_1.place(x=80,y=130) #this will accept the input string text from the user. entry_1=Entry(root) entry_1.place(x=240,y=130) #this creates 'Label' widget for Email and uses place() method. label_3 =Label(root,text="Contact Number", width=20,font=("bold",10)) label_3.place(x=68,y=180) entry_3=Entry(root) entry_3.place(x=240,y=180) #this creates 'Label' widget for Gender and uses place() method. label_4 =Label(root,text="Gender", width=20,font=("bold",10)) label_4.place(x=70,y=230) #the variable 'var' mentioned here holds Integer Value, by deault 0 var=IntVar() #this creates 'Radio button' widget and uses place() method Radiobutton(root,text="Male",padx= 5, variable= var, value=1).place(x=235,y=230) Radiobutton(root,text="Female",padx= 20, variable= var, value=2).place(x=290,y=230) ##this creates 'Label' widget for country and uses place() method. label_5=Label(root,text="Country",width=20,font=("bold",10)) label_5.place(x=70,y=280) #this creates list of countries available in the dropdownlist. list_of_country=[ 'India' ,'US' , 'UK' ,'Germany' ,'Austria',"China"] #the variable 'c' mentioned here holds String Value, by default "" c=StringVar() droplist=OptionMenu(root,c, *list_of_country) droplist.config(width=15) c.set('Select Your Country') droplist.place(x=240,y=280) ##this creates 'Label' widget for Language and uses place() method. label_6=Label(root,text="Language",width=20,font=('bold',10)) label_6.place(x=75,y=330) #the variable 'var1' mentioned here holds Integer Value, by default 0 var1=IntVar() #this creates Checkbutton widget and uses place() method. Checkbutton(root,text="English", variable=var1).place(x=230,y=330) #the variable 'var2' mentioned here holds Integer Value, by default 0 var2=IntVar() Checkbutton(root,text="German", variable=var2).place(x=300,y=330) #the variable 'var2' mentioned here holds Integer Value, by default 0 var3=IntVar() Checkbutton(root,text="Hindi", variable=var2).place(x=380,y=330) #this creates button for submitting the details provides by the user Button(root, text='SUBMIT' , width=20,bg="black",fg='white').place(x=180,y=380) #this will run the mainloop. root.mainloop()
22b87fcbb97571a6d0c2d922ddacb4a0a6bdaf98
WangXiaoTang333/python_30mintues
/lec01/currency_converter_v5.0.py
1,024
3.875
4
""" 作者:王糖糖 功能:汇率兑换currency_converter_v5.0.py 版本:5.0 日期:27/12/2018 新增功能:(1)程序更加模块化 (2)lambda函数的使用 """ # # def converter_com(im,er): # out_m = im * er # return out_m def main(): # 汇率 USD_VS_RMB = 6.77 currency_str_value = input("请输入带单位的货币输入金额(USD or CNY,退出程序请输入Q):") unit=currency_str_value[-3:] # 判断是人民币还是美元 if unit=='USD': exchange_rate = USD_VS_RMB elif unit=='CNY': exchange_rate = 1/USD_VS_RMB else: exchange_rate = -1 if exchange_rate != -1: in_money = eval(currency_str_value[:-3]) # 调用函数 # out_money=converter_com(in_money,exchange_rate) #lambda函数 converter_com2 = lambda x: x * exchange_rate out_money=converter_com2(in_money) print("转换后的货币金额为:", out_money) else: print("不支持该种货币!") if __name__ == '__main__': main()
f1cc0c7668c97331be34f84f2c1d551af942d743
haakoneh/TDT4110
/Oving_2/Oving2_5.py
829
3.703125
4
def timelonn(): timelonn = float(input('Skriv inn timelonnen: ')) timer = float(input('Skriv antall timer: ')) lonn = timelonn*timer print('Lonnen blir: ', lonn) def provisjon(): grunnlonn = float(input('Skriv inn grunnlonnen: ')) enhetlonn = float(input('Skriv inn enhetslonnen: ')) antall = float(input('Skriv antall enheter: ')) lonn = grunnlonn+(enhetlonn*antall) print('Lonnen blir: ', lonn) def main(): while True: print('Velkommen til ReveNew (tm)') check = input('Er den ansatte på [t]imelonn eller [p]rovisjon? ') if(check == 't' or check == 'timelonn'): timelonn() break elif(check == 'p' or check == 'provisjon'): provisjon() break else: print('Inputmetoden er ugyldig') print('Skriv "t" eller "timelonn" for timelonn eller "p" eller "provisjon" for provisjonslonn') main()
66c666c2936792d9251384842ed993eaacca99c7
HelloYeew/helloyeew-computer-programming-i
/OOP_Inclass_2/inclass_demo_exercise_code/Point2D_Rectangle.py
1,330
4.21875
4
class Point2D: """Point class represents and operate on x, y coordinates """ def __init__(self, x=0, y=0): self.x = x self.y = y def distance_from_origin(self): return (self.x*self.x + self.y*self.y)**0.5 def halfway(self, other): halfway_x = (other.x + self.x) / 2 halfway_y = (other.y + self.y) / 2 return Point2D(halfway_x, halfway_y) def __str__(self): return "({0}, {1})".format(self.x, self.y) def __eq__(self, other): return (self.x == other.x) and (self.y == other.y) class Rectangle: """Rectangle class represents a rectangle object with its size and location """ def __init__(self, point, width, height): self.corner = point self.width = width self.height = height def area(self): return self.width * self.height def grow(self, delta_width, delta_height): self.width += delta_width self.height += delta_height def move(self, dx, dy): self.corner.x += dx self.corner.y += dy def __str__(self): return "[{0}, {1}, {2}]".format(self.corner, self.width, self.height) def __eq__(self, other): return (self.corner == other.corner) and (self.width == other.width) and (self.height == other.height)
da7e74fe1311970da818b2792ea60feef4bcde8b
nidawi/2DV515-A4
/models/CrossValidation.py
4,607
3.546875
4
from models.NaiveBayes import NaiveBayes from lib.utils import accuracy_score, confusion_matrix, present_matrix from random import randrange from typing import List def crossval_predict(X: List[List[float]], y: List[int], folds: int) -> List[int]: """ Runs n-fold cross-validation on the provided dataset, X, with the given labels, y. Returns a list of class predictions in true order. Format (output): >>> [ int, int, int ] # and so on Procedure: 1. Shuffle the dataset randomly. 2. Split the dataset into k groups 3. For each unique group: 3.1. Take the group as a hold out or test data set 3.2. Take the remaining groups as a training data set 3.3. Fit a model on the training set and evaluate it on the test set 3.4. Retain the evaluation score and discard the model 4. Summarize the skill of the model using the sample of model evaluation scores """ # add correct labels to each row for i in range(len(X)): X[i].append(y[i]) X[i].append(None) # placeholder for prediction # step 1 and 2 workFolds = split_into_folds(X, folds) for fold in workFolds: # convert all other folds into training set: step 3.1 and 3.2 trainingSet = list(filter(lambda x : x is not fold, workFolds)) trainingSet = sum(trainingSet, []) # todo: figure out why this works trainingLabels = list(map(lambda x : x[-2], trainingSet)) # generate training set-specific labels trainingSet = list(map(lambda x : x[0:-2], trainingSet)) # remove labels etc. from the training set # otherwise the model will think that they represent another column. # setup the model model = NaiveBayes() model.fit(trainingSet, trainingLabels) # calculate predictions prediction = model.predict(fold) # add predictions to our main dataset for i in range(len(fold)): fold[i][-1] = prediction[i] # produce a true list of predictions preds = list(map(lambda x : x[-1], X)) return preds def crossval_predict_evaluation(X: List[List[float]], y: List[int], folds: int) -> List[dict]: """ Runs n-fold cross-validation on the provided dataset, X, with the given labels, y. Returns a list containing accuracy results for each fold. Each accuracy results contains the following information: total examples in the fold, matching examples (correctly predicted), and accuracy in percent. Format (output): >>> [ { total: int, matching: int, accuracy: float } ] Procedure: 1. Shuffle the dataset randomly. 2. Split the dataset into k groups 3. For each unique group: 3.1. Take the group as a hold out or test data set 3.2. Take the remaining groups as a training data set 3.3. Fit a model on the training set and evaluate it on the test set 3.4. Retain the evaluation score and discard the model 4. Summarize the skill of the model using the sample of model evaluation scores """ # add correct labels to each row for i in range(len(X)): X[i].append(y[i]) # step 1 and 2 workFolds = split_into_folds(X, folds) scores = [] for fold in workFolds: # convert all other folds into training set: step 3.1 and 3.2 trainingSet = list(filter(lambda x : x is not fold, workFolds)) trainingSet = sum(trainingSet, []) # todo: figure out why this works trainingLabels = list(map(lambda x : x[-1], trainingSet)) # generate training set-specific labels trainingSet = list(map(lambda x : x[0:-1], trainingSet)) # remove labels etc. from the training set # otherwise the model will think that they represent another column. # setup the model model = NaiveBayes() model.fit(trainingSet, trainingLabels) # calculate predictions prediction = model.predict(fold) # fetch the actual position [-2] for comparison actual = [row[-1] for row in fold] # calculate accuracy for fold and add to scores acc = accuracy_score(prediction, actual) scores.append(acc) return scores def split_into_folds(dataset: List[List[float]], foldCount: int) -> List[List[List[float]]]: """ Splits a dataset into the specified number of folds. """ folds = [] foldSize = int(len(dataset) / foldCount) dataset = list(dataset) # copy the dataset for _ in range(foldCount): fold = [] while len(fold) < foldSize: index = randrange(len(dataset)) fold.append(dataset.pop(index)) folds.append(fold) # if we get any extra examples that do not split evenly into any folds, # we try to divide them evenly across the folds (as well as we can) for i in range(len(dataset)): folds[i].append(dataset[i]) return folds
406753ae761c595afa2832ec080e83c0284315b6
ISE2012/ch3
/dino_v1.py
970
3.828125
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 15:47:38 2020 @author: xyz """ def main(): print("Welcome to the DinoCheck 1.0") print("Please answer 'True' or 'False' for each question") isSharp = input("Does the dinosaur have sharp teeth? ") isWalled = input("Is the dinosaur behind a large wall? ") isBiped = input("Is the dinosaur walking on two legs? ") isClawed = input("Does the dinosaur have sharp claws? ") isBeaked = input("Does the dinosaur have a beak? ") if isSharp == "True": print("Be careful of a dinosaur with sharp teeth!") if isWalled == "True": print("You are safe, the dinosaur is behind a big wall!") if isBiped == "True": print("Be careful of a dinosaur who walks on two legs!") if (isClawed == "True") and (isBeaked == "True"): print("Be careful of a dinosaur with sharp claws and a beak!") print("Good luck!") main()
24d8138f733cdb2d2bde10087c6600f23a9a0405
rafarikrdo/QueroPizza
/1171 Frequência de números.py
376
3.71875
4
#def achaNumeros(lista): # for i in range(0, len(lista)): # return i vezes=int(input()) a=0 list=[] for i in range(0,vezes): num=int(input()) list.append(num) list.sort() for i in range(0, vezes): a = list.count(list[i]) if list[i] != list[i-1]: print("{} aparece {} vez(es)".format(list[i], a)) else: not print()
3b27cc2f8e6ecbcab795b5837df5ccad3eaa9517
jbmasemza/katas_programming
/hello.py
95
3.765625
4
def main(): name = str(input("enter your name :")) print("hello " + name + "!") main()
31f36e9107d2fb41c529abcd77a23eb51c8efbdb
DarioSardi/AI
/Perceptron/perceptron.py
774
3.5625
4
import numpy as np def act(x): if (x > 0): return 1 else: return -1 import numpy as np class Perceptron: def __init__(self,size): #prende input e inizializza in base alla sua dimensione pesi randomici self.weights = np.random.rand(size,1) self.lr = 0.01 def guess(self,inputs): sum2=0 for i in range(0,len(self.weights)): sum2 += inputs[i] * self.weights[i]; return act(sum2) #w=w+err*input*learnRate def train(self,inputs,target): guessed = self.guess(inputs) error = target-guessed #print("p:",inputs,"g:",target,guessed) for i in range(0,len(self.weights)): self.weights[i] += error*inputs[i]*self.lr # print("")
e6b226a375e276722e80f8a36e58a3b804c2bfe4
miguelbatista21/python
/elif/test1-elif-else-if.py
1,038
4
4
num = int(input("Coloque um numero: ")) if num < 200: preco = 0.20 elif num <= 400: preco = 0.18 elif num <= 800: preco = 0.15 else: preco = 0.08 print("Resultado:", (num * preco)) print(preco) #if soma > 0: # print "Maior que Zero." #elif soma = 0: # print "Igual a Zero." #else: # print "Menor que Zero." #num = int(input("Coloque um numero: ")) #if num < 200: # preco = 0.20 #else: # if num <= 400: # preco = 0.18 # else: # if num >= 800: # preco = 0.08 # else: # preco = 0.15 #print("Resultado :", (num * preco)) #print(preco) # # # # < 200? PREÇO = 0.20 # /---------------------------------------------- # /TRUE #-----/ < 400? PREÇO = 0.18 # \ /----------------------- # \FALSE /TRUE # \---------------------- # \FALSE PREÇO = 0.15 # \-----------------------
64fdc4823f6a31b01f85bbb79e814d9e16ff3f17
kainpets/Zelle-introduction-to-CS
/code/chapter13/c13ex08.py
2,013
4.03125
4
# c13ex08.py #Turtle and Koch snowflake from graphics import * from math import cos,sin,pi class Turtle: def __init__(self,window,location = Point(0,0),heading = 0.0): # default position is (0,0) and direction is 0.0 (east) self.position = location self.direction = heading self.win = window def turnRight(self,angle): self.direction = self.direction - angle def turnLeft(self,angle): self.direction = self.direction + angle def forward(self, n): # draw a segment n units long in the current # direction and move to the new end deltaX = n*cos(self.direction) deltaY = n*sin(self.direction) oldPosition = self.position self.position = self.position.clone() self.position.move(deltaX,deltaY) Line(oldPosition,self.position).draw(self.win) def Koch(turtle,length,degree): #from the text, chapter 13 if degree <= 0: turtle.forward(length) else: sixty = 60.0*pi/180.0 length1 = length/3.0 degree1 = degree-1 Koch(turtle,length1,degree1) turtle.turnLeft(sixty) Koch(turtle,length1,degree1) turtle.turnRight(2*sixty) Koch(turtle,length1,degree1) turtle.turnLeft(sixty) Koch(turtle,length1,degree1) def main(): print() print("Let's draw a Koch snowflake") print() degree = int(input("What degree of Koch flake do you want? ")) win = GraphWin("Koch",500,500) win.setCoords(0,0,500,500) win.setBackground("green") win.flush() sixty = 60.0*pi/180.0 myTurtle = Turtle(win,Point(100,150),sixty) # The Koch snowflake is based on applying the Koch # algorithm to each side of an equilateral triangle for i in range(3): Koch(myTurtle,300,degree) myTurtle.turnRight(sixty*2) Text(Point(250,250),"Click in window to close").draw(win) win.getMouse() win.close() main()
64a316993436ab7cfef39757c733cfdd5352a453
ayusha72/PPL_ASSIGNMENT
/Assignment_1/puzzle.py
668
3.78125
4
list_a = ['goat','tiger', 'grass'] list_b = [] import random def safe_check(list_c) : if 'tiger' in list_c and 'goat' in list_c: return False elif 'grass' in list_c and 'goat' in list_c: return False else : return True while len(list_a) != 0 : result = list_a.pop() if safe_check(list_a) == False : list_a.insert(0,result) else : print ('take {}'.format(result)) list_b.append (result) if len (list_b) == 2 and safe_check(list_b) == False : if 'tiger' in list_b and 'goat' in list_b: list_b.remove('goat') elif 'grass' in list_b and 'goat' in list_b: list_b.remove('goat') list_a.insert (0, 'goat') print ('take back goat')
86c8ca8d3f5cbb170d6b14bebf69107533f758ef
Evaldo-comp/Python_Teoria-e-Pratica
/Livros_Cursos/Nilo_3ed/cap05/teste.py
672
3.921875
4
""" Escreva um programa que leia um número e verifique se é ou não um número primo. Para fazer essa verificação, calcule o resto da divisão do número por 2 e depois por todos os números impares até o número lido. Se o resto de uma dessas divisões for igual a zero, o número não é primo. Observe que 0 e 1 não são primos e que 2 é o único primo que é par. """ num = int(input("digite um número")) pri = 0 while pri <= num: x = 3 while (x < 100) : if 100 % x==0 : break x += 2 if x==100 : print(f'{x} é primo') pri+=1 else : print(f'{x} nao é primo, pois é divisivel por {x}')
a4b37a740ae68afb6e74ac5a4e4c2042daf97b49
smohapatra1/scripting
/python/practice/start_again/2021/01172021/credit_card_validation_with_algorithm.py
1,423
4.21875
4
#Validate credit card using modulous-10 algorithm #https://www.codeproject.com/Tips/515367/Validate-credit-card-number-with-Mod-10-algorithm #Card Length #Typically, credit card numbers are all numeric and the length of the credit card number is between 12 digits to 19 digits. #14, 15, 16 digits – Diners Club #15 digits – American Express #13, 16 digits – Visa #16 digits - MasterCard # This is incomplete def validate_card(): cNumber = input("Please enter the card number : ") #get the lenth of number get_len = len(cNumber) print ("Lenth of card number: ", get_len) #Break the number into list place = list(cNumber) #using slice notation get the even and odd places from list even_places = place[1::2] print ("Even places : ", even_places) odd_places = place[0::2] print ("Odd places : ", odd_places) # Now multiply 2 in each of numbers in even place #Step 1 - Starting with the check digit double the value of every other digit (right to left every 2nd digit) sq_num = [num ** 2 for num in str(even_places)] print (sq_num) #If doubling of a number results in a two digits number, #add up the digits to get a single digit number. This will results in eight single digit numbers. #Now add the un-doubled digits to the odd places # Add up all the digits in this number def main (): validate_card() if __name__ == "__main__": main()
1b547f344e13618b977166f9c59e3f58a7b422e9
longngo2002/C4TB
/session9/part1/create.py
109
3.671875
4
a = ['blue','red','yellow'] print(*a,sep=", ") b = input("Enter a new color:") a.append(b) print(*a,sep=", ")
2bb5c97808cddf506f0c16eaabd18413527cfb43
ronak148/Guessing-Number-1
/Youcan.py
798
4.0625
4
# import random print("Let's Play Guessing Number Game") a=int(raw_input("Select your range's Start Number:")) b=int(raw_input("Select your range's Last Number:")) #p#rint(a) #print(b) x = random.randint(a,b) #print(x) #y=range(a,b) #print(y) atp=3 while atp>0: y=int(raw_input("Guess and Enter any Number in your selected range:")) atp-=1 if y!=x: print ("Sorry Try again, you have %d chance left" %(atp)) else : #y==x: print("congratulation you got it") atp=0 #else: #print("Game Over") print"Game Over" #print ("Sorry Try again you have %d left" % (atp)) #y=int(raw_input("Enter Number:")) #if y == x: #print"congratulation" #else: #print('Game Over') #(y!=x): # print ('Sorry Game Over') # print(atp-1)
f658f082f40ca461f36a62f714ebcf58eab08075
Sorochtej/Python---lerning-
/Chapter 3/Ex.1.py
645
4.0625
4
# Divination drawing program. import random print("\tMaybe it's not taste as good as real one but still it have somthing...") print("\nYour divination for next year: ...") fairy_tail = random.randint(1,5) if fairy_tail == 1: print("You will fall in love this year !") elif fairy_tail == 2: print("You will get Mount Everest this year !") elif fairy_tail == 3: print("You will be broke this year") elif fairy_tail == 4: print("Alweys look on the bright side of life ! :) ") elif fairy_tail == 5: print(" Never look back, go straigt with your chest bump up !") input("\n\nAby zakończyć program nacisnij Enter:")
d863c6ccac2370669071527837380acb260fe9ea
phlalx/algorithms
/leetcode/604.design-compressed-string-iterator.python3.py
1,277
3.53125
4
# TAGS datatype, lexer class StringIterator: def __init__(self, compressedString): """ :type compressedString: str """ self.compressedString = compressedString self.i = 0 self.cur_char = None self.n = len(compressedString) self.cur_count = 0 def _getint(self): j = self.i cc = 0 while j < self.n and self.compressedString[j].isdigit(): cc = 10 * cc + int(self.compressedString[j]) j += 1 return j, cc def next(self): """ :rtype: str """ if self.cur_count > 0: self.cur_count -= 1 return self.cur_char elif self.i < self.n: self.cur_char = self.compressedString[self.i] self.i += 1 self.i, self.cur_count = self._getint() assert self.cur_count self.cur_count -= 1 return self.cur_char else: return " " def hasNext(self): """ :rtype: bool """ return self.cur_count > 0 or self.i < self.n # Your StringIterator object will be instantiated and called as such: # obj = StringIterator(compressedString) # param_1 = obj.next() # param_2 = obj.hasNext()
3dc5febdd20184c7948c52e5bd210aa0f1ebb82a
gmeneze/ase16hxx
/project/Code/Route.py
964
3.703125
4
#!/usr/bin/python """ Problem.py (c) 2016 [email protected], [email protected], [email protected]. MIT licence USAGE: python Problem.py OUTPUT: Produces an output in the format of :- """ from __future__ import division,print_function import sys,re,traceback,random, operator, string, time sys.dont_write_bytecode=True class Route(object): def __init__(self, start_node, end_node): self.start_node = start_node self.end_node = end_node self.cost_factor = random.randint(1, 3) self.distance = self.get_distance() self.speed_limit = random.randint(20, 100) def get_distance(self): self.distance = ((abs(self.start_node.xcordinate - self.end_node.xcordinate))**2 + (abs(self.start_node.ycordinate - self.end_node.ycordinate)) ** 2) ** 0.5 return self.distance def get_cost(self): return self.distance * self.cost_factor def get_speed_limit(self): return self.speed_limit
a479b4b135e5ac57886549a8bca8cdfa1c8c8ede
stevenchendan/Grokking-Algorithms-Practice
/PythonSolution/04_quicksort/04_recursive_sum.py
189
3.84375
4
def recursive_sum(list): if list == []: return 0 return list[0] + recursive_sum(list[1:]) if __name__ == "__main__": test_array = [1, 2, 3, 4] print(recursive_sum(test_array))
c5027668aeaa431baef0bbe81b8d0b9701cb67a8
Yuki-hosso/self-taught-python
/sample_str_conect.py
114
3.625
4
s1 = input("what :") s2 = input("who :") r = "私は昨日{}を書いて,{}に送った".format(s1,s2) print(r)
1b4f7ae4ea90057cd087d8e8ceffb450e9c1d768
amir-mersad/ICS3U-Unit3-02-Python
/students.py
486
4.0625
4
#!/usr/bin/env python3 # Created by Amir Mersad # Created on September 2019 # This program checks if there are more there 30 students import constants def main(): # This function checks if there are more than 30 student # Input number_of_students = int(input("Enter the number of students: ")) print("") # Process if number_of_students > constants.MAX_STUDENT_NUMBER: # Output print("Too many students!") if __name__ == "__main__": main()
3f9efdd438c678fd1a92e8d157e69178549e99c6
Roger-ELIAS/IDD
/CSV2SQL.py
2,192
3.671875
4
#lecture d'un fichier CSV -> dataframe -> table SQL import pandas as pd import pandasql as ps import re import sqlite3 #sqlRequest = "SELECT * FROM tournagesdefilmsparis2011 WHERE titre = 'COUP DE FOUDRE A JAIPUR';" class CSV2SQL(): def translateRequest(self, sqlRequest): result = re.search("FROM ([A-Za-z0-9_-]*)", sqlRequest) fileName = (result.group())[5:] newRequest = sqlRequest.replace(fileName, "data") fileName += ".csv" return fileName, newRequest def fileReader(self, fileName): fileName data = pd.read_csv(fileName, sep=';') return data def queryOnData(self, data, sqlRequest): return ps.sqldf(sqlRequest, locals()) def createTable(self, dataFrame, fileName): nomsChamps = list(dataFrame.columns.values) typesChamps = list(dataFrame.dtypes) lignes = dataFrame.values requests = [] nom = fileName.split('.') sqlQuery = '' sqlQuery += 'CREATE TABLE ' + nom[0] + '(' for i in range(0, len(nomsChamps)-1): sqlQuery += nomsChamps[i] + ', ' sqlQuery += nomsChamps[len(nomsChamps)-1] + ');' sqlQuery += '\n' requests.append(sqlQuery) sqlQuery = "" for i in range(0, len(lignes)-1): sqlQuery += 'INSERT INTO ' + nom[0] sqlQuery += ' VALUES (\"' donnees = lignes[i] for i in range(0, len(donnees)-1): sqlQuery += str(donnees[i]) + '\", \"' sqlQuery += (str(donnees[len(donnees)-1])) sqlQuery += '\");' requests.append(sqlQuery) print(sqlQuery + '\n') sqlQuery = "" return requests def executeRequest(self, request): connexion = sqlite3.connect("DatabaseName.db") curseur = connexion.cursor() for i in range(0, len(request)-1): print(i) curseur.execute(request[i]) connexion.commit() print("OPERATION FAITE") '''curseur.execute("SELECT * FROM tournagesdefilmsparis2011") resultat = curseur.fetchall() print(resultat)''' def deleteTable(self, fileName): nom = fileName.split('.') sqlQuery = "DROP TABLE " + nom[0] connexion = sqlite3.connect("DatabaseName.db") curseur = connexion.cursor() curseur.execute(sqlQuery) connexion.commit()
2481a97f228584347704394cdf10b06ae06fea85
jeansyo/Python
/producto_De_matrices_ala_antigua.py
1,104
3.625
4
# -*- coding: utf-8 -*- """ Created on Thu May 7 23:00:47 2020 @author: DELL.E5430.SSD """ p = int(input('Digite el nuemro de filas de A: ')) q = int(input('Digite el numeros de columnas de A,(filas de B): ')) r = int(input('Digite el numeros de columnas de B: ')) matriz_a = [] matriz_b = [] for i in range(p): matriz_a.append([0]*q) for i in range(q): matriz_b.append([0]*r) print() print('Matriz A') for i in range(p): for j in range(q): matriz_a[i][j] = int(input(f'Matriz A; fila {i+1}, columnas {j+1}: ')) print() print('Matriz B') for i in range(q): for j in range(r): matriz_b[i][j] = int(input(f'Matriz B: fila {i+1}, columnas {j+1}: ')) print() matriz_producto = [] for i in range(p): matriz_producto.append([0]*r) # EL CALCULO for i in range(p): for j in range(r): for k in range(q): matriz_producto[i][j] += matriz_a[i][k] * matriz_b[k][j] print('Matriz A') for i in matriz_a: print(i) print() print('Matriz B') for i in matriz_b: print(i) print() print('Matriz C') for i in matriz_producto: print(i)
b142058868beea5bd1469c8eae2f04f616944bd7
PabloYepes27/holbertonschool-higher_level_programming
/0x0B-python-input_output/100-append_after.py
776
4.1875
4
#!/usr/bin/python3 """ Write a function that inserts a line of text to a file, after each line containing a specific string (see example): """ def append_after(filename="", search_string="", new_string=""): """inserts a line of text to a file, Args: filename (str, optional): [description]. Defaults to "". search_string (str, optional): [description]. Defaults to "". new_string (str, optional): [description]. Defaults to "". """ tmp = "" with open(filename, encoding="UTF8") as file: for line in file: if search_string in line: tmp += line[:] + new_string else: tmp += line[:] with open(filename, mode="w", encoding="UTF8") as file: file.write(tmp)
66dbbeb6454327582324c03c276c41ba455ca623
PabloLanza/curso-python3
/exercicios-python/curso-python/ex032.py
574
4.0625
4
import math print('Olá! Bem Vindo ao sistema de conversão numérica.') num = int(input('Digite o número que você deseja fazer a conversão: ')) op = int(input('Você quer converter o número {} para:\n 1 - Binário\n 2 - Octal\n 3 - Hexadecimal\n'.format(num))) if op == 1: print('O número {} em Binário é: {}'.format(num, bin(num)[2:])) elif op == 2: print('O número {} em Octal é: {}'.format(num, oct(num)[2:])) elif op == 3: print('O númer {} em Hexadecimal é: {}'.format(num, hex(num)[2:])) else: print('Opção Inválida! Tente novamente.')
6acb8dcc0e5c2ad1354e71dc40c2f0f7e5cdfd9d
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_203/401.py
1,731
3.671875
4
""" Fill cake with grid initials""" from sys import stdin def find_first_non_quest(row, cols): for i in range(cols): if row[i] != '?': return i return -1 def solve_cakes(rows, cols, grid): # First fill row wise. new_grid = [] for row in grid: # find first character not a ?. If none, leave row. first_non_quest = find_first_non_quest(row,cols) if first_non_quest == -1: new_grid.append(row) continue current_char = row[first_non_quest] new_row = "" # Fill in rows with next adjacent char. for i in range(cols): if row[i] != '?': current_char = row[i] new_row = new_row + current_char new_grid.append(new_row) #now do the same thing column wise grid = [] for i in range(rows): grid.append("") for i in range(cols): column = "" for j in range(rows): column = column + new_grid[j][i] first_non_quest = find_first_non_quest(column, rows) #There should always be one current_char = new_grid[first_non_quest][i] for j in range(rows): if new_grid[j][i] != '?': current_char = new_grid[j][i] grid[j] = grid[j] + current_char return grid def main(): test_cases = int(stdin.readline()) for i in range(1, test_cases + 1): rows, cols = (int(z) for z in stdin.readline().split()) grid = [] for x in range(rows): grid.append(stdin.readline().strip()) result = solve_cakes(rows, cols, grid) print("Case #%s:" % str(i)) for row in result: print(row) main()
c2cc95527d55137b6200da6fbf562c1d809b4bd8
harishb2k/topic
/tenserflow/custom_layer_how.py
2,046
3.75
4
import tensorflow as tf from tensorflow import keras class Linear(keras.layers.Layer): def __init__(self, units=32, input_dim=32): super(Linear, self).__init__() # We should have weights as random - for this case using simple var to debug r = tf.constant([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]) self.w = tf.Variable( initial_value=r, trainable=True, ) b_init = tf.zeros_initializer() self.b = tf.Variable( initial_value=b_init(shape=(units,)), trainable=True ) def call(self, inputs, **kwargs): print("Input") print(inputs) print("W") print(self.w) print("B") print(self.b) return tf.matmul(inputs, self.w) + self.b # Training input - our input has 2 features i.e. we have 2 var input # Example - 2 feature for house cost will be "area", "no of bedrooms" # # Sample 1 - [1.0, 1.0] is first sample e.g. area=1.0, no_of_bedroom=2 # Sample 2 - [2.0, 2.0] is first sample e.g. area=2.0, no_of_bedroom=2 # Sample 3 - [3.0, 3.0] is first sample e.g. area=2.0, no_of_bedroom=3 training_input = tf.constant([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]) # First param = units -> this is 3 in this case i.e. no of samples # Second param = input_dim -> "no of features" or "no of dimension" in our input. Here it is 2 (area, no of bedrooms) linear_layer = Linear(3, 2) # This will call our "call" function y = linear_layer(training_input) # What is done in "call method" # [1. 1.] [1., 1., 1.] [3. 3. 3.] # [2. 2.] * [2., 2., 2.] + "B" = [6. 6. 6.] # [3. 3.] [9. 9. 9.] # Each row in "W" contains xi coefficient for different Neurons # x0[0] = Neuron_1 1st coefficient # x0[1] = Neuron_2 1st coefficient # x0[2] = Neuron_3 1st coefficient # # It seems that each rows in W represents coefficient for only one neurone -> but this is not true. Each row contains # Nth coefficient print(y)
82bf25c4cfc2f37e551abd1582ee757e15999de7
g00364787/52167assessments
/gmit--exercise01--fibonacci--20180123.py
1,390
4.375
4
# AUTHOR = PAUL KEARNEY # DATE = 2018-01-23 # STUDENT ID = G00364787 # EXERCISE 01 # # filename= gmit--exercise01--FIBINACCI--20180123.py # # FINONACCI NUBMERS # Ian McLoughlin # A program that displays Fibonacci numbers. def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i ## define the variables x = 0 y = 0 z = 0 l = 0 i = 0 nam = "" opstr = "" op = "" ## obtain user input nam = input("Your name:") ## process user input l = len(nam) x = ord(str.upper(nam[0])) y = ord(str.upper(nam[l-1])) ## convert ascii to position in alphabet x = x-64 y = y-64 ## display the two letters to operate on print("The two letters to operate on are: ",nam[0], "(",x,") and ",nam[l-1],"(",y,")") ## add the two ''letters'' together z = x+y ## calculate the result ans = fib(z) ## display the result ## print("The Fibonacci number for your name: ", nam, " is: ", ans) op = "My name is " op = op + nam op = op + ", so the first and last letter of my name (" op = op + str.upper(nam[0]) op = op + " + " op = op + str.upper(nam[l-1]) op = op + " = " op = op + str(x) op = op + " + " op = op + str(y) + ") give the number " + str(z) + "." op = op + " The " + str(z) + "th Fibonacci number is " + str(ans) + "." print(op) ## end
b8ece585b18abf2f49e4a981bf2c8c8a4811ce5a
Roshni-jha/ifelse
/equal or not equal .py
111
3.703125
4
# num =int(input("enter the number")) # if num==1000: # print("equal hai") # else: # print("not equal")
33c83a5df2b2f47dc794dd66386a7ed0524c9486
mitpokerbots/playground
/server/pokerbots_parser/bot.py
2,987
3.6875
4
''' This file contains the base class that you should implement for your pokerbot. ''' class Bot(object): def handle_new_game(self, new_game): ''' Called when a new game starts. Called exactly once. Arguments: new_game: the pokerbots.Game object. Returns: Nothing. ''' pass def handle_new_round(self, game, new_round): ''' Called when a new round starts. Called Game.num_rounds times. Arguments: game: the pokerbots.Game object for the new round. new_round: the new pokerbots.Round object. Returns: Nothing. ''' pass def handle_round_over(self, game, round, pot, cards, opponent_cards, board_cards, result, new_bankroll, new_opponent_bankroll, move_history): ''' Called when a round ends. Called Game.num_rounds times. Arguments: game: the pokerbots.Game object. round: the pokerbots.Round object. pot: the pokerbots.Pot object. cards: the cards you held when the round ended. opponent_cards: the cards your opponent held when the round ended, or None if they never showed. board_cards: the cards on the board when the round ended. result: 'win', 'loss' or 'tie' new_bankroll: your total bankroll at the end of this round. new_opponent_bankroll: your opponent's total bankroll at the end of this round. move_history: a list of moves that occurred during this round, earliest moves first. Returns: Nothing. ''' pass def get_action(self, game, round, pot, cards, board_cards, legal_moves, cost_func, move_history, time_left, min_amount=None, max_amount=None): ''' Where the magic happens - your code should implement this function. Called any time the server needs an action from your bot. Arguments: game: the pokerbots.Game object. round: the pokerbots.Round object. pot: the pokerbots.Pot object. cards: an array of your cards, in common format. board_cards: an array of cards on the board. This list has length 0, 3, 4, or 5. legal_moves: a set of the move classes that are legal to make. cost_func: a function that takes a move, and returns additional cost of that move. Your returned move will raise your pot.contribution by this amount. move_history: a list of moves that have occurred during this round so far, earliest moves first. time_left: a float of the number of seconds your bot has remaining in this match (not round). min_amount: if BetAction or RaiseAction is valid, the smallest amount you can bet or raise to (i.e. the smallest you can increase your pip). max_amount: if BetAction or RaiseAction is valid, the largest amount you can bet or raise to (i.e. the largest you can increase your pip). ''' raise NotImplemented("get_action")
2339fdcab9d3cfedd4887d71b31b5ba094b9844d
Hallym-OpenSourceSW/HL_Contributhon
/04_Algorithm/moveZeros.py
722
3.6875
4
""" 배열을 입력 받아서 배열내에 있는 "0" 들을 모두 뒷부분으로 옮기는 알고리즘을 만들어 보세요! 단, 배열내에 "0"이 아닌 요소들의 순서는 지켜져야 합니다. moveZeros(["false", 1, 0, 1, 2, 0, 1, 3, "a"]) returns => ["false", 1, 1, 2, 1, 3, "a", 0, 0] """ def moveZeros(array): result = [] zeros = 0 for num in array: if str(num).isdigit(): if num == 0: zeros += 1 for i in range(zeros): array.remove(0) for i in range(zeros): array.append(0) result = array return result print(moveZeros(["false", 1, 0, 1, 2, 0, 1, 3, "a"])) ## ['false', 1, 1, 2, 1, 3, 'a', 0, 0]
d608654928ecc802b8eec01a2556c2852fafd2ca
IBRAHIMDANS/TeachMePythonLikeIm5
/loops/for-loops.py
1,460
4.6875
5
# ------------------------------------------------------------------------------------ # Tutorial: For-loops in Python # ------------------------------------------------------------------------------------ # We use for loops when we have to access elements in a DS or while working within a range of numbers. # One of the loops which helps us to iterate through a particular DS. anime = ['Luffy', 'Naruto', 'Zoro', 'Midoriya', 'Lelouch', 'Levi', 'Natsu', 'Sanji', 'Shanks', 'Kakashi', 'Kageyama'] # What we have to do is print each of these names in list anime for name in anime: print(name) # This will help you to access and print each of the names in the list. # Alternate length = len(anime) for i in range(length): print(anime[i]) # Also there is an |else| stance for each of the loops so here it is for for-loop: for name in anime: print(name) else: print('Loop has finished') # It gives us a message when the loop is finished. # Practice with the below challenge # ------------------------------------------------------------------------------------ # Challenge: You have given a list of numbers and you have to output how many of the numbers are even and how many are odd. # list = [ 3, 21, 4, 56, 34, 69, 45, 63, 99 ] # Example : list = [ 2, 4, 5, 8, 34, 21 ] # Output:- Odd : 2, Even : 4 # # ------------------------------------------------------------------------------------
4d596c67482d841a01d1c3cb947dd9d1b8cf2c4a
xxcocoymlxx/Study-Notes
/CSC108/labs/lab5_handouts/lab5.py
91
3.78125
4
def every_third(lst): for i in range(len(lst)-1): i += 3 return lst[i]
17046cd3ca794f9cabee660af1d45bb58f7f157e
Noya-santiago/Python-crash-course
/1- Variables and data type/Variables and Data type.py
994
4.34375
4
print("There once was a man named John") print("he was 35 years old.") print("He really liked the name John, ") print("but didnt like being 35") """ Basically there are several types of variables in python. Booleans, Strings, Floats, etc. We can call any variables as the name we want to. Just by typping Variable_name = variable_value the strings variables will be represented with "", booleans with "False or True" and the floats with just numbers. As we can see, i can write exactly the same as before but using variables """ character_name = "John" character_age = 35 print("There once was a man named "+ character_name +", ") print("he was" + str(character_age) + "years old.") #In this scenario we have to change the variable to string because python cant interpet a integer next to a string print("He really liked the name "+ character_name +",") print("but didnt like being "+ str(character_age) +".") # We can also add another Boolean variable is_male = False
9a56ffd0963cd4be42f3c4111ae87c43d0c3a135
TiffanyNicole919/python_week_one
/for_loop_basic1.py
1,172
4.03125
4
# Basic - Print all integers from 0 to 150. # for a in range(0,151) : # print(a) # Print all the multiples of 5 from 5 to 1,000 # for number in range(5,1001) : #if number % 5 == 0 : #print (number) #Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding Dojo". #for x in range(5,101): #if x % 5 == 0: #print("Coding") #else: #x % 10 == 0 #print("Coding Dojo") #Add odd integers from 0 to 500,000, and print the final sum. #max = int(input("please enter the maximum value")) #odd_Sum = 0 #for number in range(1, max + 1): #if(number % 2 == 0): #odd_Sum = odd_Sum + number #print("The sum of odd numbers 0 to {0} = {1}" .format(number,odd_Sum)) #Print positive numbers starting at 2018, counting down by fours. #for x in range(2018, 0, -4): #if x > 0: #print(x) #Set three variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, print only the integers that are a multiple of mult. For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines) lowNum = 2 highNum = 9 mult = 3 for x in range(lowNum, highNum + 1): if x % mult == 0: print(x)
10af638db6cea5cf97b28463a81b3d1266b71f52
nameera0408/Practical-introduction-to-python_Brainheinold
/ch6_3sol.py
440
3.75
4
def check(obj,lst): d={'(':')','{':'}','[':']'} for item in lst: if( item == '(' or item == '{' or item == '[' ): Stk.push(item) elif( item == ')' or item == '}' or item == ']' ): value = Stk.pop() if d[value] != item : return 'Not Balanced' else: continue if Stk.empty(): return 'Balanced' else: return 'Not Balanced'
9a41aa7bb0756d09211df19618e286426e456931
bsivavenu/Machine-Learning
/pythonprograms/compare_arrays.py
536
3.890625
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 27 12:03:57 2018 @author: HP """ def compare(a1,a2): if len(a1)==len(a2): if set(a1)==set(a2): return print("they are same") else: return print("arrays are not same") a1 = [1,2,3] a2 = [3,1,2,4] compare(a1,a2) def compare(a1,a2): if len(a1)==len(a2): for i in a1: if a1[i] in a2: return print("they are same") else: return print("arrays are not same") a1 = [1,4,2,3] a2 = [3,1,2,4] compare(a1,a2)
927c594a8e63c578a56156b6a9c16c84e23bbf82
Triple-Z/Python-Crash-Course
/C11/11.1.py
729
3.5625
4
# 11-1 # import unittest # from C11.city_functions import city_country # # # class CityTestCase(unittest.TestCase): # # def test_city_country(self): # output = city_country('santiago', 'chile') # self.assertEqual(output, 'Santiago, Chile') # # unittest.main() # 11-2 import unittest from C11.city_functions import city_country class CityCountryTestCase(unittest.TestCase): def test_city_country(self): output = city_country('santiago', 'chile') self.assertEqual(output, 'Santiago, Chile') def test_city_country_population(self): output = city_country('santiago', 'chile', 5000000) self.assertEqual(output, "Santiago, Chile - population 5000000") unittest.main()
be2c78ad36ad09cc30f922c96a155ef219fef232
joelambert1/package_delivery
/distance.py
676
3.59375
4
class Distance: def __init__(self, location=None, address=None, distances=None, zipcode=None): self.location = location self.address = address self.distances = distances self.zipcode = zipcode def add_location(self, location): location = location.lstrip().rstrip() self.location = location.lstrip() def add_address(self, address): zipcode = int(address.split('(')[1].replace(')', '')) self.address = address.split('(')[0] def print_all(self): print("location:", self.location, ",", self.address, ",", self.distances) def print_distances(self): print(self.distances)
3dc8971af1ece90efd940995797e8bf6b3157bcc
AnthonyH93/CarScraper
/scripts/car_scraping.py
10,570
3.828125
4
# Function: Scrape Wikipedia for information about a specific car # Author: Anthony Hopkins # Year: 2021 import requests from bs4 import BeautifulSoup from .models.car import Car from random import randrange import time import re headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '3600', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0' } # Class to describe the car scraper class CarScraper: def __init__(self, manufacturer): self.base_url = 'https://en.wikipedia.org' self.manufacturer = manufacturer self.start_url = '' def setup_scraping(self): self.start_url = self.base_url + '/wiki/' + self.manufacturer # Some manufacturers need to add _Cars or other prefixes if (self.manufacturer == 'Jaguar' or self.manufacturer == 'Lotus'): self.start_url = self.start_url + '_Cars' if (self.manufacturer == 'Lincoln' or self.manufacturer == 'Pontiac'): self.start_url = self.start_url + '_Motor_Company' if (self.manufacturer == 'Mercury'): self.start_url = self.start_url + '_(automobile)' if (self.manufacturer == 'Pagani'): self.start_url = self.start_url + '_(company)' if (self.manufacturer == 'McLaren'): self.start_url = self.start_url + '_Automotive' print(self.start_url) def perform_scraping(self): # Get the first data from the start url start_page = requests.get(self.start_url, headers) if (start_page.status_code > 299 or start_page.status_code < 200): print('Invalid request for ' + self.start_url + ' status code was ' + start_page.status_code) exit soup = BeautifulSoup(start_page.content, 'html.parser') all_links = soup.find_all(lambda tag:tag.name == 'a' and 'title' in tag.attrs) # Use a dictionary to ensure links are not repeated simple_hash_table = {} hash_table_counter = 0 links_to_lists = [] # Check if manufacturer has a list of automobiles for link in all_links: if 'List' not in link.get('title'): continue else: # Make sure it is a list of vehicles from the manufacturer if ((self.manufacturer not in link.get('title')) or (('vehicle' or 'car' or 'auto') not in link.get('title'))): continue else: link_to_add = link.get('href') links_to_lists.append(link_to_add) # Decide next URL to scrape next_url = '' if len(links_to_lists) == 0: # Need to find a different link to follow next_url = self.start_url elif len(links_to_lists) > 1: # Need to pick one of the links to follow random_selection = randrange(len(links_to_lists)) next_url = self.base_url + links_to_lists[random_selection] else: # Should have a link to a list of vehicles by the given manufacturer next_url = self.base_url + links_to_lists[0] next_page = requests.get(next_url, headers) if (next_page.status_code > 299 or next_page.status_code < 200): print('Invalid request for ' + next_url + ' status code was ' + next_page.status_code) exit soup = BeautifulSoup(next_page.content, 'html.parser') # Get all links which have a title all_valid_links = soup.find_all(lambda tag:tag.name == 'a' and 'title' in tag.attrs) # Discard all links without the car manufacturer in the title possible_car_links = [] for link in all_valid_links: if (self.manufacturer not in link.get('title')): continue else: found_link = link.get('href') url_to_add = self.base_url + found_link # Ensure links are not duplicated is_new_link = simple_hash_table.get(url_to_add, -1) # Ensure links found build on base url if is_new_link == -1: simple_hash_table.update({found_link: hash_table_counter}) hash_table_counter += 1 if found_link.startswith('/'): possible_car_links.append(url_to_add) else: continue # Explore each potential car link and extract information if a car is found link_counter = 0 cars_found = [] regex = re.compile('[@_,+!#$%^&*()<>?/|}{~:]') for link in possible_car_links: # Keep a link limit to avoid long execution time if link_counter > 25: break # Delay to avoid overloading the server time.sleep(0.1) print(possible_car_links[link_counter]) current_page = requests.get(possible_car_links[link_counter], headers) link_counter += 1 # Skip invalid pages (if any exist) if (next_page.status_code > 299 or next_page.status_code < 200): continue # Determine if page contains a car and act accordingly else: soup = BeautifulSoup(current_page.content, 'html.parser') all_tables = soup.find_all('table', class_='infobox hproduct') if len(all_tables) > 0: print('Might have found a car') # Look through tables for tables that resemble a car for table in all_tables: if table.find('th', class_='fn'): table_title = table.find('th', class_='fn') if (self.manufacturer not in table_title.text.strip()): continue else: # Add this table to the cars found list if it matches the expected form if regex.search(table_title.text.strip().replace(' ', '')) == None: cars_found.append(table) print("Found: " + table_title.text.strip()) else: continue else: continue # Ready to iterate through the rows of the tables to gather car information full_cars_found = [] for car_table in cars_found: # First, get the model of the car car_table_title = car_table.find('th', class_='fn').text.strip() car_manufacturer = self.manufacturer car_model = car_table_title.replace(self.manufacturer, '').replace(' ', '') car_assembly_location = '' car_years_produced = '' car_engine = '' car_transmission = '' car_weight = '' values_found = 2 # Next, get all the rows and iterate through them car_table_rows = car_table.find_all('tr') for car_row in car_table_rows: if car_row.find('th') and car_row.find('td'): car_row_title = car_row.find('th').text.strip() car_row_data = car_row.find('td').text.strip() # Check the row titles for the data needed to create a new car if 'assembly' in car_row_title.lower(): car_assembly_location = car_row_data values_found += 1 elif 'production' in car_row_title.lower(): car_years_produced = car_row_data values_found += 1 elif 'engine' in car_row_title.lower(): car_engine = car_row_data values_found += 1 elif 'transmission' in car_row_title.lower(): car_transmission = car_row_data values_found += 1 elif 'weight' in car_row_title.lower(): car_weight = car_row_data values_found += 1 else: continue else: continue if values_found == 7: print('Fully found a car') # Clean up the data before creating the car object car_assembly_location_final = '' car_years_produced_final = '' car_engine_final = '' car_transmission_final = '' car_weight_final = '' years = car_years_produced.split('[') if len(years) > 0: car_years_produced_final = years[0] else: car_years_produced_final = car_years_produced weights = car_weight.split('[') if len(weights) > 0: car_weight_final = weights[0] else: car_weight_final = car_weight engines = car_engine.split('[') if len(engines) > 0: car_engine_final = engines[0] else: car_engine_final = car_engine transmissions = car_transmission.split('[') if len(transmissions) > 0: car_transmission_final = transmissions[0] else: car_transmission_final = car_transmission locations = car_assembly_location.split('[') if len(locations) > 0: car_assembly_location_final = locations[0] else: car_assembly_location_final = car_assembly_location car_source = self.start_url new_car = Car(car_manufacturer, car_model, car_assembly_location_final, car_years_produced_final, car_engine_final, car_transmission_final, car_weight_final, car_source) # Want unique entries in the full_cars_found list if full_cars_found.count(new_car) == 0: full_cars_found.append(new_car) # Done scraping return full_cars_found
442c91a2690794ed11eef3aec20738a0b002e305
Tedford/Exercism
/python/black-jack/black_jack.py
2,596
4.59375
5
"""Functions to help play and score a game of blackjack. How to play blackjack: https://bicyclecards.com/how-to-play/blackjack/ "Standard" playing cards: https://en.wikipedia.org/wiki/Standard_52-card_deck """ CARD_VALUES = { "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "10": 10, "J": 10, "Q": 10, "K": 10, "A": 1 } def value_of_card(card): """Determine the scoring value of a card. :param card: str - given card. :return: int - value of a given card (J, Q, K = 10, 'A' = 1) numerical value otherwise. """ return CARD_VALUES[card] def higher_card(card_one, card_two): """Determine which card has a higher value in the hand. :param card_one, card_two: str - cards dealt. J, Q, K = 10, 'A' = 1, all others are numerical value. :return: higher value card - str. Tuple of both cards if they are of equal value. """ value_one = value_of_card(card_one) value_two = value_of_card(card_two) return (card_one, card_two) if value_one == value_two else card_one if value_one > value_two else card_two def value_of_ace(card_one, card_two): """Calculate the most advantageous value for the ace card. :param card_one, card_two: str - card (J, Q, K == 10, numerical value otherwise) :return: int - value of the upcoming ace card (either 1 or 11). """ return 11 if value_of_card(card_one) + value_of_card(card_two) < 11 else 1 def is_blackjack(card_one, card_two): """Determine if the hand is a 'natural' or 'blackjack'. :param card_one, card_two: str - cards dealt. J, Q, K = 10, 'A' = 11, all others are numerical value. :return: bool - if the hand is a blackjack (two cards worth 21). """ value_one = value_of_card(card_one) value_two = value_of_card(card_two) return value_one + value_two == 11 and (card_one == 'A' or card_two == 'A') def can_split_pairs(card_one, card_two): """Determine if a player can split their hand into two hands. :param card_one, card_two: str - cards in hand. :return: bool - if the hand can be split into two pairs (i.e. cards are of the same value). """ return value_of_card(card_one) == value_of_card(card_two) def can_double_down(card_one, card_two): """Determine if a blackjack player can place a double down bet. :param card_one, card_two: str - first and second cards in hand. :return: bool - if the hand can be doubled down (i.e. totals 9, 10 or 11 points). """ return 8 < value_of_card(card_one) + value_of_card(card_two) < 12
6b33165a30d50d68a7ac087a9388ea6c334436be
simplymanas/python-learning
/PrimeNumber.py
360
4.25
4
# 7th july 2020 # Manas Dash # else with for loop # the below else: belongs to the for loop # for loop’s else clause runs when no break occurs # Prime number test for n in range(2, 8): for x in range(2, n): if n % x == 0: print (n, ' = ', x, '*', n // x, ', hence', n, 'is not prime') break else: # no factor found print (n, 'is a prime number')
facf974ae105fe8b8b8cfe7de3d735d6a2aed5c3
aravs16/DSA
/Heaps/PriorityQueue.py
1,345
3.734375
4
def max_heapify(A,node_idx,heap_max_idx): left = 2*node_idx+1 right = 2*node_idx+2 largest = node_idx if left <= heap_max_idx and A[left] > A[node_idx]: largest = left if right <= heap_max_idx and A[right] > A[largest]: largest = right if largest != node_idx: A[node_idx],A[largest]= A[largest],A[node_idx] max_heapify(A, largest, heap_max_idx) def build_max_heap(A,l): leaf_start = (l//2)-1 for i in range(leaf_start,-1,-1): max_heapify(A,i,l-1) def heap_max(heap): return heap[0] def extract_max(heap): max = heap[0] heap[0] = heap[-1] heap.pop() max_heapify(heap,0,len(heap)-1) return max def insert_to_heap(A,new): A.append(new) build_max_heap(A,len(A)) def delete_from_heap(A,i): A[i],A[-1] = A[-1],A[i] A.pop() build_max_heap(A,len(A)) def increase_key(A,i,key): if i < 0 or i > len(A): return -1 A[i] = key while i >= 0: if A[i//2] < A[i]: A[i//2], A[i] = A[i], A[i//2] i = i//2 else: break if __name__ == '__main__': A = [3,2,1,4,5,6] build_max_heap(A,len(A)) print(A) print(heap_max(A)) print(extract_max(A)) print(extract_max(A)) print(extract_max(A)) A = [3,2,1,4,5,6] build_max_heap(A,len(A)) increase_key(A,5,9) print(A) print('-'*10) A = [3,2,1,4,5,6] build_max_heap(A,len(A)) delete_from_heap(A,2) print(A) insert_to_heap(A,99) print(A)
0e6944c219b2a2169ae2da42a71a75fa36da1be0
AlexDuo/Pyreview
/components/listgeneator.py
457
3.578125
4
# print([i*2 for i in range(10)]) # #下面的就是生成器 # b= (i+1 for i in range(10000000)) # # # for i in b: # print(i) def fib(max): n,a,b=0,0,1 while n<max: yield b a,b=b,a+b n+=1 userinput = int(input('please input the lenght you want to generate')) f = fib(userinput) while True: try: print(f.__next__()) except StopIteration as e: print('generating stoped',e.value) break
5737e828b22ff155fec40db55eb0204996656eef
marcegeek/frro-soporte-2018-06
/practico_02/ejercicio_03.py
1,409
3.703125
4
# Implementar la clase Persona que cumpla las siguientes condiciones: # Atributos: # - nombre. # - edad. # - sexo (H hombre, M mujer). # - peso. # - altura. # Métodos: # - es_mayor_edad(): indica si es mayor de edad, devuelve un booleano. # - print_data(): imprime por pantalla toda la información del objeto. # - generar_dni(): genera un número aleatorio de 8 cifras y lo guarda dentro del atributo dni. import random class Persona: def __init__(self, nombre, edad, sexo, peso, altura): self.generar_dni() self.nombre = nombre self.edad = edad self.sexo = sexo self.peso = peso self.altura = altura def es_mayor_edad(self): return self.edad >= 18 # llamarlo desde __init__ def generar_dni(self): self.dni = random.randrange(10000000, 100000000) def print_data(self): print('Nombre: {nombre}'.format(nombre=self.nombre)) print('Edad: {edad}'.format(edad=self.edad)) print('Sexo: {sexo}'.format(sexo=self.sexo)) print('Peso: {peso}'.format(peso=self.peso)) print('Altura: {altura}'.format(altura=self.altura)) print('DNI: {dni}'.format(dni=self.dni)) if __name__ == '__main__': p = Persona('Carlos', 42, 'M', 50.0, 1.6) p.print_data() assert p.es_mayor_edad() p.edad = 17 assert not p.es_mayor_edad() p.edad = 18 assert p.es_mayor_edad()
655c1bb56303c8ac6444e4757f108fa5c4b6955a
davidkowalk/UkGov-Company-Harvest
/src/csvhandler.py
871
3.578125
4
import csv def combine_lists(names, creds): combined_list = [["Search Name", "Region", "Found Name", "Website"]] empty_list = [["Search Name", "Region"]] print(names) print(creds) for i in range(len(names)): cred_list = creds[i] if len(cred_list) == 0: name = names[i][0] region = names[i][2] empty_list.append([name, region]) else: for cred in cred_list: name = names[i][0] region = names[i][2] foundname = cred["name"] domain = cred["domain"] combined_list.append([name, region, foundname, domain]) return (combined_list, empty_list) def write_to_csv(list, path="ouput.csv"): with open(path, "w", newline='') as file: writer = csv.writer(file) writer.writerows(list)
fb546d39df90cb86dcf4f16c9f7cda2ffe2fd2e6
acch2016/pythonCanopy
/p4.py
985
3.671875
4
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ceci est un script temporaire. """ from scipy import * #módulos de optimización, algebra lineal, integración, #interpolación from numpy import * #manejo de arreglos y operaciones entre ellos from sympy import * #es para variables simbólicas from math import * #funciones y operaciones matemáticas from cmath import * #números complejos y sus funciones import matplotlib.pyplot as graf #librería gráfica def f(x): y = pow(x,3) + 4*pow(x,2) - 10 return y def cls(): print('\n' *50) #comentario def hola(): print('hola\n' *5) x=4;y=7 if x > y: print ('mayor') elif x < y: print ('menor') else: print ('igual') for x in range(2,4): for y in range(1,4): print ('%d * %d = %d' % (x,y,x*y)) op = double(3.1416) print('%f' %op) op #TODO investigar sizeOf en Python import sys x = 2 size = sys.getsizeof(op) print(size) # DoubleVar (float)
253742af62a5483f6ecfdd9cc06455058c9ee545
codeartisanacademy/wednesday-python
/numbers.py
452
3.90625
4
x = 20 # integer, whole number y = 10 z = 2.50 # float print(type(z)) print(type(x)) print(x + y) result = x - y print(result) division = x/y print(type(division)) print(x * y) print(x % y) print(19 % 4) # module does divide the number and give you the remainder in return print(20 / (5 * 2)) a = "2" b = "3" print(int(a)+int(b)) # built-in function for number rounded_number = round(2.3422) print(rounded_number) print(round(2.3422, 2))
6a5bb8973e356a93ca891b137e49ae83cf26e262
1339475125/algorithms
/get_index_of_num_list.py
221
3.6875
4
""" 数字序列中的某一位数字 """ def get_index_num(str, n): if n < 0: return -1 for k, s in enumerate(str): if k == n: return s print(get_index_num("1231414141414", 3))
a1888350a61a9316678f2d05c3289042563595cb
hanggun/leetcode
/20200521_countSquares.py
1,697
3.78125
4
# -*- coding: utf-8 -*- """ Created on Thu May 21 17:43:18 2020 @author: Administrator """ import numpy as np class Solution(object): def countSquares(self, matrix): """ Using dynamic programming. First pad 0s to the original matrix. Second, compare the current value to top, left and topleft value: 1 if there is 0 a[i-1][j-1] + 1 otherwise using count to sum all the value :type matrix: List[List[int]] :rtype: int """ #create a padding matrix rows = len(matrix) cols = len(matrix[0]) matrix_pad = np.zeros([rows+1, cols+1], dtype=int) #count the submatrices count = 0 #compare to the original matrix for i in range(rows): for j in range(cols): if matrix[i][j] == 0: matrix_pad[i+1][j+1] = 0 else: if matrix_pad[i][j] == 0 or matrix_pad[i][j+1] == 0 \ or matrix_pad[i+1][j] == 0: matrix_pad[i+1][j+1] = 1 count += matrix_pad[i+1][j+1] else: matrix_pad[i+1][j+1] = min(matrix_pad[i][j], matrix_pad[i][j+1], matrix_pad[i+1][j]) + 1 count += matrix_pad[i+1][j+1] return count matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] matrix = [ [0,1,1], [1,1,1], [0,1,1] ] matrix = [ [1,1,1], [1,1,1], [1,1,1] ] solution = Solution() print(solution.countSquares(matrix))
4ec5d8f6beb9c608aa61d1fa37f2923a9890b848
gpreviatti/exercicios-python
/MUNDO_01/Aula_07/Ex08.py
256
4.09375
4
#Escreva um programa que leia um valor em metros e o exiba convertido em centimetros e milimetros metros = float(input('Digite um valor em metros: ')) print('O valor em metros {} tem {} centimetros e {} milimetros'.format(metros, metros*100, metros*1000))
d082820aef2861c4f1ca9130447f27239b2796a8
sBsdu/MAI1103_repo
/day 2/my_file_total_water_need_zoo.py
274
3.5
4
# my file water = 0 my_file = open("zoo2.CSV",'rt') for i in my_file: y = i.split(',') if y[0]=='elephant': water = water+ int(y[2]) if y[0]=='elephant': water = water+ int(y[2]) print"total water need for elephant is =",water
9a0311b2be09b89844a79754f2dc9f84eb47fdce
serykhelena/sand_box
/py_algorithms/insertion_sort.py
734
4.15625
4
import random import time ''' Algorithm complexity is O(n^2) https://tproger.ru/translations/sorting-algorithms-in-python/ ''' def insertion_sort(data): # assume that first element is already sorted for d in range(1, len(data)): item_to_insert = data[d] # index of previous element j = d - 1 while j >= 0 and data[j] > item_to_insert: data[j+1] = data[j] j -= 1 data[j+1] = item_to_insert return data def runner(): start = time.time() rand_list = random.sample(range(10), 5) print(f"The innitial data: {rand_list}") result = insertion_sort(rand_list) print(f"The result data: {result}") end = time.time() print(f"Time of execution: {round(end - start, 5)} s") if __name__ == "__main__": runner()
98cb1e03df7cf8675840570ba4ca17f7b2ff5f8d
walkuper/walkup
/srp.py
3,782
3.71875
4
import random print("歡迎來訓練拍國古拳法:猜拳!") human_name = str(input("請輸入名號:")) print("拍國古拳法 Beta Come 大師對上 " + human_name + " 選手!") human_score = computer_score = 0 round_x = wb = 0 human_boxing = computer_boxing = ["scissors","paper","rock"] def round_fight(r): global wb if human_score < 3 and computer_score < 3: r = r + 1 print("第 "+ str(r) +" 回合。") wb = 0 human_go(human_name) else: whoIsWinner(human_score,computer_score,r) def boxing (temp): global wb if temp.isdecimal(): if int(temp) >= 1 and int(temp) <= 3: hb = human_boxing[int(temp) - 1] return hb else: wb = wb + 1 human_go(human_name) else: if temp.upper() == "S": temp = 1 hb = human_boxing[int(temp) - 1] return hb elif temp.upper() == "P": temp = 2 hb = human_boxing[int(temp) - 1] return hb elif temp.upper() == "R": temp = 3 hb = human_boxing[int(temp) - 1] return hb else: wb = wb + 1 human_go(human_name) def battle (hb,cb): global human_score global computer_score global round_x if hb == "scissors" and cb == "paper" or hb == "paper" and cb == "rock" or hb == "rock" and cb == "scissors": human_score = human_score + 1 print(human_name + " 選手的 " + hb + " 擊中 Beta Come 大師!\n比數 " + str(human_score) + ":" + str(computer_score) + "\n") round_x = round_x + 1 elif cb == "scissors" and hb == "paper" or cb == "paper" and hb == "rock" or cb == "rock" and hb == "scissors": computer_score = computer_score + 1 print(human_name + " 選手中了 Beta Come 大師一招 " + cb + "!\n比數 " + str(human_score) + ":" + str(computer_score) + "\n") round_x = round_x + 1 else: print(human_name + " 選手和 Beta Come 大師都用了 " + hb + " 擋下了對方攻擊!\n比數維持 " + str(human_score) + ":" + str(computer_score) + "\n") round_x = round_x + 1 round_fight(round_x) def human_go(n): temp = input("還請 " + str(n) + " 選手請出拳:\n1. (S)cissors; \n2. (P)aper; \n3. (R)ock \n") if wb >= 1 else input(str(n) + " 選手請出拳:\n1. (S)cissors; \n2. (P)aper; \n3. (R)ock \n") hb = boxing(temp) if hb != "": battle(hb,computer_go()) else: return def computer_go(): cb = computer_boxing[random.randint(1,3) - 1] return cb def whoIsWinner(hs,cs,rx): if hs > cs : print("恭喜 " + human_name + " 練成拍國古拳法!\n以 "+ str(hs) +" 比 "+ str(cs) + " 在 " + str(rx) + " 回合擊敗 Beta Come 大師!") continue_game = input("是否結束? 1. 是; 2. 否。") else: print("恭喜 Beta Come 大師以 "+ str(hs) +" 比 "+ str(cs) + " 在 " + str(rx) + " 回合擊敗 " + human_name + "!\nBeta Come 大師對 " + human_name + "說:「回家耕田吧!」") continue_game = input("是否雪恥? 1. 否; 2. 是。") playAgain (int(continue_game)) def playAgain (continue_game): global human_score global computer_score global round_x if continue_game == 1: print("有空再來!") round_x = 0 human_score = 0 computer_score = 0 return elif continue_game == 2: round_x = 0 human_score = 0 computer_score = 0 round_fight(round_x) else: print("來亂的,掰掰") round_x = 0 human_score = 0 computer_score = 0 return round_fight(round_x)
d8110188d8451df4bf041d9923ac7f03b9bc1ac6
kasra-najafi/Tiny-Python-Projects
/Some Exercises/6.py
222
3.84375
4
def f(le, he): print((he-1)*' ' + le*'*') for i in range(2, he): print((he-i)*' ' + '*' + (le-2)*' ' + '*') print(le*'*') le = int(input('Enter length: ')) he = int(input('Enter heigth: ')) f(le, he)