text
stringlengths
37
1.41M
###CS - 177 ###Sarah Hermanek, Nicholas Koontz, HeeJoon Rnoh ###lab5.py ## ###This program completes a demographic survey of some students, including a count of the number of students ###in each demographic region, and a horizontal bar graph depicting this distribution ## ##print("This program completes a demogr...
##This is the program where vertices are provided first and then edges are provided ## we will modify it just to take edges and the edgelist for it class Vertex(object): def __init__(self, n): self.name = n self.neighbours = list() def add_neighbours(self, v): if v not in self.neighbour...
#! /usr/bin/env python3 import re regex_integer_in_range = r"^[1-9]\d{5}$" # Do not delete 'r'. regex_alternating_repetitive_digit_pair = r"(\d)(?=\d\1)" # Do not delete 'r'. for P in map(str,[12345, 123456, "023456"]): print((bool(re.match(regex_integer_in_range, P)) and len(re.findall(regex_alternating_rep...
""" 功能说明:数据分页 ------------------------------------------------------------- 修改人 修改时间 ------------------------------------------------------------- 王泽华 2018-4-9 """ from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from . import paginator as api_paginator de...
def is_triangle(x, y, z): if x > y + z: print 'No' elif y > x + z: print 'No' elif z > y + x: print 'No' else: print 'Yes' def get_triangle_input(): x = int(raw_input('Enter length 1:\n')) y = int(raw_input('Enter length 2:\n')) z = int(raw_input('Enter length 3:\n')) is_triangle(x, y, z) get_triangle...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Print statements in Python print("Welcome to Python Programming") # In[14]: # Arithematic Operations 6 + 5 6 - 5 6 * 5 6 / 5 4 ** 2 # square of 4 * 4 4 ** 3 # 4 * 4 * 4 4 ** 4 # mulitple of 4 * 4 * 4* 4 # In[18]: 201 / 5 # It gives complete value 201 //...
import numpy as np from _cubature import _cubature def cubature(ndim, func, xmin, xmax, args=None, adaptive='h', abserr=1.e-8, relerr=1.e-8, norm=0, maxEval=0, vectorized=True): """Numerical-integration using cubature technique. Parameters ---------- ndim : integer N...
import tkinter as tk from tkinter import ttk from tkinter import messagebox as m_box win=tk.Tk() win.title('MSG') label_frame=ttk.LabelFrame(win,text='Contact detail') label_frame.grid(row=0,column=0,padx=40,pady=10) name_label=ttk.Label(label_frame,text='Enter your name please: ') name_label.grid(row=0,column=0,padx=...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def rotateRight(self, head, k): """ :type head: ListNode :type k: int :rtype: ListNode """ length,p=0...
# -*- coding:utf-8 -*- class Solution(object): def exist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ if not board: return False visited=[] m,n=len(board),len(board[0]) length=len(word) ...
# -*- coding:utf-8 -*- class Solution(object): def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ self.count=0 self.detectPath(1,1,m,n) return self.count def detectPath(self,down,right,m,n): if down==m and right==n:#...
# -*- coding:utf-8 -*- class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ if k==1:#k==1的时候,即只取一个元素作为组合 return [ [i] for i in range(1,n+1)] elif k==n:#如果k==n,即n个数取n个数组成组合 return [ [...
# -*- coding:utf-8 -*- class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ pathList=path.split("/") length=len(pathList) stack=[] print pathList for i in range(length): if pathList[i]=="" or pat...
def rotate_anti_clock(matrix): n = len(matrix) # 1 5 9 13 # 2 6 10 14 # 3 7 11 15 # 4 8 12 16 for i in range(0, n): for j in range(i+1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # reverse the rotated matrix for counter clock matrix = matrix[::-1] return matrix def rotate_clock(matrix):...
def createSquares(untilNum): list = range(untilNum+1) for i in list: yield i**2 squaresUntil10 = createSquares(10) for i in squaresUntil10: print i
# Machine Learning Online Class - Exercise 2: Logistic Regression import numpy as np import matplotlib.pyplot as plt import scipy.optimize as op def sigmoid(x): return 1 / (1 + np.exp(-x)) def plotData(X, y): index0 = list() index1 = list() j = 0 for i in y: if i == 0: index0...
""" base.py - base class for alphabetic encode implementations """ __author__ = 'paws@delimitize.com' class CipherError(Exception): """General purpose Exception object for inheriting at will, for exceptions""" pass class Cipher(object): """ Cipher Base Class - abstract general object mgmt/usage qol...
#https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def largestValues(self, root): ""...
#https://leetcode.com/problems/intersection-of-two-linked-lists/description/ #reference:https://blog.csdn.net/coder_orz/article/details/51615444 # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def ...
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ letters = "" for i in s: if i.isalnum(): letters += i letters = letters.lower() return letters == letters[::-1] ...
def solution(phone_book): answer = True arr = sorted(phone_book) for i in range(len(arr)-1): for j in range(i+1, len(arr)): tmp = arr[i] in arr[j] if tmp: answer = False return answer return answer solution(["119", "97674223", "119552442...
# N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오. import sys input = sys.stdin.readline def merge_sort(list): if len(list) <= 1: return list mid = len(list) // 2 leftList = list[:mid] rightList = list[mid:] leftList = merge_sort(leftList) rightList = merge_sort(rightList) return merge(l...
#coding:utf-8 """ Implementation of DPLL algorithm for solving SAT problem """ import SAT_implementation.bool_formulas as bf import SAT_implementation.algorithm_utilities as au def DPLL(formula): """ Implementation of DPLL - argument is formula in CNF form. Returns False if formula is not in SAT or values of varia...
""" Examples of using the SAT algorithm to solve the hadamard matrix problem. """ __author__ = 'Grega' import SAT_translations.hadamard_to_SAT as ha import SAT_implementation.algorithm_DPLL as dpll import time def run_example(n): """ Helper method that converts the hadamard matrix of size n to a boolean formula an...
__author__ = 'Grega' import unittest import SAT_implementation.bool_formulas as bf import SAT_implementation.algorithm_utilities as au class remove_duplicates_unit_test(unittest.TestCase): """ Unit test for the removing duplicates method of the algorithm utilities. """ def test_with_empty_list(self): """ Te...
#!/usr/bin/env python # -*-coding: utf-8 -*- # vim: sw=4 ts=4 expandtab ai # ~ """ # ~ Программистский словарь # ~ map(int , list) - применить int ко всем элементам list. # ~ lambda x: 1 if x+3 in n_list else 0 - ф-ция без названия: x = 1 если x+3 in n_list, в противном случае x = 0. Пример использования n_list_new = ...
import os import json ''' A generic class for inheritance by all the other classes in the project Provides the framework for easily reading an associated config file and a method for extracting any key from said file === This is meant to be used as a way to reduce code duplication and standardise exception handling. A...
#SRT411 Data Analysis Lab 2 #By: Connor Brozic #Code samples retrieved from Ch.3 of Data Driven Security Textbook #Libraries to import and use import urllib import os.path import pandas as pd from IPython.display import HTML import matplotlib.pyplot as plt from matplotlib import cm from numpy import arange ...
# Function to check if a certain ad suits the kind of \ # ads we would like to work with in the future def is_ad_relevant(ad): if ("Albert" in ad['campaign']): if ((not '--' in ad["clicks"]) and (ad["impressions"] != '0')): return True return False #Function to solve question number 1 def b...
nums = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] def isOdd(x): """Returns True only if the x is odd.""" return x % 2 != 0 v = list(filter(isOdd, nums)) v2 = list(filter(lambda x: x % 2 != 0, nums)) print(v) print(v2)
## ------------ Cube List Generator -------------- ## ## The program takes list of inputs from (1 - 10) and ## outputs the Cube of each numbers. ################ def cubeList(values): for i in range(len(values)): values[i] **= 3 numbers = [1,2,3,4,5,6,7,8,9,10] cubeList(numbers) print(numbers)
## The program takes inputs three integers for (hours, mins, seconds) ## and outputs the the Total Seconds passed from MIDNIGHT def secondsSinceMidnight(h, m, s): hours_in_seconds = h * 60 * 60 minutes_in_seconds = m * 60 total_seconds = hours_in_seconds + minutes_in_seconds + s return (f'It i...
import random list1 = [] for item in range(1, 10): list1.append(random.randrange(1, 10, 1)) print(list1) list2 = [i for i in range(1, 10) ] print(list2)
def fib(x): if x < 2: return x return fib(x - 1) + fib(x - 2) for x in range(1, 11): print(fib(x))
from Agent import * #implementation of agent that acts completely randomly whenever given a choice class RandomAgent(Agent): def vote(self,president,chancellor): return 1 if random.random() < 0.5 else 0 #pick the most trusted available player def select_chancellor(self,options): r...
def quick_sort(alist, first, last): if first >= last: # 只有全部分割成一个元素的,我们就返回,否则一直分割,容易出错的地方就是没有把大于考虑进去,我们只要不存在first<last就停止 return mid_value = alist[first] low = first high = last while low < high: while low < high and alist[high] >= mid_value: high -= 1 alist[low] = alist[high] while low < ...
# Сложите цифры целого числа. n = 123246369 result = 0 for i in list(str(n)): result += int(i) print(result) def sum_digits(num): digits = [int(d) for d in str(num)] return sum(digits) print(sum_digits(123246369))
# Напишите программу, которая выводит чётные числа из заданного списка и останавливается, # если встречает число 237. numbers = [ 386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, ] for x in nu...
#!/bin/python3 nums = [int(x) for x in input('Enter nums to double ').split()] res = map(lambda x:x+x,nums) print('Doubled list ',list(res))
class Results: def __init__(this, x, y, z): this.__chem = 0 this.__phy = 0 this.__math = 0 #check and loop this.Physics(int(input("Phy: "))) #check and loop this.Chemistry(int(input("Che: "))) #check and loop this.Mathematics(int(input("Math: "))) def Physics(self, p): if(p>=...
no1 = input("Please enter your annual salary between £10,000 and £20,000:\n") salary = int(no1) no2 = input("Please enter your grade between 1 and 20:\n") grade = int(no2) dept = input("Please enter your dept; IT or HR:\n") cto = input("Are you a CTO? Y or N:\n") bonus=0 pay=0 if(grade>=1 and grade<=10): ...
numbers=[] def ASCII(a): f = open(a, "r") msg = f.read() temp = "" for chr in msg: x = ord(chr) temp = temp + ("%d " %x) numbers.append(x) def Key(a): ch = ord(a[0:1]) return ch def Encrypt(a, b): print(a) print(b) #get inputs fileName = input("Document name: ") password = input("Pa...
#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. sum=0 for x in range(1000): if (x%3)==0: sum=sum+x for x in range(1000): if (x%5)==0: sum=sum+x print(sum)
import collections as c file = open("input.txt", "r") lines = file.readlines() def contains_anagram(words): hasAnagram = False for i in range(len(words)): for j in range(i + 1, len(words)): if c.Counter(words[i]) == c.Counter(words[j]): hasAnagram = True return hasAnag...
n=input("Dati numarul") def factorial(n): p=1 for i in range(1,n+1): p=p*i return p print factorial(n)
""" --- Day 11: Seating System --- Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet!...
#!/usr/bin/env python from netlab import * import numpy as np import matplotlib.pyplot as pp #"""DEMMLP2 Demonstrate simple classification using a multi-layer perceptron # # Description # The problem consists of input data in two dimensions drawn from a # mixture of three Gaussians: two of which are assigned to a sing...
""" BrainBuster.py Jordan Hand and Kevin Fong Brain Buster Problem Formulation A picture of a Brain Buster puzzle can be found here: http://www2.stetson.edu/~efriedma/rubik/misc/mis3.jpg Our implementation of Brain Buster DOES NOT use order of operations. Equations are evaluated from left to right. Uses on python 3...
# Using text2 from the nltk book corpa, create your own version of the # MadLib program. # Requirements: # 1) Only use the first 150 tokens # 2) Pick 5 parts of speech to prompt for, including nouns # 3) Replace nouns 15% of the time, everything else 10% # Deliverables: # 1) Print the orginal text (150 tokens) # 1)...
name=input("Enter the string") charname=input("enter the particular char") f=0 for x in name: if x==charname: f=f+1 print(f)
# range(start(0),end,step(1)) # end is mandatory #range(5(end))==range(0,5,1)==0,1,2,3,4 #range(5,10)==range(5,10,1)==5,6,7,8,9 #range(2,21,2)-- 2,4,6,8,10,12,14,16,18,20 #range(1,20,2)---1,3,5,7,9,11,13,15,17,19 # range(10,0,-1) for x in range(10,0,-1): #print(x) print(x,end="") #print(x) #1 print("\n...
a=5 print("a") print(a) a=99.35 print(a) a=5 b=6 print("a+b") print(a+b) a=5 b=6 bill=250.50 discountAmount=50 bill=bill+discountAmount print(bill) idno = 101 print(idno) # 101 print(type(idno)) # <class 'int'> print(id(idno)) # 15413211 age=39 age=age+1 age+=1 print(age)
marks=int(input('Enter your marks')) if marks>=90: print('Grade A') elif marks>=70: print(('Grade B')) elif marks>=60: print('Grade C')
# Reverse a string name=input("please enter your name") reverse="" for x in name: reverse=x+reverse print(reverse) print(reverse)
#Function without arguments and without return def add(): a=100 b=200 print(a,b) print("the sum is:",a+b) add() # Function with arguments and without return def add(no1,no2): print(no1,no2) print("The sum = ",no1+no2) add(100,200) # Function without arguments and with return def add(): a = 100 ...
from objects.discography import Discography class Artist: def __init__(self, artist_name, spotify_client, genius_client): """ Represents an artist whose discography will be analyzed. :param artist_name: Name of the artist :type artist_name: str :param spotify_client: An obj...
# where we will handle the data import requests def get_data(symbol, start, end): base_url = 'https://marketdata.websol.barchart.com/getHistory.json' api_key = 'f89392b5bae2f7e9737a66feaba2d376' params = {'apikey': api_key, 'symbol': symbol, 'type': 'daily', 'startDate': start, 'endDate': end} ...
user_0 = { 'username' : 'efermi', 'first' : 'enrico', 'last' : 'fermi', } favorite_lang = { 'jen': 'python', 'sarah':'C', 'edward': 'ruby', 'phill' : 'python', } #percorrendo todos os pares chave-valor com um laço for key, value in user_0.items(): print('\n key: '+ key) print('Value...
people_confirmed = { 'jen': 'python', 'sarah':'C', 'edward': 'ruby', 'phill' : 'python', } list_people = { 'jen': 'python', 'Bruno':'C', 'sarah':'C', 'Andrei':'C', 'edward': 'ruby', 'Robert': 'Html', 'phill' : 'python', } for name,language in list_people.items(): if name...
favorite_places = { 'Bruno':['Ibiza', 'Dubai', 'Canadá'], 'Andrei': ['Laguna', 'Criciúma', 'Tubarão'], 'Roberto': ['Sidney', 'Buenos Aires', 'Sincinatti'], 'Laura':['Whashington', 'Rio de Janeiro'], 'Carlos':['Paris', 'Las Vegas'], } for name,places in favorite_places.items(): print("Nome: " +n...
#Exercício 6.7 da página 163 #Exercício 6.8 tem resolução identica people = [] bruno = { 'first': 'bruno', 'last': 'pires', 'age':19, 'city':'Joinville', } andrei = { 'first': 'andrei', 'last': 'villa', 'age':19, 'city':'laguna', } italo = { 'first': 'ítalo', 'last': 'flôr', ...
import json def greet_user(): """Saúda o usuário pelo nome""" username = get_stored_username() if username: print("Welcome back, "+username+"!") else: get_new_username() def get_stored_username(): """Obtem o nome do usuário, se ja armazenado""" filename = 'Arquivos_e_E...
""" This program will import the csv file into the database (see database.py). Please provide first credentials for the server in database.py (or in the environment variables as mentioned in that file.) """ import argparse import json import math import os import sys import mysql.connector import pandas as pd # Re...
russian = 'йцукенгшщзхъфывапролджэячсмитьбю' latin = 'qwertyuiop[]asdfghjkl;\'zxcvbnm,.' def switch_layout(string: str): if not string: return '' if string[0] in russian: char_map = dict(zip(russian, latin)) elif string[0] in latin: char_map = dict(zip(latin, russian)) else: ...
# Regex Version of strip() import re def regex_strip(string, rm_str=None): if rm_str == None: return string.strip() else: string = string.strip() string_regex = re.compile(rm_str) return string_regex.sub('', string) if __name__ == '__main__': string = input('Enter a string...
def encripto(cadena): """Retorna una cadena encriptada en Cifrado César si dicha cadena es válida, es decir, si tiene solo caracteres alfanuméricos.""" lista_de_acciones = [lambda cad: cad.replace(' ', ''), lambda cad: cad.replace(',', ''), lambda cad: cad.replace('.', '')] for accion in lista_de_a...
import analyze_books, analyze_authors, preanalysis import csv as csv books_dict = [] total_books = 0 print("================================") print("==== READING THE DATA SET... ===") with open('fantlab_books_data.csv', 'r', encoding="utf8") as csv_old: reader = csv.DictReader(csv_old) books_dict = [] for...
import math import datetime def getprimes(P): primes = [0]*(P+1) for i in range(2,int(math.sqrt(P))+1): if primes[i]==0: j = i*2 while j <=P: primes[j]=1 j += i count = 0 value=[] for i in range(2,P+1): if primes[i]==0: ...
# min heap # class Heap: def __init__(self): self.heap = [] self.size = 0 def add(self, val): self.heap.append(val) self.size += 1 self.heapify_up() def peek(self): if self.size > 0: return self.heap[0] else: return False def poll(self): if self.size > 0: cur...
# 1007 def prime(x): for i in range(2,x): if x%i==0: return False return True def count_pair(list): count=0 for i,value in enumerate(list): if i+1<len(list): if list[i+1]-value==2: count=count+1 return count if __name__=='__main__': list=[] num=raw_input() for i in range(2,int(num)): if prime...
# 1021 def num_fre(x): num_map={} for item in x: num_map[item]=num_map.get(item,0)+1 return num_map def sort_map(map): return sorted(map.items(),key=lambda item:item[0]) if __name__=='__main__': strs=raw_input() maps=num_fre(strs) order_list=sort_map(maps) for item in order_list: print '%s:%s'%(item[0],i...
from tkinter import *; import random; import time; import PhysicsHelper as Math; import math; class Ball: def __init__(self, canvas, color, xv, yv, mass, x, y): self.canvas = canvas; self.hasNotCollided = True; self.id = canvas.create_oval(10, 10, 25, 25, fill=color); self.canvas.mov...
import numpy as np import unittest # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def isMultiple(num): NUM_A = 3 NUM_B = 5 if (num % NUM_A == 0) or (num % NUM_...
import unittest from problem import factorial from problem import sumAllNumberDigits class TestProblem(unittest.TestCase): def test_factorial(self): self.assertEqual(factorial(10), 3628800) def test_sum_all_numbers_from_digit(self): self.assertEqual(sumAllNumberDigits(12345), 15) sel...
import time def isDivisor(number, divisor): return number % divisor == 0 def isPrime(number): if number < 2: return False for divisor in range(2, int(number**0.5) + 1): if isDivisor(number, divisor): return False return True def checkTruncatableNumber(number): numDi...
from functools import reduce # 2520 is the smallest number that can be divided by each of the numbers # from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of # the numbers from 1 to 20? def getArrayOfNumbers(toNumber): return [i for i in range(1, toNumber + ...
# client.py # Mike Northorp # This program sends UDP pings to a server which then responds with the message in all caps # It also shows when a request is timed out. # Import time and socket import time from socket import * # Create a UDP socket # Notice the use of SOCK_DGRAM for UDP packets clientSocket = so...
from SummonerLookupFunctions import get_ranked_league def get_summoner_from_active_game(active_game, summoner_index, api_connection): """ Gets general summoner info for players in an active game :param dict active_game: The active game dictionary which includes info for each player ...
#!/usr/bin/env python from itertools import combinations, permutations from collections import defaultdict SAMPLE_BOARD = { 0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 7, 1: 8, 2: None} } BAD_BOARD = { 0: {0: 1, 1: 2, 2: 3}, 1: {0: 4, 1: 5, 2: 6}, 2: {0: 8, 1: 7, 2: None} } def gen...
#Determine if a string has all unique characters. #Assume ASCII characters, so max of 128 distinct characters import sys #Using another Data Structure def Solution1(someString): #By pigeonhole if the string has more than 128 characters, there must be some repeat if(len(someString) > 128): return True #Put ch...
def square(x): """Finds the square of the input. Args: x (float): The number to be squared. Returns: x2 (float): The squared number. """ return x**2
""" Capstone Project. Code written by Liam Enneking. Fall term, 2018-2019. """ import rosebotics_new as rb import time import ev3dev.ev3 as ev3 def main(): """ Runs YOUR specific part of the project """ # stop_on_color(5) # Red robot_beep_with_wave() def stop_on_color(color, seconds=15): star...
""" Mini-application: Buttons on a Tkinter GUI tell the robot to: - Go forward at the speed given in an entry box. This module runs on your LAPTOP. It uses MQTT to SEND information to a program running on the ROBOT. Authors: David Mutchler, his colleagues, and Grant Duchars. """ # Video URL: https://youtu.be/y4b...
class Node: ''' A node class that would represent all the node classes ''' def __init__(self, data, left=None, right=None): """ (Node, str, Node, Node) -> NoneType Initialize a new BinTreeNode with data, left and right children. """ self.data = data self.le...
#!/usr/bin/env python # coding=utf-8 import time import numpy import pandas import datetime # -------------------------------------------- # class Prometheus: """Class that handles timeseries datasets. This class is suited for financial data such as price, trades, ohlc, spread ask and bid. The root is a pandas d...
def get_even_numbers_up_to(number): counter = 1 result = '' while counter <= number: if counter % 2 == 0: result = result + str(counter) + ',' counter += 1 return result
''' Functions those an engine uses during testing ''' __all__ = ( 'calculate_distance', 'calculate_distance_between_towns', 'is_lannister_soldier', 'parent_for' ) PARENTS = { 'Daenerys Targaryen': { 'mother': 'Rhaella Targaryen', 'father': 'Aerys II Targaryen', }, 'Cersei L...
# Creating a function from previous code in the semester import os import arcpy # Warm-up function to show handiness of process # This function will take a list and multiply its contents by a factor, then fill and print the new results. # i = list # j = factor def listMultiplier(i, j): newList = [] for x in ...
"""Кодирование осуществляется следующим образом: s = 'aaaabbсaa' преобразуется в 'a4b2с1a2', то есть группы одинаковых символов исходной строки заменяются на этот символ и количество его повторений в этой позиции строки. Напишите программу, которая считывает строку, кодирует её предложенным алгоритмом и выводит закоди...
"""Катя узнала, что ей для сна надо X минут. В отличие от Коли, Катя ложится спать после полуночи в H часов и M минут. Помогите Кате определить, на какое время ей поставить будильник, чтобы он прозвенел ровно через X минут после того, как она ляжет спать. На стандартный ввод, каждое в своей строке, подаются значения X...
# Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. n = 1000 def mul_3_or_5(number): if (number%3==0) or (number%5==0): return True true_list = [] for i...
##given strings,find out the minimum changes to be done for changing them as anagram w1=raw_input() w2=raw_input() import pdb; #pdb.set_trace() total=0 for letter in "abcdefghijklmnopqrstuvwxyz": total+=abs(w1.count(letter)-w2.count(letter)) print total
###find an element in an sorted array which is rotated unkown time import random def findEle(array,key,start,end): mid=(start+end)/2 print start,end,mid if array[mid]==key: return mid if end<start: return 0 if array[mid] > array[start]: if key <= array[mid] and key >= ar...
"""轮廓检测也是图像处理中经常用到的。OpenCV-Python接口中使用cv2.findContours()函数来查找检测物体的轮廓。 cv2.findContours(image, mode, method[, contours[, hierarchy[, offset ]]]) cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset ]]]]]) """ import cv2 img = cv2.imread("water.jpg") gray = cv2.cvtC...
import unittest import os from extractor import * class TestExtractor(unittest.TestCase): def checkExtraction(sentence,type,name): pass def testSource(self): sentence = "There is a game engine Source" s, match = extract(sentence) self.assertNotEqual(len(match),0,"no match found: '" + str(s)+"' ag...
def main(): beratBadan = int(input("Berat Badan (kg) : ")) tinggiBadan = int(input("Tinggi Badan (cm) : ")) print("Dengan Berat Badan {}kg dan Tinggi Badan {}cm".format(beratBadan, tinggiBadan)) BMI = float(beratBadan*10000/(tinggiBadan*tinggiBadan)) print("BMI anda adalah : {:.2f}".format(BMI)...
#Dicts: methods, ... dct = {} # creating dict dct2 = dict() # creating dict print(type(dct)) # shoing type of variable dct age = {"Peter":10, 1:155, "smth":"Something", "mm.":True, "Ivan":25, "igor":80} print(age) age["Feder"] = 3 # adding a new element to a DICT age print(age) del age["Feder"] # Deliting the "Feder" ...
# 定义一个函数,函数名字为show,无参 def show(): print("show") def sum(n): i, s = 0, 0 while i <= n: s += i # s = s + i i += 1 return s def pow(x, y=2): return x ** y def add(*nums): # 可变参数 print(type(nums)) s = 0 for i in nums: s += i return s def show_stu(...
# Variables and Printing age = 23 print(age) #Use underscore to separate words (snake Case) friend_age = 30 #Numbers PI = 3.1415926 #Float age = 25 #integer math_operation = 1 * 3 +4 / 2-3 print(math_operation) float_division = 13 / 3 print(float_division) integer_division = 13 // 3 # double div...
f = open("Countries.txt", "r") countries = [] for line in f: line = line.strip() countries.append(line) f.close() print(countries) print(len(countries)) ##for country in countries: ## if country[0] == "T": ## print(country) ## ##v = open("Countries.txt", "w") ## ##while True: ...