text
stringlengths
37
1.41M
#Remember to use the random module #Hint: Remember to import the random module here at the top of the file. 🎲 #Write the rest of your code below this line 👇 import random; randomNumber = random.randint(0, 1) if(randomNumber == 1): print("Heads") else: print("Tails")
print("Hello"[0]) print("Hello"[3]) print(2311) #float print(3.14159) #only visual print(23_345_454) #boolena #type name = "Luis" type(name) # 🚨 Don't change the code below 👇 two_digit_number = input("Type a two digit number: ") # 🚨 Don't change the code above 👆 #################################### #Write ...
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } # 🚨 Don't change the code above 👆 #TODO-1: Create an empty dictionary called student_grades. student_grades = {} #TODO-2: Write your code below to add the grades to student_grades.👇 #print(student_scores["Harry"]) ...
import re hand = open('short.txt') for line in hand: line = line.rstrip() if re.search('From:', line): print(line) print('--------------') hand = open('short.txt') for line in hand: line = line.rstrip() if re.search('^From:', line): print(line)
country = 'Canada' exist = 'n' in country if(exist): print('Get it!') if 'd' in country: print('Found it!')
#Learn Python 3 The Hardway #Exercise 2 # A comment, this is so you can read your program laterself. # Anything after the # is ignored by Phyton. print ("I could hace code like this") # and the comment after is ignoredself. # You can also use a comment to "disable" or comment out code # print ("This won't run.") pr...
""" 230-kth-smallest-element-in-a-bst leetcode/medium/230. Kth Smallest Element in a BST Difficulty: medium URL: https://leetcode.com/problems/kth-smallest-element-in-a-bst/ """ from typing import List # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # ...
# human-readable-duration-format # https://www.codewars.com/kata/52742f58faf5485cae000b9a/ from unittest import TestCase from collections import OrderedDict def format_duration(seconds): if seconds == 0: return 'now' times = OrderedDict( second=(1, 60), minute=(60, 60), hou...
# 134-gas-station # leetcode/medium/134. Gas Station # URL: https://leetcode.com/problems/gas-station/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: i...
# leetcode/medium/80. Remove Duplicates from Sorted Array II # 80-remove-duplicates-from-sorted-array-ii # URL: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/?envType=study-plan-v2&id=top-interview-150 # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference fro...
""" leetcode/easy/160. Intersection of Two Linked Lists Difficulty: easy URL: https://leetcode.com/problems/intersection-of-two-linked-lists/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersecti...
""" 832-flipping-an-image leetcode/easy/832. Flipping an Image URL: https://leetcode.com/problems/flipping-an-image/ """ from typing import List class Solution: def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]: return list(map( lambda _list: list( ...
# even-numbers-in-an-array # Even numbers in an array # difficulty: 7kyu # https://www.codewars.com/kata/5a431c0de1ce0ec33a00000c from unittest import TestCase def even_numbers(arr, n): return list(filter(lambda e: e % 2 == 0, arr))[-n::] TestCase().assertEqual(even_numbers([1, 2, 3, 4, 5, 6, 7, 8, 9], 3), [4...
""" 141-linked-list-cycle leetcode/easy Difficulty: easy URL: https://leetcode.com/problems/linked-list-cycle/ """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head) -> bool: visite...
""" 1528-shuffle-string leetcode/easy/1528. Shuffle String Difficulty: easy URL: https://leetcode.com/problems/shuffle-string/ """ from typing import List class Solution: def restoreString(self, s: str, indices: List[int]) -> str: zipped_list = list(zip([*s], indices)) zipped_list.sort(key=lambda...
""" 938-range-sum-of-bst leetcode/easy/938. Range Sum of BST Difficulty: easy URL: https://leetcode.com/problems/range-sum-of-bst/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right...
""" 1469-find-all-the-lonely-nodes leetcode/easy/1469. Find All The Lonely Nodes Difficulty: easy URL: https://leetcode.com/problems/find-all-the-lonely-nodes/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.lef...
# leetcode/medium/912. Sort an Array # 912-sort-an-array # URL: https://leetcode.com/problems/sort-an-array/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def mergeSort(self, nums): if len(nums) == 1: return ...
# leetcode/medium/802. Find Eventual Safe States # 802-find-eventual-safe-states # URL: https://leetcode.com/problems/find-eventual-safe-states/description/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference from typing import List class Solution: def __init__(self): self.saf...
# https://leetcode.com/problems/excel-sheet-column-number from unittest import TestCase # Runtime: 32 ms, faster than 53.72% of Python3 online submissions for Excel Sheet Column Number. # Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Excel Sheet Column Number. # Runtime: 28 ms, faster tha...
""" 1221-split-a-string-in-balanced-strings leetcode/easy/1221. Split a String in Balanced Strings Difficulty: easy URL: https://leetcode.com/problems/split-a-string-in-balanced-strings/ """ class Solution: def balancedStringSplit(self, s: str) -> int: balance = 0 count = 0 for i in range(...
# https://www.codewars.com/kata/5168bb5dfe9a00b126000018 def solution(string): return ''.join(str(x) for x in list(reversed(string))) print('123'.split()) print(solution('world')) print(solution('world') == 'dlrow')
""" 78-subsets leetcode/easy/78. Subsets Difficulty: medium URL: https://leetcode.com/problems/subsets/ """ from typing import List class Solution: def get_subsets(self, nums, result, prev=[]): if len(nums) == 0: return for index, value in enumerate(nums): print(index, va...
""" 728-self-dividing-numbers leetcode/easy/728. Self Dividing Numbers Difficulty: easy URL: https://leetcode.com/problems/self-dividing-numbers/ """ from typing import List class Solution: def selfDividingNumbers(self, left: int, right: int) -> List[int]: result = [] for i in range(left, right ...
""" 3sum leetcode/medium/3sum Difficulty: medium URL: https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/776/ """ from typing import List class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: result = [] nums = sorted(nums) l...
""" 1021-remove-outermost-parentheses leetcode/easy/1021. Remove Outermost Parentheses Difficulty: easy URL: https://leetcode.com/problems/remove-outermost-parentheses/ """ class Solution: def removeOuterParentheses(self, s: str) -> str: balance = 0 result = [] for i in range(len(s)): ...
# Reverse polish notation calculator # https://www.codewars.com/kata/52f78966747862fc9a0009ae/ from unittest import TestCase def is_number(string): try: float(string) return True except ValueError: return False def calc(expr): expressions = expr.split(" ") result = 0 if...
""" 1370-increasing-decreasing-string leetcode/easy/1370. Increasing Decreasing String Difficulty: easy URL: https://leetcode.com/problems/increasing-decreasing-string/ """ class Solution: def sortString(self, s: str) -> str: s = sorted(s) result = [] delete_list = [] while len(s):...
# WeIrD StRiNg CaSe # https://www.codewars.com/kata/52b757663a95b11b3d00062d/ from unittest import TestCase def to_weird_case(string): def to_weird_string_case(word): return "".join(list(map(lambda v: v[1].upper() if v[0] % 2 == 0 else v[1].lower(), enumerate(list(word))))) return " ".join([to_weird...
""" 1827-minimum-operations-to-make-the-array-increasing leetcode/easy/1827. Minimum Operations to Make the Array Increasing URL: https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/ """ from typing import List class Solution: def minOperations(self, nums: List[int]) -> int: max...
# leetcode/medium/2390. Removing Stars From a String # 2390-removing-stars-from-a-string # URL: https://leetcode.com/problems/removing-stars-from-a-string/description/?envType=study-plan-v2&id=leetcode-75 # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference class Solution: def removeSt...
""" 704-binary-search leetcode/easy/704. Binary Search Difficulty: easy URL: https://leetcode.com/problems/binary-search/ """ from typing import List class Solution: def search(self, nums: List[int], target: int) -> int: if target not in nums: return -1 left = 0 right = len(n...
""" 1720-decode-xored-array leetcode/easy/1720. Decode XORed Array Difficulty: easy URL: https://leetcode.com/problems/decode-xored-array/ """ from typing import List class Solution: def decode(self, encoded: List[int], first: int) -> List[int]: result = [first] for x in encoded: re...
# leetcode/medium/2113. Elements in Array After Removing and Replacing Elements # 2113-elements-in-array-after-removing-and-replacing-elements # URL: https://leetcode.com/problems/elements-in-array-after-removing-and-replacing-elements/ # # NOTE: Description # NOTE: Constraints # NOTE: Explanation # NOTE: Reference fr...
""" 1038-binary-search-tree-to-greater-sum-tree leetcode/medium/1038. Binary Search Tree to Greater Sum Tree Difficulty: medium URL: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/ """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): ...
""" find-the-position codewars/8kyu/Find the position! Difficulty: 8kyu URL: https://www.codewars.com/kata/5808e2006b65bff35500008f/ """ def position(alphabet): return f'Position of alphabet: {ord(alphabet) - 96}' def test_positio(): assert position('a') == 'Position of alphabet: 1' assert position('z') ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- def fibonacci1(n): assert(n>=0) a = 0 b = 1 print(a) if n > 0: print(b) i = 2 while i <= n: c = a + b print(c) a = b b = c i += 1 def fibonacci(n): memory = {0: 0, 1: 1} def loop(n): ...
print("What is your first name?") initial = input() print("What is your surname?") surname = input() print("For how many months do you want your gym membership for?") months = int(input()) print("Hello,") print(f"{initial} {surname},") print("and welcome to your new gym membership with MathGyms Ltd!") print(f"You have ...
def gcd(a, b): while b > 0: a, b = b, a % b return a def lcm(a, b): return int(a * b / gcd(a, b)) def solution(n, m): answer = [] if n < m: answer.append(gcd(n, m)) answer.append(lcm(n, m)) elif m < n: answer.append(gcd(m, n)) answer.append(lcm(m, n)) ...
# -*- coding: utf-8 -*- """ Created on Sun Aug 21 17:23:13 2016 @author: RITURAJ """ #observing the order class A(object): def m(self): print('m of B called') class B(A): pass class C(A): def m(self): print('m of C called') class D(C , B): pass x = D(...
# -*- coding: utf-8 -*- """ Created on Tue Aug 23 16:12:52 2016 @author: RITURAJ """ def the_answer(self , *args): return 42 class EssentialAnswers(type): def __init__(cls, clsname, superclasses, attributedict): cls.the_answer= the_answer class philosophi1(metaclass=EssentialAn...
#Alunos: João Marcos Oliveira Melo, Ângelo Giordano Silveira, Leandro Moreira Souza "Faça um programa utilizando IF e que faça perguntas a cerca de uma cena de crime" "E que defina a posição do usuário diante do crime!!!" ct_crime = 0 print("\nPrazer meu nome é Jack, e eu sou o detetive dessa cidade!!!") print...
String= input("enter string= ") print("Total length of string with spaces :",len(String)) striglength=len(String) if striglength < 5: print("String is short") elif striglength > 30: print("String is too long") else: print("String is optimum")
import os print(os.getcwd()) files=[] dirs=[] for file in os.listdir(): if os.path.isfile(file): files.append(file) if os.path.isdir(file): dirs.append(file) print("files") print("------") for file in files: print(file) print ("dirs") print("-----") for file in dirs: print(file)
Stringinput= input("Enter the string: ") value=list(Stringinput) print(Stringinput) print(value) digit=0 alpha=0 for i in value: if i.isdigit(): digit+=1 print("Stringinput is digit",i) if i.isalpha(): alpha+=1 print("String is alphabet",i) print (alpha, digit) '''...
import sphere, cylinder, cone, cube, triangle, trapezoid, cuboid, equilateralTriangle #setting user selection in main program def userSelection(selection): return selection #main output loop def main(): while True: #Main menu output print("Welcome to the my Geometry Program") print("1....
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right # solution def serialize(root): if root is None: return '' return root.val + '(' + serialize(root.left) + ')(' + serialize(root.right) + ')' def deserialize(s): ...
"""Automates airconditioning control. Monitors climate inside and out, controlling airconditioning units in the house according to user defined temperature thresholds. The system can be disabled by its users, in which case suggestions are made (via notifications) instead based on the same thresholds using forecasted a...
# PROG1700 - Jin """ Name : Myeongjin Kwon(Jin)\ ID...: W0417939 """ import math def main(): #input ask = input("Please enter your original bill amout: ") #process bill = int(85) tax = float(ask) * float(0.15) tip = float(ask) * float(0.20) total = float(ask) + float(tax) + float(t...
import numpy from matplotlib import pyplot a=numpy.zeros([2,3]) print(a) b=a b[0,1]=1.5 b[1,0]=2 print(a) print(b) pyplot.imshow(a,interpolation="nearest")
from screen import Screen import curses from screens.create import CreateScreen class MenuScreen(Screen): """ Menu screen """ selection = 0 options = ["Create a new game", "Join an existing game"] def _draw_option(self, option_number, style): self.window.addstr( 5 + opt...
import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename window = tk.Tk() window.title("AStext editor") window.iconphoto(False, tk.PhotoImage(file='media/icon.png')) window.geometry("1080x720") textbox = tk.Text(width = 100,height = 44.5,font = 30) def open_file(): """Open a ...
import matplotlib.pyplot as plt class point: def __init__(self, x, y, label, weight): self.x = x self.y = y self.label = label self.weight = weight def plot(): x = [0, 1, -2, -1, 9, -7] y = [8, 4, 1, 13, 11, -1] x2 = [3, 12, -3, 5] y2 = [7, 7, 12, 9] plt.plo...
# Take any class class Class(): def __init__(self, number): self.name = "Johnathan" self.number = str(number) def sayname(self): print("This is " + self.name + " #" + self.number) # i = 1 # # All that matters is that there are as many items in "numbers" as classes you want to...
#Rümeysa Coşkun #Python basit bir syntax örneği x=5 y=6 if x > y : print("X bigger than y") if y > x: print("Y bigger than X") if y==x: print ("X equal to Y")
rows=int(input('Enter the number of rows')) def show_stars(rows): for i in range(0,rows+1): for j in range(i): print('*',end='') print() show_stars(rows)
speed=int(input('Enter Speed')) def checker(speed): if(speed<70): print('OK') else: newspeed=int(speed-70) demerit=newspeed/5 return demerit demerit = checker(speed) print('Points:'+str(demerit)) if(demerit>=12): print('Licence Suspended')
num=list(map(int,input("enter an array ").split())) num.sort() for i in range(len(num)): if (num[i+1]-num[i]!=1): x=num[i+1]-num[i] z=num[i] for y in range(x-1): z+=1 print("missing number is " + str(z))
import random game = ['scissors','rock','paper'] win_cases = {'rock':'scissors','paper':'rock','scissors':'paper'} while True: user_input = input('enter your choice :') if user_input =="exit": print('Bye!') break elif user_input not in game: print("Invalid input") continue com_choice...
def getsum(limit): x=0 for i in range(limit+1): if i%3==0 or i%5==0: x=x+i return x sum=getsum(10) print(sum)
import pandas as pd import numpy as np """ 1. user defined function으로 구현 # pandas 내부에서는 Dtype이 object로 되어 있어서 record.str 같은 방식으로 string 형식으로 변환 # pandas split함수 -> :를 기준으로 2번째 :까지 나눔, expand가 true이면 별개의 column false이면 1개의 column # pandas astype -> dataframe을 특정한 data type으로 변경 def to_seconds(record): hms = record...
players = [ { 'name': 'Derrick Henry', 'rushing_yds': 1540, 'rushing_att': 303 }, { 'name': 'Aaron Jones', 'rushing_yds': 1084, 'rushing_att': 236, }, { 'name': 'Christian McCaffrey', 'rushing_yds': 1387, 'rushing_att': 287 ...
#Aarian Dhanani print("1 2 3 4 5 6 7 8 9") print("1\n" + "2\n" + "3\n" + "4\n") print("1\n") print("2 2\n") print("3 3 3\n") for x in range(9): print(x * 2)
#Aarian Dhanani a = 7 b = 13 c = 14 d = 13 if a % 2 == 0: print(b+c) elif b % 2 == 0: print(c-d) else: print(d*c/a)
#Aarian Dhanani #Functions def testing_Functions(number): for x in range(number): for y in range(1,(number + 1) - x): print(((number + 1) - x) - y, end = " ") print() print() def running_Loops(): for x in range(1, 10): for z in range(9 - x): print(" ", end ...
# -*- coding: utf-8 -*- """ Display Yahoo! Weather forecast as icons. Based on Yahoo! Weather. forecast, thanks guys ! http://developer.yahoo.com/weather/ Find your city code using: http://answers.yahoo.com/question/index?qid=20091216132708AAf7o0g Configuration parameters: - cache_timeout : how often to ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Euler Project: Problem 1 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. """ def main(): # initialize ...
#volume of a sphere is 4/3πr3. #In this section I define all variables #that I will use to apply to my function:" import math radius_r1 = 5 # first radius float_f1 = 4.0/3.0 radius_r2 = 7 # second radius float_f2 = 4.0/3.0 radius_r3 = 11 # third radius float_f3 = 4.0/3.0 #In this section I define 3 functions #usi...
print("Только не Ноль Плиз") while True: s = input("Знак (+,-,*,/): ") if s == '0': break if s in ('+', '-', '*', '/'): a = float(input("x=")) b = float(input("y=")) if s == '+': print(a+b) elif s == '-': print(a-b) elif s == '*': ...
""" Angel David Cuellar 18382 Hoja de Trabajo 1 ejercicio 3 """ def amigos(n): divisores = [] for i in range(1,n+1): if(n%i==0): divisores.append(i) divisores.pop() suma=0 for m in divisores: suma=suma+m print "La suma de los divisores es: ", suma ...
import pyttsx3 import os import speech_recognition as sr name= input("Enter your name: ") pyttsx3.speak("hello {} how can I help you".format(name)) r=sr.Recognizer() while True: print("What would you like to do:" , end='') with sr.Microphone() as source: print('Start saying....') audio = r...
#Agata Chmielowiec, Navan 2019 #This is a program that sum up positive interegs between 1 and i - the number that user selects. #Invention taken from 8th February lecture posted: Loops: while and for. i = int(input("Please enter a positive integer: ")) total = 0 while i>0: total = total + i i = i - 1 print(...
import pandas as p # DataFrame Creation s1 = p.Series(['faiz', 'dravi', 'dishu', 'pari'], index=[0, 1, 2, 3]) s2 = p.Series(['ahmed', 'jain', 'jain', 'mamgain'], index=[0, 1, 2, 3]) s3 = p.Series([23, 23, 22.5, 23.5], index=[0, 1, 2, 3]) df = p.DataFrame({'FirstName': s1, 'LastName': s2, 'Age': s3}) print(df) # Appl...
# Print N lines M datas # Each datas on the line should have a blank between # datas on each line N = from (N-2)*M+1 to N*M # go to the next line by "\n" N = int(input("write the number of line (N) : ")) M = int(input("Write the number of int (M) : ")) for i in range(1, N+1): # line N result = [] result.cle...
###### this is the third .py file ########### #database state={"AP":'000',"DELHI":'001',"MAHARASTRA":'010'} city={"ROORKEE":'111',"KANPUR":'110',"NEWDELHI":'101'} district={"NIT":'000',"IIT ROORKEE":'001',"IIT DEHLI":'010'} print "1.add 2.modify 3.delete" choice=input("enter the operation you want to perform") #ad...
seq="ATGCATGCA" # 0 1 2 3 4 5 6 7 8 left-right # | | | | | | | | | #['A','T','G','C','A','T','G',' C','A'] #-9 -8 -7 -6 -5 -4 -3 -2 -1 right-left #left to right indexing print(seq[0]) print(seq[2]) #right to left indexing print(seq[-1]) print(seq[-3]) #program to f...
## aplicações from random import randint ### abertura do arquivo with open('data/sacramento.csv', 'rt') as arq: conteudo = arq.readlines() ## lista de strings que representam um registro # aplicar filtros em conteúdo de arquivos imoveis = [conteudo[randint(1,len(conteudo)-1)] for x in range(1,100) if float(cont...
import csv with open("file.csv",newline="") as f: reader=csv.reader(f) data=list(reader) data.pop(0) newdata =[] for i in range (len(data)): num=data[i][2] newdata.append(float(num)) n =len(newdata) newdata.sort() if n % 2==0: m1=float(newdata[n//2]) m2=float(newdata[n//2-1]) ...
# Exercise 20: Functions And Files from sys import argv script, input_file = argv # function which excepts a file and reads it def print_all(f): print f.read() # function which sets the file back to the begin of file def rewind(f): f.seek(0) # function which take in a line count and file name and prints out the l...
# helltriangle.py import sys, ast class HellTriangle(): """ Returns the maximum total from top to bottom in a triangle. This method creates a copy of the triangle and traverses the new triangle from top to bottom, updating the value in each position, summing to it the maximum value of its...
import time def bubble_sort(data, drawrectangle, delay): for i in range(len(data)-1): for j in range(len(data)-1): if data[j] > data[j+1]: data[j], data[j+1] = data[j+1], data[j] drawrectangle(data, ['blue' if x == j or x == j+1 else 'red' for x in range(l...
##################################### ## ## ## Best-First Search Algorithm ## ## ## ##################################### # This is an implementation of the SearchAlgorithm interface for the following # search algorithms: # - BestFirstGraphSearch imp...
# Escribir un programa que pida al usuario su peso en kg y su estaruta en mts # Calcular el imc(indice de masa corporal) y almacenarlo en una variable # luego mostrar por pantalla el imc redondeado con dos decimales # Codigo: peso = float(input('Ingrese su peso en kilogramos:')) alt = float(input('Ingrese su est...
#write a programm to find the fibinochii series of a agaiven set of numbers fib = [] def number(n): count = 0 c = 0 if count == 0: a = 1 b = 1 yield a yield b while c < n: temp = a a = b b += temp yield b c += 1 for i in number(int(...
class Graph(): def __init__(self): self.numberOfNodes = 0 self.adjacentList = {} def addVertex(self, node): self.adjacentList[node] = [] self.numberOfNodes+=1 def addEdge(self, node1, node2): self.adjacentList[node1].append(node2) self.adjacentList[node2].ap...
nome = input('Olá, qual é o seu Nome?') print('Olá' , nome+ '! Seja Muito Bem-Vindo') dia = input('Qual é o dia do seu aníversário?') mês = input('De que mês?') ano = input('De que ano?') país = input('Onde você mora?') print('Você se chama' , nome+'?', 'nasceu em' , país, 'em', dia + '/' + mês + '/' + ano+'?') ...
try: n=int(input()) if(n>=0): n=n%2 if(n==0): print('Even') else: print('Odd') else: print('invalid') except: print('invalid')
r = [] n = input() s = list(n) ns = list(set(s)) #removing duplicates using set and type-casting it to list. l = len(ns) for i in range(len(s)): if(l>0):# when distinct elements list length is not equal to zero it enters the loop. if n[i] in ns: r.append(s[i]) ns.remove(s[i]) #removing distinct in list whenev...
# -*- coding: utf-8 -*- # encoding=utf8 ''' This code does preprocessing on the input text to remove corner cases which cause trouble in the process of keyphrase extraction and then does the extraction process using RAKE extraction method. ''' import re import operator import nltk #File containing text #input_conte...
# coding: utf-8 ''' 求解一元二次方程 ''' import math a = int(input('Enter a: ')) b = int(input('Enter b: ')) c = int(input('Enter c: ')) delta = b * b - 4 * a * c if delta > 0: sqrt_delta = math.sqrt(delta) root1 = (-b + sqrt_delta) / (2 * a) root2 = (-b - sqrt_delta) / (2 * a) print('The root is: {0} an...
# coding:utf-8 ''' -计算圆的周长和面积 -提示用户输入半径(23) ''' import math radius = float(input("Enter the radius of circle: ")) # 参考老师的答案做了修改 circumference = math.pi * radius * 2 area = math.pi * radius * radius print('The circumference is :', round(circumference, 2)) print('The area is :', round(area, 2))
import collections def find_largest(arr): aux = collections.deque() def first_digit(num): digits = len(str(num)) first = num if digits > 1: first = num / (10**(digits - 1)) return first for x in arr: current = first_digit(x) if not aux: ...
print("enter only integer numbers") print("First Rectangle") print("Enter x position:") ax1 = int(input()) print("Enter y position:") ay1 = int(input()) print("Enter width:") w1 = int(input()) print("Enter height:") h1 = int(input()) ax2 = ax1 + w1 ay2 = ay1 + h1 print("Second Rectangle") print("Enter x position:"...
"""All the optimization methods go here. """ from __future__ import division, print_function, absolute_import import random import numpy as np class SGD(object): """Mini-batch stochastic gradient descent. Attributes: learning_rate(float): the learning rate to use. batch_size(int): the numb...
''' Program 3: Below is the python program that verifies a positive integer from the user to be a prime, composite or neither prime or composite and prints the message accordingly. Logic: * Have written a function "primenum" which takes in one argument which is the number to be tested to be a prime or composi...
#!/usr/bin/env python ''' --------------------------------------------------- PROBLEM STATEMENT: --------------------------------------------------- problem here --------------------------------------------------- INPUTS: x) binary tree representing lockable resources OUTPUTS: x) API with 3 f...
#!/usr/bin/env python ''' INPUTS: x) an array 'A' with comparable elements x) an index 'i' into the array OUTPUTS: x) a partially sorted array OBJECTIVE: x) reorder 'A' into 3 groups - initial elements < A[i] - elements == A[i] ...
#!/usr/bin/env python ''' http://stackoverflow.com/questions/13421424/how-to-evaluate-an-infix-expression-in-just-one-scan-using-stacks Dijkstra's two stack algorithm: 1) ignore left parenthesis 2) push values to value stack 3) push operand to operand stack 4) right parens, double pop values, pop operand, ev...
#!/usr/bin/env python ''' http://interactivepython.org/runestone/static/pythonds/Trees/heap.html https://en.wikipedia.org/wiki/Binary_heap Binary Heaps have 2 neat properties/requirements: - shape property. the tree is a complete binary tree. - Heap property. all nodes are either greater than or equal to or ...
''' Simple main routine for `awspricingfull` module. Call the class corresponding to your needs (EC2Prices(), RDSPrices(), etc.), and use any method with parameters needed. See the awspricingfull documentation for reference. In a nutshell: To save CSV use save_csv method for instance of any of the functional classes...