text
stringlengths
37
1.41M
maior = menor = 0 for x in range(5): peso = float(input('Informe o peso da {} pessoa'.format(x+1))) if menor == 0: menor = peso maior = peso elif peso > maior: maior = peso elif peso < menor: menor = peso print('O maior peso foi {}KG e o menor peso foi {}KG'.format(maior...
""" A decorator for caching properties in classes. Examples: >>> class Foo(object): ... @cached_property ... def bar(self): ... print("This message only print once") ... return None >>> foo = Foo() >>> foo.bar This message only print once >>> foo.bar """ impo...
#!/usr/bin/env python """ This is my implementation of Application #4 from the Algorithmic thinking course. created by RinSer """ import random from matplotlib import pyplot as plot import math import project4 # File names HUMAN_EYELESS_PROTEIN = 'HumanEyelessProtein.txt' FRUITFLY_EYELESS_PROTEIN = 'FruitflyEyele...
""" Function to draw the graph in_degree distribution plot. created by RinSer """ import matplotlib.pyplot as plot def draw(graph, plot_file, title, xlabel, ylabel, log=True): """ Draws the plot of a given graph. Returns nothing. """ plot.plot(graph.keys(), graph.values(), 'ro') plot.title(t...
# -*- coding: utf-8 -*- from modules import * def main(): clear() recipes = get_recipes() print "RESEPTIT" while True: switch = read_input("Kirjoita '1' jos haluat nähdä listan julkaisun mukaan. Kirjoita '2' niin reseptit listataan kategorian mukaan. Kirjoittamalla 'exit' poistuu päävalikkoon.") if switch == '...
from pprint import pprint from var_dump import var_dump import string class WordNode: characters = 0 def __init__(self): self.character = None self.is_word = False self.count = 0 self.children = {} WordNode.characters += 1 def addWord(self, this_tree, word...
"""Solution to problem 8 of IEEEXtreme 10.0.""" def safe_divide(a, b): """Do a safe integer division.""" if a % b != 0: return -1 else: return a / b def main(): """Main application logic.""" line = raw_input().split() atoms = [int(line[0]), int(line[1]), int(line[2])] gl...
# -*- coding: utf-8 -*- """ Created on Thu Jan 3 15:02:29 2019 @author: f556085 """ from functools import reduce buzz_fizz = lambda x: "Fizz" * ( x % 3 == 0) + "Buzz" *( x % 2 == 0) or str(x) string_newline_from_list = lambda x,y: x + "\n" + y resultado = reduce(string_newline_from_list, map(buzz_fizz, range(101)))...
import math import time import itertools from src.Surface import Surface from shapely import geometry from src.Bucket import Bucket class Road(Surface): """ One of the essential building blocks of the traffic environment. A road has a number of lanes and connects to an intersection on each of its ends. Roa...
def val(n): if (len(n)>=10 and len(n)<32): return True if(n.isupper()): d=True if(n.isdigit()): f=True p=input("enter password:") c=val(p) if(c==True): print("Valid") else: print("Invalid")
lst=[] n=int(input("number of element:")) for i in range(n): i=int(input()) lst.append(i) print(lst) j=int(input("search:")) for i in lst: if(i==j): print("element at",i)
#! usr/bin/env python3 def shuttleSort(array): """ Shuttle sort algorithm Bit like a reverse bubble sort Higher numbers sink to the bottom """ for i in range(1, len(array)): for j in range(i, 0, -1): if array[j-1] > array[j]: temp = array[j-1] ...
#! usr/bin/env python3 def bubbleSort(array): """ Bubble sort algorithm: Sum of n-1 where n = list. Max number of swaps per pass == n-1 """ for i in range(0, len(array)-1): for j in range(0, len(array)-i): if array[j+1] > array[j]: temp = array[j+1] ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # punkcja zachowujaca sie jak print w python3.x from __future__ import print_function from sys import maxsize from Graph import Graph # rysowanie minimalnego drzewa rozpinającego import networkx as nx import matplotlib.pyplot as plt # algorytm dijkstry, jako argument p...
#Describe how you could use a single array to implement three stacks #first stack would be from 0 to n/3-1 #second stack would be from n/3 to 2*n/3-1 #third stack would be from 2*n/3 to n-1 #0 1 2 3 4 5 6 class Node(): data = 0 next = None def __init__(self,data): self.data = dat...
#fresher class Fresher(): canHandleCall = True #technical lead class TL(): canHandleCall = True #project manager class PM(): canHandleCall = True class Employees(): freshers = [] def __init__(self,fresher,tl,pm): self.freshers.append(fresher) self.tl = tl self.p...
class Pawn(): line = 0 column = 0 team = "" def __init__(self , line , column , team): self.line = line self.column = column self.team = team #white or black #return a list of possible points where the pawn can move #on the given board def GetPossibl...
#P = float(input(P) #n = 1 #r = .0821 #T = float(input(T) from scipy.constants import convert_temperature from pint import UnitRegistry ureg = UnitRegistry() print("Unit Converter") print() # pressure = [] # volume = [] # n = 1 # T = [] def CalculateVolume(P, n, T): R = 0.0821 n = 1 ...
# https://courses.edx.org/courses/course-v1:MITx+6.00.1x_6+2T2015/courseware/sp13_Week_3/videosequence:Lecture_5/ def recurPowerNew(base, exp): ''' base: int or float. exp: int >= 0 returns: int or float; base^exp ''' if exp == 0: return 1 elif exp % 2 ==0: return recur...
# Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. # For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh # In the case of ties, print the first s...
方法一:递归 我们可以对这两棵树同时进行前序遍历,并将对应的节点进行合并。在遍历时,如果两棵树的当前节点均不为空,我们就将它们的值进行相加,并对它们的左孩子和右孩子进行递归合并;如果其中有一棵树为空,那么我们返回另一颗树作为结果;如果两棵树均为空,此时返回任意一棵树均可(因为都是空)。 class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t2==None: return t1 if t1==None: return t2 ...
class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: max_ = 0 for trip in trips: max_ = max(trip[2],max_) line = [0]*max_ for trip in trips: for i in range(trip[1],trip[2]): line[i] += trip[0] for l in li...
"""gffpandas depends on the following libraries: pandas (pd), itertools and defaultdict from collections.""" import pandas as pd import itertools from collections import defaultdict def read_gff3(input_file): return Gff3DataFrame(input_file) class Gff3DataFrame(object): """Creating 'Gff3DataFrame' class fo...
from employees import * import os class EmployeesManager: def __init__(self): self.employees_list = [] def run(self): self.load_employees() # 1ԱϢ while True: # 2ʾܲ˵ self.show_menu() # 3û빦 try: menu_num = int(input('ҪĹţ')...
if 5 > 4: print("helloworld!") else: print("no Hello :(") my_array = ["vamsi", "sai", "rama", "krishna"] if "vamsi" in my_array: print("vamsi listed in array!") for name in my_array: print("my name is {0}").format(name) start = 10 end = 20 inc = 2 for index in range(start, end, inc): print("my ...
'''some helpful tools for processing the natural languages''' import nltk def avg_word_length(corpus, punctuation=True): '''Calculate the average word length in a corpus or corpus subset. Used to answer question 1 and 2 particularly''' try: #First try treating the corpus as a word list wor...
print(4*5) print(5*4.2) print(20.1/4) # float divided by int gives a float print(20/3) # int divided by int can result in a float print(2**2/4-3) # multiple mathetimatical operators appears to follow PEDMAS print('hello'*2) #produces hello twice print('hey'+'dude')
# 第12章のチャレンジ # http://tinyurl.com/gpqe62e # 'りんご'から思い浮かぶ4つの属性を考え,インスタンス変数に持たせて,Appleクラスを定義するプログラム # 名前,重さ,色,腐る性質をインスタンス変数に持たせる class Apple: def __init__(self, n, w, c): self.name = n self.weight = w self.color = c self.mold = 0 def rot(self, days, temp): se...
# 第3章のチャレンジ # http://tinyurl.com/zx7o2v9 print('ジオブレイク70S', 'ジオブレイク80S', 'Fレーザー7S') x = 7 if x < 10: print('伸びしろですね') elif 10 <= x <= 25: print('もっとできるはずさ') else: print('慢心ではなく自信を持て!') print(2020 % 825) print(2020 // 825) barth_year = 2000 age = 2020 - barth_year if age >= 20: print...
#!/usr/bin/env python class Animal(object): pass class Dog(Animal): def talk(self): return "whoof whoof" class Cat(Animal): def talk(self): return "miao" class Pig(Animal): def talk(self): return "oink oink" def all_animals(): return Animal.__subclasses__() if __name__ ...
#!/usr/bin/env python # encoding: utf-8 '''Calculate distance of path in .kmz file in Km''' from collections import namedtuple from math import sqrt, sin, cos, atan2, radians from zipfile import ZipFile, BadZipfile import xml.etree.ElementTree as et namespaces = {'gx': 'http://www.google.com/kml/ext/2.2'} Coord = nam...
#!/usr/bin/env python ''' Solving http://projecteuler.net/index.php?section=problems&id=24 Note that Python's 2.6 itertools.permutations return the permutation in order so we can just write: from itertools import islice, permutations print islice(permutations(range(10)), 999999, None).next() And it'll work mu...
#!/usr/bin/env python3 ''' 字段:学生姓名 班级 Linux PHP Python stu1 = {'id':1,'sname':'tom','bj':'1','Linux':100,} ''' stu_info = [] id = 0 def menu(): print(''' | ----------学生成绩系统--------| | | | ==========主功能菜单==========| | | ...
""" RNA Alignment Assignment Implement each of the functions below using the algorithms covered in class. You can construct additional functions and data structures but you should not change the functions' APIs. You will be graded on the helper function implementations as well as the RNA alig...
import turtle from math import cos,sin from time import sleep window = turtle.Screen() window.bgcolor("#FFFFFF") mySpirograph = turtle.Turtle() mySpirograph.hideturtle() mySpirograph.tracer(0) mySpirograph.speed(0) mySpirograph.pensize(2) myPen = turtle.Turtle() myPen.hideturtle() myPen.tracer(0) m...
import pygame as game import random import math from settings import LOGO_IMAGE, BACKGROUND_IMAGE, CONTAINER_SIZE # FIXME: Maybe there is a better way to store rgb colors than dict? color = { "INFECTED": (255, 0, 0), # Red in RGB "HEALTHY": (0, 0, 255) # Blue in RGB } class Container: """ Main container...
""" COMP30024 Artificial Intelligence, Semester 1 2019 Solution to Project Part A: Searching Authors: John Stephenson (587636) Asil Mian (867252) """ import sys import json import heapq from board import Board from bprint import print_solution def main(): with open(sys.argv[1]) as file: data = json.load...
import pygame if __name__ == '__main__': # try: n = int(input()) if n <= 0: raise Exception size = width, height = 300, 300 pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption("Ромбики") w, h = width, height x,...
#!/bin/python import sys from math import log def main(argv): n = int(argv[1]) for i in range(n+1): print('%d: %d' % (i, count_factorial_zeros_iterative(i))) def count_factorial_zeros(n): """Succinctly returns number of trailing zeros in n!""" if n < 0: return -1 elif n == 0: ...
#!/usr/bin/env python3 # This is an extended Sieve of Erastosthenes, where it generates a complete prime # factorization of all integers up to some given maximum. from typing import List from typing import Dict def primefaclist(n:int) -> List[Dict[int,int]]: a = [dict() for i in range(n)] for p in range(2, l...
# will print [22.1, 23.4, 34.0, 23.0] #temps = [221, 234, 340, -9999, 230] #new_temps = [temp / 10 for temp in temps if temp != -9999] # if using else, to get the same results use #new_temps = [temp / 10 if temp != -9999 else 0 for temp in temps] #print(new_temps) def area(a,b): return a * b print(area(4,...
from time import sleep from timer import RepeatedTimer def hello(name): print ("Hello %s!" % name) print ("starting...") if __name__ == "__main__": rt = RepeatedTimer(3, hello, "World") try: finally: rt.stop()
""" Count the number of unique words in a file """ import argparse import codecs import logging from collections import Counter from multiprocessing import Pool logging.basicConfig() logger = logging.getLogger(__name__) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i',...
print("Please select operation -\n " "1. Add\n " "2. Subtract\n" "3. Multiply\n" "4. Divide\n") # Take input from the user select = input("Select operations form 1, 2, 3, 4 :").strip() number_1 = int(input("Enter first number: ").strip()) number_2 = int(input("Enter second number: ").strip()) # Function to add two nu...
import operator def most_frequent(x): d = {} for i in x: d[i] = x.count(i) d1 = dict(sorted(d.items(), key=operator.itemgetter(1), reverse=True)) for i in d1: print(i,'=', d1[i]) x = input("Enter the input string: ") most_frequent(x)
def who_do_you_know(): people = input("Bitch, who do you know?").split(",") return [person.strip() for person in people] def ask_user(): person_to find = input("Who you tryna find?") if person_to_find in who_do_you_know(): print("Yeah, you know that person.") ask_user();
peso = float(input("Qual o seu peso (kg): ")) altura = float(input("Qual a sua altura (m): ")) imc = peso / (altura)**2 print("Seu IMC é de: {:.2f}. E você esta: ".format(imc)) if imc < 18.5: print("ABAIXO DO PESO.") elif imc < 25: print("COM PESO IDEAL.") elif imc < 30: print("COM SOBREPESO.") elif imc < 40: pr...
par = 0 imp = 0 count = 0 for i in range (1,7): num = int(input("Digite o valor {}: ".format(i))) if num % 2 == 0: par +=num count += 1 #else: #imp += num print("A soma dos {} número(s) pares é igual a {}.".format(count,par))
import types from itertools import islice def group(iterable, n): """Splits an iterable set into groups of size n and a group of the remaining elements if needed. Args: iterable (list): The list whose elements are to be split into groups of size n. ...
from itertools import chain STAR = '*' def gen_rhombus(width): """Create a generator that yields the rows of a rhombus row by row. So if width = 5 it should generate the following rows one by one: gen = gen_rhombus(5) for row in gen: print(row) outpu...
import re def capitalize_sentences(text: str) -> str: """Return text capitalizing the sentences. Note that sentences can end in dot (.), question mark (?) and exclamation mark (!)""" sentences = [sentence.strip() for sentence in re.split(r'(?<=[\.\!\?]) |$', text)] return ' '.join(sentence[0...
import re VOWELS = 'aeiou' PYTHON = 'python' def contains_only_vowels(input_str): """Receives input string and checks if all chars are VOWELS. Match is case insensitive.""" # use regex for this one vowels_found = re.findall(r'[aeiou]', input_str, flags=re.I) return len(vowels_found) == len(in...
from operator import mul from functools import reduce def get_octal_from_file_permission(rwx: str) -> str: """Receive a Unix file permission and convert it to its octal representation. In Unix you have user, group and other permissions, each can have read (r), write (w), and execute...
import re def count_indents(text): """Takes a string and counts leading white spaces, return int count""" return re.match(r'^[ ]*', text).end()
WHITE, BLACK = ' ', '#' def create_chessboard(size=8): """Create a chessboard with of the size passed in. Don't return anything, print the output to stdout""" row = str(WHITE + BLACK) * int(size / 2) board = [row if count % 2 == 0 else row[::-1] for count in range(size)] print(*board, s...
#group 13 984165 and 965396 #we set move on valid for using it in the while loop move='valid' while move=='valid': #inputing the moves goat=str(input('Please enter the move of the goat(w/e):')) wolf=str(input('Please enter the move of the wolf(w/e):')) cabbage=str(input('Please enter the move of the ...
# This script basically takes as first input a number from 1 to 3, by which the search engine is selected: # 1 for conjunctive query # 2 for pages ranked with cosine similarity over TfIdf of query and documents # 3 for the custom one, that computes a score given by the average distances between the query and documents ...
aircrafts=[{'x':1,'y':7},{'x':3,'y':5},{'x':4,'y':8},{'x':9,'y':10},{'x':6,'y':12}] aircraft_number=1 for aircraft in aircrafts: print "Air-craft Number: ",aircraft_number print(aircraft['x']) print(aircraft['y']) print '\n' aircraft_number+=1
#Python Bank Main import os import csv import statistics # grabbing the csv file for budget data csvpath = os.path.join('budget_data.csv') with open(csvpath, newline='') as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') # Read t...
a=int(input()) b=int(input()) for i in range(a,b): i%2==0 print("odd numbers")
line = "smile please" list = line.split(" ") print("No. of words in the list : "+str(len(list)))
list1 = [] list2 = [] list3 = [] n1 = int(input("Total elements in first list : ")) for i in range(n1): value = int(input("input no : ")) list1.append(value) n2 = int(input("Total elements in second list : ")) for i in range(n2): value = int(input("input no : ")) list2.append(value) i...
print("enter 3 number/n") num1=int(input("first number:")) num2=int(input("second number:")) num3=int(input("third number:")) if num1>num3 and num1>num2: print(num1,"is large") elif num2>num3: print(num2,"is large") else: print(num3,"is large")
import networkx as nx class SocialGraph(): """ Creates a graph of twitter friends representing a community """ def gen_user_friends_graph(self, user: str, user_friends_getter, social_graph_setter): """ Generates a user friends graph for a given user @param user the user to gen...
from typing import List, Dict from src.model.user import User class FriendSetter: """ An abstract class representing an object that stores all of a users friends in a datastore """ def store_friends(self, user_id: str, friends_ids: List[str]): raise NotImplementedError("Subclasses should i...
from typing import List, Dict from src.model.ranking import Ranking class RankingSetter: """ An abstract class representing an object that stores tweets in a datastore """ def store_ranking(self, ranking: Ranking): raise NotImplementedError("Subclasses should implement this") def sto...
from typing import List, Dict from src.model.user import User class UserSetter: """ An abstract class representing an object that stores users in a datastore """ def store_user(self, user: User): raise NotImplementedError("Subclasses should implement this") def store_users(self, users: Li...
import msds510.util as mod import csv import sys arg_list = sys.argv #fieldname variable takes the argument list 1 filename = arg_list[1] lines = [] #use reader as a dictionary which is how the lines will be formatted with open(filename,'r') as csv_file: csv_reader = csv.DictReader(csv_file) #for each line...
#!/usr/local/bin python3 # -*- coding: utf-8 -*- # https://www.programiz.com/python-programming/global-local-nonlocal-variables x = "global" def foo(): #global x # x = x * 3 # 如果不使用global关键字, 则python 会查找local variable x 并进行赋值,由于没有找到 local variable x而抛出错误 print(x) #即使不使用global,print 也可以访问 全局变量 foo() ''' ...
#!/usr/local/bin python3 # -*- coding: utf-8 -*- #python 约定使用大写定义常量,例如 JAN = 1 FEB = 2 #好处是简单,缺点是类型是int,并且仍然是变量。 #更好的方法是为这样的枚举类型定义一个class类型,然后,每个常量都是class的一个唯一实例。Python提供了Enum类来实现这个功能: from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) ...
#!/usr/local/bin python3 # -*- coding: utf-8 -*- #------------------------------------------------------------------------------------------------------------------------- # slice #------------------------------------------------------------------------------------------------------------------------- #L[0:3]表示,从索引0开...
"""Python serial number generator.""" class SerialGenerator: """Machine to create unique incrementing serial numbers. >>> serial = SerialGenerator(start=100) >>> serial.generate() 100 >>> serial.generate() 101 >>> serial.generate() 102 >>> serial.reset() >>> serial.generat...
player1 = "1 or 2" player2 = "2 or 1" Board = [["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_","_","_","_","_","_","_","_"],["_","_...
with open("./input.txt") as f: content = f.readlines() # you may also want to remove whitespace characters like `\n` at the end of each line content = [x.strip() for x in content] # print(content) def build_path(right,down): output = "" current_y = 0 current_x = 0 height = len(content) width =...
fname = input("Enter file name: ") fh = open(fname) lst = list() for line in fh: slst = list() slst = line.split() for num in range(len(slst)) : if slst[num] not in lst : lst.append(slst[num]) lst.sort() print(lst)
""" This is was Part 1 of a Python Skills Refresher assignment. """ import string def preceding(letter): alphabet = string.ascii_letters alphabet_as_list = list(alphabet) alphabet_as_list.remove('A') alphabet_as_list.remove('a') if letter is 'A': code = chr(int(ord('Z'))) elif letter is 'a': code = chr(in...
def reverse_detail(str1): return str1[-1:] + str1[1:-1] + str1[:1] print(reverse_detail('ears'))
def odd_remove(str1): str2="" for st in range(len(str1)): if st % 2 == 0: str2 += str1[st] return str2 print(odd_remove('legs'))
# Jordan Leung # 2/13/2019 # printing out what is given print("Given: ") cubes = [num**3 for num in range(1,11)] print(cubes) # printing out the first three items print("The first three items in the list are: ") print(cubes[:3]) # printing out the middle of the list print("Three items from the middle of...
# Jordan Leung # 2/11/2019 guests = ['Henry', 'Sifu Jeff', 'Tayler', 'Mat'] print(guests) print(guests[0] + ", " + guests[1] + ", " + guests[2] + ", and " + guests[3] + " are invited to this family dinner!") print("But I just realized that not everyone on the list are part of my family...") print(guests[0] + ...
print("Mary had a little lamb.") print("Its fleece was white as %s." % 'snow') #전체 괄호 치면 됨 print("And everywhere that Mary went.") print("." * 10) # what'd that do? end01 = "C" end02 = "h" end03 = "e" end04 = "e" end05 = "s" end06 = "e" end07 = "b" end08 = "u" end09 = "r" end10 = "g" end11 = "e" end12 = "r" # watch t...
class Person: TITLES = ('Dr', 'Mr', 'Mrs', 'Ms') def __init__(self, title, name, surname, allowed_titles=TITLES): if title not in allowed_titles: raise ValueError("%s is not a valid title." % title) self.title = title self._name = name self.__surname = surn...
""" Program: employee.py Author: Spencer Cress Date: 6/30/2020 """ import datetime class Person: def __init__(self, _last_name, _first_name, _address, _phone_number, _salaried, _salary, _start_date): """ :param _last_name: string, employee's last name :param _first_name: st...
# -*- coding: utf-8 -*- """ Created on Sun Oct 22 00:00:16 2017 @author: ANEESH """ import numpy as np import matplotlib.pyplot as plt #x = np.random.randn(10,1) ranges = [i for i in range(1,101)] angle = [i*np.pi/16 for i in ranges] radius = [6.5*(104-i) for i in ranges] x1 = radius*np.cos(angle) y1 = radius*...
# Выведите первый и последний элемент списка. lst = [1, 2, 3, 4, 5, 6, 7] print(lst[0], lst[-1])
# Нужно проверить, все ли числа в последовательности уникальны. lst1 = [34, 60, 44, 15, 99] lst2 = [34, 60, 34, 15, 99] print(len(lst1) == len(set(lst1))) print(len(lst2) == len(set(lst2)))
"""Provides methods for getting user input for Mastermind game.""" import random class MastermindUI: def __init__(self): self.keywords = {'help' : 'help', 'info' : 'info'} self.color_options = ('black', 'blue', 'green', 'red', 'white', 'yellow') print('Welcome to Mastermind in Python, wri...
A=[] B=[] A= input('enter for list A:') B= input('enter for list B:') def fizzbuzz (A,B): C=len(A)+len(B) if (C%5==0 and C%3==0): print( 'fizzbuzz') elif (C%3==0): print ('fizz') elif (C%5==0): print ('buzz') else: print (C) fizzbuzz(A,B)
list=[1,2,3,4,5,6,7,8,9,0] i = 0 z = [] while i < len(list): j = 0 x = [] while j < 3: d = i+j x.append(d) j += 1 z.append(x) i += 3 print(z)
import pandas as pd import seaborn as sns from sklearn.decomposition import PCA sns.set(style="white", color_codes=True) import warnings import matplotlib.pyplot as plt warnings.filterwarnings("ignore") dataset = pd.read_csv('CC.csv') dataset = dataset.fillna(dataset.mean()) x = dataset.iloc[:,[1,2,3,4,5,6,7,8,9,10,1...
#Author: Nithin Prasasd #Date Created: 28/09/2019 #Program Name: palindrome_permutation.py #Program Description: (CTCI 1.4) Given a string, write a function to check if it is a # permutation of a palindrome (not limited to dictionary words). #Note: case of letters are irrelevant AND ignore non-letters! #Note: ...
#Author: Nithin Prasad #Date Created: 28/09/2019 #Program Name: one_away.py #Program Description: Given 2 strings, this program checks if they are one away (by # insert, remove or delete) #Note: spaces and non-alphabetic characters count, case does not! #Note: algorithm is of complexity O(n) in time, O(1) in sp...
# 基于灰度的形态学的车牌定位: # 首先根据车牌区域中丰富的纹理特征,提取车牌图像中垂直方向的边缘并二值化。 # 然后对得到的二值图像进行数学形态学(膨胀、腐烛、幵闭运算等)的运算,使得车牌区域形成一个闭合的连通区域。 # 最后通过车牌的几何特征(高、宽、宽高比等)对得到的候选区域进行筛选,最终得到车牌图像。 import numpy as np import cv2 __GaussianKernelSize = 5 __closingKernelSize = np.ones((3, 17), np.uint8) __SobelOperatorSize = 3 ASPECT_RATIO = 44 / 14 # ...
import os import sys sys.path.append('.') import numpy as np import pandas as pd import psycopg2 # Import survey data loading script from src.data.make_survey_dataset import load_data_as_dataframe ### ----- Set up project directory path names to load and save data ----- ### FILE_DIRECTORY = os.path.split(os.path.rea...
#-*- coding:utf-8 -*- # 18) Seja a lista [3, 5, 1, 7, 2, 8, 11, -2, 3 -6, 0]. # Escreva um programa em Python que gere esta lista e apresente seus valores na ordem original e na ordem invertida. numbers = [3, 5, 1, 7, 2, 8, 11, -2, 3 -6, 0] print(numbers) print(numbers[::-1])
#-*- coding:utf-8 -*- # 8) Escreva um programa em Python que escreva na tela os números de 1 a 10. Use a estrutura de repetição for. numberList = [] for i in range(1,11): numberList.append(i) print(f'Lista: {numberList}')
#-*- coding:utf-8 -*- # 11) Escreva um programa em Python que leia repetidamente 5 números do teclado e indique, para cada, se é positivo. for i in range(1,6): number = int(input(f'Digite o {i}º número: ')) print(f'Número é {"positivo" if number >= 0 else "negativo"}.')
import pprint birthdays={'Austin':'April 30','Joseph':'August 8','Rozy':'June 04','Hawi':'September 25','Rosa':'October 10'} while True: print("Enter Your name:(Blank to quit)") name=input() if name=='': break if name in birthdays: print(birthdays[name]+" is the birthday of "+ name) else: print("I do not ha...
# This program says hello and asks for my name. print('Hello World!') print('What is Your Name?')#as for their name myName = input() print('it is Good to meetyou, ' + myName) print('the length of your name is:') print(len(myName)) print('What is Your age?')# ask for their age myAge = input() print('You will be ' +str(...
#This is a guessing game. import random secretnumber=random.randint(1,10) print("I am thinking of a number between 1 AND 10") # ask the player to guess 5 time. for guesstaken in range(1,6): print('Take A guess.') guess=int(input()) if guess<secretnumber: print("The guess is too low.") elif guess>secretnumber: ...