text stringlengths 37 1.41M |
|---|
# 665.py -- Non-decreasing Array
'''
Description:
Given an array nums with n integers,
your task is to check if it could become non-decreasing by modifying at most 1 element.
We define an array is non-decreasing if nums[i] <= nums[i + 1] holds
for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
Input: nu... |
# 669.py -- Trim a Binary Search Tree
'''
Given the root of a binary search tree and the lowest and highest boundaries as low and high,
trim the tree so that all its elements lies in [low, high].
You might need to change the root of the tree,
so the result should return the new root of the trimmed binary search tre... |
# 145.py -- Binary Tree Postorder Traversal
'''
Oppsite of 144
'''
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def postorderTraversal(self, root):
'''
dfs
'''
res = ... |
# 88.py -- merge sorted array
'''
Description:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional ... |
# 93.py -- Restore IP Addresses
'''
Desciption:
Given a string s containing only digits, return all possible valid IP addresses that can be obtained from s.
You can return them in any order.
A valid IP address consists of exactly four integers, each integer is between 0 and 255,
separated by single dots and cannot ... |
# 725.py -- Split Linked List in Parts
'''
Description:
Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to... |
# 139.py -- Word Break
'''
Description:
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words,
determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
Y... |
# 130.py -- Surrounded Regions
'''
Description:
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X... |
# 583.py -- Delete Operation for two strings
'''
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.
Example 1:
Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" ... |
# 415.py -- Add Strings
'''
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
'''
def addStrings(num1, num2):
'''
same with 67
'''
carry = 0
res = ''
num1 = list(num1)
num2 = list(num2)
while num1 or num2 or carry:
if num1:... |
# 501.py -- Find mode in BST
'''
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node's key.
The right subtree of a no... |
# 160.py -- Intersection of Two Linked Lists
'''
Description:
Write a program to find the node at which the intersection of two singly linked lists begins.
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def getIntersectionNode(self, headA, headB):
... |
# 452.py -- Minimum Number of Arrows to Burst Balloons
'''
Description:
There are a number of spherical balloons spread in two-dimensional space.
For each balloon, provided input is the start and end coordinates of the horizontal diameter.
Since it's horizontal, y-coordinates don't matter and hence the x-coordinates... |
''' This is the main module. It is used to run the game.
All the different modules are called here.
Music: Payday by Jason Farham
Player graphic: art by Kenney from opengameart.org '''
import pygame
import constants
import levels
from player import Player
import tkinter
from tkinter import message... |
a = 1
b = 2
c = 3
list_ex = (a, b, c)
list_ex_2 = range(10)
# for item in list_ex_2:
# print(item)
# while item == 9:
# print(item)
# item += 1
# print('Item is '+ str(item))
for item in list_ex_2:
if item % 2 == 0:
print(item)
elif item ==3:
print('This is elif ... |
# TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr)):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for j in range(i+1,len(arr)):
... |
x, y = "I'm Adam'".lower().strip("i' ").strip().replace(" ", ''), 'Madam'.lower()
# method 1
if x == y:
print('A palindrome')
else:
print('Not a palindrome')
# method 2
index = len(y) - 1
lcount = 0
for i in x:
if i == y[index]:
lcount += 1
index -= 1
else:
break
if lcount > le... |
#!/usr/bin/env python
#
# Author: Marcin Koculak <koculak.marcin@gmail.com>
# Created: 01.09.2017
#
# Copyright (C) Marcin Koculak
# For license information, see LICENSE.txt
import pandas as pd
import numpy as np
from string import ascii_lowercase
def shuffle_ans(series):
'''
Function shuffles answers for... |
def getCircle(r):
return r*r*3.14
r = int(input())
print(getCircle(r)) |
'''
A class to hold data associated with a die.
@Author Dustin Roan (dustin.a.roan@gmail.com)
@Version 8/12/2018
'''
import random
class Die:
"""Defalut constructor of a die.
@param sides int The number of sides a die has. Default is 6
@raises ValueError if sides param is not an integer
"""
def _... |
import csv
import random
def csv_reader():
with open('data2.csv', 'r') as file:
reader = csv.reader(file)
# Skip CSV's header using next() function
next(reader)
data = []
for row in reader:
data.append(row)
random_data = random.sample(data, 3)
... |
# This line imports the argv class from the sys module
from sys import argv
# This line unpacks the arguments
script, filename = argv
# This line assigns the contents of the sample file to the variable txt
txt = open(filename)
# This line prints out a sentence with the filename formatted in
print "Here's your file %... |
import unittest
from grammaranalyzer.helpers import is_true, is_not_dunder
class TestHelpers(unittest.TestCase):
def test_is_true(self):
self.assertEqual(is_true(''), False, '"" is not true')
self.assertEqual(is_true('not empty string'), True, '"not empty string" is true')
def is_not_dunder... |
import random
import time
import matplotlib.pyplot as plt
import numpy as np
# from task_03.Initial import initial_solution
def follow_way_succed(board, x, y, path):
"""
Follow path and return path to entertance if found.
:param board:
:param x:
:param y:
:param path:
:return:
"""
... |
import tkinter as tk
root = tk.Tk()
def sumar():
a = float(numero1.get())
b = float(numero2.get())
resultado.set(str(a+b))
numero1.set('')
numero2.set('')
def restar():
a = float(numero1.get())
b = float(numero2.get())
resultado.set(str(a-b))
numero1.set('')
numero2.set('')
de... |
secret = 9
guesses = 0
guess_limit = 3
while guesses < guess_limit:
guess = int(input("Guess a number: "))
guesses += 1
if guess == secret:
print("You won!")
break
else:
again = input("You lose! Sorry!")
|
# -*- coding: utf-8 -*-
import codecs as cs
import math
from typing import Dict, List, Tuple
ciphertext_filename = "09.txt"
alphabet = list("абвгдежзийклмнопрстуфхцчшщьыэюя")
inacceptable_bigrams = [ "жы", "шы", "аь", "аы", "уы", "еы", "оы" ]
freq = [
'то', 'ов', 'на', 'не', 'но', 'ст', 'по', 'ко', 'он', 'от', 'е... |
from collections import Counter, OrderedDict
import re, math
def extra_remover(file):
space_file = file.read().lower() # Read data from file and convert to lowercase
space_file = re.sub(r'[^А-Яа-я ]', '',
space_file) # Remove all the characters, accept for cyrillic letters and whites... |
import random
import math
def gcd(x,y):
while (y):
x,y=y,x%y
return x
def miller_rabin(p):
for number in [2,3,5,7]:
if gcd(number,p) != 1 or pow(number,p-1,p) != 1:
return False
d = p - 1
s = 0
alredy_chosen = []
while d % 2 == 0:
d //= 2
s += 1
... |
import random, sys, math
def Miller_Rabin(n):
r=int(math.log(n,2))
if n == 2:
return(True)
elif n == 3:
return(True)
elif n % 2 == 0:
return(False)
else:
power=0
t=n-1
while t%2==0:
t=t//2
power+=1
for k in range(r):
... |
import math
def pearson_correlation(independent, dependent):
"""
Implements Pearson's Correlation, using several utility functions to
calculate intermediate values before calculating and returning rho.
"""
# covariance
independent_mean = _arithmetic_mean(independent)
dependent_mean = _ar... |
a=int(input("enter number"))
b=int(input("enter number"))
c=int(input("enter number"))
d=int(input("enter number"))
k=a**b
l=c**d
m=k+l
print(m) |
var=2018
word= "This is a Simple Calculator"
print("Game On Python!!!!!", var, word)
print("Enter two digits you want to Compute")
a= int(input("Enter Value Of First Digit"))
b= int(input("Enter Value Of Second Digit"))
op= input("Enter Operator")
if (op== "+"):
print(a+b)
elif (op== "-"):
print(a-b)
elif (o... |
# nameAndAge.py
# This program reads in a number and adds 1 to it
# author: Barry Gardiner
name = input("Enter your Name:")
age = input("Enter your Age:")
print('Hello {}\nYour Age is {}'.format(name, age))#using format to fromat name
print(24 - 7)
print(2==3) |
fib = [1, 1]
def getNthFib(n):
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
return fib[-1]
if __name__ == "__main__":
n = 3
print(getNthFib(n)) |
import numpy as np
import random
def check(secret_number,guessed_number):
cows=0
bulls=0
secret_num_str = str(secret_number)
guessed_num_str = str(guessed_number)
for i in range(len(guessed_num_str)):
if guessed_num_str[i] in secret_num_str:
if guessed_num_str[i]== secret_num_s... |
#Your code go here:
x=20
result=""
while x>0:
if x%5==0:
result=result+ str(x)+"!\n"
else:
result=result + str(x) +"\n"
x-=1
print(result+"LISTOFF") |
my_list = [2323,4344,2325,324413,21234,24531,2123,42234,544,456,345,42,5445,23,5656,423]
#Your code here:
average1=0
for x in my_list:
average1=average1+x
average1=average1/(len(my_list))
print(average1) |
# Script para mostrar el uso de las funciones
def saluda(nombre):
resultado = "Que onda " + nombre + " ¿todo bien?"
return resultado
nombres = ["Zuleima","Nora","Francisco","Juan Carlos"]
for nombre in nombres:
print(saluda(nombre))
|
# Script para mostrar el uso del tipp de una variable y su impresión en pantalla
# Obten de la librería datetime lo que necesitamos para saber la fecha
from datetime import date
import random
# Crea una variable que almacene un entero al azar
numero_entero = random.randint(0,10)
# Crea una variable que almacene un f... |
# Script para mostrar el uso de las listas
def promedio_2D(lista):
resultado = []
for numero_en_lista in lista:
print("--",numero_en_lista)
suma = 0
for numero in numero_en_lista:
print("valor:",numero)
suma += numero
print("suma:",suma)
re... |
# Script para mostrar el uso de for each
cadena_texto = "En esta cadena de texto hay ocho palabras"
cantidad_espacios = 0
print(cadena_texto)
for caracter_actual in cadena_texto:
if caracter_actual == " ":
cantidad_espacios += 1
print("Hay " + str(cantidad_espacios + 1) + " palabras en la cadena de texto")
|
class Base1(object):
def __init__(self,nm):
self.name1 = "Peter"
print("Passed to Base1")
super(Base1, self).__init__(nm)
def showName1(self):
print(self.name1)
class Base2(object):
def __init__(self,nm):
self.name2 = "John"
print("Passed ... |
f = open("01.input","r")
floor=0
count=0
line = f.read()
for item in line:
if (item=="("):
#print "up"
count=count+1
floor=floor+1
elif (item==")"):
#print "down"
count=count+1
floor=floor-1
if (floor==-1):
print count
else:
print "WTF!", item
#print "count, floor", count, floor
#print li... |
f = open("08.input","r")
import string
tots=0
new=0
for line in f:
print "---"
line=line.strip()
#cmd=line.split(" ")
print line
print "len",len(line)
tots=tots+len(line)
line=string.replace(line,"\"","||")
line=string.replace(line,"\\","||")
print line
new=new+len(line)+2
#remove quotes
print "tots", ... |
#-----------------------------------------------------------------------
# Program name: Voter eligibility and polling station program
# Author: Ryan Wallace
# Date: 2-29-16
# Purpose: To find locations to vote
#-----------------------------------------------------------------------
# GLOBAL VARIABLE DEFINITIONS
... |
import unittest
from common.encoder import Encoder
class TestEncoder(unittest.TestCase):
def setUp(self):
self.separator = '\n—weird—\n'
def test_Encoder_if_text_is_empty_string(self):
text = ""
list_of_encoded_words = ""
encoded_text = Encoder.encode_text(text)
expect... |
110. Write a Python program to get numbers divisible by fifteen from a list using an anonymous function. Go to the editor
num_list = [45, 55, 60, 37, 100, 105, 220]
i=0
while i<len(num_list):
if num_list[i]%15==0:
print(num_list[i])
i=i+1
|
print the pettern of 1 to 5
i=0
while i<6:
j=0
while j<i:
j=j+1
print(j,end='')
i=i+1
print()
|
7. Write a Python program to remove duplicates from a list.
a = [10,20,30,20,10,50,60,40,80,50,40]
b=[]
i=0
while i <len(a):
if a[i] not in b:
b.append(a[i])
i=i+1
print(b)
|
Exercise Question 3: Accept n number from user and calculate the sum of all number between 1 and n including n
i=1
sum=0
while i<10:
sum=sum+i
i=i+1
print(sum)
|
Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service.
if employee is female, then she will work only in urban areas.
if employee is a male and age is in between 20 to 40 then he may work in anywhere
if employee is male and age is in between 40 t0... |
1. Write a Python program to calculate the length of a string. Go to the editor
check=[2,4,5,7,9]
i=0
while i<len(check):
i=i+1
print(i)
|
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
data_path = 'https://github.com/Jack4589/AirBnB-App-BW-TFT9DS/raw/main/Data/listings.csv'
nyc_simple = pd.read_csv(data_path)
# Set target
target = "price"
# Create target vector
y = nyc_simple[target]
# Create simple (1 vari... |
class ListNode:
def __init__(self, value, next_value=None):
self.value = value
self.next = next_value
class Solution:
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if head is... |
class Aluno(object):
def __init__(self):
self.cr=0
self.tCargaHoraria=0
self.nota = 0
self.ch = 0
self.operacao = 0
def processar_dados(self,nota,ch):
self.nota = int(nota)
self.ch = int(ch)
self.tCargaHoraria += self.ch
self.oper... |
"""
This file contains heuristics used to evaluate a certain game state
"""
from othello import Othello
import util
from constants import POSITION_TO_DATABASE
import database
# Generate sets of fields with similar value
ALL_FIELDS = {(a, b) for a in range(8) for b in range(8)}
CENTER = {(3, 3), (3, 4), (4, 3), (4, 4)... |
def tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest):
"""
Write a function that returns the maximum possible total speed or the minimum possible total speed of all of the
tandem bicycles being ridden based on an input parameter, fastest .If fastest = true your function should return the
maximum p... |
#! -*- coding: utf-8 -*-
"""
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s
elements are subset of nums2. Find all the next greater numbers for nums1's
elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to
its right in... |
# Node of a Decision Tree
class Node:
totalcount = 0
def __init__(self, dataset, parent):
Node.totalcount += 1
#
self.id = Node.totalcount
self.level = 1 if (parent is None) else parent.level + 1
#
self.data = dataset
#
self.predicate = None
self.line = None
self.answer = N... |
"""
Copyright (c) Steven P. Goldsmith. All rights reserved.
"""
"""Train model with the MNIST database of handwritten digits. This example was taken from https://github.com/tankala/ai-examples and updated to TensorFlow 2.
@author: sgoldsmith
"""
import logging, numpy, tensorflow as tf
from tensorflow.keras.datasets... |
#Alan Chiang, 903129489, achiang31@gatech.edu, Section B
#We worked on the homework assignment alone, using only this semester's course materials.
from math import *
def circleArea(r):
area = (pi*r*r)
print(area)
def circleCircumference (d):
float(d)
circumference = (pi*d)
return(ci... |
nombre = input("Ingrese su nombre: ")
inicial = nombre[0]
print("Primera letra del nombre:",inicial)
largo = str(len(nombre))
print("Largo del nombre:",largo)
|
"""
获取http 请求和相应
"""
from socket import *
def handle(connfd):
data = connfd.recv(1024 * 10)
print(data.decode())
# 换行\r\n
file=open("kb.jpg","rb")
response="HTTP/1.1 200 OK\r\n"
response+="Content-Type: image/jpg\r\n"
response+="\r\n"
response=response.encode()+file.read()
connfd.se... |
from tkinter import *
def update():
print("updating....")
root.geometry(f"{width.get()}x{height.get()}")
root=Tk()
root.geometry("455x233")
width=StringVar()
height=StringVar()
Label(text="widht").pack(anchor="w")
Entry(root,textvariable=width).pack()
Label(text="height").pack(anchor="w")
Entry(roo... |
from random import randint
nouns = ["cheese", "humans", "cow", "bear"]
verbs = ["waking", "running", "talking", "barking"]
adjectives = ["brave", "calm", "cool", "courageous"]
madlibs = ["Zoos are places where wild","N", "are kept in pens or cages so that","N", "can come and look at them.", "A", "Isnt it?"]
def creat... |
"""
This problem was asked by Jane Street.
cons(a, b) constructs a pair, and car(pair) and cdr(pair)
returns the first and last element of that pair.
For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4.
Given this implementation of cons:
def cons(a, b):
return lambda f : f(a, b)
Implement car an... |
N = int(input(""))
lista_de_numeros = []
for i in range(N):
numero = int(input(''))
if numero == 0:
del(lista_de_numeros[-1])
else:
lista_de_numeros.append(numero)
print(sum(lista_de_numeros)) |
def input_message(prompt):
'''输入学生信息,过滤空值'''
while True:
msg = input(prompt)
if msg == "":
print("输入不能为空,请重新输入")
else:
return msg
name = input_message("请输入学生姓名:")
print(name)
class People():
def hand(self,a,b):
return a+b
def add(s... |
## Version 1 read directly from the command prompt
contactList = []
name = input();
while name:
contactList.append(name)
name = input()
contactList.sort()
for name in contactList:
print(name)
|
##Sum with a while
n = int(input())
suma = 0
for i in range(1,n+1):
suma=suma+i
print(suma)
|
##Sum with a for
n = int(input())
i=1;
suma=0
while i<=n:
suma=suma+i
i+=1
print(suma)
|
#Global dictionary used to store the permutations
dictionary = dict()
def stringPermutation(word,lower,higher):
#If lower has been incremented to the same value as higher
if lower == higher:
#Convert word list back to string
newWord = ''.join(word)
#Add the string to the dictionary as k... |
def top_ten():
n = 1
while n <= 10:
sq = n * n
yield sq
n += 1
value = top_ten()
for i in value:
print(i) |
""" In this example we are going to use tensorboard. Specifically
we are going to visualize the graph and loss of the model. We
will be using the MNIST data set for our model."""
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST/data", one_ho... |
import math
arr=[0]*5
arr=list(map(int,input().split()))
a=0
for i in range(5):
if(arr[i]<2):
print("number one")
continue
k=0
for j in range(2,int(math.sqrt(arr[i]))+1):
if(arr[i]%j==0):
print("composite number")
k+=1
break
if(... |
class persona:
def __init__(self,id_persona,id_usuario,nombre,apellido_paterno,apellido_materno,correo,celular,genero):
self.id_persona=id_persona
self.id_usuario=id_usuario
self.nombre=nombre
self.apellido_paterno=apellido_paterno
self.apellido_materno=apellido_materno
... |
str1 = input('Van welk woord wilt u weten of het een palindroom is?:')
str1Reverse = str1[::-1]
def palindroom():
if str1 == str1Reverse:
print('Dit is een palindroom')
else:
print('Dit is geen palindroom')
def palindroom2():
if str1 == reversed(str1):
print('Dit is een palindroo... |
age_guess = int(input("Guess what age Michael is: "))
age_actual = 39
if age_guess == 39:
print("Bingo! You are correct.")
elif age_guess > 46:
print("Oh come on! Lockdown must've really aged me!")
elif age_guess >= 35 and age_guess <= 45:
print("Close enough, Michael is " + str(age_actual))
elif age_guess... |
# Write a function `remove_duplicates` that takes
# in a list and returns a list without duplicates.
# For example:
# `remove_duplicates([1,1,2,2])` should return `[1,2]`.
def remove_duplicates(a_list):
b_list = [a_list[0]]
for i in a_list:
if i in b_list:
continue
else:
... |
def isPalindrome(my_str):
my_str = my_str.casefold()
rev_str = reversed(my_str)
if list(my_str) == list(rev_str):
print("{} is palindrome".format(my_str))
else:
print("{} is not palindrome".format(my_str)) |
import numpy as np
import matplotlib.pyplot as plt
class TreeNode(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self._length = 1
def __str__(self):
return "{}".format(self.key)
def __len__(self):
return self._le... |
class Garage():
def __init__(self,tickets, parkingSpaces):
self.tickets = tickets
self.parkingSpaces = parkingSpaces
def garageSize(self):
while True:
size = int(input("How big is the garage? (1 - 100) "))
if (size > 0) and (size < 101):
for x in... |
# Load modules and defining variables #
from tkinter import *
from tkinter import messagebox
master = Tk()
outFlex = 0
inFlex = 0
totFlexLabel = StringVar()
# Display the entry fields #
inInput = Entry(master, width=50)
inInput.pack()
inInput.focus_set()
outInput = Entry(master, width=50)
outInput.pack()
... |
print("Ingresa 3 números:")
n1=int(input())
n2=int(input())
n3=int(input())
sum=n1+n2
if sum > n3:
print("la suma del primer núermo y el segundo número es mayor que el tercero")
else:
print("La summa del primer número y el segundo núermo es menor que el tercero") |
def suma(num,num2):
suma=num+num2
return suma
num=float(input("Ingresa el primer número para hacer la adición:"))
num2=float(input("ingresa el ultimo número para hacer la adición:"))
print(f"La adición de {num} y {num2} es=", suma(num,num2))
|
print("Ingresa dos números, uno de esos números debede ser mayor que el otro")
n=int(input())
m=int(input())
sum=0
if m>n:
for i in range(n+1,m):
sum=i+sum
print(f"La suma de los números: {sum}")
else:
print("Error")
|
n = int(input("Ingresa la cantidad de números que quiera ingresar: "))
par = 0
sumpar = 0
impar = 0
sumimpar = 0
for i in range(n):
numero = int(input("Ingresa un número: "))
if numero % 2 == 0:
par = par+1
sumpar = sumpar+numero
else:
impar = impar+1
sumimpar = s... |
def area (n1,n2):
area=(n1*n2)/2
return area
n1=float(input("ingresa el perimetro para hallar el área del hexagono:"))
n2=float(input("ingresa el apotema para hallar el área del hexagono:"))
print("el área de tu hexagono es de:", area(n1,n2))
|
distancia=int(input("Ingrese la distancia que va a recorrer su vuelo:"))
dias=int(input("Ingrese cuantos días va a estar en su destino:"))
valor_precio=distancia*5000
if distancia==20:
precio=100000
print("Tu pasaje tendra un valor de $",precio)
if distancia!=20:
print(f"Tu pasaje tendr... |
# program to create a class and its objects
class Person:
# method which gets executed when the class is initiated
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print("\n",self.name, "is" ,self.age, "years old")
#driver code
def mai... |
#creating variables
string = "This is within quotes" #string type
num = 5 #number
comp_num = 1 + 8j #complex number
x = eval("1+2") #evaluating
print("string : " , string)
print("num : " ,num)
print("comp_num : " ,comp_num)
print("x : " ,x)
#multiple assigments
a,b... |
#simple funcction to compute factorial of given number
def fact(num):
if num == 0 or num == 1:
return 1
else:
return num*fact(num-1)
def main():
x = int(input("Enter the number : "))
print(x,"! = ",fact(x))
if __name__=="__main__":
main() |
# name = raw_input("What is your name?")
# name1= raw_input("What is your pair's name")
# if len(name) > len(name1):
# print "My name is greater"
# elif len(name) < len(name1):
# print "Their name is greater"
# else:
# print "Our names are equal"
# date = int(raw_input("What day of the month is today?"))
# if date ... |
#Actvity 1
#1a
# def hello_print():
# print "Hello"
# hello_print()
#1b
# def hello_print():
# print "Hello"
# hello_print("hi")
#this will give an error because there are no parameters that have been given.
#you can't have an argument without having any parameters
#2a
# def hello_return():
# return "Hello"
# h... |
def tail_rev(in_string,rev_string):
if in_string=='':
return rev_string
else:
rev_string+=in_string[-1]
return tail_rev(in_string[:-1],rev_string)
in_string=input("Enter String: ")
rev_string=tail_rev(in_string,'')
print(f"Reverse is {rev_string}")
#Code gained from @AshishIsh on Stac... |
from keras.models import Sequential, load_model
from keras.layers import Conv2D,MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.utils import np_utils
import keras
import numpy as np
classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
num_classes = len(classes)
image_size ... |
print("당신이 태어난 연도를 입력하세요 : ")
birth_year = input()
age = 2019-int(birth_year)+1
if age <=26 and age >=20:
print("대학생")
elif age <20 and age >=17:
print("고등학생")
elif age<17 and age >=14:
print("중학생")
elif age<14 and age>=8:
print("초등학생")
else :
print("학생이 아닙니다")
|
'''
/**
* The goal is to generate the clauses to verify the existence of a critical pair with different length.
* Ensure the existence of a faulty path, check faulty path with length lf in range(k,bound).
*
*
*
* @author Lulu HE
* @Email helulu@lri.fr
**/
'''
class CheckSat:
def __init__(self,kvalue,ln,lf):... |
"""Contains methods for the generation of cipher text and cipher keys"""
from random import shuffle
from string import ascii_lowercase
def generate_key():
"""
Creates a key table to encipher and decipher plain text
Returns:
The 5 x 5 array of unique letters (not containing 'j'), stored in a 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.