text
stringlengths
37
1.41M
#find all numbers between 2000 and 3200, divisable by 7 but NOT multiple of 5 #solution should be comma separated on a single line empty_list = [] #iterate through the rangeof numbers for i in range(2000, 3201): #if (i%7 == 0) and (i%5 != 0): #use modulo to find the divisables if (i % 7 == 0) and no...
#################################################### ## ## Projects suggested by CupOfCode01 ## Name Generator using random, string ## #################################################### import random, string, pprint, sys #### quick create random string lowercase ascii of user selectable length # length = input("h...
################################################################# # # From MIT 6.0001 course 2016 # if, elif and else branches # conditions, semicolon, indent 4 characters # ################################################################# Continue = False Input = 0 print("\n" * 100) ...
a=int(input()) for i in range(0,a): for j in range(0,a): print("*",end=" ") print() ''' sample input: 5 sample output: * * * * * * * * * * * * * * * * * * * * * * * * * '''
# MODUŁY TIMIE I DATE_TIME import time import datetime # print("START") # # czas = time.time() # czas2 = time.time() # czas3 = time.time() # print(czas) # time.sleep(2) # time.time()-czas # elapsed = time.time()-czas # print(elapsed) # print("STOP") # # while True: #PETLA, KTORA CO 2 SEKUNDY WYSWIETLA KOMUNIK...
def say (powitanie): print(powitanie) say("Eloszka") def addNumbers(a,b): return print(a+b) addNumbers(5,10) korzysci =["Wieksza czytelnosc kodu", "Latwiejsze wielokrotne uzycie kodu", "Mozliwosc dzielenia sie kodem i laczenia go w calosc przez rozne osoby"] def lista_korzysci (number): return print(kor...
#This program allows you to search for a person's father #programed by Hethur Aluma | 2/13/20 fathers = {"son1": "dad1", "dad1": "grandpa1", "son2": "dad2", "dad2": "grandpa2", "John Quincy Adams": "John Adams", "John Adams": "John Adams Sr.", "Bar...
def dec2bin(target): amari = [] while target != 0: amari.append(target % 2) target = target // 2 amari.reverse() return amari print(dec2bin(26))
""" This file contains functions for sensibly printing text to the console. The utilities allow you to re-write previously-written text, all without worrying about newlines, etc. (c) 2015 Matthew Cotton """ import os import sys import time #################################### # META (unix) def disable_echoing(): ...
#Edited by Inz Haque #Encrypts all ASCII values from 32-126 by shifting them by give amount from user #First asks the user to input the string, then shift the amount by a given value #If the shifting causes the new ASCII value to go out of range, it wraps around starting at value 32 userstring= raw_input('Please ente...
# -*- coding: utf-8 -*- # 给你一个字符串,比如zzzyz,那么他的只包含相同字母子串有多少个,比如"zzz", "y",同时角标不一样,视为不同子串。 # 比如输入是"zzz",那么有6个子串"z","z","z","zz","zz","zzz" # 如果是"zzzyz",那么有8个。 def FindNumSubstrings(s): res = 0 n = len(s) i = 0 while i<n: j=1 while (i+j < n) and (s[i+j] == s[i]): j=j+1 ...
# -*- coding: utf-8 -*- # 给一个数字在range [0, 1million] 找出来到最近的Fibnacci数字的距离 # Test examples: #Fibonacci range wrapping 1044 is [987, 1597] #Fibonacci range wrapping 8999913 is [5702887, 9227465] #Fibonacci range wrapping 7 is [5, 8] #Fibonacci range wrapping 67 is [55, 89] # Recurson is too slow!!! #def F(n): # if n ...
aList = [100, 200, 300, 400, 500] aList.reverse() print(aList) list1 = ["M", "na", "i", "Ke"] list2 = ["y", "me", "s", "lly"] list3 = [list1[0] + list2[0], list1[1] + list2[1], list1[2] + list2[2], list1[3] + list2[3]] print(list3) list20 = [5, 10, 20, 25, 50, 20] del list20[2] list20.insert(2, 200) print(list20) list2...
from turtle import Turtle from time import sleep name = input("Whats your name? > ") kappa = Turtle() kappa.begin_fill() def square(side, color, x, y): kappa.penup() kappa.goto(x, y) kappa.pendown() for i in range(4): kappa.color(color) kappa.pencolor(color) kappa.fillcolor(color...
from builtins import print class Step: """ Represents a step taken by the agent. Contains the change in x and y coordinates and head direction """ def __init__(self, change_x, change_y, head_dir): self.change_x = change_x self.change_y = change_y self.head_dir = head_dir ...
count=0 a=int(input("")) while(a>0): a=a//10 count=count+1 print(count)
# example to understand f-string and format function # f-string name = "Gaurang" print(f"My name is {name}! Hi!") name = "Urja" print(f"Hi there! My name is {name}!") # another way to print dynamic values in a message is using format() function user = "Urja" print("Hello World! I am {}".format(user)) ...
# unpacking arguments also called variable length argument # put * before the variable name to indicate that it's an argument that can take multiple values def multiply(*number): total = 1 for num in number: total = total * num return total print(multiply(1, 2, 3)) def calculate(...
# fibonacci series first_n = int(input("Enter the value for first n numbers of fibonacci you want to print.")) fib = [0, 1] for i in range(2, first_n): ans = fib[i-1] + fib[i-2] fib.append(ans) print("First {} numbers from fibonacci series are: {}".format(first_n, fib)) # find if given series is fibo...
import string import logging from pprint import pprint class MyClass1: 'This is the first python class of the project!!!' # class variable studentCount = 0 # constructor for class instances def __init__(self, studentName, marks): # instance variables self.studentName ...
# here we will see how objects are passed in python #passing mutable object def change_list1(another_list): print "got: ", another_list another_list.append('we') l1 = ['he', 'she', 'they'] print '\nbefore: ', l1 change_list1(l1) print 'after: ', l1 #here, list is mutable so appending new member...
# check username and password for login using dictionary comprehension users = [ (0, "Urja", "123"), (1, "Gaurang", "456"), (2, "uname", "pword") ] user_details = {user[1]:user for user in users} # here, user[1]: user is the (key, value) pair that will go in the dictionary. Rest is the for loop. ...
# find sum of elements in a list list = [2, 43, 65, 77, 12, 89] sum = 0 for item in list: sum = sum + item print("Sum of elements of given list is: {}".format(sum))
# class composition is better approach than class inheritance class Bookshelf: def __init__(self, *books): self.books = books def __str__(self): return f"The bookshelf has total {len(self.books)} books in it." class Book: def __init__(self, title, pages): self.title =...
# 10.1 def nested_sum(list_in): total = 0 for intlist in list_in: total = total + sum(intlist) return total # print(nested_sum([[2,3],[5,6],[12,11]])) # 10.2 def capitalize_all(string): res = [] for s in string: res.append(s.capitalize()) return res def nested_capitalize(list...
from datetime import datetime today = datetime.today() # print(datetime.datetime.today().weekday()) birthday = datetime(1995, 2, 20) def birthday_calculator(birthday): '''Receive birthday <datetime> and out put years old, time to next birthday''' year_old = today.year - birthday.year print('You are ...
"""Typing test implementation""" from utils import * from ucb import main, interact, trace from datetime import datetime ########### # Phase 1 # ########### def choose(paragraphs, select, k): """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the paragraph returns true. If there are few...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Jul 1 15:17:36 2017 This is a test set on backtracking 回溯法,用DFS解决 combination组合数 permutation排列数 @author: guochendai """ ############### combination #--------------------------------- combination O(N!) # or will use k for to solve it import itertools...
# Function calculates the sum of all even elements of Fibonacci sequence that are less than 1 million def calculate(threshold=1000000): fibonacciNumbers = [0, 1] while True: nextFiboNumber = fibonacciNumbers[-1] + fibonacciNumbers[-2] if nextFiboNumber < threshold: fibonacciNumbe...
# Function reads users form users.json file, creates objects of type User using namedtuple from collections module # Returns objects in a list import json from collections import namedtuple def json_to_object(): with open('JSON_files/users.json', 'r', encoding='UTF-8') as jsonFile: ListOfUsers = json.loa...
# Function converts JSON data (users.json) to CSV data (users.csv) import json import csv def json_to_csv(): # jsonData = list() with open('JSON_files/users.json', 'r', encoding='UTF-8') as jsonFile: jsonData = json.loads(jsonFile.read()) with open('CSV_files/users.csv', 'w', encoding='UTF-8') a...
# Function calculates the score of a given word (like in the Scrabble game) # Punctation: # empty (represented by space) - 0 pkt # EAIONRSTUL - 1 pts # DG - 2 pts # BCMP - 3 pts # FHVWY - 4 pts # K - 5 pts # JX - 8 pts # ZQ - 10 pts def score(word): punctation = {' ': 0, 'EAIONRSTUL': 1, 'DG': 2, 'BCMP': 3, 'FHVWY...
# Function finds the amount of all 3-digit palindromic numbers def calculate(): palindromicNumbers = list() for numb in range(100, 1000): if str(numb) == str(numb)[::-1]: palindromicNumbers.append(numb) return len(palindromicNumbers) print(calculate())
from os import listdir, system import sys """ Command that parse downloaded files from Blackboard activities into separated directories. It uses the student's code as classifier Args: PATH (str): Path where the files were downloaded from blackboard. PATH_DEST (str): Path where the files will be extracted...
# -*- coding: utf-8 -*- """ Created on Thu Oct 12 11:01:34 2017 @author: rameen """ import random mylist=[random.randint(1,100) for index in range(0,10000)] random.seed(2312) print(mylist) mylist.sort() print(mylist) def quart1(mylist): if len(mylist)%2==0: x=mylist[len(mylist)//4] ret...
#Converter temperatura celsius em fahrenheit temp = float(input('Temperatura em Celsius: ')) f = (temp * 9/5) + 32 print('A temperatura de {} celsius corresponde a {:.2f} Fahrenheit.'.format(temp,f))
#faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o 1o e o ultimo nome separadamente nome = str(input('Digite seu nome completo: ')).strip() split = nome.split() print('O seu primeiro nome é: {}.'.format(split[0])) print('O seu último nome é: {}.'.format(nome[len(nome) - 1]))
# Write a program that receives a number and does its multiplication table n = int(input('digite um número para ver sua tabuada: ')) print('-' * 15) print('A tabuada é: \n {} x 1 = {}\n {} x 2 = {}\n {} x 3 = {}\n {} x 4 = {}\n {} x 5 = {}\n {} x 6 = {}\n {} x 7 = {}\n {} x 8 = {}\n {} x 9 = {}\n {} x 10 = {}'.format(n...
"""The physical.color module defines a few colors, which can be used to color things. It also defines an RGB data type, which allows you to conveniently define your own new colors. """ from __future__ import division, print_function __all__ = ('RGB', 'red', 'green', 'blue', 'yellow', 'cyan', '...
class School: def __init__(self, name=None, roster={}): self.name = name self.roster = roster def add_student(self, name, grade): list_of_students_in_grade = self.roster.get(str(grade), []) list_of_students_in_grade.append(name) self.roster[str(grade)] = list_of_students...
# event.py from __future__ import print_function class Event(object): ''' Event is the blase class for providing an interface for all subsequent (inherited events), which will trigger further events in the trading program ''' pass class MarketEvent(Event): ''' Handles the event of recei...
''' 请实现一个函数,输入一个整数,输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。 示例 1: 输入:00000000000000000000000000001011 输出:3 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 示例 2: 输入:00000000000000000000000010000000 输出:1 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 示例 3: 输入:11111111111111...
""" 在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。 请找出数组中任意一个重复的数字。 示例 1: 输入: [2, 3, 1, 0, 2, 5, 3] 输出:2 或 3 """ def findRepeatNumber1(nums): # 考虑时间,空间O(n),时间O(1) num_dict = set() for num in nums: if num in num_dict: return num else: ...
''' 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。   示例 1: 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5] 示例 2: 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 输出:[1,2,3,4,8,12,11,10,9,5,6,7] x ''' class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :...
''' 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。 在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。   示例 1: 输入: [0,1,3] 输出: 2 示例 2: 输入: [0,1,2,3,4,5,6,7,9] 输出: 8 ''' # 因为这里是排序数组,所以数组分成两个部分 # 1.左部分:nums[i] = i # 2.右部分:nums[i] != i # 所以只需要找到右部分的左边界即可 class Solution(object): def missingNumber(self, nums): """ ...
''' 11.16 请定义一个队列并实现函数 max_value 得到队列里的最大值, 要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 若队列为空,pop_front 和 max_value 需要返回 -1 示例 1: 输入: ["MaxQueue","push_back","push_back","max_value","pop_front","max_value"] [[],[1],[2],[],[],[]] 输出: [null,null,null,2,1,2] 示例 2: 输入: ["MaxQueue","pop_front","max_value"] [[...
''' 请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。   例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其层次遍历结果: [ [3], [20,9], [15,7] ] ''' # 之字形的需要两个栈 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # ...
''' 输入两个链表,找出它们的第一个公共节点。 注意: .如果两个链表没有交点,返回 null. .在返回结果后,两个链表仍须保持原有的结构。 .可假定整个链表结构中没有循环。 .程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None # 不能改变原链表 class Solution(object): def get...
''' 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。 一个机器人从坐标 [0, 0] 的格子开始移动, 它每次可以向左、右、上、下移动一格(不能移动到方格外), 也不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。 请问该机器人能够到达多少个格子?   示例 1: 输入:m = 2, n = 3, k = 1 输出:3 示例 2: 输入:m = 3, n = 1, k = 0 输出:1 提示: 1 <= n,m <= 100 0 <= k <= 2...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode "...
### TRABALHANDO COM REPETIÇÃO ##repetição simples até o 100 : FOR/RANGE for x in range(100): print(x) ##repetição simples de 20 a 100 for x in range(20,100): print(x) ##verificar os numeros primos a = int(input('Entre com o número: ')) div = 0 for x in range(1, a+1): resto = a % x #fazendo...
def getPermutations(array): # Write your code here. if len(array) < 1: return [] chosen = [] notChosen = array.copy() permutations = getPermutationsHelper(chosen, notChosen, []) return permutations #O(n^2*n!) Time | O(n*n!) Space, where n is length of array def getPermutationsHelper(chosen, notChosen, p...
#O(n + m) Time | O(1) Space where n and m are rows and columns of matrix def searchInSortedMatrix(matrix, target): # Write your code here. node = [0, len(matrix[0]) - 1] while(node[0] < len(matrix) and node[1] >= 0): if target == matrix[node[0]][node[1]]: return node elif target > matrix[node[0]][node[1...
#O(v + e) Time | O(v) space where v is the length of edges #and e edges in graph def cycleInGraph(edges): # Write your code here. visitedNodes = [False for index in edges] for index in range(len(edges)): visitedNodes[index] = True isCycle = explore(index, edges, visitedNodes) if isCycle: return True ...
#Solution 1 #O(n^2) Time | O(1) Space where n is number of cities def validStartingCity(distances, fuel, mpg): # Write your code here. for city in range(len(distances)): capacity = 0 nextCity = city + 1 capacity += (fuel[city] * mpg) - distances[city] citiesVisited = 0 while capacity >= 0 and citiesVisit...
# O(n) Time | O(1) Speed, where n is length of redShirtSpeeds def tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest): # Write your code here. redShirtSpeeds.sort() blueShirtSpeeds.sort() totalSpeed = 0 riders = len(redShirtSpeeds) if fastest: for index in range(riders): totalSpeed += max(redShirtSpee...
# O(n) Time | O(n) Space, where n is total elements in matrix def spiralTraverse(array): # Write your code here. if len(array) < 1: return array spiralElements = [] rowMin = 0 colMin = 0 rowMax = len(array) colMax = len(array[0]) while colMin < colMax and rowMin < rowMax: # col traverse (left to right) ...
# Average and Worst -> O(n^2) Time | O(1) Space, where n is length of array # Best O(n) Time | O(1) Space, where n is length of array def insertionSort(array): # Write your code here. for index in range(len(array)): start = getInsertPosition(array, index) if start != index: insertAndSwap(array, start, index...
# O(n^2*m) Time, O(n*m) Space, where n is length of pi and m is # length of numbers def numbersInPi(pi, numbers): # Write your code here. numbersHash = {} for number in numbers: numbersHash[number] = True space = getMinSpaces(pi, numbersHash, {}) if space is None: return -1 else: return space - 1 de...
employee = {'name':'김말똥', 'salary':2000} print('{}, {}'.format(employee['name'], employee['salary']))
# 클래스 메소드와 스태틱 메소드 # 인스턴스 메소드는 self인 인스턴스를 인자로 받고 인스턴스에만 한정된 데이터를 # 생성하거나 변경하거나 참조한다. # 클래스 메소드는 cls인 클래스를 인자를 받고 모든 인스턴스가 공유하는 클래스 변수처럼 # 데이터를 생성하거나 변경하거나 참조하기 위한 메소드이다. class Employee: raise_ratio = 1.1 def __init__(self, name, salary): self.name = name self.salary = salary def empIn...
p = (4, 5) x, y = p data = ['ACME', 50, 20, 3, (34, 4, 5)] name, share, price, other = data s = 'Hello' a, b, c, d, e = s def drop_first_last(grades): first, *middle, last = grades return avg(middle) record = ('dave', 'dave@example.com', '86765444', '8765555') name, email, *phone_number = user_record *t...
s = input("input word: ") for i in range(len(s)): if s[i] == s[-i]: break
import math, random import numpy as np import rythm import functions class Agent: def __init__(self, initial_density): self.density = initial_density self.success_communication = 0 self.success_repetition = 0 def learn(self, rythm_list): """ Learn the rythm list""" for rythm i...
import re def add(*romans_numbers): if "IIII" in romans_numbers: raise ValueError roman_numbers_as_Is = [_roman_number_to_I(check_valid_char(roman_number)) for roman_number in romans_numbers] nombres_concaténés = "".join(roman_numbers_as_Is) nombres_concaténés = Is_to_roman(nombres_concaténés...
myList = ['pear','apple','plum','peach'] myList.sort() print(myList) myList = [2,43,1,17] myList.sort() print(myList) myDictionary = {'id':'001','name':'Superman','power':'x-ray vision'} x = myDictionary[input("what do you want to know: ")] print(myDictionary[x])
from math import sqrt, ceil def is_prime (n): if n == 1: return False if n == 2: return True for i in range(2, ceil(sqrt(n)) + 1): if n % i == 0: return False return True from TestClass import Tester tester = Tester() tester.test(is_prime(11)) tester.test(not is...
from collections import deque s = deque(input()) q = int(input()) flag = True for i in range(q): x = input() if x == '1': flag = not flag else : if x[2] == '1' and flag : s.appendleft(x[4]) elif x[2] == '2' and not flag : s.appendleft(x[4]) else : ...
# https://leetcode.com/problems/jewels-and-stones/description/ class Solution: def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ jewel_set = set(J) jewel_list = list(jewel_set) jewel_list.sort() count = 0 ...
from scipy import stats import numpy as np # This method computes entropy for information gain def entropy(class_y): # Input: # class_y : list of class labels (0's and 1's) # TODO: Compute the entropy for a list of classes # # Example: # entropy([0,0,0,1,1,1,1,1,1]...
import unittest def classifyTriangle(a, b, c ): if a == b == c: print("Equilateral Triangle") if a**2 + b**2 == c**2 | a**2 + c**2 == b**2 | b**2 + c**2 == a**2: print("Right Triangle") elif a == b != c | a != b == c | a == c !=b: print("Scalene Triangle") if a...
num = int(input()) sum = 0 temp = num while temp > 0: digit = temp%10 sum += digit**3 temp // = 10 if num == sum: print (num, "is an amstrong number") else: print (num, "is not an amstrong number")
def add_number(number1, number2): print(number1 + number2) return (number1 + number2) * 2 print(add_number(10, 10)) print(print("hi")) # print(input("Enter the number")) print('a', 'b') print(1, "a,b") print(type(1)) print(type(0.1)) print(type('a')) print(type("hai")) print(type("a,b")) print(type(print())) ...
class Animal(): def __init__(self, name): self.name = name def eat(self): return self.name class Dog (Animal): def __init__(self, sound): self.sound = sound def bark(self): return self.sound class Cat (Animal): def __init__(self, sound): self.sound = sound...
def dictionary(): create_dictionary = dict() for values in range(1, 16): create_dictionary[values] = values ** 2 print(create_dictionary) dictionary() ''' def dictionary(): num = int(input("Enter the number")) for i in range(0, num + 1): num = int(input("Enter the number")) ...
def add(*args): sum_ = 0 for num in args: sum_ = sum_ + num print(sum_) print(type(args)) add(1, 2, 3, 4, 5, 6, 7, 8, 9) # a = [1,2] # def x(*num): # num[0]=10 # num[1]=20 # print (num) # x(1,2)
# count = 0 # count += 1 def fizz_buzz(): for values in range(0, 51): if values % 3 == 0 and values % 5 == 0: print("fizz buzz") elif values % 3 == 0: print("fizz") elif values % 5 == 0: print("buzz") else: print(values) # count...
""" Cria tipos em C automaticamente a partir de um arquivo """ # ask for the name of the file to copy to filename = raw_input('Enter the name of the file in this directory: ') # open the file only to read the variables type_file = open(filename, 'r') # read the lines content = type_file.readlines() # ta...
class Teacher: def __init__(self,name,age):#实例方法 self.name=name #把 self.age=age pass def coding(self,lines,language='python'):#实例方法 print (self.name+"会敲{0}代码,写了{1}行代码".format(language,lines)) def cooking(self,*args): for item in args: print (self...
class N: def __init__(self, head, new_head=None, random=None): self.head = head self.new_head = new_head self.random = random #Print를 위한 재귀 함수 def finding(node): if node is None: print("null") return # 현재의 노드 head와 random한 포인터 데이타 print(node.head, end='') if node.random: text = "[%d]"%(n...
import pygame from boardslot import * class TicTacToeBoard(object): def __init__(self, screen, game_state=None): """ Constructor for the board object. Should initialize a variable called self.grid to store state. State is represented by a single list [a0, a1, a2..a8]. They correspo...
from math import * import pygame from BlackHoleFiles import button from BlackHoleFiles import colour as col class game_circle(object): ''' Class to create circle objects ''' def __init__(self, radius=None, centre=(0, 0), colour=(0, 0, 0), value=None): ''' Constructor....
# basado en https://codereview.stackexchange.com/questions/191550/minesweeper-in-python-tkinter # hecho por jdelvalle2002 import tkinter, configparser, os, random, tkinter.messagebox, tkinter.simpledialog, webbrowser from tkinter.font import BOLD from tkinter.constants import LEFT window = tkinter.Tk() window...
import turtle as t import math t.shape('turtle') rad=0.1 degr=rad*(180/math.pi) for i in range (100): ro=rad t.forward(ro/5) t.left(degr) rad+=0.1 ro+=ro t.exitonclick()
count = 0 print "Before", count for the_num in [9, 41, 12, 3, 74, 15]: count = count + the_num print count,the_num print "After", count
fhand = open("mbox.txt") for line in fhand: line = line.strip() if line.startswith("From:"): ##new command that is why a colon is required print line ##for each line in fhand remove spaces and then find a line that starts with our parameter ##then print that particular line
for i in [5,4,3,2,1]: #python list an iteration is called i here print i print "Blast Off!"
addName = raw_input("New Name:") addid = raw_input("ID:") dictionary = {} dictionary[addName] = addid print('Name: ' + addName + ' ID: ' + addid)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 13 00:1:59 2019 @author:ritambasu61 """ import numpy as np def g(z): return np.exp(z) x=np.arange(0,1,.001) y=g(x) print('Integration of exp(x) from x=0 to x=1 (by trapezoidal Method) is =:',np.trapz(y,x))
""" I'm working on writing math formulas in python, but I'm having trouble. Can you help me fix them? Operations in Python: addition: a+b subtraction: a-b negation: -a multiplication: a*b division: a/b integer division: a//b (returns a/b with the decimals chopped off) exponentiation: a**b (...
#-*-coding:utf-8-*- import math from resultEvaluation import * from dataProcess import * def itemSimilarity (data) : """ calculate the similarity between each pair of items paraments : data : the data for training return : sim : the matrix of the similarity between each pair of items...
# - *- coding: utf- 8 - *- def min_coin_count(value, coin_list): # 코드를 작성하세요. default_coin_list.sort() i=-1 count =0 while True: if value >= default_coin_list [i]: value = value - default_coin_list [i] count += 1 else: i = i - 1 if ...
class Sword: """검 클래스""" def __init__(self, damage): self.damage = damage def slash(self, other_character): """검 사용 메소드""" other_character.get_damage(self.damage) class GameCharacter: """게임 캐릭터 클래스""" def __init__(self, name, hp, sword: Sword): self.name = name ...
class Employee: company_name = "My King Burger" raise_percentage = 1.03 def __init__(self, name, wage): self.name = name self.wage = wage def raise_pay(self): self.wage *= self.raise_percentage def __str__(self): return Employee.company_name + " staff: " +self.na...
# - *- coding: utf- 8 - *- def sum_in_list(search_sum, sorted_list): #brute force for i in sorted_list: for j in sorted_list[::-1]: if i + j == search_sum : return True return False print(sum_in_list(15, [1, 2, 5, 6, 7, 9, 11])) #binary search # for i in so...
def is_palindrome(word): word_list = list(word) word_half_len = int(len(word_list)) result_same = True for i in range(word_half_len): front_letter = word_list[i] #print(front_letter) end_letter = word_list[-(i+1)] #print(end_letter) if front_letter != end_lett...
#program for returning a list of pincodes available in the string passed from the given Picture import re def pin_finder(result1): #regex pattern for finding 6 digits pincode with any single character #before or after it negligible (character like "," or "-" before or after pincodes) h = re.findall(r...
import random def is_valid_play(play): return play in ['rock', 'paper', 'scissors'] def random_play(): """vybírá náhodně ze tří možností r, p, s""" return random.choice(['rock', 'paper', 'scissors']) def determine_game_result(human, computer): if human == computer: return 'tie' elif human...
ri=int(input("")) sum=0 for i in range(1,ri+1): sum=sum+i print(sum)
import random # Guessing Game # Rock Paper Scissors # Dice Roll # Fortune Teller def guessingGame(): # print("This is going to be a Guessing Game") # cpu will choose a randon number from 1-10 cpu = random.randint(1,10) # user guesses until they are correct user = int(input("Guess what number I am thinking of: "))...