text stringlengths 37 1.41M |
|---|
days=int(input("Input dys"))*3600*24
hour=int(input("Input hour"))*3600
minute=int(input("Input minutes"))*60
seconds=int(input("seconds"))
time=days+hour+minute+second
print("the amount of seonds",time)
|
print("Writen by Oli4.0 Verwoerd\n") # Don't change the imports
import csv
import os
try:
with open('export.csv') as check:
check.close()
except:
print("ERROR FILE CAN NOT BE OPENED. check if the file is called export.csv")
print("Please note it's csv")
input('Press ENTER to continue...')
exit()
dat... |
"""
This is code to let humans play Atari games, via the Arcade Learning Environment
and the pygame library. This is based on code originally written by Ben
Goodrich, who modifed ale_python_test_pygame.py to provide an interactive
experience to allow humans to play.
I can also display RAM contents, current action, and... |
import os
from environments import River, Swamp, Coastline, Grassland, Forest, Mountain
def annex_habitat(arboretum):
#os.system('cls' if os.name == 'nt' else 'clear')
print("1. River")
print("2. Swamp")
print("3. Coastline")
print("4. Grassland")
print("5. Forest")
print("6. Mountain")
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def is_odd(n):
return n%2 == 1
print(list(filter(is_odd,[1,2,3,4,5,6,7,8,9])))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty,['A','','B',None,'C',' '])))
def main():
# 生成1000以内的素数
for n in primes():
if n < 1000:
... |
#函数
import sys
sys.setrecursionlimit(10000)#设置递归的最大次数
def fun1(param1,param2):
res1 = param1 * 2
res2 = param2 + res1
return res1,res2
result1,result2 = fun1(2,3)
print(result1,result2) |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from collections import Iterable,Iterator
print(isinstance('acv',Iterable))
print(isinstance([1,2,3],Iterable))
def g():
yield 1
yield 2
yield 3
print('Iterable?[1,2,3]:',isinstance([1,2,3],Iterable))
print('Iterable?\'abc\':',isinstance('abc',Iterable))
prin... |
#encoding=utf-8
sum = lambda a,b:a+b if a > b else a-b
def sum(a,b):
return a+b
sum = sum(1,2)
print(sum)
|
#coding: utf-8
class Student():
name = ""
age = 0
gender = ""
phone = ""
address = ""
email = ""
def __init__(self,name,age,weight,grade,gender,phone,address,email):
self.name = name
self.age = age
self.gender = gender
self.phone = phone
self.address ... |
# coding: utf-8
'''
一、编程逻辑
3、给定一个序列,计算任意个连续元素的最大平均值和其中的元素。
示例:
输入:序列list=[1,2,3,3,4,8,5,7],k=2
输出:最大平均值:(8+5)/2=6.5 元素为:[8,5]
输入:序列list=[1,2,3,5,4],k=3
输出:最大平均值:(3+5+4)/3=4 元素为:[3,5,4]
输入:序列list=[1,10,2,5,4],k=2
输出:最大平均值:(10+2)/2=6 元素为:[10,2]
'''
'''
思路:
下标从0开始移动,每个开始下标都遍历至末尾
'''
num_list = eval(input("请输入一个... |
fruit = 'Banana'
fruit[0] = 'b'
# This gives an error as you can't change a string
new_fruit = fruit.upper()
print new_fruit
# You can create a new variable |
# Import json
import json
# Create Data: Dictionary
# If dictionary, data parsed will be dictionary
data = '''{
"name" : "John",
"phone" : {
"type" : "international",
"mobile" : "999"
},
"email" : {
"hide" : "yes"
}
}'''
# Deserialization from string to int... |
n = 5
while n > 0:
print n
n -= 1
# n = n - 1
print 'Blastoff!'
print n
# Results
# 5 --> print 5 then subtract 1 = 4
# 4 --> print 4 then subtract 1 = 3
# 3
# 2
# 1 --> print 1 then subtract 1 = 0
# Blastoff
# 0 --> result of last subtraction
# Loops (repeated steps) have iteration varia... |
n = 6
while n > 0:
n -= 1 # augmented assignment & iteration variable
print(n)
print('Blastoff!')
|
"""The class extends the class named Service and it manages the saving for the Amazon S3 service
The class accepts a dict with the follow properties:
'force' (list): list of services identifier that they have to be forced for deleting
'timezone' (str): Timezone string name, default is Etc/GMT
Here's an exampl... |
"""
Here we are calibrating IR sensors by doing some measurements, then finding
a function that converts voltage (or, more precisely, the digitized voltage readings) into
distance. Some boring math follows.
The datasheet for the sensor suggests that distance is linearly related to a biased inverse voltage. In other
te... |
import os
import math
n = int(raw_input())
sm = 0
limit = n+1
a = [1 for i in range(0,limit)]
a[0] = a[1] = 0
b = [0 for i in range(0,limit)]
c = [0 for i in range(0,limit)]
def sieve():
for i in range (2,int(math.sqrt(limit))+1):
# print "i+"+str(i)
for j in range(i*2,limit,i... |
import os
def OneString(num):
num = int(num)
ones = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
print ones[num-1],
def TenString(num):
num = int(num)
tens = ["Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"]
print tens[num-1],
def OneTenString(num):
num = int(nu... |
n = input()
list = n.split(" ")
countU=0
countL=0
for i in list:
for j in i:
if(j.isalpha()):
if j.isupper():
countU+=1
else:
countL+=1
print("UPPER CASE %d"%countU)
print("LOWER CASE %d"%countL)
|
#Write a function that calculate factorial based on a positive integer input. 3! is 3 x 2 x 1 = 6.
num = int(input("Enter a number for factorial calculation"))
fact = 1
for i in range(1, num+1):
fact *= i
print("The factorial of" + ' ' + "{}".format(num) + ' ' + "is" + ' ' + "{}".format(fact)) |
# Here we generate the data in the form of linear regression (y = a*x + b) for the demonstration of gradient descent.
import numpy as np
from matplotlib import pyplot as plt
from sklearn.utils import shuffle
import pandas as pd
# init
w = 3 # y = b + wx
b = 5
n = 1000 # n: number of data
mean = 0 # add normal distr... |
city=input("enter your city: ")
print("You live in " + city )
zip=input("enter your zip code: ")
print("Your zip code is " + zip )
|
import numpy as np
# for holding sub-arrays with maximum sum
larray = []
larray_temp = []
rarray = []
rarray_temp = []
def max_sum_crossarray(arr, left, right, mid):
'''
Function for getting the maximum sum of sub-array crossing the middle
arr = find maximum sum and sub-array that produces that sum fro... |
# Importando a biblioteca tkinter e todos os seus modulos
from tkinter import *
# Criando a janela principal da aplicação através de classe Tk()
# criando uma instância da classe Tk()
janela = Tk()
# Criando uma função para quando o 1° botão for clicado,
# ele pegue o nome que foi digitado na caixa de texto através ... |
class Banco():
def __init__(self, nome, saldo=2000):
self.nome = nome
self.saldo = saldo
def exibir_saldo(self):
print(f'Seu Saldo atual: R${self.saldo}')
def depositar(self, valor):
self.saldo += valor
self.exibir_saldo()
def sacar(self, valor):
se... |
# It's prime sieve time!
from math import sqrt, floor
# the first one is something I wrote without doing research
def first_primes(limit):
"""generates primes up to the given limit"""
yield 2
for test_prime in range(3, limit + 1, 2):
if is_prime(test_prime):
yield test_prime
def is_pri... |
"""
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
from math import floor, sqrt
number = 13195
number_high = 600851475143
############## Initial Solution #####################
def get_factors(n):
# Returns all the factors of n
top = floor(sq... |
"""
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.
"""
high = 1000
def easy_solution(high):
result = 0
for i in range(high):
if i%3==0 or i%5==0:
resul... |
from overlap import overlaped
import random
#Test overlaped function with integer random numbers
print('Integer overlap test')
#Generate a list of integer random numbers
numbers = [random.randrange(1, 100, 1) for i in range(4)]
#Pass the numbers of the list as parameters to the function overlaped
result = overlaped(nu... |
"""
Purpose of this is to find a target element in an already sorted list L.
We use the fact that it is already sorted and get a O(log(n)) search algorithm.
Programmed by Aladdin Persson <aladdin.persson at hotmail dot com>
# 2019-03-12 Initial programming
"""
def binarysearch_iterative(L, target):
low = 0
... |
"""
# Purpose of the bisection method is to find an interval where there exists a root
# Programmed by Aladdin Persson
# 2019-10-07 Initial programming
"""
def function(x):
# return (x**2 - 2)
return x ** 2 + 2 * x - 1
def bisection(a0, b0, eps, delta, maxit):
# Initialize search bracket s.t a <= b
... |
"""
Purpose is to sort a list. The reason why randomizing is better is that on average, regardless on the input
randomized quicksort will have a running time of O(n*logn). This is regardless of the ordering of the inputted list.
This is in constrast to first pivot, median pivot, etc Quicksort.
Programmed by Aladdin Pe... |
def merge_sort(array):
total_inversions = 0
if len(array) <= 1:
return (array, 0)
midpoint = int(len(array) / 2)
(left, left_inversions) = merge_sort(array[:midpoint])
(right, right_inversions) = merge_sort(array[midpoint:])
(merged_array, merge_inversions) = merge_and_count(left, righ... |
import random
class Num_Guess():
attempts = 1
# def __init__(self):
def accept_upper(self):
upper = int(input('Enter the upper bound to start the game: '))
return upper
def randnum_gen(self, upper):
randnum = random.randint(1, upper)
return randnum
def accept_gu... |
def cubic(x):
result = x * x * x
return result
def cubic2(x):
y = 20
return x * x * x
def adder (n1, n2):
return n1+n2
def avg_three (n1,n2,n3):
temp = n1+n2+n3
return temp/3.0
x = 100
value1 = cubic(3)
value2 = cubic2(3)
print "x -", x
print "Value 1 - ", value1
print "value 2 - ", val... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Utilities function for stuff
"""
from datetime import datetime, timedelta
import numpy as np
def all_divisor(num):
"""
Return all the divisors of a number
:param num: The number to find the divisors
:return: A list of divisors
"""
divisor ... |
#ROCK-PAPER-SCISSORS game
import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
... |
a = float(input("enter a no"))
print (a)
b = float(input("enter a no"))
print (b)
c=a*b
print("result is"+str(c))
|
num=int(input("enter the limit"))
i=1
sum=0
while(i<=num):
sum=sum+i
i=i+1
print(sum)
|
# -*- coding: utf-8 -*-
class Accout():
ac_n=0;
name='';
deposit=0
type="";
def CreateAccount(self):
self.ac_no=int(input("Enter the account number:"))
self.name=input("Enter your name:")
self.type=input("enter the type of account you are making(C/S):")
... |
class Game:
def __init__(self, w, h):
# makes a 2d list for the board
self.board = [[True for j in range(w)] for i in range(h)]
# remvoes one peg to start
self.board[0][0] = False
self.w = w
self.h = h
def __repr__(self):
returnStr = ""
for i in r... |
#imports here
from game import game
#from board import board
#from tile import tile
#from pieces import pieces
#from deck import deck
#from dice import dice
if __name__ == "__main__":
difficulties = ["easy", "medium", "hard"]
MAX_PLAYERS = 4
numbers_of_players = [str(player) for player in range(1+1, MAX_PLAYERS+1)]... |
# Hashmap provides Insert and Delete in average constant time, although has problems with GetRandom.
# Array List has indexes and could provide Insert and GetRandom in average constant time, though has problems with Delete.
# To delete a value at arbitrary index takes linear time. The solution here is to always dele... |
#Approach 1: Annotate Parent
#Intuition
#If we know the parent of every node x, we know all nodes that are distance 1 from x. We can then perform a breadth first search from the target node to find the answer.
#Algorithm
#We first do a depth first search where we annotate every node with information about it's parent.
... |
class Solution:
# time:O(log(n!))
# space:O(1)
def binarysearch(self,matrix,target,s,v):
lo =s
hi = len(matrix[0])-1 if v else len(matrix)-1
while lo<=hi:
mid = lo+(hi-lo)//2
if v:
print('matrix[s][mid]'... |
class Solution:
def trap(self, height: List[int]) -> int:
# // 思考过程:
# // brute force: for each bar, how much water the water can be saved above this bar
# // Math.min(leftmost larger than cur bar, rightmost larger than current bar) - self height
# // time: O(n^2)
# // 想想怎么降低时间复杂度, 看哪个部分是重复操作的,浪费了时间?... |
def makeMove(obs, move, color):
"""
Args:
obs (list): 1D array of the board
move (int): 1D index that indicates where to place the piece
color (int): -1 means black, 1 means white
Returns:
list: 1D array of the board
"""
obs = obs.copy()
empty = 0
allie... |
class Board:
def __init__(self):
self.gameOver = False
self.winner = None
self.numMoves = 0
self.currentPlayer = 'X'
self.currentMove = ""
self.coordinate1 = ""
self.coordinate2 = ""
self.board = [
[" ", " ", " ",],
[" ",... |
(python_by_example)=
# An Introductory Example
## Overview
We\'re now ready to start learning the Python language itself.
In this lecture, we will write and then pick apart small Python
programs.
The objective is to introduce you to basic Python syntax and data
structures.
Deeper concepts will be covered in later... |
#! /usr/bin/env python
import argparse
import re
import os
parser = argparse.ArgumentParser(description="Text File to Csv File")
# I&O file
parser.add_argument('--input_file', dest="input_file", type=str, default="./data/data_statistic.txt", help="Data File")
args = parser.parse_args()
def txt_to_cs... |
from random import randint
nmb = randint(0, 20000)
nmb2 = 0
compteur = 0
while nmb != nmb2:
compteur += 1
nmb2 = int(input("Ecrire un nombre"))
if nmb2 > nmb:
print("Trop Grand")
elif nmb2 < nmb:
print("Trop Petit")
else:
print("Gagné avec ", compteur, " coups")... |
import turtle
from random import randint
T = turtle.Turtle()
for i in range(0,20):
randomx = randint(-400,400)
randomy = randint(-400,400)
randomcircle = randint(0,75)
T.penup()
T.goto(randomx,randomy)
T.pendown()
T.circle(randomcircle)
T.penup()
T.goto(0,0)
|
def fact(n):
f=1
while(n>0):
f=f*n
n-=1
print(f)
x=int(input())
fact(x)
|
# Binary tree node.
class Node:
# Constructor for new binary tree Node.
def __init__(self,key):
self.key = key
self.children = []
self.parents = []
def addChild(node,child):
node.children.append(child)
def addParent(node,parent):
node.parents.append(parent)
# findPath comput... |
while (True):
str1=input("Enter the age: ")
if not str1:
break
if (int(str1) >0 and int(str1) <=1):
print ("Infant")
elif (int(str1) >=1 and int(str1) < 18):
print("Child")
elif (int(str1) >=18 and int(str1) <= 60):
print("Adult")
else:
print ("... |
from pathlib import Path
from PyPDF2 import PdfFileMerger
current_path = Path.cwd()
def pdf_pathes():
"""
returns list of paths of file taken from input --> list
"""
file_names_input =input("Enter file names separated with spaces")
file_names_list = file_names_input.split()
files_paths = []
... |
# hari = ["senin", "selasa", "rabu" , "kamis", "jumat", "sabtu", "minggu" ]
# counter = 0
# for i in hari:
# print (i)
# print ("=" *50)
# while counter <7 :
# print (hari[counter])
# counter += 1
# a = 2
# b = 2
# print(hari.index("sabtu"))
# print(hari [a + b])
hari1 = ["senin"... |
import sys
# Nomer 1
kata = input("Masukan kalimat yang ingin anda decode/encode (bila kode morse dipisahkan dengan | : ")
kata = kata.lower()
char = "abcdefghijklmnopqrstuvwxyz"
morse = "._"
def split(word):
return [char for char in word]
database = {
"a" : ". _",
"b" : "_ . . .",
"c" : ". . .",... |
# import sys
# def rumus(input1):
# a = 7
# hasil = input1 + 2 + a
# return(hasil)
# print(rumus(2))
# a = 10
# print(a)
# print(rumus(a))
# def kuadrat(a):
# x = a ** 2
# return x
# print("="*50)
# bubur = "banteng banget"
# x = list()
# symbol = "!@$%^&*"
# bule = bubur.index("a")
... |
# https://leetcode.com/problems/solving-questions-with-brainpower/description/
from typing import List
class Solution:
def mostPoints(self, questions: List[List[int]]) -> int:
n = len(questions)
dp = [0] * (n+1)
for i in range(n-1, -1, -1):
point = questions[i][0]
j... |
# https://leetcode.com/problems/uncrossed-lines/
from typing import List, Tuple
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
if n > m:
return self.maxUncrossedLines(nums2, nums1)
dp = [0] * (n + 1)
... |
if __name__ == '__main__':
for tc in range(1, int(input()) + 1):
s = input()
stack = []
for letter in s:
if stack and letter == stack[-1]:
stack.pop()
else:
stack.append(letter)
print('#{} {}'.format(tc, len(stack))) |
if __name__ == '__main__':
for tc in range(1, int(input()) + 1):
s = input()
stack = []
brackets_dict = {'}': '{', ')': '('}
flag = 1
for letter in s:
if letter in brackets_dict.values():
stack.append(letter)
if letter in brackets_dict.... |
#Intro to JSON
#Data Modeling in JSON
#Objects may have different fields
#May have nested Objects
#May have nested Arrays
#In Python
#JSON Objects -> Dictionaries
#Arrays -> Lists
#JSON Playground
#Web service is a database you can access using http requests
# formulate queries as url's
|
import numpy as np
def get_values(rosalind_file):
"""
Function that extracts the necessary data from .txt Rosalind
file to convert to the following:
n: number of vertical values
m: number of horizontal values
vert: Matrix of vertical values
hori: Matrix of horizontal values
... |
print("Введите элементы массива")
try:
array = [int(x) for x in input().split()]
delta = int(input("Введите значение delta:"))
except:
print('Ошибка')
else:
a = min(array) + delta
print ("Количество элементов массиве,отличающихся от минимального на delta = " + str(array.count(a)))
|
"""
CSCI-141: Homework F: Top Baby Names
Author: Sean Strout (sps@cs.rit.edu)
Author: John Judge
This program will find the top baby names for a range of years,
based on a state and gender. It will also determine what name
in that range occurred the most times in a row.
This program, as a collection of modules, requ... |
"""
Project: Unigrams
Task: Letter Frequencies (Part One)
This is a test program that students can use to verify that they are
able to compute the correct letter frequencies using the unigram file
'very_short.csv'.
Author: Sean Strout (sps@cs.rit.edu)
Language: Python 3
"""
import letterFreq # letterFr... |
#!/usr/local/bin/python3
"""
File: testList.py
Author: Sean Strout <sps@cs.rit.edu>
Contributor: ben k steele <bks@cs.rit.edu>
Language: Python 3
Description: A test module for the linked list data structure, MyList.
"""
# see main() for imports of the module.
def testAppendAndToString( module ):
print("Testing... |
#File: tower.py
#Name: John J.
#Description: This program solves the Tower of Hanoi Puzzle in conjuction with tower_animate.py, rit_object.py, myNode.py, and myStack.py
from tower_animate import *
def DO_ANIMATION():
return True
def solve(stacks, numDisks, original, other, final):
"""
Solve is a recursi... |
"""
file: heapSort.py
version: python3
author: Sean Strout
author: John Judge
purpose: Implementation of the heapsort algorithm, not
in-place, (lst is unmodified and a new sorted one is returned)
"""
import heapq # mkHeap (for adding/removing from heap)
import testSorts # run (for individual test run)
def hea... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:茁
# date:2019/5/6
import re
string = 'The ghost that says boo haunts the loo.'
word = re.findall('[bl]oo', string)
print(word)
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:茁
# date:2019/4/24
class Horse:
def __init__(self, name, gender, rider):
self.name = name
self.gender = gender
self.rider = rider
class Rider:
def __init__(self, name):
self.name = name
person1 = Rider('LvBu')
print(p... |
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user.
#Hint: how does an even / odd number react differently when divided by 2?
#Stretch goals:
#- If the number is a multiple of 4, print out a different message.
#- Ask the user for two numbers: one nu... |
"""
HW 02 exercise 8, 9 & 10
"""
__author__ = 'tiago'
from matplotlib import pyplot as plt
import numpy as np
#
import drawing as dr
import random_things as rt
#
import run_hw02_regression as reg
#
from sklearn import linear_model
class NoisyFunc:
"""
The function
"""
noise_prob = 0.10
@staticme... |
"""
Several methods to generate random things. Shared among several exercises.
"""
__author__ = 'tiago'
from __init__ import BOX_A, BOX_BA
import numpy as np
import math
def random_line():
"""
Generate a random line crossing the board.
@return: w (vector), and px[], py[]
"""
px = BOX_BA * np.rando... |
# Define lista que funcionará como memória e suas operações
MEMORY_SIZE = 4095
# memory allocation starts in 0 and goes to 65562
memory = [None for i in range(0, MEMORY_SIZE)]
def read_byte(address):
if(address < 0 or address > MEMORY_SIZE - 1):
return "UNABLE TO ACCESS ADRESS"
else:
return ... |
# TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
print(f"merge({arrA}, {arrB})")
print("elements", elements)
merged_arr = [0] * elements
print(f"merged_arr: {merged_arr}")
# TO-DO
i = 0
j = 0
k = 0
... |
# adapted from SVM from Scratch in Python by Madhu Sanjeevi
# https://medium.com/deep-math-machine-learning-ai/chapter-3-1-svm-from-scratch-in-python-86f93f853dc
from matplotlib import pyplot as plt
from sklearn.datasets.samples_generator import make_blobs
import math
import numpy as np
def SVM_Training(dat... |
class StackMin:
def __init__(self):
self.items = []
self.min = []
def push(self, data):
if not len(self.min):
self.min.append(data)
elif data <= self.min[-1]:
self.min.append(data)
self.items.append(data)
def pop(self):
if self.... |
from linkedListOwn import Node, LinkedList
def partition(ll, x):
before_head = before = Node(0)
after_head = after = Node(0)
itr = ll.head
while itr:
if itr.data < x:
before.next = itr
before = before.next
else:
after.next = itr
a... |
from linkedListOwn import Node, LinkedList
# this is for the case when we have access to every node
def delete_middle_node(ll, node):
itr = ll.head
while itr.next:
if itr.next.data == node.data:
itr.next = itr.next.next
return ll
itr = itr.next
# the offi... |
from linkedListOwn import Node, LinkedList
def reverseLL(ll):
itr = ll.head
previous = Node(itr.data, None)
if itr.next is None:
return {'ll': LinkedList(previous), 'll_len': 1}
ll_len = 1
while itr.next:
temp = Node(itr.next.data, previous)
previous = temp
itr = ... |
"""
Tut by sentdex : https://www.youtube.com/watch?v=sZyAn2TW7GY and {}
"""
"""
RegEx Identifiers:
\d - any number
\D - anything but a number
\s - a space
\S - anything But a space
\w - any character
\w - anything But a character
. - any character except a newline
\b - the whitespace around words
\. - an actu... |
# https://stackoverflow.com/questions/3211292/two-processes-reading-writing-to-the-same-file-python
from threading import Thread
import os
import time
import itertools
def write_every_3_sec():
f = open('2.txt', 'a', os.O_NONBLOCK)
abc = itertools.cycle('abcdefghijklmnopqrstuvwxyz')
while True:
ch... |
import numpy as np
import tensorflow as tf
from tensorflow import keras
# Successive layers are defined in Sequence
model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
X = np.array([-1, 0, 1, 2, 3, 4], dtype=np.int32)
Y = np.array([-3,-1,... |
'''
IF statement:
'''
a,b=1,2
if a<5 and b>0 : print("yayy") # -> && should not be used anymore .
if a==1 or b==1 : print("super") # -> || should not be used anymore
if a in range(5) : print("cool")
if b not in range(2) : print("not so cool")
'''
The elif keyword is pythons way of saying "if the previous conditions... |
from matrix import Matrix
from vector import Vector
def main():
'''a = Matrix(2, 3)
a.set_row(0, [1, 2, 3])
a.set_row(1, [3, 2, 1])
print("a: ", a.contents)
b = Matrix(3, 2)
b.set_col(0, [0, 1, 0])
b.set_col(1, [2, -1, 1])
print("b: ", b.contents)
ab = a * b
print("ab: ", ab.... |
from main_day_11 import *
def test_is_occupied():
# Given
grid = [['#', '.'],
['#', '.']]
# When Then
assert is_occupied(grid, 0, 0)
assert not is_occupied(grid, 0, 1)
assert not is_occupied(grid, -1, -1)
def test_count_adjacent_occupied():
# Given
grid = [['#', '.'],
... |
while(True):
inputStr = raw_input().split()
n = int(inputStr[0])
k = int(inputStr[1])
chiken = n
coupon = n
while coupon >= k:
chiken = chiken+1
coupon = coupon-k
coupon = coupon+1
print chiken |
#!/usr/bin/env python
# encoding: utf-8
import itertools
#------------------------------------------------------------------------------
# [ chain_iter method ] (iterable items of type contained in multiple list arguments)
# Generator that returns iterable for each item in the multiple list arguments in sequence
#-... |
sal=int(input("enter ur salary"))
initial=int(input("enter ur joining year"))
final=int(input("enter ur current year"))
bonus=(5/100)*sal
year=final-initial
if(year>=5):
newsal=bonus+sal
print(newsal)
else:
print("experience less than 5") |
#what will be the output of this code?
s=[4,5,6,7,8]
res=s[-0]+s[-3]
print(res) |
# my_tuple=('p','e','f','s','o')
# print(my_tuple[0])
# print(my_tuple[4])
#using keywords
my_tuple=('a','p','p','l','e')
print(my_tuple.count('p')) #2
print(my_tuple.index('p')) #3
|
def linear():
num=int(input("enter the number"))
b=[1,5,8,6,9,7,23,4]
for i in b:
if i==num: #when using integer
print("num is in list")
linear()
|
#binary search;split elements with midterm then check less or greater
a=[2,4,7,3,56,89,1,79,35,49,78]
print(a)
def bsearch():
a.sort()
print(a)
ele=int(input("enter the element"))
flag=0
low=0
upp=len(a)-1
print(upp)
while low<=upp:
mid=(low+upp)//2
if ele>a[mid]:
... |
#program to calculate bmi(body mass index) of a person. body mass index is a simple
#calculation using a person's height and weight.the formula is BMI=kg/m2 where kg is a
#person's weight in kilograms and m2 is their height in meters squared.
weight_in_kg=float(input("enter the weight in kg:"))
height_in_meter=float(in... |
# arr=[2,3,4,5,6]
# def square(num):
# return num**2
# #map(function,iterable)
# squarelist=list(map(square,arr))
# print(squarelist)
arr=[2,3,4,5,6]
squarelist=list(map(lambda num:num**2,arr))
print(squarelist)
# lst=["ajay","arun","nikil","nivin"]
# def to_upper(name):
#print names in uppercase letters
lst=["aj... |
#x='[abc]' either a,b or c
#x='[^abc]' except abc
#x='[a-z]' a to z
#x='[A-Z]' A to Z
#x='[a-zA-Z]'both lower and upper case are checked
#x='[0-9]' check digits
# x='[^a-zA-ZO-9]'special symbols
# x='\s' check space
# x='\d' check the digits
# x='\D' except digit
# x='\w' all words except special characters
# x='\W' fo... |
#create person class using constructor,use inheritance in constructor
class Person:
def __init__(self,name,age,gender):
self.name=name
self.age=age
self.gender=gender
def printval(self):
print("name",self.name)
print("age",self.age)
print("gender",self.gender)
cla... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.