text stringlengths 37 1.41M |
|---|
# The Collatz Sequence
def collatz(number):
if (number%2) == 0:
value=number//2
else:
value=3*number+1
print(value)
return(value)
try:
inputVal=int(input('Enter an integer: '))
retVal=inputVal
while retVal !=1:
retVal=collatz(retVal)
except ValueError:
... |
x_1 = int(input())
y_1 = int(input())
x_2 = int(input())
y_2 = int(input())
if (x_1 + y_1 + x_2 + y_2) % 2 == 0:
print('YES')
else:
print('NO')
|
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## COP 4531: Complexity and Analysis of Data Structures and Algorithms
## Programming Assignment 3, Due Date - 12/10/2013 11:59 PM
## Assigned - 10/10/2013
##
## John Cyr - j... |
import csv
with open('accountsprod.csv') as csvfile:
reader = csv.reader(csvfile)
emails = [row[18] for row in reader]
with open('accountsprod.csv') as csvfile:
reader = csv.reader(csvfile)
emails_to_ids = {row[18]: row[0] for row in reader}
loweremails = [e.lower() for e in emails]
duplicates = [e for... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to ana... |
c=float(input("Please enter your amount"))
c = c*100
print(c//25, "Quarters")
c = c%25
print(c//10, "Dimes")
c = c%10
print(c//5, "Nickels")
c = c%5
print(c//1, "Pennies")
|
still_playing = True
while still_playing:
try:
users_number = int(input("Please type in a number: "))
if users_number > 3:
print("too high")
elif users_number == 3:
print("you guessed correctly")
still_playing = False
else:
print("too... |
# variable names in python have underscores
# snake_case
user_name = input("What is your name? ")
# in JavaSCript we would write username
# camelCase
# String subsitution has three parts:
# 1. A string...with placeholders
# 2. The interpolation operator
# 3. Values to interpolating into the string
# Values should... |
"""
Given a linked list containing characters that form a string such as
--------- "my career stack" ---------
Reverse the characters of each word, keeping the order of the words same such
that the output will be
--------- "ym reerac kcats" ---------
*******************************************************
logic to... |
numeros = [15,-5,0,3,-56,2,2,3,7,58,87,10]
print (numeros [2])
if numeros [2] > 0:
print(" ES positivo")
if numeros [2] < 0:
print (" ES negativo")
if numeros [2] ==0:
print ("es cero=)") |
def change_format(data):
strip_data = data.lstrip("-0")
try:
format_data = format(int(strip_data), ",d")
except ValueError:
print(f"strip_data: {strip_data}")
format_data = format(int("0"), ",d")
if data.startswith("-"):
format_data = "-" + format_data
return forma... |
from pprint import pprint
def exclusive_elem(arr: list):
"""
Returns exclusive elements in array
"""
arr_result = []
for x in arr:
if x not in arr_result:
arr_result.append(x)
return arr_result
def sort_dict(d: dict):
"""
sorts the dictionary by values reverse... |
# def words_order(text: str, words: list) -> bool:
# sen_word_list = text.split(" ")
# j = 0
# if text.find(words[0]) != 1:
# for i in range(text.find(words[0])):
# if sen_word_list[i] != words[j]:
# return False
# return True
# else:
# return False
d... |
import timeit
"""
Задание 1.
Приведен код, который позволяет сохранить в
массиве индексы четных элементов другого массива
Сделайте замеры времени выполнения кода с помощью модуля timeit
Попробуйте оптимизировать код, чтобы снизить время выполнения
Проведите повторные замеры
Добавьте аналитику: что вы сделали и поч... |
# More on loops
# Basic FOR loop
for i in range(5, 51, 5):
print(i, end=" ")
print()
# RANGE function (alternative for comprehension)
my_list = [x for x in range(100)]
print(my_list)
my_list = list(range(100)) # iterable
print(my_list)
# BREAK (breaks out of the loop)
for number in my_list:
if number > 10:
... |
#Algotimo que lea entero y verifique sea mayor a 10.
#Si lo es, escribir el número, si no, mensaje que diga que es menor o igual
numeroentero=int(input("Ingrese un número entero: "))
if int(numeroentero) >10:
print(f"{numeroentero}")
else:
print(f"El número ingresado es menor o igual a 10") |
#ACCESSING VALUES: variable={ key: value, (...)} / print(variable)[key]
Alien1={"colour": "green", "points": 5}
print(Alien1["colour"])
print(Alien1["points"])
NewPoints=Alien1["points"] #new variable to create message
print(f"You have just earned {NewPoints} points!")
#Adding new values: variable["key"]=value
Ali... |
print ('>> Mohit Namdeo')
print ('>> Program to Remove Duplicate Element From a List')
print ('Using set()')
list_1 = [1, 2, 1, 4, 6]
print(list(set(list_1)))
print ('Remove the items that are duplicated in two lists')
list_1 = [1, 2, 1, 4, 6]
list_2 = [7, 8, 2, 1]
print(list(set(list_1) ^ set(list_2))) |
"""Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. """
import random
number = random.randint(0, 9)
guess = -1
guess_counter = 0
while guess != number:
if guess > number:
print("guess is too hi... |
def databaseConstructor(tag_list = {'tag123': ('song1', 'song2', 'song3'), 'tag245': ('song2', 'song4', 'song5'), 'tag31': ('song3', 'song1')}):
#Creates a dictionary database of songs and their tags
song_database = {}
print(tag_list)
for current_tag in tag_list:
for current_song in tag_lis... |
#이진 탐색 알고리즘
def binary_search(n_List,number):
start_value = 0
end_value = len(n_List) - 1
value = 0
if number in n_List:
while True:
mid_value = (start_value + end_value) // 2
if n_List[mid_value] == number: #발견했을경우
print(mid_value)
... |
# a function in python are called definitions, is a piece of code that can be called from
# somewhere else. they are meant to be re-usable and to make things clea
# if you have complicated code, then you can break it into pieces to make
# eaiser to understand
# reapting your code is bad,
# - copy and paste errors
#... |
# DATA 211
# ASSIGNMENT 2
# NAME (ID): RICARDO CRUZ (30074052) AND COOPER CHUNG (30061289)
# RICARDO CRUZ 50%, COOPER CHUNG 50%
# LAB: B03
# DATE: FEBRUARY 28th, 2019
# Bar chart: line 21 - 303
# Pie chart: line 306 - 564
from SimpleGraphics import *
# Introduce program, notify user of choices
print("There are two t... |
__version__ = "0.2.0"
def cipher(text, shift, encrypt=True):
"""
Encodes a string using a Caesar function which shifts each letter n positions in the alphabet based on a numerical input.
Parameters
----------
text : A string.
shift : An integer.
Returns
-------
An encoded string.
... |
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import scale
import matplotlib.pyplot as plt
import seaborn as sns... |
#
# [694] Number of Distinct Islands
#
# https://leetcode.com/problems/number-of-distinct-islands
#
# algorithms
# Medium (40.89%)
# Total Accepted: 1.7K
# Total Submissions: 4K
# Testcase Example: '[[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]'
#
# Given a non-empty 2D array grid of 0's and 1's, an island is a... |
"""Middle Characters
You are given some string where you need to find its middle characters.
The string may contain one word, a few symbols or a whole sentence.
If the length of the string is even, then you should return two middle characters,
but if the length is odd, return just one. For more details look at the Exam... |
"""Compare Functions
Two functions f and g are provided as inputs to checkio.
The first function f is the primary function and the second function g is the backup.
Use your coding skills to return a third function h which returns:
- the same output as f unless f raises an exception or returns None.
- In this case h sh... |
""" Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common pref... |
"""In Jypiter Notebook
%%writefile myfile.txt
hello this is content of my file
To open file in read write append and close
"""
"""METHOD 1"""
myfile=open('NewTextFile.txt',mode='r')
print(myfile.read())
myfile.close()
"""It is important to close open file to execute error free problems.
here in method one To read ... |
def prime(n):
for i in range(2, n):
if(n % i == 0):
return False
else:
return True
#Filter method
num = int(input("Enter the limit- "))
filtered = filter(prime, range(num))
print(f"The prime number llist are- {list(filtered)}")
|
num1 = int(input("Enter the first number- "))
num2 = int(input("Enter the second number- "))
num3 = int(input("Enter the third number- "))
if num1 > num2 and num1 > num3:
largest = num1
elif num2 > num1 and num2 > num3:
largest = num2
else:
largest = num3
print(f"The greatest number is- {largest}")
|
# Testing Python's JSON module with the PokeAPI
#! python3
# Importing the needed modules
import sys, requests, json, pyperclip
# Asking for the pokemon to look for in case it wasn't given
if len(sys.argv) < 2:
print('Please enter the pokemon to search: ', end='')
sys.argv.append(input())
# Displaying infor... |
# Chapter 12
# Spreadsheet to Text Files project
#! python3
# Importing the needed modules
import os, openpyxl, sys
from openpyxl.utils import get_column_letter
# Asking for the location of the spreadsheet
print('Please enter the location of the spreadsheet: ',end='')
filesPath = input()
filesPath = os.path.realpath... |
# Chapter 16
# Random Choice Assigment Emailer Project
#! python3
# Importing the needed modules
import random, sys, smtplib
from getpass import getpass
# Creating the chores
chores = ['cooking','dusting','doing the dishes','walking the dog']
# List with emails
emails = [] # Add emails here
# We need the same amou... |
# Chapter 10
# Asserts asked in the chapter's practice questions
# Creating a function that covers the requested assert statements
def checkAsserts(quest):
if quest == 1:
# Assert to check the value of spam
spam = 10
print('The value of spam is %s ' %(spam))
spam = 12
print(... |
# Chapter 13
# Getting all text in a docx file in a single string
#! python3
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return'\n'.join(fullText) |
def commaString(values):
result = ''
counter = 0
for i in values:
if i == values[-1]:
result += ' and ' + i
elif i == values[-2]:
result += '' + i
else:
result += i + ', '
counter += 1
print (result)
spam = ['Anne','Louis','Herb','Thom... |
# Chapter 17
# Identifying Photo Folders on the Hard Drive Project
#! python3
# Importing the needed modules
import os
from PIL import Image
# Walking the directory looking for image files
for foldername, subfolders, filenames in os.walk('C:\\'):
numPhotoFiles = 0
numNonPhotoFiles = 0
# Cheking the ... |
def triangle(number):
if number == 0:
print ('The number must be greater than 0')
for i in range(number + 1):
if i != 0:
print ('*' * i)
triangle(5) |
from db import db
class UserModel(db.Model):
"""Class representation of user table in database.
User table has id, username and password columns. Id and username values
are unique."""
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80))
... |
def sumDigits(n):
return sum(map(int,(str(n).split(''))))
"""
Returns true if n is a happy number.
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares
of its digits, and repeat the process until the number equals
1 (where it will stay)... |
import unittest
def reverseList(lst):
for i in range(len(lst)//2):
temp = lst[i]
lst[i] = lst[len(lst) - 1 - i]
lst[len(lst) - 1 - i] = temp
return lst
class isReversed(unittest.TestCase):
def testOne(self):
self.assertEqual( reverseList([1,3,5]), [5,3,1])
def test... |
'''
Let's follow the 5' → 3' direction of DNA and walk along the chromosome from terC to oriC (along a reverse half-strand), then continue on from oriC to terC (along a forward half-strand). In our previous discussion, we saw that the skew is decreasing along the reverse half-strand and increasing along the forward hal... |
import random
from PriorityQueue import PriorityQueue
from Vertex import Vertex
def lcm(numbers):
"Return the least commom multiple of numbers's elements"
i = 2
length = len(numbers)
lcm = 1
while (sum(numbers) != len(numbers)):
usefull = False
for j in range(length):
if (numbers[j]%i == 0):
numbers[... |
valor = float(input())
#NOTAS
nota100 = valor//100
print('NOTAS:')
print('{:.0f} nota(s) de R$ 100.00'.format(nota100))
valor -= nota100 * 100
nota50 = valor//50
print('{:.0f} nota(s) de R$ 50.00'.format(nota50))
valor -= nota50 * 50
nota20 = valor//20
print('{:.0f} nota(s) de R$ 20.00'.format(nota20))
valor -= nota... |
valores = input().split()
a = int(valores[0])
b = int(valores[1])
c = int(valores[2])
maior = max(a, b, c)
print('{} eh o maior'.format(maior)) |
vertebradoOuInvertebrado = str(input().strip().lower())
especie = str(input().strip().lower())
caracteristica = str(input().strip().lower())
#vertebrado
if vertebradoOuInvertebrado == 'vertebrado' and especie == 'ave' and caracteristica == 'carnivoro':
print('aguia')
elif vertebradoOuInvertebrado == 'vertebrado' a... |
numeroFunc = int(input()) #numero funcionario
horasTrabalhadas = int(input())
valorHora = float(input())
print('NUMBER = {}\nSALARY = U$ {:.2f}'.format(numeroFunc, horasTrabalhadas*valorHora)) |
class Node:
def __init__(self, data, prev=None):
self.data = data
self.prev = prev
class stackMgmt:
def __init__(self):
self.head = None
def is_empty(self):
if self.head == None:
return True
else:
return False
def insert(self, data):
... |
class PriorityQueue:
def __init__(self):
self.min_heap = list()
self.min_heap.append(0)
def is_empty(self):
if len(self.min_heap) == 1:
return True
return False
def put(self, data):
if (len(data) != 2) and type(data) is tuple:
return False
... |
a = dict()
from collections import defaultdict
a = {1: {2: 4, 3: 3}, 2: {1: 4, 3: 2}, 3: {1: 3, 2: 2}}
print(list(a.get(1).keys()))
a = [1, 2, 3]
root, b = a
print(root)
b = [9, 99]
a.pop(0)
b.reverse()
for i in b:
a.insert(0, i)
print(a) |
# closure1.py 에서 계속되는 파일
# closure가 변수값을 저장하는 비밀
def outer_func(): #1
message = 'Hi' #3
def inner_func(): #4
print(message) #6
return inner_func #5
my_func = outer_func() #2
print(my_func)
print()
print(dir(my_func))
print()
print(type(my_func.__closure__))
print()
print(my_func.__closure_... |
list1=["Bishow","raj","Baral","Pokhara",13,"Aarva"]
for key,value in enumerate(list1):
print(key,value)
print("===========================")
|
list1=[1,2,3,4,5,6,7,8,9,10]
evens=list(filter(lambda n:n%2==0, list1))
print(list1)
print(evens)
print("#######################")
#SECOND EXAMPLE
list2=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
even_list2=list(filter(lambda x:x%2==0,list2))
print(list2)
print(even_list2)
print("#################... |
def health_calculator(age,apple_ate,cigs_smoked):
answer=(100-age)+(apple_ate*3.5)-(cigs_smoked*2)
print("your health index is:",answer)
buckys_data=[27,20,0]
health_calculator(buckys_data[0],buckys_data[1],buckys_data[2])#this makes program bulky so we use following
health_calculator(*buckys_data) |
"""print("this is the programming in python")
print("programming in python is always easier than in java")
"""
#above is multiple lines comments in python
print("hello world1")
'''
print("hello world2")
'''
magicNumber=26
for x in range(101):
if x is magicNumber:
print(x,"is the magic number")
... |
num_int=123
num_str="456"
print("Data type of num_int:", type(num_int))
print("data type of num_str:", type(num_str))
print(num_int+num_str) |
d={'Jolly':'Talks too much', 'Shree':'noisy study','Boka':'left Kathmandu'}
for i,j in d.items():
print(i,j) |
class Employee:
def __init__(self, first, last):
self.fname=first
self.lname=last
@property
def fullName(self):
return '{1} {0}'.format(self.fname,self.lname)
emp1=Employee('anil','Bhandari')
emp1.fullName="Shree Raj" #THIS IS NOT ALLOWED SO HERE COMES @setter
|
list1=[]
list2=[]
list3=list1
print(list1==list2)
print(list1 is list2)
print(list1==list3)
print(list1 is list3) |
#JUMPS THE LOOP
numberTaken=[2,4,6,8,10]
print("there are still the other numbers thata re available")
for n in range(1,20):
if n in numberTaken:
continue
print(n) |
def missing_number(lst1, lst2):
'''
Compares the numbers in list1 and list2 and return the number that is not in
both lists
'''
if lst1 == lst2:
return 0
else:
'''Looking if a number is not in both list.'''
for number in lst2:
if number not in lst1:
... |
# O(n^2) time // O(1) space
def selectionSort(array):
i = 0
j = 0
for i in range(0, len(array)):
for j in range(i, len(array)):
if array[j] < array[i]:
array[i], array[j] = array[j], array[i]
return array
|
def balancedBrackets(string):
openBrack = "{[("
closeBrack = "])}"
opposites = {
'}': '{',
')': '(',
']': '[',
}
stack = []
for s in string:
if s in openBrack:
stack.append(s)
elif s in closeBrack:
if len(stack) == 0:
... |
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def nodeDepths(root):
# Write your code here.
sum = calcNodeDepth(root, 0)
return sum
def calcNodeDepth(root, depth):
if root is... |
# -*- coding: UTF-8 -*-
"""
快速排序原理
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
选择一个值,然后将大于和小于他的值划分为两部分,然后递归对每个划分的集合再进行操作
直到每一个集合都只有一个元素位置
"""
import random
def first_sort(array, low, high):
key = array[low]
while low < high:
# 先处理最高上限的值降低到最小
while low < high and array[high] >= key:
high... |
#!/usr/bin/python3
# b to decimal
validate = bool(1)
while(validate):
number = input("Type a number: ")
base = int(input("Type its base: "))
number_c = int(number, base)
print("The number in decimal base is: " + str(number_c)) |
class Game:
def __init__(self):
self.board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
self.finished = False
self.turn = 1
self.play()
def is_finished(self):
for i in self.board:
if sum(i) == 3:
return [T... |
def hago_algo():
x=input("dime un numero")
y=0
for cont in range(0,x,1):
y=y+cont
print y
hago_algo()
|
def sumador_de_cifras():
numero=input("dime un numero de 2 cifras")
decenas=numero/10
unidades=numero%10
print "la suma de las cifras del numero",numero,"vale",decenas+unidades
sumador_de_cifras()
|
def cambiadordevocales():
texto=raw_input("escriba un texto")
for cont in range(0,len(texto),1):
if texto[cont]=='a' or texto[cont]=='u' or texto[cont]=='i' or texto[cont]=='o':
print 'e'
else:
print texto [cont]
camb... |
"""
Написать декоратор instances_counter, который применяется к любому классу
и добавляет ему 2 метода:
get_created_instances - возвращает количество созданых экземпляров класса
reset_instances_counter - сбросить счетчик экземпляров,
возвращает значение до сброса
Имя декоратора и методов не менять
Ниже пример использов... |
#!/usr/bin/env python
import time
import random
import datetime
def main():
def spin(seconds):
start = time.time()
while time.time() < start + seconds:
pass
while True:
spin_time = random.random() * 20
print '%s spinning for %s...' % (datetime.datetime.now().strftime... |
#!/usr/bin/python3
import argparse
def leer_archivo( archivo ):
'''
recibe una cadena con el nombre del archivo leer
regresa una cadena de texto sin saltos de linea
'''
try:
with open(archivo,"r") as fh:
texto = fh.read()
lineas = texto.splitlines()
texto_limpio = " ".joi... |
from numpy.linalg import norm
class Edge():
def __init__(self, vertex1, vertex2, distance = None):
'''Stores the two vertices as the two nodes that make up this edge.
Calculates the distance, but can receive a precalculated distance as well.
'''
self.vertex1, self.vertex2 = vertex1,... |
import random
from BasicTest import *
"""
This tests random packet duplications. We randomly decide to duplicate about
half of the packets that go through the forwarder in either direction. The
number of the extra packets sent is randomly chosen between 1 and 3. The "true"
case is for when the duplication occurs, a... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from linkedList import ListNode;
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return None
odd = head... |
# [easy] https://leetcode.com/problems/reformat-phone-number/
class Solution:
def reformatNumber(self, number: str) -> str:
def split3(num):
return '-'.join([ num[i:i+3] for i in range(0, len(num),3) ])
number = number.replace('-', '').replace(' ', '')
n,m = divmod(len(number),3... |
class ListNode:
def __init__(self, val: int = 0, next=None):
self.val = val
self.next = next
def create_linklist(self, arr: list):
self.val = arr.pop(0)
currNode = self;
for val in arr:
nextNodde = ListNode(val)
currNode.next = nextNodde;
... |
# https://leetcode.com/problems/copy-list-with-random-pointer/
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
from randomLinkedList import Node
class Solution:
... |
from __future__ import print_function
def hello():
""" Returns a Hello, World! """
return("Hello, Q User!")
def say_hello():
""" Prints Hello, World message """
print(hello())
def is_even(x):
if x%2==0:
return True
else:
return False |
L = ['Bart', 'Lisa', 'Adam']
for name in L:
print(r'Hello,', name)
i = 0
while i <= 10:
print(i)
i += 1
|
def get_unique_num(arr):
result=0
if len(arr) == 0 or 0 not in arr:
result = 0
else:
arr.sort()
more1 = [i for i in arr if i+1< len(arr) and arr[i+1] - i>1]
if len(more1) == 0:
result = max(arr) + 1
else:
result = min(more1) + 1
return resu... |
import threading, sys
from random import randint
from time import sleep
def print_number(number):
# Sleeps a random 1 to 10 seconds
rand_int_var = randint(1, 10)
sleep(rand_int_var)
print "Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"
thread_list = []
for i in ... |
"""
# Here a new file will be created. the w is for write.
#The 'w'mode only allows you to write to a file and if that file doesn't exist, then a new one will be created.
f=open('newfile.txt', 'w')
f.write("Hello\n") #/n for new line
f.close()
#If we change the "w" for an "a"(apendice), it will add whatever your pu... |
import turtle
# create a turtle obj
amy = turtle.Turtle()
amy.width(5)
# Move back without drawing anything
amy.penup()
amy.back(250)
amy.pendown()
# for loop start
for pretty_color in ["red", "yellow", "blue"]:
amy.color(pretty_color)
# nesting loop start
sides = [1, 2, 3, 4]
for side in sides:
... |
import turtle
# create a turtle obj
rainbow = turtle.Turtle()
rainbow.width(5)
# Move back without drawing anything
rainbow.penup()
rainbow.back(250)
rainbow.pendown()
# Create a specific color list
colors = ["red","orange","yellow","green","blue","purple"]
for pretty_color in colors:
rainbow.color(pretty_color)
... |
#Given a sorted array of strings which is interspersed with empty strings,
# write a method to find the location of a given string
class StringFinder:
def FindString(self, strList, s,left,right):
if(strList == [] or strList == None):
return None
if(left>right):
return None
... |
#-------------------------------------------------------------------------------
# Name: playing cards.py
# Purpose: playing card class and test
#
# Author: Adrienne Sands
#
# Created: 05/05/2013
# Copyright: (c) Adrienne Sands 2013
# Licence: <your licence>
#--------------------------------------... |
#-------------------------------------------------------------------------------
# Name: gpaSort.py
# Purpose: A program to sort student information into GPA order
#
# Authors: John Zelle, Adrienne Sands
# as - amended to allow for greater sort control, use graphical interface
#
# Created: 17/05/2013
#... |
#-------------------------------------------------------------------------------
# Name: allUnique
# Purpose: algorithm determines if a string has all unique characters
#
# Author: Adrienne Sands
#
# Created: 18/05/2013
# Copyright: (c) Adrienne Sands 2013
#-------------------------------------------... |
#-------------------------------------------------------------------------------
# Name: stringPermutation.py
# Purpose: determines if a string is a permuation of another
#
# Author: Adrienne Sands
#
# Created: 18/05/2013
# Copyright: (c) Adrienne Sands 2013
#----------------------------------------... |
#__author__ = 'Adrienne'
#Challenge Description:
#Write a program to determine the sum of the first 1000 prime numbers.
#Input sample:
# None
#
#Output sample:
#Your program should print the sum on stdout, i.e. 3682913
def sumOfPrimes(n=1000):
primes = []
num = 2
while len(primes)< n:
if checkIf... |
#Author: 'Adrienne'
#Challenge Description:
#Given a positive integer, find the sum of its constituent digits.
#
#Input sample: The first argument will be a text file containing positive integers, one per line. e.g.
#23
#496
#Output sample: Print to stdout, the sum of the numbers that make up the integer, one per line.... |
# pass x and y as keyword arguments to the calc_position function
def calc_position(directions, **current):
curr_x = current['x']
curr_y = current['y']
def_dirs = {
'>': 1,
'<': -1,
'^': -1,
'v': 1
}
for d in directions:
if d =... |
class Character(object):
def __init__(self, name, initiative, health, power, evasion, treasure=0):
self.name = name
self.initiative = initiative
self.health = health
self.power = power
self.evasion = evasion
self.treasures = treasure
def special_power(self):
... |
# Librairie(s) utilisée(s)
from flask import *
import sqlite3
def renvoie():
'''
Cette fonction renvoie les élements de la table sous forme de tuples
'''
# Ouverture de la connection à la base de donnée
connexion = sqlite3.connect('sneakers.db')
cursor = connexion.cursor()
resultat = cur... |
'''Introduction to data Visualtzation in Python with Matplotlib'''
'''The video in the wakelet (link below) provide a walk through of
of the Data vidualsation in python with MatPlotlib using gas'''
#Load the libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
#read csv file
gas = pd.read... |
class Tower:
__slots__ = 'rings', 'capacity'
def __init__(self, cap: int):
self.rings = list()
self.capacity = cap
def add(self, ring_size:int):
if len(self.rings) >= self.capacity:
raise IndexError('Tower already at max capacity')
if (len(self.rings) > 0) and (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.