text stringlengths 37 1.41M |
|---|
first_number = input("What is the first number to add? ")
first_number = int(first_number)
second_number = input("What is the second number to add?")
second_number = int(second_number)
|
#!/usr/bin/env python
# coding: utf8
import rospy
from std_msgs.msg import Int32,String
import sys
import tty
# ---------------------------------------------------------------
def questions():
# node name
rospy.init_node('questions_keyboard')
pub=rospy.Publisher('questions_keyboard',String,queue_size=10)
r = rospy... |
def filter_sort(items):
lst = []
for item in items:
if isinstance(item, str):
lst.append(item)
return lst.sort()
items = [1,2,'a','c','a']
print(filter_sort(items)) |
# Project: PoW Solution Generation Module
# Author: Jonathan Kenney
# imports
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
# main program
def main():
# init vars
target = 0
message = b''
s = '0'.encode('utf-8') # start solution counter at '0'
... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
Author: Chul Lee
"""
from math import *
import scipy as sci
import numpy as np
#import plot.matplotlib as plt
import sympy as sym
from sympy.physics.mechanics import dynamicsymbols
"""Question 1"""
t,u,v,w =sym.symbols('t u v w') #declares t u v w as symbols for d... |
# MECH3750: Semester 2, 2018
# author: Travis Mitchell
# Part II: Parabolic PDE example
# Solving the diffusion equation with finite difference
# df/dt=D*d2f/dx^2 by finite difference
# with the Dirichlet boundary conditions: f=0 at x=0 and f=0 at x=xb
import math
import numpy as np
import matplotlib
imp... |
m=int(input("Enter the month: "))
d=int(input("Enter the day: "))
if m in range(1,5):
print("Winter")
if m in range(5,9):
print("Summer")
if m in range(9,13):
print("Monsoon") |
#!/usr/bin/env python3
import random
from ex2_rpsls_helper import get_selection
def rpsls_game():
compRes=0
userRes=0
drawRes=0
while (compRes-userRes)!=2 and (userRes-compRes)!=2:
userChoice=int(input(" Please enter your selection: "+
"1 (Rock), 2 (Paper), 3 (Scissors), 4 (Liz... |
__author__ = 'win7'
import string
def get_words(text):
wordList = []
for word in text.split():
for char in word:
if char not in string.ascii_letters:
break
else:
wordList.append(word.lower())
return sorted(wordList)
print(get_words('abc ascka a$R#fv ... |
############################################################################
# FILE: ex3.py
# WRITER: Aviad Levy
# EXERCISE : intro2cs ex3 2013-2014
#
# Description:
#
# constant_pension: calculate retirement fund assuming constant pesnion
# variable_pension: calculate retirement fund assuming variable pension
# choose... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 4 11:18:50 2017
@author: Hailey Cray-Dubaz
Spirit Animal User ID: Yellow Butterfly
Date Last Edited: 10/6/17
Challenge #3
Tutor for Python: Will Sanefski
Code taken from Lecture 10 and Class Wiki
"""
import matplotlib.pyplot as mplot
from PIL impo... |
# test_functions.py
# testing functions / added a docstring for greet
#def greet(name):
# """Return string Hello and a person name assigned to variable name"""
# print(f"Hello, {name}!")
#greet("Dave")
#### a set of temperature conversion functions ####
def convert_cel_to_far(C):
F = C * 9/5 + 32
return... |
# problem link: https://leetcode.com/problems/move-zeroes/
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
""""""
Do not return anything, modify nums in-place instead.
""""""
j = 0
for i in range(len(nums)):
# if current elemen... |
# problem link: https://leetcode.com/problems/pacific-atlantic-water-flow/
class Solution:
def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:
ans = []
dirs = [[-1,0], [0,-1], [1,0],[0,1]]
num_r = len(matrix)
num_c = len(matrix[0]) if num_r > 0 else 0
... |
import sqlite3
def show_color(username):
#connect the db
connection = sqlite3.connect('Flask_tut.db', check_same_thread = False)
cursor = connection.cursor()
# SQL Query
cursor.execute(""" SELECT favorite_color FROM users WHERE username = '{username}' ORDER BY pk DESC;""".format(username = use... |
for i in range(0,13):
power = 2 ** i
if len(str(power)) == 1:
print("0" + str(power))
else:
print(power % 100)
|
s = input("Input a word...\n").lower()
def repeated(s, sub):
sum_sub = 0
for i in range(len(s)):
if s.startswith(sub, i):
sum_sub += 1
print("Number of times 'aaa' occurs is:", sum_sub)
repeated(s, "aaa") |
#!/usr/bin/env python
import socket
import os
import re
from threading import Thread
from SocketServer import ThreadingMixIn
import sys, select
import time
#Client threads to perform asynchronous communication. It creates threads, for each message recieved, and prints messages when recieved.
#initializat... |
print('digite o numero da conta: \n')
numero_conta = int(input('>>> '))
print('nome do titular:\n ')
nome = (input('>>> '))
saldo = 0.0
class banco():
def __init__(self):
self.banco = '999'
self.conta = numero_conta
self.agencia = '08'
self.nome = nome
def saque(self):
... |
n = int(input("Enter n value: "))
for i in range(0,n):
for j in range(0,i):
print(j, end = " ")
print(i)
|
def countingValleys(n, s):
if n == 1:
return 0
valley_count = 0
sum = 1 if s[0] == 'U' else -1
for i in range(1, n):
if sum == 0 and s[i - 1] == 'U':
valley_count += 1
if s[i] == 'U':
sum += 1
elif s[i] == 'D':
sum -= 1
return (vall... |
'''
Array (VetoresEmatrizes)
Um vetor(array) é um conjunto ordenado de variaveis de um mesmo tipo.
Definimos:
-tipo do dado
-nome
-tamanho(da celula)
obs: cada celula e numerada,começando em 0 indo até tamanho-1
Vetores sao normalmente usados com comandos de repetiçao (for ou while)
No Python , nao h... |
#Helper function that returns predecessor of 'n' in tree of depth 'p'
def loop(p,n):
(previous_largest_possible_parent,largest_possible_parent) = (-1,2**p-1)
running_total = 0
while n!=largest_possible_parent:
#print(previous_largest_possible_parent,largest_possible_parent,n)
if n<2**(p-1)+r... |
# однострочный коммент
'''
первая строка
вторая строка
'''
print('Hello')
print('=' * 8, 'Hello', 'World!', '=' * 8)
print('=' * 8, 'Hello', 'World!', '=' * 8, sep = '')
print('=' * 8, 'Hello', 'World!', '=' * 8, sep = ' *** ')
print('=' * 8, 'Hello', 'World!', '=' * 8, end = ' yyy')
# Ввод
name = input('\nВведите в... |
Dict={}
a=input("Bir değer giriniz:")
for i in range(1,int(a)):
print({i:i*i})
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 定义元组
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (3, 6, 7, 8, 9)
print 'tup1:', tup1
print 'tup2:', tup2
# 访问元组
print 'tup1[0]', tup1[0]
|
#! /usr/bin/python
# -*- coding: utf-8-*-
# 打印乘法口诀表
for x in range(1, 10):
print
for y in range(1, x + 1):
print "%d*%d=%d" % (x, y, x * y),
|
#!/usr/bin/python
# -*-coding:utf-8 -*-
# 题目:输入三个整数x,y,z,请把这三个数由小到大输出。
# 我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换,然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
a = int(raw_input('请输入a:'))
b = int(raw_input('请输入b:'))
c = int(raw_input('请输入c:'))
l = []
l.append(a)
l.append(b)
l.append(c)
n = len(l)
for x in range(0, n - 1):... |
class Calculadora:
def __init__(self,numero1,numero2):
self._num1=numero1
self._num2=numero2
def suma(self):
return self._num1+self._num2
def resta(self):
return self._num1-self._num2
def multiplicacion(self):
... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
# use a list as a stack of ele... |
def array_of_array_products(arr):
""" arr = input product of everything except arr[i]
for every i for empty case, return empty array
if n=6 i=3 i keep track of the
sum so far [1,2,[3],4,5] [_,_,] ? [,_, _] [1, 2, 3, 4, 5] ^ ^ ^
"""
if arr==[]: return arr
if len(arr)==1: return []
num=len(arr)
r... |
class Node:
def __init__(self, node):
self.node = node
self.next = None
class Stack:
def __init__(self):
self.top_node = None
def push(self, node):
if self.top_node is None:
self.top_node = Node(node)
else:
temp = self.top_node
... |
#-*- coding: utf-8 -*-
# @Time : 2017/9/30
# @File : 快速排序.py
# @Author : zhaohui.ren
# 快速排序
def quicksort(array):
if len(array)<2:
return array #基线条件:为空或只包含一个元素的数组是‘有序’的
else:
pivot=array[0] #递归条件
less=[i for i in array[1:] if i<=pivot] #由所有小于基准值的元素组成的子数组
print(less)
... |
"""
File: my_drawing.py
Name: Luke
----------------------
TODO:
"""
import math
from campy.graphics.gobjects import GOval, GLine
from campy.graphics.gcolor import GColor
from campy.graphics.gwindow import GWindow
# Declare constants
SIDES = 4 # Canvas is recta... |
# Thomas Reagan
# ID: 001265074
import csv
from HashTable import *
from Location import *
from Package import *
# Function used to build all the necessary tables needed
# for the program. Creates a list of locations, a list of
# packages, and a hash table of packages that contain a
# location object within them
# O(n... |
def countChange(money, coinList): # [3, 2, 1]
"""
This function counts the number of different ways an amount of money can be exchanged,
given a lst of coin denominations
E.g: countChange(3,[2,1]) = 3 sice 3 can be exchanged with 1+1+1 or 2+1
Parameters:
money (int): The amount o... |
# using array-scalar type
# to determine type of each element in array
import numpy as np
dt=np.dtype(np.int32) # int32 eq string 'i4'
print (dt)
# name can be used to access content of age column
dt = np.dtype([('age',np.int8)])
a = np.array([(10,),(20,),(30,)], dtype=dt)
print(a['age'])
student=np.dtype([('name'... |
import numpy as np
a=np.array([[1,2,3,10,1],[4,5,6,7,3]])
# print(a)
# [start:end:step]
# note end must be end+1
# get intersection sub array from overall
print(a[1:3:,0:2:])
|
simple_list = [1,2,3,4]
simple_list.extend([5,6,7])
print(simple_list)
del(simple_list[0])
# or del simple_list[0]
print(simple_list)
d = {'name': 'Max'}
#Get tuple of keys and values in dict
print(d.items())
# iterate over keys/values and print themS
for k, v in d.items():
print(k,v)
del(d['name'])
print(d)
t = ... |
from math import log
#Criando um vetor/lista
meuVetor = []
for i in range(1,11):
#Calcularemos o fatorial para todos os "i's", independente se ele será utilizado na geração do valor ou não
fat = 1
j = 2
while j <= i:
fat = fat*j
j = j+1
#Verificando se o índice é pa... |
import os
from banner import banner
banner(" HTML TAG COUNTER"," Skyler")
def load(filename):
data = []
if os.path.exists(filename):
print(f"..... loading from {filename}")
with open(filename) as fin:
for entry in fin.readlines():
data.append(entry.rstrip())
... |
"""
CP1404/CP5632 Practical
Email dictionary
update to commit to prac_05 feedback
"""
email_dict = {}
user_email = input(">>> ")
while user_email != "":
user_name = user_email.split("@")[0].replace(".", " ").title()
if input(f"Is your name {user_name}? (Y/n) ").lower() == "n":
user_name = input("Name? ... |
import random
nums = []
while len(nums) < 5:
nums.append(random.randint(1, 100))
Sum = str(sum(nums))
print("Five random numbers: ", end= '')
print(*nums)
print("The sum is " + Sum) |
S = int(input("Initial savings: "))
P = int(input("Interest rate (in percentages): "))
P_percent = P/100 + 1
S_after = round((P_percent**5) * S)
print("The value of your savings after 5 years is: ", S_after) |
import random
from math import pi
print("choose N ammount of (x,y) points")
print()
print("1: n = 100")
print("2: n = 10000")
print("3: n = 1000000")
n_select = int(input("input: "))
if n_select == 1:
n = 100
elif n_select == 2:
n = 10000
elif n_select == 3:
n = 1000000
else:
print(... |
def says():
return 'hello'
def say(animal, nature):
"""
returns the voice of animals
"""
if (animal == 'dog'):
return nature + ' Bhow! Bhow!'
elif (animal == 'cat'):
return nature + ' Meow!'
elif (animal == 'lion'):
return nature + ' Whraaarr!!'
animals = ['dog', ... |
#!/usr/bin/env python3
"""Print a pyramid to the terminal
A pyramid of height 3 would look like:
--=--
-===-
=====
"""
from argparse import ArgumentParser, RawDescriptionHelpFormatter
def print_pyramid(rows):
"""Print a pyramid of a given height
:param int rows: total height
"""
width = 2 * rows ... |
# -*- coding: utf-8 -*-
#Modo auditória para checar variáveis (Em desenvolvimento)
class ModoAudit(object):
def __init__(self, obj):
#Recebe a instância da classe statistic
self.obj= obj
def print_dada(self):
print("self.amplitude:", self.obj.amplitude)
print("self.initial:", self.obj.initial)
pri... |
'''
# data augmentation
In deep learning tasks, a lot of data is need to train DNN model, when the dataset is not big enough, data augmentation
should be applied.
keras.preprocessing.image.ImageDataGenerator is a data generator, which can feed the DNN with data like : (data,label),
it can also do data augmentation at... |
# add two numbers 50+50 and 100-10
print((50+50) + (100-10))
# 30+*6, 6^6, 6**6, 6+6+6+6+6+6
# I'm not sure what the first one is because it's invalid syntax
print(f'Bitwise XOR: 6^6 = {6^6}. 0b110 ^ 0b110 = 0b000')
print(f'6 to the 6th power = {6**6}')
print(f'6+6+6+6+6+6 = {6+6+6+6+6+6}')
print('Hello Worl... |
#-------------- list of symbols and words ---------
# # - allows you to type comments in your code
# """ - allows you to write a string that covers multiple lines of code.
# + - * / - signs used to add, subtract, multiply, and divide
# print() - prints the contents within the parentheses
# = - assigns a value to ... |
#line prints string
print ("Mary had a little lamb.")
#line prints string and uses .format to insert the string snow into another string
print("It's fleece was white as {}.".format('snow'))
#line prints string
print ("And everywhere that Mary went.")
#line prints "." 10 times
print("."*10) #what'd that do?
#line assig... |
#lines 2-4 use argv to get a filename from the user
from sys import argv
script, filename = argv
#this line uses the command open to open the specific file and that open file object is assigned to the variable txt
txt = open(filename)
#this line prints a little string using a refference
print(f"Here's your file {filen... |
import sys
import re
import numpy as np
fd=open("livres/Les 3 Mousquetaires.txt")
lines=fd.readlines()
fd.close()
## lexique_raw is a sorted unique list
## of space separated words found in file
lexique_raw=[]
for l in lines:
lexique_raw+=l.split(" ")
lexique_raw=list(set(lexique_raw))
## lexique is a sorted ... |
# Numpy
import numpy as np
# Creating array from list with type float
a = np.array([[10, 11, 12], [13, 14, 15]], dtype = 'float')
print(a)
print(a[1,2])
# Transpose
at = a.T
print(at)
# Reshape the array
b = a.reshape(3,2)
print(b)
c = a.reshape(1,-1)
print(c)
d = a.reshape(-1,1)
print(d)
# Create a matrix of zero... |
if __name__ == "__main__":
class Employee:
num_of_employees = 0
def __init__(self, first, last, salary, performance_rating):
self.first = first
self.last = last
self.salary = salary
self.email = first + "." + last + "@company.com"
self.p... |
# Function that takes in a list and multiplies each element with 5
a = [2,4,10,16]
def multiply(array):
for i in range(len(array)):
array[i] = array[i] * 5
return array
b = multiply(a)
print b
|
from datetime import datetime, date, timedelta
from dateutil import relativedelta
import calendar
ONEDAY = timedelta(days=1)
ONEMONTH = ONEDAY * 30
# Symbol meanings in function name:
# dt: datetime.datetime object
# date: usually a datetime.datetime object representing a date e.g. (datetime(2015, 11, 8, 0, 0)), some... |
#!/usr/bin/env python
# coding: utf-8
# In[4]:
# tuplas são listas, porém são imutáveis
tupla = (12, 'string', 13.7, 'outra string')
print(tupla)
#posso imprimir um elemento só da tupla
print ('elemento 2: ', tupla[2])
# In[5]:
# posso juntar duas tuplas
tupla1 = (10, 'string')
tupla2 = (20, 'mais uma')
tup... |
from Q1_1 import get_data
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
train_x,train_y,test_x,test_y = get_data()
train_x = train_x.append(test_x)
km = KMeans(n_clusters=3).fit(train_x)
y = km.predict(train_x)
pca = P... |
test = input("enter the word")
s = ""
for i in range(0, len(test)):
if test[i].islower():
s = s+test[i].upper()
elif test[i].isupper():
s = s+(test[i].lower())
else:
s = s+test[i]
print(s)
print(test.swapcase())
|
again=input("If you want to encrypt/decrypt password enter yes, not Enter no : ")
while(again=="yes"):
n=input("Enter Your choice (Encrypt=1 Decrypt=2) : ")
if(n=="1"):
plaintext=input("Enter Password : ")
alphabet="abcdefghijklmnopqrstuvwxyz"
k=3
cipher=''
for c in plainte... |
# Binary Converter
# By Ex094
class txt2bin:
def __init__(self):
pass
def encode(self, text):
enc = ""
for char in text: enc += bin(ord(char))[2:].zfill(8)
return enc
def decode(self, text):
dec = ""
txt = []
for x in range(int(len(text) / 8)):
... |
def reverse_lookup(d,v):
l = []
for k in d:
if d[k] == v:
l +=[k]
return l
def hist(s):
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
hist = hist("hangover")
k=reverse_lookup(hist,2)
print(k)
|
def has_duplicates(str):
for i in range(0,len(str)):
if(str[i]==str[i+1]):
return True
else:
return False
print(has_duplicates([1,1,2,2,3,3,5]))
|
def nested_sum(list):
total=0
for l in list:
if (type(l) == type([])):
total = total + nested_sum(l)
else:
total = total + l
return total
n = [[2,3],[2,3],[5,7]]
print("Sum is:", nested_sum(n))
|
#python basics Assignment - 7
# Task: Print the FizzBuzz numbers.
# FizzBuzz is a famous code challenge used in interviews to test basic programming skills. It's time to write your own implementation.
# Print numbers from 1 to 100 inclusively following these instructions:
# if a number is multiple of 3, print "Fizz" in... |
from random import randint
from time import time
from array import array
def clock():
start = time()
while 1:
yield time() - start
def bubble_sort(a):
n = len(a)
while n != 0:
newn = 0
i = 1
while i < n:
fir = a[i - 1]
if fir > a[i]:
... |
dict1 = {"name": "pavichaya", "age": "20"}
dict2 = {"name": "pavichaya", "age": "20"}
dict3 = dict1
print(dict1 is dict3)
print(dict1 is dict2)
print(dict1 == dict2) |
vectorSaga=['luck','yoda','mike']
def barrido (vector,pos):
if vector==[]:
return 'NO HAY PERSONAJES'
else:
if pos<len(vector):
return vector[pos]+ str(barrido(vector,pos+1))
print(barrido(vectorSaga,0))
# #QUERIA SABER SI DE LA PRIMERA MANERA TAMBIEN SE PUEDE
def barri... |
import pygame
pygame.init()
SIZE = WIDTH, HEIGHT = 1000, 800
BLACK = 0, 0, 0
screen = pygame.display.set_mode(SIZE)
done = False
clock = pygame.time.Clock()
class Ball():
def __init__(self, x, y, radius, color = (255,0,0)):
self.x = x
self.y = y
self.color = color
self.radius = r... |
# CS122-Win-17
import bs4
import urllib3
import csv
import sqlite3
def crawl_census(variable_codes=None, cbsa_codes=None, filename='census.csv'):
'''
Crawls 2015 American Community Survey
Inputs:
variable_codes: a list of strings, each string is a code for a
census variable
cbsa_codes: a li... |
#sol 1
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def isMirror(L, R):
if not L and not R:
return True
if L and R and L.val == R.val:
return isMirror(L.left, R.right) and isMirror(L.right, R.left)
return False
ret... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
prev = None
current = head
#현재 위치가 null값이 아닐 때까지 tail마저 벗어나버린 상태가... |
```
sol 1
```
# Time Complexity: O(N)
# Space Complexity: O(1)
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
# initiate ans list (ans 리스트 초기화)
ans = []
for num in range(1,n+1):
divisible_by_3 = (num % 3 == 0)
... |
import math
import os
import random
import re
import sys
def getRank(arr):
rank = {}
for i in arr:
if i in rank.keys():
rank[i] = rank[i] + 1
else:
rank[i] = 1
return rank
def countTriplets(arr, r):
sum_array=[]
if r==1:
for i in range(len(arr)-1):
sum_array.append((i*(i+1))/2)
return sum(sum_... |
class Stack:
def __init__(self, data):
self.data = data
def get_top(self):
return self.data[-1]
def pop(self):
top = self.data[-1]
del(self.data[-1])
def computeMap(self):
numMin_for_maxWin = {}
while(self.data!=[]):
top = self.get_top()
max_win_size = 0
idx = len(self.data)-1
while... |
def swap_case(s):
new_s = ""
for word in s:
for char in word:
if char.isupper():
new_s = new_s + char.lower()
else:
new_s = new_s + char.upper()
return new_s
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(resul... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
if __name__ == "__main__":
input = input().split()
n = int(input[0])
m = int(input[1])
#n = 7
#m = 21
design = ".|."
no_of_design = 1
no_of_dashes = (m-3)/2
msg = "WELCOME"
for i in range(n):
if i <... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the poisonousPlants function below.
class Stack:
def __init__(self):
self.data = []
self.size = 0
def peek(self):
return self.data[-1]
def front(self):
return self.data[0]
def push(self, elem):
self.data.append(elem... |
class Stack:
def __init__(self):
self._data = []
self._size = 0
def is_empty(self):
return self._size == 0
def __len__(self):
return self._size
def peek(self):
return self._data[-1]
def push(self, elem):
self._data.append(elem)
self._size = self._size + 1
def pop(self):
if self.is_empty():
... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the miniMaxSum function below.
def getSum(arr):
total = 0
for i in arr:
total += i
print("Total:", total)
return total
def miniMaxSum(arr, total):
min = total
max = 0
for i in arr:
a = to... |
"""
A Statements which are executed by given conditions is known as Conditional statements
if condition:
print("If condition is true then this if statement will execute")
else:
print("If condition is false then else statement will execute")
Here we can use below Operators in conditional statements
1.) Compariso... |
"""
What is a variable?
Variables are containers for storing values.
We can store any data values in python variable
In python no need to declare any command to create a variable.
A variable is created the moment you first assign a value to it.
Python variables Rules
=========================
A variable name must star... |
# ***************************** 5. Dictionary Data Type *****************************
"""
-Dictionaries are the key and value pairs. Which are written with curly brackets. " { } "
Ex :
employeeData = {
"name": "Anil",
"number": "9876543210",
"DOB": 1990
}
"""
# Create a Dictionary
employeeData={"name":"Anil"... |
"""
To perform the operations on variables and its values we will use Operators.
In Python there are divides the operators into 7 groups.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
"""
# **************************** 1.)... |
#basic
for x in range(151):
print(x)
#multiples of five
for x in range(0, 1001, 5):
print(x)
#counting, the dojo way
for x in range(1, 101):
if x % 5 == 0:
print("Coding")
continue
elif x % 10 == 0:
print("Coding Dojo")
continue
print(x)
#whoa. that sucker's huge
y=0
... |
class BankAccount:
def __init__ (self,int_rate,balance):
self.int_rate = int_rate
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self
def withdraw(self, amount):
self.balance -= amount
if self.balance >= amount:
sel... |
'''Given an array of integers, return a new array such that each element at
index i of the new array is the product of all the numbers in the
original array except the one at i'''
input_array = [1,2,3,4,10]
output_array = []
for i in input_array:
prod = 1
for j in input_array:
if i!=j:
... |
a = 10
b = 13
if (a % 2 == 0) and (b % 2 == 0) :
print("모두 짝수 입니다.")
if (a % 2 == 0) or (b % 2 == 0) :
print("두 수중 하나 이상이 짝수입니다.") |
selected = None
while selected not in ['가위','바위','보'] :
selected = input('가위,바위,보 중에서 선택>')
print('선택한 값은:',selected)
|
#! python3
'''
Zebra Puzzle
'''
import itertools
def immediate_right(house1, house2):
'''
House house1 is immediately right of house2 if house1-house2 == 1.
'''
return house1 - house2 == 1
def next_to(house1, house2):
'''
Two houses are next to each other if they differ by 1.
'''
re... |
#!/usr/bin/python3
import psycopg2
DBNAME = "news"
def execute_query(query):
"""
Executes the given query against the given database name
:param query: SQL query to execute
:return: Result of the database query
"""
try:
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
... |
import re
gpa_map = {
"A": 4.0,
"AB": 3.5,
"B": 3.0,
"BC": 2.5,
"C": 2.0,
"D": 1.0,
"E": 0.0,
}
def parse_command(command: str):
"""
command (str): "4A 3B 2C 5BC 2AB 2E 2AC initial 3.72 72"
"""
arguments = command.split("initial")[-1]
regex_match = re.compile(r'(\d... |
'''This code is written after watching this: https://www.youtube.com/watch?v=EK32jo7i5LQ&t=100s
In short we take the Prime Numbers (or Natural Numbers) and plot them taking each number as a parametric coordinate
i.e if the number is say p, the corresponding (r,theta) is (p,p). Then we convert this to cartes... |
import sys
from sequences.sequence import *
from sequences.sequence_list import *
################
### Implements a simple sequence example taken from wikipedia
### States are Sunny and Rainy
### Observations are: Shop, Clean, Walk
#################
class SimpleSequence:
def __init__(self):
y_dict = {'r... |
def find_score(player_list):
hearts = 0
diamonds = 0
clubs = 0
spades = 0
for card in player_list:
if card.get_suit() == "Hearts":
if card.get_value() == "Jack" or card.get_value() == "Queen" or card.get_value() == "King":
hearts += 10
elif card.get_va... |
import math
T = [int(x) for x in raw_input().split()][0]
def find_sum_of_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
while T > 0:
T -= 1
N = [int(x) for x in raw_input().split()][0]
sqrt_of_N = long(math.sqrt(N))
sqrt_of_half_N = long(math.sqrt(N / 2))
fo... |
first_line = [int(x) for x in raw_input().split()]
repo = {}
def count_minimum(strength):
if repo.get(strength) is not None:
return repo.get(strength)
if strength == 1:
return 0
if strength % 3 != 0 and strength % 2 != 0:
count1 = count_minimum(strength - 1) + 1
count2 = ... |
"""A collection of non-contextual bandits"""
import numpy as np
# basic bandit to test the functionality of agents
class Bandit:
"""Class for a simple k-armed bandit without context dependence.
It includes variable number of arms, initialization reward distribution for
each arm (hidden from agent) and met... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.