text
stringlengths
37
1.41M
""" Exercise 5, question 2 This program is using generators to execute the 'napa' function and using it to print a list of all the prime dividers of the inserted N. """ def primeList(n): return [i for i in range(2, n + 1) if all([True if i % j != 0 else False for j in range(2, i - 1)])] def primeFact...
""" Exercise 2, question 4 This program is checking if the number that was given is a palindrome or not and prints out the matching message. """ def isPolindrome(num): if num[0] == '-': # if it's a negative number it cuts the sigh out num = num[1:] if num == num[::-1]: return True ...
""" Exercise 1, question 8 """ """import random #r = random.randint(3, 9) #print(r) r = int(input("Enter N numbers in the range 3 - 9: ")) nums = [] for i in range(r): nums.append(random.randint(1, 9)) nums = tuple(nums) print(nums)""" #e1q5 - all functions as asked plus recursive (for the t...
import os def check_dir(dir_name: str) -> str: input_video_path = dir_name if not os.path.isdir(input_video_path): os.mkdir(input_video_path) print(f'{dir_name} directory is created and now put a video in the directory') return False if len(os.listdir(input_video_path)) == 0: ...
import random def answer(h, q): p = [] num = 2**h - 1 for x in q: p.append(find_parent(x, num, num)) return p def find_parent(value, high, num_values): # Check if at root of current subtree if (high == value): return -1 # Check if in right subtree, else left subtree ...
import random import operator import itertools dice = ['AAEEGN', 'ELRTTY', 'AOOTTW', 'ABBJOO', 'EHRTVW', 'CIMOTU', 'DISTTY', 'EIOSST', 'DELRVY', 'ACHOPS', 'HIMNQU', 'EEINSU', 'EEGHNW', 'AFFKPS', 'HLNNRZ', ...
#!/usr/bin/python3 """ Test for rectangle.py """ import unittest from models import base, rectangle import pep8 import json class TestRectMethods(unittest.TestCase): """rect tests""" def test_inherits(self): """test rectangle.Rectangle""" pass def test_no_args(self): with self....
#!/usr/bin/python3 def weight_average(my_list=[]): if my_list == []: return 0 i = 0 j = 0 for x in my_list: i += x[0] * x[1] j += x[1] i = i / j return i
#!/usr/bin/python3 """ my_list """ class MyList(list): """ sub class of list """ def print_sorted(self): """ public instance of sorted list """ new = self[:] new.sort() print(new)
# Create a calculator c = 50 h = 30 # use this formula Q = square root lf [(2*c*d)/h] # find d import math x = [] y = [i for i in input('Give me a number: ').split(',')] for d in y: x.append(str(int(round(math.sqrt(2*c*float(d)/h))))) print(','.join(x)) # the join method is for str so we need to conver our int...
# Create an array of 5 integers and display array items, access them via index from array import * array_num = array('i', [1,3,5,7,9]) # Any numbers work for i in array_num: print(i) print('Access first three items individuals') print(array_num[0]) print(array_num[1]) print(array_num[2]) # Append a new item to en...
""" Program: modelview.py Author: Chad Lister Date: 01/31/2021 This program defines the view for the PFEvaluatorModel class. DS Chapter # 7 Project # 4: add the ^ operator to the expressions processed by the expression evaluator of the case study. """ from scanner import Scanner from model import * de...
""" Program: patron.py Author: Chad Lister Date: 01/10/2021 This program defines the Patron class and defines the interface used in a library class. """ class Patron(): """ This class represents a library patron. """ MAX_BOOK_COUNT = 3 def __init__(self, name, bookCount, bookList): """ Const...
""" Program: testfunction.py Author: Chad Lister Date: 12/23/2020 This program tests the printAll function with tracing. 1) The input is: a sequence 2) The output is: a reducing sequence and tracing for sequence argument """ def printAll(seq): i = 1 last = len(seq) if seq: ...
""" Program: new_decryption.py Author: Chad Lister Date: 12/18/2020 this program inverses the enryption from Chapter # 4 Project # 6 1. Input is: encryptedString 2. Computation is : if it's not blank split it into substrings shift substring 1 right convert shifted string f...
""" Program: myprogram.py Author: Chad Lister Computes the area of a square or rectangle. 1. Significant constants: None. 2. The inputs are: width height 3. Computations: area = width * height 4. The output is: The area of the square or rectangle """ # Request the i...
import sqlite3 class Schema: def __init__(self): self.conn = sqlite3.connect('todo.db') #self.create_user_table() self.create_to_do_table() self.conn = sqlite3.connect('userinformation.db') self.create_user_table() # Why are we calling user table before to_do table ...
# Stephen Randall # 11/15/17 # Folder: Unit9Project File: compare.py # This is a card game that compares two players cards who ever has the greatest card wins. Uses two classes card.py and # deck.py import card import deck new_card = card.Card(1, "Hearts",) new_deck = deck.Deck() new_deck.shuffle() print("======DONE SH...
#Logical Operator ; And use num1 = 20 num2 = 10 num3 = 80 if num1 > num2 and num1 > num3: print(num1) elif num2 > num1 and num2 > num3: print(num2) else: print(num3)
def main(): with open("input_day_3") as f: lines = f.readlines() codes = map(code_parser, lines) locations = list(map(location_calculator, codes)) intersections = [] c = 0 for i in locations[0]: c += 1 if c % 1000 == 0: print(c) if i in locations...
# import only standard Python 3 libraries here. """Implement all the TODOs""" # input: positive integer x # output: True or False def isDivBySeven(x): print(x) # do not remove this line """ TODO: finish implementing the function as described on the HW1 handout.""" if x<10: return True if x==7 ...
valid = 0 list = [] while valid<5: x = int(input("Podaj liczbe: ")) list.append(x) valid= valid+1 for i in list: print(i)
# Purpose: Ask user what the month and day is and print it on the screen. # Ask user for month month = raw_input("Please enter the current month (January, February etc.): ") # Ask user for the day day = raw_input("Please enter the day (1, 2,...31): ") # Concatenate month and day and print on screen # Import...
from collections import defaultdict from typing import List """ Given a non-empty array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Example 1: Input: [2,2,1] Output: 1 Example 2: Input: [4,1,2,1,2] Output: 4 """ de...
def create_dictionary(list1,list2): dictionary = {} for i in range((len(list1))): dictionary[list1[i]] = list2[i] return dictionary list1 = list(input("Enter the words: ").strip().split()) list2 = list(map(int,input("Enter the numbers: ").strip().split())) create_dictionary(list1,list2) def m...
class DataType(object): def __init__(self): self.type = 'generic' self.description = '' def compare_data_objects(self, other): """ Used to compare two data types """ return self.type == other.type def __eq__(self, other): if type(other) is str: ...
class Column(object): def __init__(self, column_name, column_type, primary_key=False): """ Describes a column in a table :param column_name: the name of the column :param column_type: a DataType object representing the type of the column """ self.name = column_name ...
"""Integration tests for Parser""" import os from unittest import TestCase from parser import Parser from sample_data import test_case_data from validation import field_validators DATA_FILE = 'test.csv' JSON_FILE = 'test.json' class ParserTestCase(TestCase): """Test read file function""" def setUp(self): ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 6 11:43:47 2021 @author: anand """ # The algorithm starts at 3 cur_x =5 # Learning Rate rate = 0.1 # This tells us when to stop the algorithm precision = 0.5 previous_step_size = 1 # Maximum number of iterations max_iters = 1000000 # iteration counter i...
def main(): series = int(input()) a=0 b=1 for i in range(series): print(a, end= " ") a,b=b,a+b main()
""" https://leetcode.com/problems/different-ways-to-add-parentheses/ """ from typing import List class Solution: def diffWaysToCompute(self, inputs: str) -> List[int]: output = [] for i, s in enumerate(inputs): if s in ["+", "-", "*"]: str_1 = inputs[:i] ...
def isSymbol(name): x = 0 symbol = "~`!@#$%^&*()_-+={}[]:>;',</?*-+" for i in name: if i in symbol: x += 1 if x > 0: return True if x == 0: return False def isNum(name): x = 0 symbol = "1234567890" for i in name: if i in symbol: x += 1 if...
def getKey(item): return item[0] filename = 'ee41.txt' txt = open(filename) content = txt.readlines() content = [x.strip() for x in content] Map = sorted(content, key=getKey) print("Total number of names: ", len(Map)) for i in Map: print(i)
gen = {'men' : 0.73, 'women' : 0.66} A = 12*float(input("How many drinks have you had? "))*.06 r = gen[input(str("What is your gender? "))] w = float(input("What is your body weight?" )) H = float(input("How many hours has it been since your last drink? ")) BAC = round(A*(5.14/w)*r-(.015*H),2) print(f"Your BAC is {...
import random as r N, List = [], [] while True: if N != '': N = input("Enter a name? ") List.append(N) if N == '': List.remove(N) break Winner = r.randint(0,len(List)) print(f"The 1st winner is {List[Winner]}") del List[Winner] Winner = r.randint(0,len(List)) print(f"The 2nd w...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 4 20:42:54 2017 @author: christophernovitsky """ from babel.numbers import format_currency while True: try: P = float(input("Enter principle? ")) r = float(input("Enter the intrest rate? ")) t = int(input("Enter the ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Dec 2 18:57:36 2017 @author: christophernovitsky """ x = input(" What us the quotes? ") y = input(" Who said it?") print(f'{y} says, "{x}"')
def setup_puzzle(): # Return a valid sudoku puzzle to solve. Temporarily hardcoded, # but this board can be modified and should still be solveable for any "easy" solveable board board = [ [None, None, 3, None, None, None, 1, 6, None], [None, None, None, 6, 4, None, None, 5, 2], ...
cube = lambda x: pow(x, 3) # complete the lambda function def fibonacci(n): y = 2 s = [] if y >= 2: s.append(0) s.append(1) for y in range(2, n + 1): s.append(s[y - 2] + s[y - 1]) return s[0:n] if __name__ == '__main__': n = int(input()) print(list(...
""" Input;: 7 UK China USA France New Zealand UK France 7 is the number of countries as input. Ans: 5 """ #Solution 2 is better because it does not check the whole list to find the count. def count_country1(no,inp): s = [] for x in inp: if x not in s: s.append(x) ...
class theaterMovies: def movies(): show1 = 1 show2 = 2 show3 = 3 show4 = 4 print(' ') print('Nite Striker is 1, Day Breaker is 2, Lethal Dragon is 3 and Man Cave is 4') print(' ') customer = int(input('please enter your movie of choice: ')) while(True): if(customer == show1 o...
for i in range(101): if i%7==0 or i%10==7 or i//10==7: continue else: print(i)
import re from itertools import permutations def clean_name(n): return re.sub("[\W_]+", '', n).lower() def is_palindrome(n): return n == n[::-1] Dwarves = ["Gimli", "Fili", "Ilif", "Ilmig", "Mark"] dwarves = [clean_name(d) for d in Dwarves] # clean input for d in dwarves: # check input if dwarves.c...
# defining the string_alternative function def string_alternative(ip): return ip[::2] # defining the main function def main(): word = input("Enter the word:") result = string_alternative(word) print("Result:", result) if __name__ == "__main__": main()
string = input('Enter the string:') sub = string[0:2] + string[3] + string[5] print(sub[::-1])
# This Python file uses the following encoding: utf-8 ## # (C) 2007, 2008, 2013, 2015, 2016 Muthiah Annamalai <ezhillang@gmail.com> # (C) 2013 msathia <msathia@gmail.com> ## # This file is dual licensed - originally GPL v3 from Ezhil, and # then as part of open-tamil package in MIT license. ## # Licensed under GPL Vers...
""" Insertion sort is the method to sort an array. In insertion sort we divide an array into two parts: sorted part and unsorted part. Every time we select the first value from the unsorted part and find its position in sorted part and place it there. """ def insertion_sort(arr): # Insertion sort is compos...
# Recurrent Neural Networks # Part 1 - Data Preprocessing import math import matplotlib.pyplot as plt import numpy as np import pandas as pd from keras.layers import LSTM, Dense, Dropout from keras.models import Sequential from sklearn.metrics import mean_squared_error from sklearn.preprocessing import MinMaxS...
""" Tree is a type of nonlinear data stricture, where data is connected to each other in hierarchy. Every container of data is called node. Top node is called root node, and nodes at the end of tree are called leaf nodes. "Binary Search Tree is a type of data structure which have at most two children. It cannot hav...
""" Breadth First Search """ class Node: def __init__(self, name): self.name = name self.adjacencyList = [] self.visited = False self.predecessor = None class Breadth_First_Search: def bfs(self, startNode): queue = [] queue.append(start...
""" K-Means """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.cluster import KMeans # Import the dataset dataset = pd.read_csv('data/Mall_Customers.csv') # Create independent variable X = dataset.iloc[:, [3,4]].values # Using the Elbow Method to...
""" simple Linear Regression with Gradient Descent """ import pandas as pd # Open dataset df = pd.read_csv('data/data.csv') # Convert Pandas DataFrame into List df = df.values """ In our case Y = b + m*X where, m is slope and b is intercept To find best estimates for slope and intercept we need to define c...
# Tip calculator # Ask for meal price # Ask how waiter was #suggested tip based on service #choose tip #calculate tip # Extra: total meal cost # Extra: Ask for weekly budget and subtract from budget # Welcome print("Welcome to the X Tip Calculator!") input("How was your meal?") print("Wonderful! ...
def remove(arr): pass def print_gray_code(arr1, arr2): print(arr1, arr2) if len(arr2) > 1: arr2 = arr2[1:] arr1 += arr2[:1] arr1, arr2 = print_gray_code(arr1, arr2) elif arr2[0] == 1: print_gray_code([], arr1 + [0]) elif arr2[0] == 0: return arr1, arr2 else: return arr1, [0] return arr1, arr2 if ...
# This script uses the Montecarlo method to find the # [approximated] area under a curve (definite integral) import math import random import time import numpy as np import scipy.integrate as integrate import matplotlib.pyplot as plt def montecarlo_iterative_integration(fun, a, b, num_puntos=1000): #...
# coding: utf-8 # In[5]: get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt x=[30,30,70,70,100] a=20 b=70 plt.xlabel('EJE X') plt.title('FUNCION HOMBRO') plt.grid() def f(x,a,b): if (x<a): ans=0 if (x>=a)&(x<b): ans=(x-a)/(b-a) if (x>=b): ...
from abc import ABC from abc import abstractmethod from gamestatus import Gamestatus import random from numpy import random class Challenge (ABC): def __init__(self, victim, challenged_card, n_players, players, deck): self.victim = victim self.challenged_card = challenged_card self.n_p...
#code created by NamanNimmo Gera #12:42pm, April 10, 2019. from itertools import permutations #importing permutations :) perm = permutations([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for count, item in enumerate(perm): #to find the millionth permutation if count == 999999: print(item)
#approach no. 2 for solving problem 33 import math frac=1.0 for b in range(1,10): for a in range(1,b): for c in range(1,10): if (a*10+b)/(b*10+c)==a/c: frac*=(a/c) print(math.ceil(1/frac))
## # Main function of the Python program. # ## # from math import pi # returns the area of a circle, given it's radius def area_of_circle(radius): area = 0 return area # Returns the distance travelled, given speed and time which are integer values (km/h and hours respectively) def distance_tra...
import palmero plm = palmero.Palmero() def main(): plm.logo() print("\n0: Create test file") print("1: Encrypt File") print("2: Decrypt File") print("3: Generate Key") print("4: Help") next = input() if next == "0": with open('example.txt', 'w') as exm: exm.write("Th...
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * from flask import url_for class Books(Contro...
#typeDynamic language """ commente chand khati khate dovom khate sevom """ #niaz be taine noe nist va noe var mitavanad taghir konad a = "sadegh" print(a) a = 10 print(a) #nahve neveshtane do khat code dar yek khat b = 15; b+=10 print(b) #anvae vars #number #string #list #tuple #dictionary #chand entesab hamzaman ...
#!/usr/bin/env python3 ''' This method checks if the number is a prime number or not ''' def IsPrime (n): # loop from 2 to n (exclusive) for i in range (2, n): # if n is divisible by i, then we dont have a prime number if (n % i == 0): return False # if we get here...
friend_name = "Eric" print("Hello, " + friend_name + ". It's good to see you again.") print(friend_name.upper()) print(friend_name.lower()) print(friend_name.title()) famous_person = "Caesar" quote = "'E tu, Brutus.'" print(famous_person + " once said, " + quote) whitespace_name = " Diana Arruda " print(whitespace_n...
users = ['admin', 'diana', 'jeff', 'molly'] if users == []: print("We need to find some users!") else: for user in users: if user == 'admin': print("Hello admin, would you like to see a status report?") else: print("Welcome, " + user.title() + ".") current_users = ['di...
''' Dane są trzy zbiory: A, B i C. Napisz algorytm, który powie, czy istnieje taka trójka a, b, c z odpowiednio A, B, i C, że a + b = c. Nie wolno korzystać ze słowników! ''' # ALGORYTM : ''' Sortujemy A i B, i dla każdego elementu C, przeprowadzamy szukanie idąc dwoma wskaźnikami: jednym z początku...
''' Dany jest graf nieskierowany G oraz dwa jego wierzchołki s i t. Proszę zaproponować algorytm, który sprawdza czy istnieje taka krawędź, po usunięciu której długość najkrótszej ścieżki z s do t (lub taka ścieżka przestaje istnieć). ''' # ALGORYTM: ''' Obliczamy ilość najkrótszych ścieżek między s i t przy...
''' Podaj algorytm, który mając na wejściu niezrównoważone drzewo BST przekształca je w drzewa dające się pokolorować jako czerwono-czarne. ''' # ALGORYTM ''' rekurencyjnie wpisujemy do tablicy wartości inorder O(n), następnie z posortowanej tablicy łatwo możemy zrobić zbalansowane drzewo, biorąc jako roota medianę....
'''Mamy daną tablicę stringów, gdzie suma długości wszystkich stringów daje n. Napisz algorytm, który posortuje tę tablicę w czasie O(n).(Najpierw po dlugosciach, potem leksykograficznie) Można założyć, że stringi składają się wyłącznie z małych liter alfabetu łacińskiego.''' #z elementow tablicy robie krotki (dlugo...
'''Masz daną tablicę zawierającą n (n >= 11) liczb naturalnych w zakresie [0, k]. Zamieniono 10 liczb z tej tablicy na losowe liczby spoza tego zakresu (np. dużo większe lub ujemne). Napisz algorytm, który posortuje tablicę w czasie O(n).''' ''' Dzielimy tablicę na dwie - te "psujące" 10 elementów i te posortowane (p...
''' implementacja kolejki priorytetowej min jako kopiec ''' # w 0 komorce przechowuje rozmiar kopca def size(k): return k[0] # przy heapify zakladam ze drzewa zaczepione w synach sa naprawione, tylko el. i moze byc mniejszy, # chce sprawic y ta wartosc splynela w dol i wszystko od i w dol bylo posortowane #...
''' Zaimplementuj funkcję average_score(arr, n, lowest, highest). Funkcja ta przyjmuje na wejściu tablicę n liczb rzeczywistych (ich rozkład nie jest znany, ale wszystkie są parami różne) i zwraca średnią wartość podanych liczb po odrzuceniu lowest najmniejszych oraz highest największych. Zaimplemen...
''' Operacja intersection otrzymuje na wejściu dwa zbiory zrealizowane jako tablice asocjacyjne i zwraca ich liczbę elementów, które występują w obu. Proszę zaimplementować tę operację dla tablic asocjacyjnych realizowanych jako: 1. drzewa BST ''' # ALGORYTM: ''' Przechodzimy in-order oba drzewa, dostajemy 2 posort...
''' Rozważmy drzewa BST, które dodatkowo w każdym węźle zawierają pole z liczbą węzłów w danym poddrzewie. Proszę opisać jak w takim drzewie wykonywaćnastępujące operacje: 1. znalezienie i-go co do wielkości elementu, 2. wyznaczenie, którym co do wielkości w drzewie jest zadany węzeł ''' class Node: ...
# -*- coding: utf-8 -*- """ Started 07/11/2018 This script connects to the Department of Business, Environment, and Industrial Strategy (DBEIS) website, downloads the carbon factors in the 'flat file' format, and saves the factors in a SQLite3 file. If the 'flat file' format is not available, the script looks...
# https://projecteuler.net/problem=2 # Each new term in the Fibonacci sequence is generated by adding # the previous two terms. By starting with 1 and 2, the first 10 # terms will be: # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values # do not exceed four million,...
def is_acceptable_password(password): if len(password) > 6: return True else: return False def is_acceptable_password(password: str) -> bool: return len(password) > 6 is_acceptable_password = lambda password: len(password) > 6
from typing import List from functools import reduce import operator def solve (data: List[str], right: int, down: int) -> int: position = 0 row = 0 result = 0 width = len(data[0]) while True: try: if data[row][position] == '#': result += 1 row += do...
#!/usr/bin/env python from datetime import datetime, timedelta class IntervalTimer(object): """ Timer which triggers each time the specified number of seconds has passed. """ def __init__(self, name, interval, startTriggered=False): self.__name = name self.__isTime = startTriggered ...
prime_numbers = [] for i in range(1, 100): #if prime_numbers == []: # prime_numbers.append(i) count = 0 if i % i == 0: count += 1 for x in prime_numbers: if i % x == 0 : count += 1 if count <= 2 and i != 1: prime_numbers.append(i) ...
from tkinter import * window = Tk() window.title("Mile to Km Converter") window.config(padx=50, pady=50) # window.minsize(width=300, height=100) def action(): x = float(entry.get()) y = x * 1.609 label_3.config(text=str(y)) button = Button(text="Calculate", command=action) button.grid(row=2, column=1) e...
# fiz buzz game game = [] for i in range(1,101): game.append(i) if i % 3 == 0 and i % 5 == 0: game[i-1] = "FizzBuzz" elif i % 3 == 0: game[i -1] ="Fizz" elif i % 5 == 0: game[i - 1] = "Buzz" print(game[i-1])
def sort012(a,arr_size): lo = 0 hi = arr_size - 1 mid = 0 while mid <= hi: if a[mid] == 0: a[lo], a[mid] = a[mid], a[lo] lo = lo + 1 mid = mid + 1 elif a[mid] == 1: mid = mid + 1 else: a[mid], a[hi] = a[hi], ...
def countSetBits(n): count = 0 while (n): n &= (n - 1) count += 1 return count n = int(input()); print(countSetBits(n))
n=int(input()) n = list(str(n)) if n == sorted(n, reverse = True): print("Not possible") else: for i in range(len(n)-1, -1, -1): if(n[i-1] < n[i]): n[i:len(n)] = sorted(n[i:len(n)]) break for j in range(i, len(n)): if(n[i-1] < n[j]): n[i-1], n[j...
#safe to say, maður byrjar alltaf í 1,1. þannig það fyrsta sem hægt verður að gera er að fara norður, ekkert annað x = 1 y = 1 while True: if x == 1 and y == 1: print("You can travel: (N)orth.") elif x == 1 and y == 2: print("You can travel: (N)orth or (E)ast or (S)outh.") elif x == 2 and y...
# encoding: utf-8 # module System.Numerics calls itself Numerics # from System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a # by generator 1.145 # no doc # no imports # functions def Vector(*args, **kwargs): # real signature unknown """ Provides a collection of sta...
import json def translate_item(item, translator = None, exclusive = False, print_debug = False): """ Translate a single json Parameters -------------- item : dict Item to translate. translator : Dict[str, str] Dict specifying translation, where the key is the fi...
#!/usr/bin/env python3 i = 1 for i in range(1,101): if i%7 ==0: continue elif i%10==7 or i//10 ==7: continue else: print(i) i+=1
'''Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams. ''' def is_anagram(string1,string2): if sorted(string1) == sorted(string2): return True else: return False st...
def is_palindrome(s): res= s== s[::-1] return res s = 'mom' res=is_palindrome(s) print("is the string palindrome :" ,res)
'''The greatest common divisor (GCD) of a and b is the largest number that divides both of them with no remainder. One way to find the GCD of two numbers is based on the observation that if r is the remainder when a is divided by b, then gcd(a, b) = gcd(b, r). As a base case, we can use gcd(a, 0) = a. Write a function ...
# Name: Elena Rangelov # Date: 1.7.2021 import random class RandomBot: def __init__(self): self.white = "O" self.black = "@" self.directions = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] self.opposite_color = {self.black: self.white, self.white: self.bla...
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('/home/amartya/Desktop/Udemy_data/K_Nearest_Neighbors/K_Nearest_Neighbors/Social_Network_Ads.csv') X = data.iloc[:, 2:4].values y = data.iloc[:, 4:5].values from sklearn.cross_validation import train_test_split X_train, X_test,...
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('/home/amartya/Desktop/Udemy_data/Simple_Linear_Regression/Salary_Data.csv') X = data.iloc[:, 0:1].values y = data.iloc[:, 1:2].values '''For splitting the data into training and test set''' from sklearn.cross_validation impor...
print("hello"+"world") print("hello","world") print("-------------------") name=input("请输入你的名字:") age=input("请输入你的年龄:") hobby=input("请输入你的爱好:") print("你的名字为:"+name+",\n年龄是:"+age+",\n爱好为:"+hobby)
# OOP Aggregation class Salary: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus def annual_salary(self): return (self.pay * 12) + self.bonus # Instantiating the salary class in the Employee class so # salary class is the content and Employee class is container class Employee: def __init...
# Class Attributes class Person: number_of_people = 0 # This is a Class Attribute which is same for all people and hence it is # common to all instances of the class def __init__(self, name): self.name = name Person.number_of_people += 1 p1 = Person("Aditya") print(p1.number_of_people) p2 = Person("So...
# Introduction to Inheritance # Upper Level Class and all other classes borrow from it # generalisation class Pet: def __init__(self, name, age): self.name = name self.age = age def show(self): print(f"I am {self.name} and I am {self.age} years old") def speak(self): print("I don't know what to say") cl...