text
stringlengths
37
1.41M
__author__ = 'Brown' class TreeNode: def __init__(self,val): self.val=val self.left=None self.right=None class Solution: def dfs(self,nums): if len(nums)==0: return [None] res=[] for root_index in range(len(nums)): left=self.dfs(nums[:root...
__author__ = 'Brown' class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ if strs==['']: return [['']] dict={} res=[] for word in strs: tmp=''.join(sorted(word)) ...
__author__ = 'Brown' class TrieNode: def __init__(self): self.childs={} self.isWord=False class WordDictionary(object): def __init__(self): self.root=TrieNode() def addWord(self,word): node=self.root for s in word: if not s in node.childs: ...
__author__ = 'Brown' class Solution(object): def getLongestPalindrome(self,s,l,h): while l>=0 and h<len(s) and s[l]==s[h]: l-=1; h+=1 return s[l+1:h] def longestPalindrome(self, s): """ :type s: str :rtype: str """ max_palindrome='' for...
__author__ = 'Brown' class TreeNode(object): def __init__(self,val): self.val=val self.left=None self.right=None self.next=None class Solution(object): def connect(self,root): if root and root.left: root.left.next=root.right if root.next: ...
__author__ = 'Brown' class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() mindiff=10**10 res=0 for i in range(len(nums)): left=i+1 right...
class Human: """This is a class Human""" def __init__(self, name, surname, sex, age, nationality, salary, job): self.name = name self.surname = surname self.sex = sex self.age = age self.nationality = nationality self.__salary = salary self.job = job ...
from main import * from studentLifeASCII import studentLife from Player_0 import player #write((studentLife())) def return_entry(data): #gets input and returns it data = console.get() #print(data) #write(data) choose(data) return data console.bind('<...
class PriceTrend(object): _money_shorthands = {"k": 1000, "m": 1000000, "b": 1000000000} def __init__(self, price, trend, change): self.price = self._extract_price(price) self.trend = trend self.change = self._extract_change(change) def _extract_price(self, price): if pric...
# generator function def firstn(n): num = 0 while num < n: yield num num += 1 print firstn(5) for n in firstn(2): print n # generator expression items = (s for s in [10, 12, 14, 20]) print items print next(items) # prints 10 print next(items) # prints 12
#!/usr/bin/python def numerus(roman): num = 0 idx = 0 while idx < len(roman): n = roman[idx] if n == 'i': num+=1 if n == 'v': if idx>0 and roman[idx-1] == 'i': num+=3 else: num+=5 if n == 'x': if idx>0 and roman[idx-1] == 'i': num+=8 ...
# 0, 1, 1, 2, 3, 5, 8, 13, 21, ... def fibbo(n): t = 0 if n==0: return 0 if n==1: return 1 t1=0 t2=1 for m in range(1, n): t = t1 + t2 t1 = t2 t2 = t return t if __name__ == "__main__": n = 6 print "Fibbo {0} : {1}".format(n, fibbo(n))
def f(x): return x ** 5 def diff2(f, x, h=1e-5): dif = (f(x + h) - 2 * f(x) + f(x - h)) / (h ** 2) return dif print(diff2(f, 1))
num1, num2, num3 = eval(input('enter three numbers separated by commas:')) answer = (num3 + num2 + num1)/3 print('the Average of number 1 ,2 & 3 is ', answer)
user = {} def client(): for i in range(3): name = input('enter name') age = int(input('enter age')) user[name] = age def use(): print(user) def print_details(): client() use() print_details()
import random def roll_dice(): die_1 = random.randrange(1, 7) die_2 = random.randrange(1, 7) return (die_1, die_2) def display_dice(dice): die_1, die_2 = dice print(f' {die_1} + {die_2} = {sum(dice)} ') dice_value = roll_dice() display_dice(dice_value) sum_of_dice = sum(dice_value) if sum_o...
user={} for i in range (3): name=input('enter name') age=int(input('enter age')) user[name]=age print(user)
colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'} print(colors) print(len(colors)) print('pink' in colors) print('red' in colors) for color in colors: print(color.upper(), end=" ") print() num = list(range(11)) + list(range(5)) print(num) a = set(num) print(a)
year = eval(input("Enter a Year to check if it's a leap year \n")) isLeapYear = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) if isLeapYear: print(year, " is a Leap Year", isLeapYear) else: print(year, " is not a Leap Year") print(isLeapYear)
import math if __name__ == '__main__': ab = int(input()) bc = int(input()) deg = round(math.degrees(math.atan2(ab, bc))) print("{}°".format(deg))
# Ask the user for their name. name = input("What is your name? ") # Prints the output print("hello, " + name)
""" Main program loop """ import init import speech_processor """ Initial Setup """ margoinitstatus = init.margo_initialisation() print ("Margo initialised: " + margoinitstatus) """ Choose operating mode """ """ operatingmode = init.choose_mode() """ """ Variable setup""" conversation = False """ Enter Program Sta...
"""Provides an n-dimensional bounding box representation.""" class BoundingBox(object): """Represents an n-dimensional bounding box.""" def __init__(self, p1, p2): """Set the edges of the bounding box based on the observed data.""" self._max = tuple(max([p1[i], p2[i]]) for i in xrange(len(p1...
P = int(input("Enter P modulo:")) G = int(input("Ente primitive root:")) a = int(input("enter first secret:")) b = int(input("enter second secret:")) x = (G**a) % P y = (G ** b) % P if (y**a)%P == (x**b)%P: print("Alice and Bob can communicate with each other") print("their secret key is " + str((x**b)%P)) ...
''' Week 1 MIT Practice: Core Elements of Programming Conditionals, Branching and (for and while) Loops ''' #if-else x = 4 y = 8 if x == y: print('x and y are equal') if y !=0: print('therefore x/y is', x/y) elif x > y: print('x is bigger than y') else: print('y is bigger') #while lo...
def sum_of_factors(num): _sum=0 for x in xrange(1,(num/2)+1): if num%x==0: _sum+=x return _sum def main(): num=0 total=0 while num<10000: sum_f=sum_of_factors(num) if sum_f!=num and num==sum_of_factors(sum_f): total+=num print num num+=1 print total if __name__ == '__main__': main()
def isprime(number): if number!=2 and (number<=1 or number%2==0): return False if number==3: return True check=3 maxneeded=number while check<maxneeded+1: maxneeded=number/check if number%check==0: return False check+=2 return T...
from __future__ import division Onum = 100 count = 0 r=0 while r != 0.99: Onum+=1 num = Onum num = list(str(num)) if num == sorted(num) or num[::-1] == sorted(num): continue else: count+=1 r = count/Onum print Onum #if list(num1) == sorted(list(num1)): print 'increasing' #if list(num2)...
def downR(): sums=0 for x in xrange(2,1001): if x%2==0: sums += x*x - (x-1) return sums def downL(): sums=0 for x in xrange(2,1001): if x%2==0: sums += x*x + 1 return sums def upR(): sums=0 for x in xrange(2,1002): if x%2!=0: sums += x*x return sums def upL(): sums=0 for x in xrange(2,1001)...
def leap(year): return (((year%400==0) and (year%100!=0)) or (year%4==0)) ; year = int(input('enter year')) if (leap(year)) : print('leap year') else: print('not a leap year')
import nltk movie = "I like the movie Mr. & Mrs. Smith! Brad Pitt, Angelina Jolie, etc. are in it." def main(): ## Use our own sentence tokenizer sentences = naive_sentence_tokenizer(movie) for s in sentences: print(s) ## Use NLTK's sentence tokenizer print("-------...
# x = [1, 2, 3] # y = x # # print(y) # # y[0] = 500 # # print("y", y) # # print("x", x) ### What is going on here??? ### List aliasing #################### ## Loops stuff # print(0) # print(1) # print(2) # print(3) # print(4) # print(5) ### A loop to print 0 to 5 for number in range(1001): print(number) ...
#################### ## Loops stuff # print(0) # print(1) # print(2) # print(3) # print(4) # print(5) ### A loop to print 0 to 5 # for number in range(1001): # print(number) # print("The loop ended!") ### This one goes from 5 to 9 # for x in range(5, 10): # print(x) # print("squaring x gives", x * x) #...
from PIL import Image def main(): image = Image.open("eliza.jpg") # image.show() my_pixel = Pixel((40, 100, 254)) print(my_pixel) print("R component:", my_pixel.r) print("RGB tuple:", my_pixel.get_tuple()) # my_pixel.set_rgb(255, 255, 0) # print("RGB tuple after changing it:"...
def main(): ## Create a grid of color strings, which could be pixels in an image. colors = [["green", "orange", "brown", "orange"], ["blue", "green", "green", "orange"], ["purple", "red", "blue", "red"], ["yellow", "brown", "green", "yellow"]] ### Want to pri...
import random RANKS = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] SUITS = ["Spades", "Hearts", "Clubs", "Diamonds"] def main(): # card = PlayingCard("A", "Spades") # print(card) # print(card.rank) # print(card.suit) # print(card.rank_number()) ### Create a list representing a deck o...
if keyboard.Left.isPressed(): car.x = car.x - 3 if keyboard.Right.isPressed(): car.x = car.x + 3 # ...which allows you to press and hold left and right to move the car # ...but if you don't want press and hold... if keyboard.Up.wasJustReleased(): mario.y = mario.y + 10
#Reverses a string def reverse(str): #Null input if str == None: return "" elif len(str) < 2: return str else: reversed = "" for word in str.split(" "): reversed = word + " " +reversed return reversed if __name__== '__main__': print reverse("The rain in Spain stays mainly in the plain")
"""Utilities functions for jupyter notebook""" import shelve from os.path import join __all__ = ['save_to_shelve', 'save_dict_to_shelve', 'retrieve_from_shelve', 'retrieve_dict_from_shelve', 'print_content_of_shelve'] def save_to_shelve(filename, key, value, foldername='shelve'): """Save the key and...
"""Useful tools for data processing""" import warnings import numpy as np def extract_numbers(text_file, identifier, columns=None): """ Extract numbers from a text file containing ordered columns of numbers """ with open(text_file) as fnm: for line in fnm: if identifier in line: ...
num = int(input("porfavor ingrese un número, positivo:")) while num < 0: print("El número no es positivo!") num = int(input("Ingrese un número positivo: "))
num1 = int(input("Escriba un número: ")) if num1%2==0 : print("su número es par.") elif num1%2!=0 : print("Su número es impar") elif num1==0 : print("Su número es igual a 0")
#Definir una función max_de_tres(), que tome tres números como argumentos y devuelva el #mayor de ellos. def max_de_tres(numI): if num1>num2 and num1>num3 : print(num1) elif num2>num1 and num2>num3 : print(num2) elif num3>num1 and num3>num2 : print(num3) num1=int(input...
# Este es un prograa que emula la funcion de una calculadora num1= int(input("Irtroduzca el primer número:")) op= input("Introduzaca el operador:") num2= int(input("Introduzaca el segundo número:")) if op == ("+"): print(num1+num2) elif op == ("-"): print(num1-num2) elif op == ("*"): print(num1*num2) e...
#Definir una función que tome como argumento dos números y devuelva el mayor de ellos. #(Es cierto que python tiene una función max() incorporada, pero hacerla nosotros mismos es #un muy buen ejercicio. def mayornúmero(numI): if num1>num2 : print(num1) elif num1 < num2 : print(num2) ...
''' Self implement version of simple fully connected NN Input Layer = 1 with Size of features Output Layer = 1 (Probability to be positive class) Hidden Layer = 1 with Size of features * 2 ''' import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import accuracy_sco...
""" Name: problem1.py Description: The program allows a user to input three side lengths. The program will compute and output whether or not the figure is a triangle. Author: Lauren M Created: 23/02/2021 """ print ("Welcome to the Triangle Checker") #The user will input three side lengths lengt...
from enum import Enum class Action(Enum): NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 TERMINAL = 4 def turn(self, clockwise:bool): """ Returns the Action you get when turning this action either clockwise or counter-clockwise. Will return this the terminal acti...
""" Learning linked_list implementation in Python """ # # # # # # class LinkedList(): # # """ # # Class for initialising linked list object. # # """ # # # # def __init__(self): # # self.list_obj = [] # # # # def add_last(self, value): # # self.list_obj.append(value) # # # # def...
class student: def __init__(self, rno, name, marks): self.rno = rno self.name = name self.marks = marks def talk(self): print("my name is ", self.name) print("my rno is ", self.rno) print("my marks are ", self.marks) try: rno = int(input("Enter rno ")) ...
#! /usr/bin/env python import argparse import sys, os if __name__ == '__main__': parser = argparse.ArgumentParser(description='Convert text tables to excel files') parser.add_argument('infiles', type=str, nargs='+', metavar='FILE', help='input text file') parser.add_argument('-o', '--outfile', ...
places = ['thailand', 'japan', 'syberia', 'egypt', 'cuba'] print(places) print(sorted(places)) print(places) print(sorted(places, reverse=True)) print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse=True) print(places)
active = True while active: age = input("How old are you? ") if age == 'quit': break else: age = int(age) if age < 3: price = 0 elif age < 12: price = 10 else: price = 15 if price == 0: print("It is free for you.") else: ...
terms = { 'list': 'A data structure containing a collection of objects.', 'boolean': 'A data type that can have either True or False value.', 'dictionary': 'A data structure that can hold many key-value pairs.', 'for loop': 'A programming mechanism to iterate through elements' + ' of a containe...
alien_0 = {'color': 'green', 'points': 5} print(alien_0['color']) print(alien_0['points']) new_points = alien_0['points'] print("You just earned " + str(new_points) + " points!") alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) # Starting with an empty dictionary alien_0 = {} alien_0['color'] = ...
invited = ['Kadir', 'Mustafa', 'Ozgur'] print(invited[0] + ", please join me this evening at the dinner.") print(invited[1] + ", I am waiting for you this evening for the dinner.") print("I didn't forget you " + invited[2] + '!') excused = 'Ozgur' print("Unfortunately " + excused + " will not be with us this evening."...
print(2+3) print(2-3) print(2 * 3) print(2/3) print(2 ** 3) print(2 + 3*4) print((2+3)*4) # Floats print(0.1 + 0.2) print(0.1 * 3) # Casting to string age = 28 print("Happy " + str(age) + "th age, old man!")
#!/usr/bin/env python3 from abc import ABC, abstractmethod from functools import wraps from typing import Callable class Parameter(ABC): def __init__(self, i_0: int, c: float, d: float, kappa: int, omega: int, **kwargs): """ Every model involves the same mutation model (for now). This involves the paramet...
""" Write a program that will ask the user to enter in three legs of a triangle and then test to see if the triangle is: """ #Not a triangle (a + b < c) a = float(input ("Please enter a positive value, a: ")) b = float(input ("Please enter a positive value, b: ")) c = float(input ("Please enter a positive value, c: ")...
class Player: def __init__(self, game_piece, name): self.game_piece = game_piece self.name = name class Move: def __init__(self, author, position): self.author = author self.position = position class Board: def __init__(self): self.moves = { 'a':["...
''' Input: Lista de preferências de par de cada homem e cada mulher, Output: Lista de pares resultantes. A ideia é seguir o algoritmo de Gale-Shapley, em que iteramos sobre todos os homens disponíveis. Para cada homem, o homem verifica cada uma das mulheres da lista em ordem, se a mulher está disponível eles entram e...
# Laboratório 3 - Sistemas Lineares # # Nicholas Scharan Cysne T22.1 # Professor: Johnny # Data: 29/04/2019 # # Método de Gauss-Jacobi import numpy as np import math # Identificação dos Parâmetros print("Digite a ordem do sistema linear:") order = int(input()) # Ordem do Si...
import turtle, sys, math bob = turtle.Turtle() print(bob) def square(bob, length): bob.pd() for _ in range(4): bob.fd(length) bob.lt(90) bob.pu() #bob.mainloop() #bob.done() #square(bob,200) def polygon(bob, length, n, a): bob.pd() for _ in range(n): bob.fd(length...
"""Solver for Day 3, Problem 2 of Advent of Code 2020.""" from functools import reduce from operator import mul def load_map(): """Load the map to the airport.""" my_map = [] with open("map-to-airport.txt") as f: for line in f.readlines(): line = [1 if x == "#" else 0 for x in line.str...
"""Solver for Day 8, Problem 1 of Advent of Code 2020.""" def load_boot_code(): """Read the boot code from the assembly dump. Will return a ``list`` of "instructions", i.e., a 2-tuple of ``(opcode, arg)``. """ boot_code = [] with open("assembly.txt") as f: for line in f.readlines(): ...
import random import math def mod_invers(a, m): a = a % m for x in range(1, m): if ((a * x) % m == 1): return x return 1 def is_prime(num): if num == 2: return True if num < 2 or num % 2 == 0: return False for n in range(3, int(num ** 0.5) + 2, 2): ...
# Author: Dimgba Martha O # @martha_samuel_ # 37 this creates a new list containing one person per string including their name and email address between angled # brackets def full_emails(people): result = [] for email, name in people: result.append('{} <{}>'.format(name, email)) return result pr...
# Author: Dimgba Martha O # @martha_samuel_ # 51 This returns the name of the city and its country (separated by a comma), when comparing the 3 defined instances # for a specified minimal population class City: pass # initializing attributes class City: name ='' country='' elevation = 0 population ...
# Author: Dimgba Martha O # @martha_samuel_ # 35 this code checks if a string is palindromic. Spaces and letters are ignored. # A palindrome is a string that can be equally read from left to right or right to left, # omitting blank spaces, and ignoring capitalization def palindrome(input_string): new_string = inp...
# Author: Dimgba Martha O # @martha_samuel_ # 26 This recursively counts the amount of users that belong to a group in a system going through each member of # a group and if one of them is a group, recursively calling the function and counting the members. def count_users(group): count = 0 for member in get_...
# Author: Dimgba Martha O # @martha_samuel_ # 50 This code shows that when 2 people who have 1 orange each exchange their oranges they will have 1 orange each but # when they exchange an idea they will have 2 ideas each.Famoue quote by George Bernard class Person: pass class Person: apples =0 ideas =0 jo...
# Author: Dimgba Martha O # @martha_samuel_ # 07 converting miles to km def convert_distance(miles): km = miles * 1.6 result = '{} miles equals {:.1f} km'.format(miles, km) return result print(convert_distance(12)) print(convert_distance(5.5)) my_trip_miles = 5.5 my_trip_km = my_trip_miles * 1.6 print('...
# Author: Dimgba Martha O # @martha_samuel_ # 10 using loops x = 0 while x < 5: print('Not there yet. x = ' + str(x)) x += 1 print('x = ' + str(x)) # prints number of attempts def attempts(n): x = 1 while x <= n: print("Attempt " + str(x)) x += 1 print("Done") attempts(5) #...
class Node: def __init__(self, value): self.data = [value] self.parent = None self.child = [] def __str__(self): if self.parent: return str(self.parent.data) + " : " + str(self.data) return "Root: " + str(self.data) def _is_leaf(self): return len...
# CSC 376 - Programming Exercise 1 # YouTube link: https://youtu.be/kO63M4DubOw import sys print("Standard Input:") words = [] for i in sys.argv: if(i[0] != '-' and i != 'input_program.py'): words.append(i) for line in sys.stdin: print(line, end='') if (len(sys.argv) > 1): print("Command line ...
f = open("input3.txt", "r") treeMap = [] for x in f: x = x.rstrip('\n') y = list(x) treeMap.append(y) def findTrees(treeMap, rightSlope, downSlope): treeCount = 0 x = 0 y = 0 numCols = len(treeMap[0]) numRows = len(treeMap) while x < len(treeMap): if (treeMap[x][y] == '#'):...
#imports import imutils import os from PIL import Image import numpy as np import cv2 import PIL from matplotlib import pyplot as plt from pathlib import Path def display_bounding_box(image,box_coordinates, display=True, resize=(0,0),cropBox=None): ''' Display_bounding_box is a function that draws the corres...
#!/usr/bin/python # -*- coding: utf-8 -*- #指定编码格式,python默认unicode编码 ''' 删除指定文件夹里面的非 .jpg 文件 删除小于10K大小的文件(单位:K) ''' import os def del_files(path): ''' 删除指定文件夹里面的非 .jpg 文件 ''' for root , dirs, files in os.walk(path): print root,dirs,files for file in files: if file.endsw...
class Time: def __init__(self, hour,minute,second): self.hour = hour self.minute = minute self.second = second def __add__(self, other): return self.hour + other.hour, self.minute + other.minute, self.second + other.second t1 = Time(2,10,10) t2 = Time(4,15,20) t3 = t1+...
#!/usr/bin/python # coding = utf-8 __author__ = "liyy" ''' name = raw_input('what\'s you name: ') print 'Hello '+ name+'!' ''' print repr('hello jim') print str(23455)+'JISM' num = 200 print 'num is '+ repr(num) nums = [1,2,3,4]+[5,6,7,8] print nums * 3 list = [None]*10 print list del list[0] pr...
# import platform # print("This is python version {}".format(platform.python_version())) # for accuracy in calculation when working with floats as computer sacrificies accuracy for precision # so import the below module from decimal import * x= Decimal('0.20') print("x is {}".format(x)) print(type(x)) x= 9 pri...
# Игра викторина, надо ответить на вопросы из текстового файла import sys, shelve def open_file(file_name, mode): """открывает файл""" try: the_file = open(file_name, mode, encoding='utf-8') except IOError as e: print(f'Невозможно открыть файл {file_name}. Работа будет завершена', e) ...
import random def bubbleSort(arr): n = len(arr) for i in range(0, n - 1): for j in range(0, n - 1 - i): if arr[j + 1] >= arr[j]: arr[j + 1], arr[j] = arr[j], arr[j + 1] n = int(input("Enter number of elements: ")) array = [random.randint(1, 1000) for i in range(n)] print(...
def merge_sort(list_to_sort): """ Sort the input list using the merge sort algorithm, and return it.""" def merge(left, right): """ Return the merged left and right sorted (sub)lists.""" if not left: return right if not right: return left if left[0] < rig...
import numpy as np import pandas as pd import os def question01(data, labels): """ Returns a dataframe from the given data (a dictionary of lists), and list of labels. >>> data = {'column1': [0,3,5,6], 'column2': [1,3,2,4]} >>> labels = 'a b c d'.split() >>> out = question01(data, labels...
import numpy as np import os def data2array(filepath): """ data2array takes in the filepath of a data file like `restaurant.csv` in data directory, and returns a 1d array of data. :Example: >>> fp = os.path.join('data', 'restaurant.csv') >>> arr = data2array(fp) >>> isinstance(a...
import os import pandas as pd import numpy as np # --------------------------------------------------------------------- # Question # 1 # --------------------------------------------------------------------- def data_load(scores_fp): """ follows different steps to create a dataframe :param scores_fp: fi...
name = 'Filip' age = 30 daysInYear = 365 message = '%s is %d years old, so is about %d days old' print(message % (name,age,age*daysInYear)) name = 'Ania' age = 29 print(message % (name,age,age*daysInYear)) message = '{0:s} is {1:d} years old, so is about {2:d} days old' print(message.format(name,age,age*daysIn...
import math import random import datetime inputdata = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] factortable = [0, 0.01, 0.02, 0.03, 0.05, 0.08, 0.13, 0.21, 0.34, 0.55, 0.89] print(len(inputdata)) print(len(factortable)) if len(inputdata) == len(factortable): i = 0 while i < len(inputdata): ...
def give_geom_seq_element(a1=2, factor=2, index=2): # returns n-th term of geometric sequence starting with element a1 value = a1 * pow(factor, index - 1) return value print(print('2^64 =', give_geom_seq_element(1, 2, 64))) a1 = 3 factor = 2 maxIndex = 10 for i in range(1, maxIndex): n ...
Tax = (4, 7, 8, 23) print(Tax[2]) print(Tax) print(Tax[-1]) print(Tax.count(8)) print(Tax.index(4)) print(max(Tax)) TaxList = list(Tax) print(TaxList) TaxList.append(30) print(TaxList) NewTax = tuple(TaxList) print(NewTax) (tax1, tax2, tax3, tax4) = Tax print(tax1, tax2, tax3, tax4) a=1 b=10 print("a =...
# program to implement Naive Bayes Classification using Iris data from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = trai...
# Multiple Logistic Regression using Housing Data import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model, metrics from sklearn.model_selection import train_test_split boston = datasets.load_boston(return_X_y=False) X = boston.data y = boston.target X_train, X_test, y_train, y_...
#filme = { 'titulo': 'teste' , 'duracao': '2 horas' } #print(filme) # ---------------- como acessar o item do filme ====== #print(filme['titulo']) # ----------------------- quero adicionar alguem ------- filme['Autor'] = 'Felipe Honorio' print(filme) # ===================================== para remover === d...
""" 1111 2222 3333 4444 """ n = int(input()) row = 1 while row <= n: col=1 while col<=n: print(row,end= "") col+=1 print() row+=1 """ 123456 123456 123456 123456 123456 123456 """ n = int(input()) row =1 while row <=n: col = 1 wh...
n = int(input()) sum = 0 i=1 while i <= n: if i%2==0: sum = sum + i i +=1 print(sum) # ================== Prime number using list =========================================================== # # n = int(input()) # i = 2 # primeList = [] # while i < n : # if n%i==0: # p...
# -*- coding: utf-8 -*- """ Created on Sun Mar 1 23:47:19 2020 @author: cheerag.verma """ def bubbleSort(a,n): for i in range(n-1): for j in range(n-i-1): if a[j] > a[j+1]: a[j],a[j+1] = a[j+1],a[j] return a #n = int(input()) n = 6 a = [13,24,39,...
# -*- coding: utf-8 -*- """ Created on Wed Mar 4 15:30:26 2020 @author: cheerag.verma """ """ Problem : Given an integer array, which is sorted (in increasing order) has been rotated by some number k in clockwise direction. Find and return the k. Input: 6 5 6 1 2 3 4 ...
num = int(input()) sum_even =0 sum_odd = 0 while num >0 : lastdigit = num%10 if lastdigit % 2 == 0 : sum_even = sum_even+lastdigit else: sum_odd = sum_odd + lastdigit num = num//10 print(sum_even," ",sum_odd)
# -*- coding: utf-8 -*- """ Created on Mon Mar 9 17:26:08 2020 @author: cheerag.verma """ """ Given a 2D integer array of size M*N, find and print the sum of ith row elements separated by space. """ def rowWiseSum(arr): newlist = [] for i in arr: sum = 0 for j in i: ...