text
stringlengths
37
1.41M
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] # Copy your logic functions from part A below: # This file contains the core functions needed to validate moves in the Tic Tac Toe game # Implement each function and choose "Run Tests" from the drop down menu to see how you did. # Once you pass all the tests, ...
class RadioStation: def __init__(self, frequency): self.frequency = frequency def get_frequency(self): return self.frequency class StationList: def __init__(self): self.stations = [] self.counter = 0 def add_station(self, station): self.stations.append(stati...
#%% # Add the dependencies. import pandas as pd import numpy as np import os #%% # Files to load school_data_to_load = os.path.join("Resources", "schools_complete.csv") student_data_to_load = os.path.join("Resources", "students_complete.csv") #%% # Read the school data file and store it in a Pandas DataFrame. school...
""" Python program that takes in a spreadsheet of medical terminology and makes flash cards author: Erica J. Lee updated: June 13,2016 """ import random dict= { 'a(n)':'absence of a major part of the brain, skull, scalp', 'ab':'removal of diseased organ away from the body', 'acr(o)':'increased production of growt...
S = "Xavier2.0" print("True" if len([s for s in S if s.isalnum()]) > 0 else "False") print("True" if len([s for s in S if s.isalpha()]) > 0 else "False") print("True" if len([s for s in S if s.isdigit()]) > 0 else "False") print("True" if len([s for s in S if s.islower()]) > 0 else "False") print("True" if len([s for ...
##large number## num=[any] print(num) num=int(input("num:")) for i in range(2,num): if num%i==0: print("large numer:") break else: print("oh!small number")
# s = 'azcbobobegghakl' vowelCount = 0 for char in s: if char in ["a", "e", "i", "o", "u"]: vowelCount += 1 print("Number of vowels: " + str(vowelCount))
num=0 while num<=9: num=num+1 print (num)
import turtle; def janela(): lapis = turtle.Pen() lapis.color('black', 'blue') lapis.begin_fill() for x in range(4): lapis.forward(50) lapis.right(90) lapis.penup() lapis.left(180) lapis.pendown() for x in range(4): lapis.forward(50) lapis.left(90) ...
import pygame import random import os import numpy as np # initialize pygame.init() pygame.mixer.pre_init() pygame.mixer.init() def init_variables(): """Initialize all the required variables for the game to start.""" # Game speed speed = 200 # We add a ticking event for the snake to move au...
# -*- coding: utf-8 -*- """Object to read lines from a stream using an arbitrary delimiter""" from math import ceil __all__ = ['ReadLines'] # the default amount of data to read on a buffer fill DEFAULT_BLOCK_SIZE = 1048756 class ReadLines: # pylint: disable=too-few-public-methods, too-many-instance-attributes ...
import nltk from nltk.corpus import wordnet word = 'suit' def wordnet_get(word): x = wordnet.synsets(word) if x == []: print('Sorry, we can\'t find this word, you might want to check the spelling') definition = [i.definition() for i in x] pos=[p.pos() for p in x] # synonyms=[s...
def bottles_of_beer(): i = 99 while i > 0: if i > 1: print(str(i) + " bottles of beer \n") else: print(str(i) + " bottle of beer") i -= 1 bottles_of_beer()
import random import time def convert(unconverted_input): string_user_word = "" for letter in unconverted_input: string_user_word += letter return string_user_word def letter_duplicates(word, letter): # to enable to guess multiple letters with one guess start_at = -1 duplic...
# マージO(n)かかっちゃうやつ class union_find(object): """union-find tree""" def __init__(self, length): self.length = length self.unionnumber=0 self.unionlist=[[]] self.num=list(-1 for i in range(length)) def unite(self,i,j): if self.num[i]==-1: if self.num[j]==-1: self.unionlist[self.unionnumber]....
# # # ''' A -> B B -> C B -> D B -> E C -> B D -> B E -> B ''' graph = {'Birth Spring': ['B'], 'B': ['C', 'D', 'E'], 'C': ['B'], 'D': ['B'], 'E': ['B']} def find_path(graph, start, end, path=[]): path = path + [start] if start == end: print "no need" return path if not graph.has_ke...
import requests import json def main(): url = "https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22" # Requests will allow you to send HTTP requests using Python. read = requests.get(url) # Json converts the variable read which contains the URL into ...
#Linklist class Node(): def __init__(self,data, next_node=None): self.data = data self.next = next_node def append_node(self, data): if self.next == None: self.next = Node(data) return self.next.append_node(data) def ins...
import random #1 def load_map(filename): ''' (str) -> list of lists Read data from the file with the given filename and return it as a nested list of strings. e.g. if the file had a map like this: 1 2 5 3 -1 4 this function would return [['1','2','5'], ['3','-1...
Handout, Question 1 class Node: def __init__(self, value): self.value = value self.next = None a = Node(4) a.next = Node(5) b = Node(6) c = a.next c.next = b The resulting list is: 4->5->6->None Variable 'a' refers to the head of this list. ----- Handout, Question 2 class Node: def __init__(s...
# This question ended up being a bit too tricky in light of the test 1 grades # I accepted the 'helper' code as a correct solution # even though it does not always place chr correctly. # But as a student has asked for the full deal, here it is # The full solution removes chr, permutes the string, # then puts chr i...
"""Test module Queue. Authors: Francois Pitt, January 2013, Danny Heap, September 2013, February 2014 """ import unittest from linked_list import Queue class EmptyTestCase(unittest.TestCase): """Test behaviour of an empty Queue. """ def setUp(self): """Set up an empty queue. ""...
#带壳的双向linked list class Node(): def __init__(self, data, next_node=None, prev=None): '''双向linked list,有next也有previous指向。''' self.data = data self.next = next_node self.prev = prev def __str__(self): return str(self.data) class EmptyError(Exception): pa...
def percentage(raw_mark, max_mark): ''' (float, float) -> float Return the percentage mark on a piece of work that received a mark of raw_mark where the maximum possible mark is max_mark. >>> percentage(15, 20) 75.0 ''' return ((raw_mark / max_mark) * 100) def contribution(mark_as_percent, ...
"""Incomplete Binary Search Tree implementation. Author: Francois Pitt, March 2013, Danny Heap, October 2013. """ class BST: """A Binary Search Tree.""" def __init__(self: 'BST', container: list =[]) -> None: """ Initialize this BST by inserting the values from container (default []) ...
class BTNode: """Binary Tree node.""" def __init__(self: 'BTNode', data: object, left: 'BTNode'=None, right: 'BTNode'=None) -> None: """Create BT node with data and children left and right.""" self.data, self.left, self.right = data, left, right def __repr__(self: 'BTNode'...
''' ############################################################################################################# ##Be able to write all three class questions incliding the __main__ function. Practice! Practice! Practice!## ################################################################################################...
class LinkedNode(): def __init__(self,data, next_node=None): self.data = data self.next = next_node class LinkedList(): '''把一些基本的queue会用到的method添加进来。''' def __init__(self): self.head = None def append(self, data): if self.head == None: self.hea...
import random #1 def make_grid(w, h, player_coord, gold_coord): ''' (int, int, tuple of two ints, tuple of two ints) -> None Given two integers width w and height h, append sublists into the variable "grid" to make a maze of the specified width and height. The coordinates for the player an...
"""A simple implementation of the Queue ADT. Authors: Francois Pitt, January 2013, Danny Heap, September 2013 """ class EmptyQueueError(Exception): """An exception raised when attempting to dequeue from an empty queue. """ pass class Queue: """A collection of items stored in 'first-in, first-out...
# EXAMPLE THAT WE DID IN CLASS def remove_three(lst): '''(list of int) -> list of int Return a new list with all elements of lst except the 3s. lst has no nesting. >>> remove_three([1, 2, 3, 3, 4]) [1, 2, 4] ''' if L == []: return [] elif L[0] == 3: return remove_three(L[1:]) else: r...
''' Call(): Create your call class with an init method. Each instance of Call() should have a few attributes: unique id caller name caller phone number time of call reason for call The call class should have a display method that prints all call attributes. ''' from string import ascii_uppercase, digits, ascii_lower...
students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'}, {'first_name' : 'Mark', 'last_name' : 'Guillen'}, {'first_name' : 'KB', 'last_name' : 'Tonel'} ] # for student in students: # print student['first_name'], student['last_name'] users ...
#!/usr/bin/env python3 """ Jeu de devinette par: Olivier Vezina """ from random import randrange nbEssai = 0 nbParties = 1 MAX_ESSAIS = 10 WIN = "GGG" LOST = "PPP" def main(): """ Fonction principale """ print("Bonjour, je m'appelle Pedro CallMe") print("J'ai choisi un nombre entier en...
############################################### # Skyler Kuhn # BNFO 501: Project 2 Program # Implementing Merge Sort ################################################ from __future__ import print_function import time dataFh = open("project1_data.txt", "r") filedatalist = dataFh.read().splitlines() dataFh.close() # Do...
# Skyler Kuhn # This function multiplies two number using recursion. # Parameters must be two positive integers. def multiply_recur(a, b): if a == 0 or b == 0: return 0 if a == 1: return b # if a > 700: # return 'R.I.P Computer, just use a calculator!' if a > 1: return mu...
#WAPT update a dictionary with content of another dictionary d1={'a':350,'b':200,'c':351} d2={'b':400,'e':300,'f':250} for i in d2: if i not in d1: d1[i]=d2[i] else: d1[i]=d1[i]+d2[i] print(d1)
for x in range(2, 1000): is_prime = True for i in range(2, x): if x % i == 0: is_prime = False break if is_prime: print(x)
import os from Hero import Hero import Monster from random import randint # from gold import Gold os.system('clear') gameOn = True while gameOn: #======================= #======== Banner ======= #======================= text = "Tower of Vengeance" textLength = len(text) w = 4 ...
import re with open('input.txt', 'r') as f: arr = f.read().split('\n\n') n_yes = 0 for group in arr: letters = set(re.findall('[a-z]', group)) n_yes += len(letters) print(f"Part 1: {n_yes}") n_yes = 0 for group in arr: answers = [set(x) for x in group.splitlines()] common = set.intersection(*ans...
import math import sys import time def trialPrime(cur): i=3 while i**2 <= cur: if cur%i == 0: return False i += 2 return True def lucasTest(prime): # Define Lucas-Lehmer sequence until necessary value while len(s) <= prime - 2: s.insert(len(s), s[-1]**2 - 2) residue = divmod(s[-1],2**prime - 1) if re...
def isAnagram(s1, s2): list1=list(s1) list2=list(s2) list1.sort() list2.sort() if list1==list2: print('is an anagram') else: print('is not an anagram') s1=input('please enter the first string:') s2=input('please enter the second string:') isAnagram(s1,s2)
def superfloat(n): if n%1==0: return int(n) else: return float(n) import string class polynomial(): def __init__(self,expression='x^2'): self.expression=expression def new_expression(self): new_expression=input('Please enter a polynomial:') self.expression=...
import utils from cell import Cell class Board: def __init__(self, puzzle_file): # Initialize the board by reading in numbers from numbers.txt values = utils.read_puzzle(puzzle_file) self.board = [] self.board_size = len(values) for row_num, row in enumerate(values): ...
import sys import time print('a linguagem br é uma linguagem feita para aprendizado ela não é apropriado para projetos grandes') start = '' #INT IntValor = 0 nameInt = '&' #STRING nameString = '&' StringValor = 0 #STRING REP nameString2 = '&' stringvalorrep = '&' rep1 = '&' rep2 = '&' #FLOAT ...
#ForDictionary dict={"key1":"Value1", "key2":"Value2", "key3":"Value3"} print(dict) print("\n") for key in dict: print("for key in dict: ", dict[key]) print("\n") for key,value in dict.items(): print("for key,value in dict.items(): ", key,value) print("\n") for val in dict.values(): print("for val in dict.va...
class Vehicle: def general_usage(self): print ("general use Transportation") class Car (Vehicle): def __init__(self): print ("i am a car") self.wheels = 4 self.has_roof = True def specific_usage(self): print("specific use : commet to work and vaction with family ")...
# for x in range(5): # print (x) # if x ==3: # break # solution # 0 # 1 # 2 # 3 # for x in range(5): # if x ==3: # break #(dont continou the loop skip the print (x) thefore we got 012): # print(x) # # solution # 0 # 1 # 2
# for letter in 'hello': # if letter == 'e': # pass # print("pass") # print(letter) # solution # h # pass [ we got pass because the condition of e] # e # l # l # o
def is_unique_v1(string): """ Function that verifies if all the characters in a string are unique. It is case sensitive, meaning "A" and "a" are considered different characters :param string: string to verify for uniqueness. :return True: if it doesn’t have any duplicate characters False: otherwi...
import sys def max_number(a, b): """ Return the max of two numbers, without using if/else or comparision. En caso de igualdad, se devolvera 0 :param a: first integer :param b: second integer :return: a if a > b, b if b >a """ # I want an integer with all zeros except the first bit (the...
#!/bin/python import sys from graph import * def findWeight(vertex1, vertex2): """ Finds the weight between two vertices in accordance to specs given in homework """ # assume lengths will be the same numDiff = 0 word1 = vertex1.word word2 = vertex2.word for n in range(0, len(vertex1.word)): if word1[n] != wo...
def solution(s): s=s.lower() answer = s[0].upper() sign=1 for word in list(s[1::]): if sign==0: answer+=word.upper() else : answer+=word sign=1 if word==" ": sign=0 return answer
def bfs(computers,start,visited,answer): queue = [] if visited[start]: return queue.append(start) visited[start] = True while queue : v = queue.pop(0) print(v,end=" ") for ind,val in enumerate(computers[v]): if (not visited[ind] )and (val==1): ...
class LinkedList(object): class Node(object): def __init__(self, data=None): self.data = data self.next = None self.prev = None def __repr__(self): return str(self.data) def __init__(self): self.size = 0 self.sntl = self.Node() ...
# Python program showing # use of json package import json # {key:value mapping} a = {"name": "John", "age": 31, "Salary": 25000} print(a.get('name')) # conversion to JSON done by dumps() function b = json.dumps(a) # printing the output """ Output: {"age": 31, "Salary": 25000, "name": "...
#12 planeta=input("ingrese el nombre del planeta en que vive:") p=int(input("ingrese el % de la contaminacion del planeta:")) c=int(input("ingrese el % del planeta en su maxima vida:")) vida=(c-p) cuerpo_en_destruccion=(vida<49) print("###################") print("# vida del planeta #") print("#################...
#1 cliente=input("ingrese el nombre del cliente:") kg=int(input("ingrese nro de kg de manzanas:")) precio=float(input("ingrese precio de cada unidad:")) total=(precio*kg) comprador_compulsivo = (total > 130) print(" + #################### +") print(" + # voleta de compra +") print(" + #################### +") ...
#13 ferreteria=input("ingrese el nombre de la ferreteria:") f=int(input("ingrese la cantidad de fierro comprado:")) precio=float(input("ingrese precio de c.u de fierro:")) total=(precio*f) tienda_grande= (total > 600) print(" + #################### +") print(" + # voleta de compra +") print(" + ###############...
#We will write program to convert years to seconds years = int(input("Please enter number of years : ")) ''' No of months = 12 No of days = 365 No of hours in a day = 24 No of minutes in hour = 60 No of seconds in minute = 60 ''' calc_of_seconds = years * 12 * 365 * 24 * 60 * 60 print((f"{years} years contain {calc_...
def insertBeg(head,x): temp=head(x) if head==None: temp.next=temp return temp curr=head while curr.next!=head: curr=curr.next curr.next=temp temp.next=head return temp
# 03 August 07:11AM-07:16AM 5min # SELF #GFG # Logic 2min 1min # Coding 0min 2min # link - https://practice.geeksforgeeks.org/problems/sum-of-digits-of-a-number/1/?track=DS-Python-Recursion&batchId=273 def fun(n): if n/10==0: r...
# 05 August 05:43PM-05:48PM 5min # SELF # Logic 5min # Coding 0min # Link https://practice.geeksforgeeks.org/problems/power-of-numbers-1587115620/1/?track=DS-Python-Recursion&batchId=273 # def Power(n,r): r='56' s=reversed(r) print(int(s))
def mergesort(arr,l,m,r): i,j,k=0,0,l left=arr[l:m+1] right=arr[m+1:r] while i<len(left) and j<len(right): if arr[i]<arr[j]: arr[k]=arr[i] k=k+1 i=i+1 else: arr[k]=arr[j] k=k+1 j=j+1 while i<len(left): ar...
# 27 July 06:37AM-06:57AM Completed by SELF 20min # Write a Python function that takes a list of words and return the longest word and the length of the longest one. Go to the editor # Sample Output: # Longest word: Exercises # Length of the longest word: 9 # ------My Code-------- s="highest this is the jdifbhjvrvj...
# 03 August 06:41PM-06:51AM 10min # SELF #GFG # Logic 3min 1min # Coding 6min 1min # link - https://practice.geeksforgeeks.org/problems/factorial-using-recursion/1/?track=DS-Python-Recursion&batchId=273# def fun(n): if n==1: r...
# 7:00AM-7:25AM 25min Not Completed # Kth smallest element # Medium Accuracy: 46.66% Submissions: 87860 Points: 4 # Given an array arr[] and a number K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct. # Example 1...
# Link = https://leetcode.com/problems/merge-intervals/ # 20-July 07:15Am-07:30AM 15 min Not Completed # 56. Merge Intervals # Medium # 8363 # 403 # Add to List # Share # Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping in...
# 03 August 06:56PM-07:03AM 9min # SELF #GFG # Logic 3min 0min # Coding 2min 4min # link - https://practice.geeksforgeeks.org/problems/count-total-digits-in-a-number/1/?track=DS-Python-Recursion&batchId=273 # My Code------ def fun(n): ...
# 30 July 1:10PM-01:26PM 6min # SELF GFG # Logic 3min 5min # Coding 3min 5min # 30 July 08:15PM-08:30PM 15min # GFG # Logic 10min # Coding 5min # Link https://practice.geeksfo...
# 27 July 07:03AM-07:07AM Completed by SELF 4min # Write a Python program to remove the nth index character from a nonempty string. # ------My Code-------- s="This is good as well as very good" l=s.split() print(l) l.pop(3) print(l) # -----Solution From Website------- def remove_char(str, n): first_part = st...
a=[20,4,23,5,2] a.sort() print(a) a=[20,4,23,5,2] a.sort(reverse=True) print(a) a=["courses","gfg","pyhton"] a.sort() print(a) def MyFun(s): len(s) a=["courses","gfg","pyhton"] a.sort(key=MyFun) a.sort(reverse=True) print(a) # print(a)
from Book import Book from Library import Library from queue import PriorityQueue def find_book_in_array(book_id, master_array): for book in master_array: if book.get_id() == book_id: return book # def get_max_rating(libraries): # max = -9999999 # for library in libraries: # if __name...
class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False elif x < 10: return True result = 0 pre = x while x != 0: ...
def isValid(s): check = {'(':')','{':'}','[':']'} brackets = list(s) current = [] result = 0 for i in brackets: if check.has_key(i): current.append(i) elif len(current) != 0: if i != check[current.pop()]: return False else: ...
# 编程判断一个人是否是微博活跃用户 x = int(input("最近三天登录次数是?")) y = int(input("最近三天发微博数是?")) print("该用户是",end="") #end=""是什么意思?表示的是以换行符结尾 # 判断是否是非常活跃用户 if x > 20 or y > 10 : print("非常活跃用户") # 判断是否是活跃用户 elif 10 <= x < 20 or 5 <= y < 10: print("活跃用户") # 判断是否是消极用户 elif x < 3 and y <= 1: print("消极用户") # 判断是否是普通用户 else: print("普通用户")
import random confirmed_friends = [] friends_dict = {} try: num_friends = int(input("Enter the number of friends joining" " (including you):\n")) except ValueError: print("\nNo one is joining for the party") else: if num_friends >= 1: print("\nEnter the name of every fr...
"""Example for getting the data from a station.""" import asyncio import aiohttp from luftdaten import Luftdaten SENSOR_ID = 155 async def main(): """Sample code to retrieve the data.""" async with aiohttp.ClientSession() as session: data = Luftdaten(SENSOR_ID, loop, session) await data.get...
#!/usr/bin/python3.6 #EXERCICE : 1b-dic #DESCRIPTION : Trier et stocker les noms saisis par l'utilisateur par ordre alphabétique dans une collection. #NOM : SEGHIR #PRENOM : Souleimane #DATE : 23/10/2018 def addDic(): #Fonction appelée par le script. name_dic={} #On crée un liste vide. ...
# 구구단 구하기 # def GuGu(a): # result = [] # for i in range(1, 10): # result.append(a*i) # return result # c = GuGu(3) # print(c) # 1000 미만의 수에서 3과 5의 배수들의 합 구하기 # l = [] # result = 0 # for i in range(1, 1000): # if (i % 3) == 0 or (i % 5) == 0: # l.append(i) # result += i ...
# Q1 # a = 80 # b = 75 # c = 55 # d = (a + b + c) / 3 # print(d) # 70.0 # Q2 # a = 13 # print(a % 2) # 1 (나머지가 1이므로 홀수) # Q3 # a = "881120-1068234" # print(a[:6]) # 881120 # print(a[7:]) # 1068234 # Q4 # pin = "881120-1068234" # print(pin[-7]) # 1 # Q5 # a = "a:b:c:d" # print(a.re...
""" Graham Earley, 2015. Read more about the algorithm here: https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm """ import random import numpy as np from CharacterFrequencyCalibrator import CharacterFrequencyCalibrator from SwapEncryptor import SwapEncryptor def calculate_score(text, calibrator): score...
def getPrimes(_max) : primes = [True] * (_max + 1) primes[0] = primes[1] = False ret = [] for i in range(2, _max + 1) : if primes[i] : ret.append(i) t = i * 2 while t <= _max : primes[t] = False t += i return ret
import sieve import math def lcf(nums) : _lcf = 1 # should be global... but primes = sieve.getPrimes(max(nums)) for prime in primes : nums = [num for num in nums if num != 1] if len(nums) == 1 : return _lcf * num[0] maxCnt = 0 for num in nums : cnt = 0 ...
#python3 ''' 学以致用,边学边练,在开发中发挥强大的生产力 下载python解释器: https://www.python.org/downloads/release/ ''' """ 机器指令-》cpu """ #输入、输出 #用户输入 输出函数 #字符在计算机存储为0和1,ASCII码1个字节,gbk汉字为2个字节,utf-8汉字3个字节,是对unicode万国码(都是2个字节)的优化和压缩 ''' notice = "请输入:" #print notice str = input(notice) type_str = type(str) print (type_str) num = int(str) type_n...
import sys import numpy as np primes = set([2]) def is_prime(x): global primes for i in set(list( primes ) + range(max(primes),int(np.sqrt(x)))): if x%i==0: return False return True def more_primes(min_n, max_n): global primes for i in xrange(min_n,max_n): if is_prime(...
# read in the input x1, y1, x2, y2 = map(int, input().split()) x3, y3, x4, y4 = map(int, input().split()) a = x2 - x1 b = x4 - x3 if (x2-x1) != 0 and (x4-x3) != 0: slope_1 = (y2-y1)/(x2-x1) #abs(slope_1) slope_2 = (y4-y3)/(x4-x3) #abs(slope_2) if slope_1-slope_2 == 0: print('parallel') else: print('not para...
# read the input string = input('') # solve the problem vowels = ['a','e','i','o','u','A','E','I','O','U'] count = 0 for letters in string: if letters in vowels: count=count+1 # output the result print(count)
# #ファイルの操作 # # f = open('test.txt', 'w') # # f.write('Test\n') # # # print('My', 'name', 'is', 'Mike', sep='#', end='!', file=f) # # f.close() # # with open('test.txt', 'w') as f: # # f.write('Test\n') # s = """\ # AAA # BBB # CCC # DDD # """ # with open('test.txt', 'r') as f: # # while True: # # chunk = ...
# https://www.hackerrank.com/challenges/electronics-shop/problem # with itertools from itertools import product def getMoneySpent(keyboards, drives, b): prod = list(product(keyboards,drives)) prods = [x[0]+x[1] for x in prod if x[0]+x[1] <= b] if len(prods) == 0: return -1 return...
## Declarando Variaveis 2 a = 5 b = "doodoo" c = 1.3 print(type(a)) print(type(b)) print(type(c)) print(type(10 > 5)) ## Declarando Variaveis 2.1 #a) Lista classe = ['healer', 'warrior', 'druid', 'assassin', 'mage'] print(type(classe)) ##b) Conjunto idades = {62,58,27,34,12} print(ty...
from abc import ABCMeta, abstractmethod import functools # Abstract class declaration # This ensures compatibility between Python 2 and 3 versions, since in # Python 2 there is no ABC class ABC = ABCMeta('ABC', (object,), {}) class Backend(ABC): """ Base class for RDataFrame backends. Subclasses of this clas...
#dice rolling simulator import random import string def dice_rolling(): i = True while i is True: print 'You have rolled: ', random.randint(1,6) roll = raw_input('Roll the dice? (Y) / (N) : ') if roll == ('Y' or 'y'): i = True else: i = False dice_rolling()
import os def rename_files(): #(1) get file names from a folder file_list = os.listdir(r"C:\Python27\prank") #r stands for rawpath print file_list saved_path = os.getcwd() #tells python to use the current working directory print ("current working directory is" +saved_path) '''now we see that pyt...
#coding:utf8 import numpy as np import time def RadixSort(A,d): B = A[:] for i in range(d-1,-1,-1): C = np.zeros(256,dtype=np.int32) AA = B[:] for a in AA: C[ord(a[i])] += 1 for j in xrange(1,256): C[j] += C[j-1] for k in range(len(AA)-1,-1,-1): B[ C[ord(AA[k][i])] -1 ] = AA[k] C[ord(AA[k][i])]...
# coding:utf8 import numpy as np import time def qsort(A,p,r): if p<r: q = partition(A,p,r) qsort(A,p,q-1) qsort(A,q+1,r) def partition(A,p,r): x = A[r] i = p for j in xrange(p,r): if A[j] <= x: tmp = A[j] A[j] = A[i] A[i] = tmp i += 1 A[r] = A[i] A[i] = x return i n = 1000000 x = np.r...
################################### ##| |## ##| |## ##| Rocky Vargas |## ##| |## ##| |## ################################### # This function is used to allow the user to input numbers....
import cv2 as cv import numpy as np roi = cv.imread('pic1.jpg') #67페이지에 축가해야할 코드가 있음 binary = np.zeros((roi.shape[0],roi.shape[1],roi.shape[2]),dtype=np.uint8) # Opencv에서 imread함수를 사용하면 흑백이미지여도, rgb 3채널로 입력된다. for i in range(roi.shape[0]): for j in range(roi.shape[1]): if (roi.item(i,j,0) >= 127): ...
with open('input.txt') as input_file: expenses = [int(line) for line in input_file] # x = 2020 - y def find_year_numbers_multiplied(year): for i in expenses: key = year - i for j in expenses: if key == j: return i * j print(find_year_numbers_multiplied(2020))
def sum1(a,b): try: c = a+b return c except : print "Error in sum1 function" def divide(a,b): try: c = a/b return c except : print "Error in divide function" print divide(10,0) print sum1(10,0)