text
stringlengths
37
1.41M
print("Donam el radi de la circunferencia") entrada1=input() radi=int(entrada1) import math print("la seva area es",math.pi*radi**2) print("el seu perimetre es:",2*math.pi*2)
import numpy as np import matplotlib.pyplot as plt import innout as io def plot_cities(cities, route): plt.ion() plt.figure() #plt.scatter(cities[:,0], cities[:,1], s=1, c='black', alpha=0.5) plt.plot(cities[route[0],0], cities[route[0],1], c='red', alpha=0.5) plt.axis('tight') plt.hold(True) ...
# Вывод приветствия. # Здесь мы создаем две функции, которые вызываются из третьей функции. # Здесь мы можем рассмотреть работу стека вызовов. # ---------- # Printing greetings. # Here we create two functions, that are called by the third function. # Here we can see how a call stack works. # Создаем функцию "how_are_...
from random import randint as random print('welcome mubas') ''' this program is called dice rolling simulator the program will randomly pick a number from 1 - 6 and ask the user if he will like to continue or not ''' while True: first_num = random(1, 6) second_num = random(1, 6) print(f'(...
import datetime class Person: def __init__(self, name, age): super().__init__() self.name = name self.age = age @staticmethod def is_teen(age): """This is a toolbox function - it does not affect class properties""" return age in range(13, 20) def check_teenage...
from dogClass import Dog patient1 = Dog() patient2 = Dog() patient3 = Dog() patient4 = Dog() patient5 = Dog() currentPatients = [patient1, patient2, patient3, patient4, patient5] currentRoster = [patient1.name, patient2.name, patient3.name, patient4.name, patient5.name] def printCurrentRoster(): counter = 1 ...
from threading import Thread,Lock import time num = 0 def test1(): global num mutex.acquire() for x in range(1000000): num += 1 mutex.release() print("---test1---num=%d"%num) def test2(): global num mutex.acquire() for x in range(1000000): num += 1 mutex.release() print("---test2---num=%d"%num) mutex...
def single_letter_count(string,letter): return string.lower(). count(letter.lower()) print(single_letter_count('sangram','A')) def multiple_letter_count(string): return {letter: string.count(letter) for letter in string} print(multiple_letter_count('sojoeijeoaioie')) def multiple_letter_count1(stringg): ...
def str (name): return "hello, to" + name print ("A sweet"), str("Eleni") if not true: print "haha" if (2*2)>2: print "hoho" if str("Eleni") != b: print "haha" def add(a,b): return a+b x = 0 if not false and (true and false) or false: print x if ((add(1,2))-- != 3) and (not...
operations = { 1: '+', 2: '-', 3: '*', 4: '/' } try: # Displaying the possibilities for key, value in operations.items(): print(f"Enter {key} to perform {value} operation") user_input = int(input()) # Taking Numbers from user first_num = int(input("Enter the f...
class Employee: number_of_leaves=8 def __init__(self,name,salary,role): self.name=name self.salary=salary self.role=role def printdetail(self): return f"The name is {self.name}.\nsalary is {self.salary}.\nrole is {self.role}" @classmethod def change_leaves(cls,newle...
class Parent: def __init__(self,name): print('Parent__init__',name) class Parent2: def __init__(self,name): print('Parent2__init__',name) class Child(Parent2,Parent): def __init__(self): print('Child__init__') super().__init__('max') child=Child() print(child.__dict__) pr...
from array import * vals=array('i',[2,3,4,5]) for i in range(4): print(vals[i]) # # for i in vals: # print(i) # # for i in range(len(vals)): # print(vals[i])
# -*- coding: utf-8 -*- """ Nelson: Exercise 2.7 Created on Thu Nov 13 11:17:48 2014 @author: sbroad """ import numpy as np import matplotlib.pyplot as plt """ Calculate demand on any given day according to the data in the book. """ inv_f = np.array([415,704,214,856,620,353,172,976,735,433,217,860,598,833]) orde...
# -*- coding: utf-8 -*- """ Exponential least squares Created on Fri Aug 22 11:41:12 2014 @author: sbroad """ import numpy as np import matplotlib.pyplot as plt # the x and y data x = np.array([0.0, 1.0, 2.0, 3.0, 4.0]) y = np.array([0.12, 0.24, 0.72, 1.30, 1.90]) # plot this data plt.plot(x, y, '+') # compute th...
# -*- coding: utf-8 -*- """ Created on Fri Oct 17 10:00:49 2014 @author: sbroad """ import numpy as np import matplotlib.pyplot as plt def empirical_cdf(xvals,data=np.random.random(50)): """ Compute the cumulative probabilities of possible outcomes of a random variable, given an empirical data set as ...
import random SUIT_LIST = ["♠", "♥", "♦", "♣"] RANK_DICTIONARY = { "A": 11, # Special case - sometimes this can be 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} def create_card_deck(): card_deck = [] for suit in SUIT_LIST: for rank in ...
from AIPlayer import AIPlayer from HumanPlayer import HumanPlayer from GameBoard import GameBoard def main(): clear_screen() print('Welcome to our Naughts & crosses game. Do you feel lucky punk?') while True: play_game() if players_are_bored(): break def play_game(): gl...
import pygame from Cell import Direction from Point import Point class Player: def __init__(self, maze, location): self.maze = maze self.point = Point(location) self.colour = pygame.Color("yellow") self.direction = Direction.UP self.look() def look(self): dire...
def main(): x1,y1,x2,y2 = eval(input("Enter two points x1, y1, x2, y2: ")) p2 = Point(x2,y2) p1 = Point(x1,y1) distance = p2.distance(p1) print("The distance between the two points is: "+format(distance,"0.2f")) if(p2.isNearBy(p1)): print("The two points are near each other") else: ...
n1,n2 = eval(input("Enter two integers to find their GCD: ")) gcd_found = False if n1 > n2: d = n2 else: d = n1 while d > 1: if n1%d == 0 and n2%d == 0: gcd_found = True print("The GCD of ",n1," and ",n2," is ",d) break d -= 1 if not gcd_found: print("The GCD of ",n1...
number_elements = eval(input("Enter the number of elements: ")) numbers = [] for count in range(number_elements): number = eval(input("Enter a number: ")) numbers.append(number) rev_numbers = [] for count in range(len(numbers),0,-1): rev_numbers.append(numbers[count-1]) print("Entered Elements: ",n...
import time class Time: def __init__(self): total_seconds = int(time.time()) self.__second = total_seconds % 60 total_minutes = total_seconds // 60 self.__minute = total_minutes % 60 total_hours = total_minutes // 60 self.__hour = total_hours % 24 def getHou...
def sumDigits(n): digit = n%10 rem = n//10 if n != 0: return digit + sumDigits(rem) else: return 0 input_int = eval(input("Enter an integer: ")) print("The sum of digits in ",input_int," is ",sumDigits(input_int))
str1 = input("Enter the first string: ").strip() str2 = input("Enter the second string: ").strip() def isASubstring(s1, s2): index_start = 0 rem_len = len(s2) while len(s1) <= rem_len: if s1!= s2[index_start : index_start + len(s1)]: index_start += 1 rem_len += 1 el...
import turtle turtle.pensize(2) turtle.penup() turtle.goto(-120, -120) turtle.pendown() turtle.color("black") for grid_square in range(0,4,1): turtle.forward(240) turtle.left(90) for y_axis in range(-120, 90, 60): for x_axis in range(-120, 120, 60): turtle.penup() turtle.goto(x_axis, y...
import random random_card_number = random.randint(0, 51) rank_number = random_card_number % 13 if rank_number == 0: rank = "Ace" elif rank_number == 10: rank = "Jack" elif rank_number == 11: rank = "Queen" elif rank_number == 12: rank = "King" else: rank = str(rank_number) suit_number = rand...
def bubbleSort(lst): for i in range(len(lst)): for j in range(len(lst)-1,i,-1): if lst[i] > lst[j]: temp = lst[j] lst[j] = lst[i] lst[i] = temp print(lst) input_list = input("Enter a list of 10 numbers: ") input_items = input_list.split() l...
import numbers import collections import abc x = 30 y = [20, 30] print(type(x)) def f(x): if isinstance(x, int): x += 20 if isinstance(x, list): x += [20] return x print(f(x)) print(x) print(f(y)) print(y)
raspuns_corect = "is reading" raspuns_primit = "" numar_raspunsuri = 0 limita_raspunsuri = 3 limita_depasita = False puncte = 10 print("") print("Pune verbele din paranteza la Prezent Continuu.") print("") print("Exemplu: My sister (watch) is watching TV.") print("") while raspuns_primit != raspuns_corec...
import secrets import string def password_generator(length): chars = string.ascii_letters + string.digits + string.punctuation pwd = ''.join(secrets.choice(chars) for _ in range(length)) print('The password generated by python is:', pwd) length = int(input('Enter the length of the password: ')) p...
# List project on inviting guest for dinner # If you could invite anyone, living or deceased, to dinner, who # would you invite? Make a list that includes at least three people you’d like to # invite to dinner. Then use your list to print a message to each person, inviting # them to dinner. # guest = ['raj', 'dhruv',...
## NICHOLAS BROWN ## CPS 300 def one (): # replace this for-loop with a while loop # don't change any more than is necessary ## for j in range(20): ## print ("{0:2} x 2 = {1:<2}".format(j,j*2)) ## j = 0 while j < 20: print ("{0:2} x 2 = {1:<2}".format(j,j*2)) j+=1 def...
# # Name: Nicholas Brown # CPS 300 # Homework 1 # # Use this program and the accompanying library graphics.py to draw a house # from graphics import * ################################################################# # # Refinement Task 1: Allow user to set colors # ##################################################...
#!/usr/bin/env python import itertools sums = {} sums[1] = 1 sums[2] = 1 def flatten(listOfLists): return itertools.chain.from_iterable(listOfLists) def combs(n): if n == 1: combs = [1] else: if n == 2: combs = [1, 1] else: combs = [] for k ...
#!/usr/bin/python2.7 from utils import isprime def p(n, c): return n*n + c if __name__ == "__main__": limit = 1000000 cs = (3, 7, 9, 13, 27) print "Generating groups" groups = [[n, p(n, 1)] for n in xrange(limit) if isprime(p(n,1))] for c in cs: groups = [item + [p(item[0], c)] for it...
#!/usr/bin/python def sumdigs(num): return sum(map(lambda x: int(x), str(num))) if __name__ == "__main__": m = 0 for a in xrange(1,100): for b in xrange(1,100): num = pow(a,b) s = sumdigs(num) if s > m: print a,b,s m = s
import os import sys def main(): # return usage information and exit if incorrect number of command-line arguments if len(sys.argv) != 2: exit("Usage: python bleep.py dictionary") filename = sys.argv[1] # return error message if dictionary file does not exit if not os.path.isfile(filenam...
#Specifying types isn't commonly seen in Python as Python does not make you statically type. #In the line below we define the subtraction function. We specify that Five and ten are integers and that the result should be an integer as well. def subtraction(five: int, ten: int) -> int: print (ten - five) subtractio...
#Requests is a library that you can use to make API calls. import requests from bs4 import BeautifulSoup #This line creats the get request page = requests.get('https://michaellevan.net') #This line pulls all of the content form the entire website. soup = BeautifulSoup(page.content, 'html.parser') #This line gets th...
participants = 62 if participants < 50: print('it is not busy here') elif 30 <= participants < 40: print('at least some are here') elif 20 <= participants < 30: print ('I expected more than that') elif 50 <= participants < 70: print ('I like it') # if not enough people are around, be critical def hi(): ...
# -*- coding: utf-8 -*- #listeler değiştirilir tuplelar değiştirilmez. ogrenci1 = "Engin" ogrenci2 = "Derin" ogrenci3 = "Salih" ogrenciler = ["Engin","Derin","Salih"] ogrenciler.append("Ahmet") # append ekleme yapar. ogrenciler[0] = "Veli" print(ogrenciler[3]) ogrenciler.remove("Salih") # .remove kaldırır. print(o...
from random import sample, shuffle def myshuffle(str): l = list(str) shuffle(l) result = ''.join(l) return result print("Welcome to The Game of Guesses!") print("The purpose of the game is to guess the number I'm thinking. There are a few rules to play this game:") print("1- The number in my mind will...
# -*- coding: utf-8 -*- # [] bir listedir. lights = ["red","yellow","green"] currentLight = lights[0] print(currentLight) if currentLight == "red": print("STOP!") if currentLight == "yellow": print("READY!") if currentLight == "green": print("GO!")
# -*- coding: utf-8 -*- def topla(sayi1,sayi2): return sayi1 + sayi2 def cikar(sayi1,sayi2): return sayi1 - sayi2 def carp(sayi1,sayi2): return sayi1 * sayi2 def bol(sayi1,sayi2): return sayi1 / sayi2 print("Operasyon:") print("=======================") print("1 : Topla") print("2 : Çıkar") print(...
from typing import List def maxProfit(prices: List[int]) -> int: # arg - got bitten by 0 in a boolean context holding = False transactions = [] buyAt = None sellAt = None for idx in range(len(prices)-1,-1,-1): today = prices[idx] if not holding: sellAt = today ...
def merge(nums1, n, nums2, m): q = len(nums1)-1 def push(k): for i in range(q, k, -1): nums1[i] = nums1[i-1] n1idx = 0 n2idx = 0 mCount = 0 while n2idx < n and mCount < m: print(f"{n1idx},{n2idx},{nums1}") n1 = nums1[n1idx] n2 = nums2[n2idx] ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # okay that's ugly, and shortcuts were taken. but it passed! def generateTrees(self, n: int) -> List[Tre...
def firstBadVersion(n: int): """ :type n: int :rtype: int """ start, end = 1, n while True: midpoint = start + (end-start) // 2 if isBadVersion(midpoint): # then it must be before end = midpoint else: # then it's after...
def removeDuplicates(nums: List[int]) -> int: count = 0 curr = None for elem in nums: if elem == curr: next else: curr = elem nums[count] = curr count += 1 return count
# Problem Set 4 # Name: Alvin Zhu # Collaborators: # Time Spent: 5:30 # Late Days Used: 0 import matplotlib.pyplot as plt import numpy as np from ps4_classes import BlackJackCard, CardDecks, Busted ############# # PROBLEM 1 # ############# class BlackJackHand: """ A class representing a game of Blackjack. ...
# 6.0002 Problem Set 2 # Graph Optimization # Name: Alvin Zhu # Collaborators: # Time: 4 # # A set of data structures to represent the graphs that you will be using for this pset. # class Node(object): """Represents a node in the graph""" def __init__(self, name): self.name = str(name) def get_na...
''' 定义一个学生类,用来形容学生 ''' # 定义一个空的类 class Student(): # 一个空类,pass 代表直接跳过 # 此处pass 必须有 pass # 定义一个对象 # mingyue 就是一个对象,属于Student()类中的一个个体 mingyue = Student() # 在定义一个类,用来描述听python的学生 class PythonStudent(): # class关键字 + PythonStudent() 类名单词首字母大写 + 冒号: # 用None 给不确定的值赋值 # 定义变量的属性名及赋值 name = None ...
# -*- coding:utf-8 -*- from collections import Iterable #Iterable print(isinstance([],Iterable)) print(isinstance('abc',Iterable)) #Iterator from collections import Iterator print('Iterator') print(isinstance((x for x in range(10)),Iterator)) #True print(isinstance([],Iterator)) #False print("把Iterable变成Iterator可以使用ite...
# -*- coding:utf-8 -*- # print("__str__方法:") class Student(object): def __init__(self,name): self.name = name def __str__(self): return 'student[name:%s]' % (self.name) s = Student("ZhangSan") print(s) # print("__iter__()方法:斐波那契数列") class Fib(object): def __init__(self): self.a,self...
# -*- coding:utf-8 -*- from enum import Enum print("定义一个月份的枚举:") Month = Enum('MonthTest', ('Jan','Feb','Mar','Apr','May','Jun','Aug','Sep','Oct','Nov','Dec')) for name,member in Month.__members__.items(): print(name,'==>',member,',',member.value) print(Month.Feb, Month.Feb.value) #MonthTest.Feb 2 print("如果想要更精确的...
# -*- coding:utf-8 -*- age=20 if age>=18: print("可以枪毙了!") print("冒号下面所有缩进的代码是一个代码块。") age=16 if age>=18: print("18岁以上") elif age>14: print("大于14小于18岁") else: print("还不满14岁") l1 = [] print("对于0、空字符串、空list,都等于False") if l1: print(True) else: print(False) print("输入进行if判断:") birth=inp...
# -*- coding:utf-8 -*- print("打印方法的名称:") def now(): print('now 方法内部。') f = now f() print(now.__name__) print(f.__name__) print("定义一个打印日志的装饰器:") def log(func):#接收一个函数作为参数,并返回一个函数 def wrapper(*args, **kw): print("call %s():" % func.__name__) return func(*args, ** kw) return wrapper @log def test1():#把@log放在test...
# -*- coding:utf-8 -*- #切片 L=[1,2,3,4,5,6,7] print(L[0:3])#[0:3]前包后不包,取了0、1、2三个位置的三个数 print(L[-2:])#倒数第一个是-1 L100 = list(range(100)) print(L100) # print("前10个数,每两个取一个:") print(L100[:10:2]) # print("所有数,每五个取一个:") print(L100[::5]) # print("原样复制一个list:") L100Copy = L100[:] print(L100Copy) #迭代 for ch in 'ABC': print(ch...
#!/usr/bin/python3 from sys import argv if __name__ == "__main__": narg = len(argv) - 1 args = "argument" if narg == 1 else "arguments" if narg == 0: print('{} {}.'.format(narg, args)) else: print('{} {}:'.format(narg, args)) for idx, arg in enumerate(argv): if idx != 0: ...
import tweepy import csv #Twitter API credentials consumer_key = "IWSVC6OEOK41wPBtwJPNXQAT4" consumer_secret = "8DOZOOmT2gQN3CVnQ0MCXghyif3m3R80AFQPSU2y5Fa5D2DX9K" access_key = "4360002133-HIi8Mun9T1Ig61XcCKPGZBJIUsWQ5KR8q6OiGsc" access_secret = "CtwLUfKqg8jl7LYuuOXD7vgJVfqJz9MKIeZ2XWrHKzOq0" def get_all_tw...
# persons = {'Jack':34, 'Anna':27} # # for item in persons.items(): # # print(item) # persons_other = {'Anna':42, 'Jack':67,} # persons.update(persons_other) # print(persons) products = [{"name": "water", "price": 12, "title": "bonaqua"}, {"name": "bread", "price": 9, "title": "Whitebread"}, ...
# 2)You're given strings J representing the types of stones that are jewels, and S representing the # stones you have. Each character in S is a type of stone you have. You want to know how many of the # stones you have are also jewels. # The letters in J are guaranteed distinct, and all characters in J and S are lett...
import math oz = float(raw_input("Enter an amount in ounces: ")) lb = oz * 0.0625; print(str(oz) +"oz is "+str(lb)+" lbs")
""" Напишите простой калькулятор, который считывает с пользовательского ввода три строки: первое число, второе число и операцию, после чего применяет операцию к введённым числам ("первое число" "операция" "второе число") и выводит результат на экран. Поддерживаемые операции: +, -, /, *, mod, pow, div, где mod — это вз...
""" Вам дается текстовый файл, содержащий некоторое количество непустых строк. На основе него сгенерируйте новый текстовый файл, содержащий те же строки в обратном порядке. Пример входного файла: ab c dde ff Пример выходного файла: ff dde c ab """ # Первый вариант # lst = [] # with open('file.txt', 'r') as file: # ...
""" Напишите программу, которая считывает список чисел lstlst из первой строки и число xx из второй строки, которая выводит все позиции, на которых встречается число xx в переданном списке lstlst. Позиции нумеруются с нуля, если число xx не встречается в списке, вывести строку "Отсутствует" (без кавычек, с большой бук...
"""Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.""" import nu...
"""Write a function that computes the running total of a list.""" def total_of_list(L): total = 0 for i in L: total += i return total # Test test_list = [-5, -10, -15, 1, 10, 11, 14, 2, 4, 7] x = total_of_list(test_list) print(x)
"""Write a function that combines two lists by alternatingly taking elements, e.g. [a,b,c], [1,2,3] → [a,1,b,2,c,3].""" def combine_two_lists_alternatingly(L1, L2): L = [] for i, j in zip(L1, L2): L.append(i) L.append(j) return L a = ['a','b','c'] b = [1,2,3] print(combine_two_lists_alte...
#problem-a '''a=int(input("Enter the height of the triangle:")) for i in range(1,a+1): for j in range(5): print('*',end='') print('\n') for i in range(1,a+1): print('*'*a)''' #Problem-b '''a=int(input("Enter the height of the triangle:")) for i in range(1,a+1): for j in range(i): prin...
s=input("Enter the string:") a=int(input("Enter the value of n:")) for i in range(len(s)): print(s[i+a-len(s)],end='')
n = int(input()) wardrobe = {} items = [] while n > 0: items = [] n -=1 user_input = input().split(' -> ') key = user_input[0] values = user_input[1].split(',') if key not in wardrobe.keys(): wardrobe[key] = values else: wardrobe[key] += values user_input3 = input().split...
book = {} user_input = input().split(' : ') while user_input[0] != 'Over': if user_input[1].isdigit(): value = user_input[1] key = user_input[0] book[key] = value else: value = user_input[0] key = user_input[1] book[key] = value user_input = input().split(...
class Human: def __init__(self, first_name, last_name): self.first_name = first_name self.last_name = last_name @property def first_name(self): return self.__first_name @first_name.setter def first_name(self, value): for i in value: if i.isupper(): ...
import math class Point: def __init__(self, x:int, y:int): self.x = x self.y = y def create_point(self): point = [self.x, self.y] return point @staticmethod def calculate_distance(point_1:[], point_2:[]): side_a = abs(point_1.x - point_2.x) side_b = ab...
user_input = input() count_of_letters = {} for item in user_input: if item in count_of_letters: count_of_letters[item] += 1 else: count_of_letters[item] = 1 for key,value in count_of_letters.items(): print(f'{key} -> {value}')
class Zadacha(): my_number = input() def calculate(self): sum_even = 0 sum_odd = 0 for i in self.my_number: if i == '-': continue i = int(i) if i % 2 == 0: sum_even += i if i % 2 != 0: ...
##zadacha2 part 1 CountReal user_input = list(map(float, input().split())) #user_input = [8, 2.5, 2.5, 8, 2.5] my_dict = {} for num in user_input: counter = user_input.count(num) my_dict[num] = counter my_dict_sorted = sorted(my_dict.items()) for item in my_dict_sorted: print(f'{item[0]} -> {item[1]} t...
##optimized banking system class BankAccount: def __init__(self, name:str, bank:str, balance:str): self.name = name self.bank = bank self.balance = balance def sort_data(self): pass def __str__(self): return f'{self.name} -> {self.balance} ({self.bank})' def col...
user_input = input().split(' -> ') data_dict = {} while user_input[0] != 'login': key = user_input[0] value = user_input[1] data_dict[key] = value user_input = input().split(' -> ') login_attempt = input().split(' -> ') failure = 0 while login_attempt[0] != 'end': if login_attempt[0] in data...
smallest = 0 i = 20 numbers = [i for i in range(10, 21)] # bogus solution; will update with prime factorization def isDivisible(n, numbers): for number in numbers: if n % number != 0: return False return True while smallest == 0: if isDivisible(i, numbers): smallest = i ...
file=input('Enter file name:\n') x=open(file,'rt',encoding='UTF8') text=x.read() list=[] for c in text: list.append(ord(c)) for c in range(len(list)): list[c]=128-list[c] for c in range(len(list)): list[c]=chr(list[c]) print(list) for c in list: print(c[::-1],end=" ") x.cl...
from datetime import date def meetup_day(year, month, weekday, day): """ year: int month: int weekday: str, full name of weekday (e.g, "Monday", "Sunday") day: str, nth occurance of day (e.g., 1st, 2nd, 3rd, etc) or "last" """ if day == 'teenth': searchRange = range(13, 20) elif...
def is_isogram(word): wordLow = word.lower() charCount = {} for char in wordLow: if char in 'abcdefghijklmnopqrstuvxyz': if char in charCount and charCount[char] > 0: return False else: charCount[char] = 1 return True
#C:/Anadonda/python.exe import numpy as np from FuncionesI import * print("########## BIENVENIDO AL MULTIPLICADOR DE MATRICES ##########") print("Solo se permite operar dos matrices.") print("Recuerde que la cantidad de columnas de la primera matriz debe de ser \ igual al número de filas de la segunda matriz.") canti...
#!/usr/bin/env python3 """ Author : mattmiller899 Date : 2019-03-14 Purpose: Rock the Casbah """ import argparse import sys # -------------------------------------------------- def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Bottles of beer song', ...
# coding: utf-8 """ 判断点是否在多边形内 Reference: http://www.cnblogs.com/yym2013/p/3673616.html """ class Point(object): def __init__(self, x, y): self.x = float(x) self.y = float(y) # 求p1p0和p2p0的叉积,如果大于0,则p1在p2的顺时针方向 def multiply(p1, p2, p0): return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x)...
# efficient way to multiply two numbers say x, y # let x = 10^(n/2)a + b # and y = 10^(n/2)c + d # then the product x*y can be recursively computed as # => xy = 10^(n)ac + 10^(n/2)(ad + bc) + bd # but we know, (a + b)(c + d) = ac + bd + ad + bc # using this we can reduce the number of calls from 4 to 3 # => xy = 10^(n...
def readFile1(fileName): with open(fileName) as file: data = file.read() print(data) def readFile2(fileName): with open(fileName) as file: data = file.read() while True: print(data) for i in range(10): print(data) def readFile3(fileName): with open(...
#PYTHON 3 #NOT PYTHON 2 def scoreVal(state): if uin[0] == uin[1] and uin[1] == uin[2]: return -10 elif uin[2] == "B" and uin[1] == "A": if uin[0] == "L": return 10 return 2 elif uin[2] == "B" and uin[1] == "L": if uin[0] == "M": return 20 return 2 elif uin[2] == "M" and uin[1] != "M": return 1 e...
#!/usr/bin/env python3 def revLine(line): """Reverse the words in a line of text""" simpleLine = line.strip() words = simpleLine.split() revWords = reversed(words) newLine = ' '.join(revWords) return newLine # Read lines of text from a file, reverse it and then write to output from sys import...
leeftijd= eval(input('Wat is je leeftijd: ')) paspoort= input('Ben je in het bezit van een nederlandse paspoort: ')=='ja' if leeftijd >= 18 and paspoort==True: print('Gefeliciteerd, je mag stemmen!')
stations = ['Schagen', 'Heerhugowaard','Alkmaar','Castricum','Zaandam','Amsterdam Sloterdijk','Amsterdam Centraal','Amsterdam Amstel','Utrecht Centraal','’s-Hertogenbosch','Eindhoven','Weert','Roermond','Sittard','Maastricht'] def inlezen_beginstation(stations): beginstation = input('Voer hier uw vertrekpunt ...
def swap(lijst): if len(lijst) >1: lijst[0],lijst[1]=lijst[1],lijst[0] return lijst lijst =[4,0,1,-2] abc= swap(lijst) print(abc)
'''Basic Program to print area of square''' side = 10 area = side**2 print('Area of square is: ',area)
''' Write a program to evaluate the factorial of a number n This program demonstrates a pattern called as 'guardian' ''' def calc_factorial(n): if not isinstance(n, int): print('Factorial is only defined for Integers') elif n < 0: print('Factorial is not defined for negative Integers') elif n == 0: ...
from collections import Counter alphanumeric_string = "12abcbacbaba344ab" str_int=[] str_alp = [] for i in alphanumeric_string: if i.isalpha(): str_alp.append(i) else: str_int.append(i) print(str_int) print(str_alp) print(Counter(str_alp))
""" Datastore.py will establish a connection with the database that will fill in the content of this application. It will be the persistent data store for the classes and student status. Authors: (RegTools) Joseph Goh Mason Sayyadi Owen McEvoy Ryan Gurnick Samuel Lundquist References: https://www.tutorialspoint.com/s...
# 7-4 list_pizza = "\nPlease enter minue:" list_pizza += "\n Enter 'quiet' when you are finished" while True: minue = raw_input(list_pizza) if minue == 'quiet': break else: print("I will aad " + minue + ' to pizza!') # 7-5 message = "\nHow old are you? " message += "\n Enter 'quiet' to finis...