text stringlengths 37 1.41M |
|---|
"""
Write a Python program to find intersection of two given arrays using Lambda.
"""
number_array1 = list(range(1, 20))
number_array2 = list(range(1, 10))
intersection = list(filter(lambda x: x in number_array1, number_array2))
print("Given arrays: \n {} \n {}".format(number_array1, number_array2))
print("\nInterse... |
"""
Write a Python program to get a single string from two given strings, separated
by a space and swap the first two characters of each string.
"""
def swap(x, y):
a = y[:2] + x[2:]
b = x[:2] + y[2:]
return a + ' ' + b
print(swap('abc', 'xyz'))
|
"""
Write a Python program to create Fibonacci series upto n using Lambda.
"""
from functools import reduce
fibonacciSeries = lambda n: reduce(lambda n, _: n + [n[-1] + n[-2]], range(n - 2), [0, 1])
print(fibonacciSeries(9))
|
"""
Write a Python program to remove the characters which have odd index values of a given string.
"""
def removeOddIndex(input_string):
output_string = ''
for i in range(len(input_string)):
if i % 2 == 0:
output_string = output_string + input_string[i]
return output_string
print(re... |
"""
Write a Python script to check whether a given key already exists in a dictionary.
"""
def checkKey(input_dict, input_key):
if bool(input_dict.get(input_key)):
return 'key Exists !'
else:
return 'Key does not exists'
dict = {'one': 1, 'two': 2}
print(checkKey(dict, 'three'))
|
"""
Write a python program to get a string from a given string where all occurrences of its first char
have been changed to $, except the first char itself
"""
def replace(user_input):
char = user_input[0] # first char
user_input = user_input.replace(char, '$') # replaced all char with $
user_input = ch... |
# calcúlo de potência em kWh de aparelhos.
# para trasnformar kWh em Joules só mudar para 3,6 * 10^6
potencia = int(input())
minutos_ligado = int(input())
tempo = minutos_ligado * 60
gasto = potencia * tempo
kwh = gasto * 2.778 * 10 ** - 7
print(f'{kwh:.1f} kWh')
|
class Employee:
def __init__(self, name='Default'):
self.name = name
self.address = 'Default'
self.role = 'Default'
self.manager = 'Default'
# ID?
def print_attr(self):
# A custom print statement
print('name:', self.name)
print('address:',... |
import random
numOfJavelinas = 300
lenOfWall = 600
javelinas = []
class Javelina( object ):
def __init__( self ):
self.position = 0
self.direction = ''
self.ID = 0
self.endOfWall = False
self.inTransit = False
def __cmp__( self, other ):
return cmp( self.posit... |
"""
Methods all classes should define.
Methods that are at the base of the class, but don't need to be defined
in base_dice.py. These are things like :code:`str`, :code:`repr` and
:code:`bool`.
These are magic methods that any class should define to make Pythonic
development easier.
"""
from __future__ import annota... |
"""
Problem Description
Given two integer array A and B, you have to pick one element from each array such that their xor is maximum.
Return this maximum xor value.
Problem Constraints
1 <= |A|, |B| <= 105
1 <= A[i], B[i] <= 109
Input Format
First argument is an integer array A.
Second argument is an integer arr... |
def merge_sort(A:list,beg:int,end:int)->None:
"""
A=[12,3,1,2,3,342,2324,5]
beg=0,end=8
mid=(0+8)//2=4
B=[12,3,1,2,3,342,2324,5,4]
beg=0,end=9
mid=(0+9)//2=4
:param A:
:param beg:
:param end:
:return:
"""
if beg>=end:
return
mid = (beg+end)//2
merge_s... |
"""
Find if Given number is power of 2 or not.
More specifically, find if given number can be expressed as 2^k where k >= 1.
Input:
number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range)
Output:
return 1 if the number is a power of 2 else return 0
Example:
Input : ... |
"""
Problem Description
Given a string A denoting a stream of lowercase alphabets. You have to make new string B.
B is formed such that we have to find first non-repeating character each time a character is inserted to the stream and append it at the end to B. If no non-repeating character is found then append '#' at... |
"""Given a matrix of integers A of size N x M in which each row is sorted.
https://www.interviewbit.com/problems/matrix-median/
Find an return the overall median of the matrix A.
Note: No extra memory is allowed.
Note: Rows are numbered from top to bottom and columns are numbered from left to right.
Input Format
... |
def drone(route):
"""
IN: route, [3d coordinates]
OUT: minimum fuel requirement to complete route
drone: [dict] -> Int
route = [{x:0, y:2, z:10}, {x:3, y:5, z:0}, {x:9, y:20, z:6}, {x:10, y:12, z:15}, {x:10, y:10, z:8}]
X: Side to side (free movement)
Y: Forward (free movement)
Z: A... |
class Node(object):
def __init__(self, data=None, left=None, right=None):
""" """
self.data = data
self.left = left
self.right = right
def __repr__(self):
return "<__main__.Node object %d>" % (self.data)
def get_min(self):
"""
Returns val... |
"""
This program implements different methods of denoising an images and comparing the
results obtained. There are two parts 'a' and 'b'. In part a we are using Gaussian
blur and Median blur, in part b used bilateral filter for the same which is very effective
at edges.
"""
import numpy as np
imp... |
# Assigning int value to Variable x and then multiplying with 5
x = 5
print(x * 5)
##OP - 25
# Assigning string value to Variable yt and then multiplying with 5
yt = 'Youtube'
print(yt * 5)
##OP - YoutubeYoutubeYoutubeYoutubeYoutube
# if we create string Variable and then add brackets [] and pass the int value that i... |
m = input('Please input number 1\n')
n = input('Please input number 2\n')
o = input('Please input number 3\n')
p = input('Please input number 4\n')
q = input('Please input number 5\n')
print('float of 1 equal ',float(m))
print('complex of 1 equal ',complex(m))
print('float of 2 equal ',float(n))
print('complex of ... |
name = input('What is your name?\n')
surname = input('What is surname?\n')
collegeyears = input('What is collegeyears\n')
code = input('What is your code\n')
print('My name is :%s.' %name)
print('My surname is :%s.' %surname)
print('My collegeyears is :%s. ' %collegeyears)
print('My code is :%s.,' %code) |
"""
Name: Alexis Steven Garcia
Project: Space Invaders
Date: October 8, 2018
Email: AlexisSG96@csu.fullerton.edu
"""
import pygame
from pygame.sprite import Sprite
from pygame import Surface
class Bunker(Sprite):
"""Represents bunker bits and pieces that can be destroyed"""
def __init__(self, ai_settings, scr... |
import matplotlib.pyplot as plt
import numpy as np
import csv
# Часть 1
"""
x = []
y = []
with open('example.csv', 'r') as csvfile:
plots = csv.reader(csvfile, delimiter=',')
for row in plots:
x.append(int(row[0]))
y.append(int(row[1]))
plt.plot(x, y, label='loaded from file')
"""
# Часть 2
... |
# Structure itérative
# La boucle for
# Exemple 1 : méthode Couet
print('=' * 60)
print('Exemple 1')
print("Méthode Couet.")
print('=' * 60)
print('Auto-motivation')
for i in range(5):
print('Je suis le meilleur ' + str(i) + ' fois sur 5')
print('Source : https://fr.wikipedia.org/wiki/M%C3%A9thode_Cou%C3%A9')
# ... |
#! python3
# mapIt.py - Launches a map in the browser
# using an address from the
# command line or clipboard
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
# Get address from command line.
address = ' '.join(sys.argv[1:])
else:
# Get address from clipboard
address = pype... |
# Document Clustering using K-means clustering algorithm
import random
import math
from dataset import data,doc_title
# Distance calculation using Pearson Correlation Score
def distance(v1,v2):
# Sums
sum1=sum(v1)
sum2=sum(v2)
# Sums of the squares
sum1Sq=sum([pow(v,2) for v in v1])
sum2Sq=sum([pow(v,2) for v... |
import unittest
from ordered_list import *
class TestLab4(unittest.TestCase):
def test_isempty(self):
# test empty list
list0 = OrderedList()
self.assertTrue(list0.is_empty())
# test list with one item
list0.add(1)
self.assertFalse(list0.is_empty())
# list ... |
import os
import sys
import random
import pickle
from Game import Game
def save_game(game, filename):
with open('saves/{}'.format(filename), 'wb') as f:
pickle.dump(game, f)
def load_game(filename):
with open('saves/{}'.format(filename), 'rb') as f:
return pickle.load(f)
os.system("cls")
p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 24 16:16:10 2018
@author Frevel
"""
def get_primes(limit = 1000):
"""
Computes all primes up to limit. Uses the sieve of Erastothenes.
limit (int) : Upper limit for value of prime number
Returns list
"""
numbers = list... |
# Celsius('C) to Fahrenheit('F) Conversion
c = input('Celsius:')
c = float(c)
f = c * 9 / 5 + 32
print("Fahrenheit:", f) |
def count_orbits(orbit_map):
queue = ['COM']
distance = 0
orbit_count = 0
while queue:
next_queue = []
for planet in queue:
orbit_count += distance
if planet in orbit_map:
next_queue.extend(orbit_map[planet])
distance += 1
queue = next_queue
return orbit_count
... |
ejercicio="""Dada una cadena cambiar las palabras que empiezan con una voca a mayuscula,
Las palabras que empiezan por una consonante dividirlas si su longitud es par"""
print(ejercicio)
cad=input("cadena>>>")+" "
pal=""
nCad=""
for i in cad:
if i==' ':
if pal!="":
if pal[0] in "aeiou... |
#devuelve las palabras de una cadena en forma de lista
def palabras(cad):
pals=[]
aux=""
cad=cad+" "
for i in range(len(cad)):
if cad[i]!=' ':
aux=aux+cad[i]
else:
pals.append(aux)
aux=""
return pals
#devuelve el mensaje secreto de un... |
def llenarLista(n,mensaje=""):
'Hace llenar una lista de longitud n con mensaje como encabezado'
lista=[]
print(mensaje)
for i in range(n):
lista.append(int(input("[%d]: "%(i+1))))
return lista
def mostrarLista(lista,mensaje=""):
"Se muestra lista con mensaje como encabezado"
... |
def llenaLista(n):
print("Ingrese uno a uno los elementos del vector:")
v=[]
for i in range(n):
v.append(int(input("v[%d]:"%i)))
return v
def mostrarLista(lista):
for i in range(len(lista)):
print("[%d]"%lista[i],end="")
return
#nicia el programa
print("Dad... |
#program takes SRIM output and converts to units of micrometer and MeV
#C. B. Hamill September 2018
import math
import matplotlib.pyplot as plt
import sys
def unit_conversion_energy(energy,energy_unit): #converts to MeV
# print(energy)
# print(energy_unit)
if energy_unit == "keV":
energy=energy/10... |
#!/usr/bin/env python
'''
Made by Ethan Gyllenhaal (egyllenhaal@unm.edu)
Last updated 23 AUG 2022
Script for converting haploid SNAPP input to diploid input.
Quick and dirty script, takes in haploid SNAPP input and outputs diploid in that order, no flags.
'''
import csv, sys
# Generic function for readin... |
print("------Update a tuple in python------")
a=("Anana","Mango","Orange","Apple")
b=list(a)
b[1]="Banana"
a=tuple(b)
print(a) |
# Python program to swap two variables using third variable
a=input('Enter value of a:')
b=input('Enter value of b:')
temp=a
a=b
b=temp
print('Value of a after swapping: {}'.format(a))
print('Value of b after swapping: {}'.format(b))
|
#WAP in python to add two matrices of size 3x3 using list.
K=[]
s=int(input("Enter the size of the first matrix:X*X: "))
print("Please enter the elements")
for i in range(s):
z=[]
for j in range(s):
z.append(int(input()))
K.append(z)
print(K)
print("The first Matrix is:")
for i in range... |
#WAP in python to implement
#multi-level
#In this type of inheritance, a class can inherit from a child class or derived class.
class MyFamily:
def show_my_family(self):
print("My family:")
class Father(MyFamily):
fathername=""
def show_father(self):
print(self.fathername)
class Mother(M... |
#Program in Python to implement
#Single level
class Parent:
parentname=""
childname=""
def show_parent(self):
print(self.parentname)
class Child(Parent):
def show_child(self):
print(self.childname)
ch1=Child()
ch1.parentname = "TOKPE"
ch1.childname="Kossi"
ch1.show_parent()
ch1.show_ch... |
"""
Day 28: RegEx, Patterns, and Intro to Databases
https://www.hackerrank.com/challenges/30-regex-patterns
"""
import unittest
import re
class Contacts(object):
def __init__(self):
self.contacts = []
def add(self, name, email):
self.contacts.append(
{
"name": na... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 25 15:48:00 2018
@author: Matt
"""
from scipy import *
import numpy as np
from scipy.special import *
from time import time
from matplotlib.pyplot import *
import gaussxw as gs
# ====================================================================... |
# 运算符
"""
运算符分类
1.算数运算符
2.关系运算符
3.赋值运算符
4.逻辑运算符
5.位运算符
6.成员运算符
7.身份运算符
8.运算符优先级
"""
# 算数运算符
'''
+ 加
- 减
* 乘
/ 除
% 取余
** 幂
// 向下取整
'''
a = 100
b = 3
print(a + b, '+')
print(a - b, '-')
print(a * b, '*')
print(a / b, '/')
print(a % b, '%')
print(a ... |
from tkinter import *
from tkinter import messagebox
from tkinter.messagebox import askquestion
from tkinter.filedialog import askopenfile
import smtplib, time, os
root = Tk()
server = StringVar()
port = [587, 465]
smtpObj = ""
server_frame = Frame(borderwidth= 5)
login_frame = Frame(padx = 5, bg = "grey")
... |
import random
import time
import math
'''
show time complexity
'''
array = [423,5643,2345786,345,567,43,6,23,87,4,783,7]
#array = [423,5643,2345786,-345,567,43,-6,23,87,-4,783,7]#negatives
#array = [423,5643,234.5786,345,56.7,43,6,23,87,4,783,7]#floats
element = len(array)
def TimeComplex():
pa... |
# -*- coding: utf-8 -*-
"""
Dylan Sosa
Numerical and Scientific Methods
Day 11
Python 3 & Python 2.7 compatible
"""
from math import sin, cos, log, ceil, pi
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
# model parameter... |
#!/usr/bin/python
import sys
def doubleit(x):
if not isinstance(x, (int, float)):
raise TypeError
var = x*2
return var
def doublelines(filename):
with open(filename) as fh:
num_list = [ str(doubleit(int(val))) for val in fh]
with open(filename, 'w') as fh:
fh.write('\n'.joi... |
# class MaxSizeList(object):
# def __init__(self, max):
# self.max = max
# self.list = []
# self.length = 0
# def push(self, val):
# if(self.length >= self.max):
# self.list.pop(0)
# self.length -= 1
# self.list.append(val)
# self.length += 1
# def get_list(self):
# return self.list
# ... |
"""
manual creation vs list comprehension
"""
import time
def main():
timeStart = time.clock()
theList1 = [i for i in range(10000000)]
timeStop = time.clock()
print('comprehension: ')
print(timeStop - timeStart)
timeStart = time.clock()
theList2 = []
for i in range(10000000):
theList2.append(i)... |
import Radix as r
def processInput(alist):
theList = [int(e) for e in alist[1:-1].split(',')]
return theList
def main():
theInput = input("Enter collection to be sorted: ")
theInput = processInput(theInput)
theInputUnsorted = theInput.copy()
theInput.sort()
numIterations = 0
while theInput !=... |
import math
import os
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw # Подключим необходимые библиотеки.
def sum3Tuple(a, b, c):
y = [a[temp] + b[temp] + c[temp] for temp in range(0, min(len(a), len(b)))]
return tuple(y)
def sumTuple(a, b):
y = [a[temp] + b[temp] for temp in range(0,... |
""" Note: Although the skeleton below is in Python, you may use any programming language you want so long as the language supports object-oriented programming,
and you make use of relevant object-oriented design principles.
"""
class Board(object):
board = [['_','_','_'],['_','_','_'],['_','_',... |
# CTI-110
# P3LAB - Debugging
# Jonathan Lopresto
# 3/24/2020
#When score is equal to A_score display "Your grade is A."
#When score is equal to B_score display "Your grade is B."
#When score is equal to C_score display "Your grade is C."
#When score is equal to D_score display "Your grade is D."
#When score ... |
import pandas as pd
# Demo of a simplified Recommender System
#
#
# First an introduction to some of the popular types of Recommender Systems:
# Simple Recommender (based on item ratings only)
# Recommends n top-rated movies to all users.
# This approach requires only the movie ratings (item_id, rating).... |
from pandas import DataFrame
from sklearn.base import TransformerMixin
class ModelTransformer(TransformerMixin):
"""
Wrapper to use a model as a feature transformer
Taken from http://zacstewart.com/2014/08/05/pipelines-of-featureunions-of-pipelines.html
The pipeline treats these objects like any of t... |
"""
# My first app
Here's our first attempt at using data to create a table:
"""
import numpy as np
import pandas as pd
import streamlit as st
# Basic Display of Data
st.markdown("## Displaying Data")
st.write("Here's our first attempt at using data to create a table")
df = pd.DataFrame({"first column": [1, 2, 3,... |
import itertools as it
import math
from collections import namedtuple
from functools import cmp_to_key as ctk
Point = namedtuple('Point', 'x y')
def collect_asteroids_coordinates(data):
asteroids = []
for idy, line in enumerate(data):
for idx, point in enumerate(line):
if point == '#':
... |
"""
This part of code is the Q learning brain, which is a brain of the agent.
All decisions are made in here.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
"""
import numpy as np
import pandas as pd
class QLearningTable:
def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, ... |
def suffix(x):
if(x==1):
return "one";
elif( x==2):
return "two";
elif( x==3):
return "three";
elif(x==4):
return "four";
elif(x==5):
return "five";
elif( x==6):
return "six";
elif(x==7):
return "seven";
elif(x==8):
return "eight";
elif( x==9):
return "nine";
return "";
def prefix(x):
if(... |
import sys
import math
import os
import itertools
import re
from collections import defaultdict
from operator import add
from pyspark import SparkConf, SparkContext
from itertools import combinations
#This function is used to calculate the user user pairs of every book
def getCombinations_User_Rating(userRating):
#lis... |
#Print Even numbers in a list using Lambda function
n = [3,5,2,11,6,8]
print (list(filter(lambda varX: varX % 2 == 0,n)) |
import time
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
if value < self.value:
# check left add left if none if less than self.value
if not self.left:
... |
import zipfile
from os import path
from tqdm import tqdm
while(1):
wordlist = input("wordlist file : ")
if (path.exists(wordlist) ) :
break
print("[-] File does not exist")
while(1):
zip_file = input("Zipfile : ")
if (path.exists(zip_file) ) :
break
print("[-] File does not exist")
zip_f... |
"""
The world_values data set is available online at http://54.227.246.164/dataset/. In the data,
residents of almost all countries were asked to rank their top 6 'priorities'. Specifically,
they were asked "Which of these are most important for you and your family?"
This code and world-values.tex guides ... |
n = int(input("Times table:"))
x = 1
while x <= 10:
print("%d x %d = %d" % (n, x, n*x) )
x = x + 1 |
#Given a number count the total number of digits in a number
num = input ("Digite um número extenso qualquer: ")
num = int (num)
count = 0
while num != 0:
num //= 10
count+= 1
print("O total de dígitos neste número é: ", count) |
#primeiro exemplo da função for
for x in ( 1, 7, -2, 4.8 ) :
print ( "Número : " , x )
print ( "Tenha um bom dia ! " ) |
grade = input ("Enter grade value:")
grade = float (grade)
if grade >= 5.0:
print ("Congratulations! You are approved!")
if grade < 5.0:
print ("Recovery!")
print ("Need to study more!")
print ("And try hard!")
print ("Have a nice day!")
|
a = int(input('Square side size: '))
print(a)
print ('The perimeter of this square is: ', 4*a) |
from unittest import TestCase
from MinHeap import MinHeap
class TestMinHeap(TestCase):
def test_minHeap(self):
l = [5, 3, 4, 2, 6, 1]
h = MinHeap()
for item in l:
h.push(item)
last_element = 0
while h.peak() is not None:
if h.peak() < last_element:
... |
a = int(input()) #Входное значение а
b = int(input()) #Входное значение b
while b != 0: #Цикл пока b не равен 0
a, b = b, a % b #переменной 'a' присваивается значение переменной 'b', переменной 'b' присваивается остаток от ('a' / 'b')
print('НОД', a) #Наибольший общий делитель |
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
# Runtime: 60 ms, faster than 85.59% of Python3 online submissions for Two Sum II - Input array is sorted.
# Memory Usage: 14.8 MB, less than 32.26% of Python3 online submissions for Two Sum II - Input array is sorted.
def twoSum2(nums: [int], target: i... |
from my_timer import timed
from prime_numbers import count_factors_with_primes, sieve
# A dict of triangular numbers
tnum = {1: 1, 2: 3, 3: 6}
def find_tnum(x):
"""Find the x'th triangular number.
A triangular number is generated by adding the natural numbers.
:param x: The triangular number to get
... |
"""@author: Ramkishan K Pawar
program to convert a given nameslist into usernames"""
names = ["Ramkishan Pawar", "Madhuri Jaju", "Sonal Patwari", "Yashika Lalwani", "Arjun Londhe", "Payal Roul"]
usernames = []
for name in names:
usernames.append(name.lower().replace(" ", "_"))
print(usernames)
|
"""@author: Ramkishan K Pawar
program to create html list using python."""
items = ["first string", "second string"]
html_str = "<ul>\n"
for each_item in items:
html_str += "<li>{}</li>\n".format(each_item)
html_str += "</ul>"
print(html_str)
|
import numpy as np
from global_utils import *
class DirectMappingNN:
"""
No hidden layer, only input -> output.
Asssuming, sigmoid activation on the output layer, although the sigmoid
activation function for the output layer is not called inside of
this network but instead inside of the memory net... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 17:10:37 2018
@author: chuxuan
"""
"""
利用字典,每次减去已经表达的数字
"""
def solution(num):
results = ""
left = num
roms_list = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
roms = {5: "V", 1: "I", 10:"X", 50: "L", 100: "C", 500:"D", ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 24 22:18:53 2018
@author: chuxuan
"""
def gengeratePar(n):
res =[]
generate(n,n,"",res)
return res
def generate(left,right,str,res):
if left == 0 and right == 0:
res.append(str)
return
if left > 0:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 23 21:35:01 2018
@author: chuxuan
"""
# Utlize the Dynamic programming
def findTargetSumWays(nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
sum_num = sum(nums)
if (S > sum_num) or ((S+sum_num)%2==1):
... |
'''
Construir um algoritmo que contenha 3 listas:
• Nomes de produtos
• Preços de cada produto
• Quantidades de cada produto
• Construir uma função para imprimir um dos produtos da lista e uma função para retirar um dos produtos das listas
Criar um repositório GIT remoto (Github, Gitlab ou Bitb... |
import random
import tkinter as tk
import os
class Game(tk.Frame):
"""GUI for Monty Hall show"""
doors = ('a', 'b', 'c')
def __init__(self, parent):
super(Game, self).__init__(parent)
self.parent = parent
self.img_file = 'all_closed.png'
self.choice = ''
self.winner = ''
self.rev... |
# Python code to create the two tables and insert data
import sqlite3
conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('''CREATE TABLE person (
id INTEGER PRIMARY KEY ASC, name varchar(250) NOT NULL)''')
c.execute('''CREATE TABLE address (
id INTEGER PRIMARY KEY ASC, street_name va... |
#!/usr/bin/env python3
#Input string that use different characters as delimiters
s1 = "Donald, Victoria, Andrew, Sarah"
s2 = "Donald Victotia Andrew Sarah"
s3 = "Donald@Victoria@Andrew@Sarah"
#print out the initial strings
print("s1: ", s1)
print ("s2: ", s2)
print ("s3: ", s3)
#Split the string, creae a... |
#!/usr/bin/env python3
s1 = "%to, two, too!"
print(s1)
#This illustrates more string slicing
#This shows the first character in the string
print(s1[0])
#This shows the last characher in the string
print(s1[-1])
#This gets he frist three characters in the string
#This includes indexes 0 to 2. It does ... |
#!//usr/bin/env python3
my_num = 1234.56789
my_pi = 3.1415926535
print("My number is:",my_num)
print("The value of pi: ",my_pi)
#######################################################################
# Format to 2 decimal places
# NOTE that you don't need the 0 before.2f
##################################... |
#!/usr/env python3
#Import the operating system module
import os
#Open the input file for reading
in_file = open('infile_002.txt', 'r')
line_count = 0
total_glucose = 0
total_insulin_dose = 0
#############################################################
#Read the imput file...it is stored in a list
######... |
from math import gcd;
def nth_root(n, index):
return n ** (1 / index);
class Number():
""" Object for representing numerical values in an expression """
def __init__(self, value=0):
if isinstance(value, (int, float)):
self.numerator, self.denominator = float(value).as_... |
"""
x^3 + 4x^2 - 10 = 0 en [1,2]
"""
###Funciones auxiliares
#funcion a resolver
def func(x):
value = x**3 + 4*x**2-10
return value
def sign(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
###Metodo
#longitud intervalo
ai = 1.0
bi = 2.0
#Tolerancia
Tol = 1.0e-4
#Error inicia... |
#!/usr/bin/env python
# coding: utf-8
# **Linear Regression project using PySpark**
#
# Data has been taken from UC Irvine Machine Learning repository. It is a description of Ship carriers and the related parameters which includes:
# * Ship Name
# * Cruise Line
# * Age of the ship
# * Tonnage
# *... |
#!/usr/bin/python3
def ChangeInt(a):
a = 10
b = 2
ChangeInt(b)
print(b) # 结果是 2
# !/usr/bin/python3
# 可写函数说明
def printme(str):
"打印任何传入的字符串"
print(str);
return;
# 调用printme函数
printme(); |
# -*- coding: UTF-8 -*-
import os;
# document = open("testfile.txt", "w+");
# print ("文件名: ", document.name);
# document.write("这是我创建的第一个测试文件!\nwelcome!");
# print (document.tell());
# #输出当前指针位置
# document.seek(os.SEEK_SET);
# #设置指针回到文件最初
# context = document.read();
# print (context);
# document.close();
doc=open("20... |
from random import randint
def calc_monster_attack(attack_min, attack_max):
return randint(attack_min, attack_max)
def game_ends(winner_name):
print(winner_name + " won!")
def main():
game_running = True
game_results = []
while game_running:
counter = 0
new_round = True
... |
# PdfText.py
"""
Classes for managing the production of formatted text, i.e. a chapter.
PdfChapter()
PdfParagraph()
PdfString()
"""
from PdfDoc import PdfDocument
from PdfFontMetrics import PdfFontMetrics
import math
# global
metrics = PdfFontMetrics()
FNfontkey = 'F3'
FNfontsize = 5
FONTMarker = '^'
# function copie... |
import unittest
import sys
sys.path.insert(0, '../')
from Graph import Graph
from Metro import Metro
from Route import Route
class TestGraph(unittest.TestCase):
'''
A unit test suite for the Graph class.
'''
def setUp(self):
'''
Sets up the test suite by creating a new graph before every test is ran
'''
... |
import unittest
from src.pub import Pub #capital P because class names always begin with capital letter
from src.drink import Drink
from src.customer import Customer
class TestPub(unittest.TestCase):#these parameters tell python this is a test, and not a normal class
def setUp(self):
self.pub = Pub("The Pr... |
#Rotate array k times
#Method1
# O(N*K) - may take much time when k and n is large
def rotate_m1(arr, k):
s = len(arr)
if s < 1 or s == k:
return A
k = k % s
for x in range(k):
tmp = arr[s - 1]
for i in range(s - 1, 0, -1):
arr[i] = arr[i - 1]
arr[0] = tmp
... |
class BST:
def __init__(self, value):
self.value=value
self.left=None
self.right=None
#iterative
def insert(self,value):
curr=self
while True:
if curr.value>value:
if curr.left is None:
curr.left= BST(value)
... |
#To solve Rat in a maze problem using backtracking
#initializing the size of the maze and soution matrix
N = 4
solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ]
def is_safe(maze, x, y ):
'''A utility function to check if x, y is valid
return true if it is valid move,
return false otherwise
'''
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.