text stringlengths 37 1.41M |
|---|
class strReplace:
def strReplace(self,str1,reStr):
str1 = str1.replace(" ", reStr, 1)
return str1
str1 = "hello world"
str1 =strReplace().strReplace(str1,"$")
print(str1) |
from typing import List
g_list: List[str] = []
while True:
person = input()
if person == '.':
break
else:
g_list.append(person)
print(g_list)
print(len(g_list))
|
while True:
current_number = int(input())
if 10 <= current_number <= 100:
print(current_number)
elif current_number < 10:
continue
else:
break
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 18:58:29 2018
@author: seele
"""
import sys
from random import seed, randrange
from queue_adt import *
def display_grid():
for i in range(len(grid)):
print(' ', ' '.join(str(grid[i][j]) for j in range(len(grid[0]))))
def find_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 8 14:32:46 2018
@author: seele
"""
import sys
import statistics
file_name = input('Which data file do you want to use? ')
L1=[]
L2=[]
try:
f = open(file_name)
R = f.readlines()
#read is look at every line in the file
if (R==[]):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 10 18:32:17 2018
@author: seele
"""
def fibo(n):
if n <= 1:
return n
return fibo(n-1)+fibo(n-2)
#复杂每次都要算前面 指数级增长
def fibo_1(n):
if n <= 1:
return n
previours, current = 0, 1
for _ in range(2,n+1):
previou... |
# Written by Eric Martin for COMP9021
import re
from functools import partial
from binary_tree_adt import BinaryTree
'''
Builds a parse tree for an expression generated by the grammar:
EXPRESSION --> EXPRESSION TERM_OPERATOR TERM
EXPRESSION --> TERM
TERM --> TERM... |
# Written by Eric Martin for COMP9021
'''
A Doubly Linked List abstract data type
'''
from copy import deepcopy
class Node:
def __init__(self, value = None):
self.value = value
self.next_node = None
self.previous_node = None
class DoublyLinkedList:
def __init__(self, L = None, ke... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 11:07:17 2018
@author: seele
"""
# Uses National Data on the relative frequency of given names in the population of U.S. births,
# stored in a directory "names", in files named "yobxxxx.txt with xxxx being the year of birth.
#
# Prompts the user... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 23:47:15 2018
@author: seele
"""
# Randomly generates a binary search tree whose number of nodes
# is determined by user input, with labels ranging between 0 and 999,999,
# displays it, and outputs the maximum difference between consecutive leav... |
class User:
#fields and method definitions
def __init__ (self,name,number):
self.name=name
self.genders=[]
self.countries=[]
self.age=number
self.hungry=False
def password(self,password):
self.password=password
input_name= input('What is your name?')
input_a... |
i=int(input("Enter Score: "))
while(i>-1):
print(i)
i=int(input("Enter Score: "))
if i ==-1:
break |
#!/usr/bin/python
# Import the required modules
import cv2
import os
import numpy as np
from PIL import Image
from utils import Utilities as uti
face_size = 70
# For face detection we will use the Haar Cascade provided by OpenCV.
cascadePath = "/home/daniel/opencv/data/haarcascades/haarcascade_frontalface_default.xm... |
class Node:
def __init__(self,value):
self.value=value
self.next=None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
if not self.head:
self.head = node
else:
current = self.head
... |
import numpy
import math
#import pyfftw
def power( x, dt = 1., nbin = 1, binsize = 0, detrend = False,
Bartlett = False, Welch = False, Hann = False,
useRegular = False):
"""
Take the power spectrum of input x.
dt is the time sample spacing (seconds).
Can break a long input ... |
# Importing tkinter
from tkinter import *
# creating the window instance
win = Tk()
# We dont want the window to be resizeable
win.resizeable(0, 0)
# Giving a geometry to our window
win.geometry("400*300")
# Title of the application
win.title("MEGA-CALCULATOR")
# Defining all our needed functions to make the calcu... |
# JESUS SALVADOR VALLES MACIEL
#CARRERA: INFORMATICA
#DESARROLLO DE APLICACIONES WEB
#PRACTICA 2.1 VOTOS
#mostramos las opciones que tienen
print("""
1) AMARILLO 3) MORADO
2) ROJO
""")
#definimos las variables que usaremos, asi como las librerias
import random
A = (0)
B = (0)
C ... |
class Card:
def __init__(self, figure, color):
self.figure = figure
self.color = color
@property
def value(self):
if self.figure in ['K', 'Q', 'J']:
return 10
elif self.figure in ['2', '3', '4', '5', '6', '7', '8', '9', '10']:
return int(self.figure)
... |
import csv
import os
file_to_load = "budget_data.csv"
file_to_output = "budget_analysis.txt"
#defining
total_months = 0
month_of_change = []
revenue_change_list = []
greatest_increase = ["", 0]
greatest_decrease = ["", 9999999999999999999]
total_revenue = 0
# Read and convert it into a list
with open(file_to_load)... |
# coding: utf-8
import pandas as pd
df1 = pd.DataFrame([[1,2],[2,3],[9,4]], columns=['a','b'])
df2 = pd.DataFrame([[9,2],[2,3],[1,4]], columns=['a','b'])
print "original : df1"
print df1
print "original : df2"
print df2
print "corr ( col <-> col )"
print df1['a'].corr(df2['b'])
print "corrwith ( df <-> df )"
print... |
Below is code with a link to a happy or sad dataset which contains 80 images, 40 happy and 40 sad. Create a convolutional neural network that trains to 100% accuracy on these images, which cancels training upon hitting training accuracy of >.999
Hint -- it will work best with 3 convolutional layers.
import tensorflow... |
from typing import List
# TODO Revise
# class Node:
# def __init__(self, data: int):
# self.data = data
# self.parent = None
#
#
# class TreeAncestor:
#
# def __init__(self, n: int, parent: List[int]):
# self.root, self.node_dict = self.populateTree(parent)
# self.total_nodes =... |
#*******
#* Read input from STDIN
#* Use: echo or print to output your result to STDOUT, use the /n constant at the end of each result line.
#* Use: sys.stderr.write() to display debugging information to STDERR
#* ***/
import sys
lines = []
for line in sys.stdin:
lines.append(line.rstrip('\n'))
numbers = lines[1:]
a... |
#Import os and csv modules so that we can find and import the csv
import os
import csv
#Create os path for csv to be read and the text file to written.
csvpath = os.path.join('Resources', 'election_data.csv')
text_file = os.path.join('Analysis', 'election_results.txt')
#Setup our list for finding total votes, the dic... |
#!/usr/bin/python
import csv, json, os, sys
# pass the filename as an argument when calling this script
if len(sys.argv) < 2:
sys.exit('Usage: json-to-csv.py /path/to/file.json')
fileIn = sys.argv[1]
fileOnly = os.path.basename(fileIn)
try:
fileOut = sys.argv[2]
except IndexError:
fileList = [fileIn.split('.')[0], ... |
import re
def star_one():
lines_parsed = []
for line in (y for y in get_input_as_strings() if len(y) > 0):
parsed = re.search("(\d+)-(\d+) (.): (.*)", line).groups()
lines_parsed.append([int(parsed[0]), int(parsed[1]), parsed[2], parsed[3]])
valid_count = 0
for line in lines_parsed:
... |
#匿名函数及函数做参数
def test(a,b,func):
return func(a,b)
print(test(10,20,lambda x,y:x+y))
print(test(10,20,lambda x,y:x-y)) |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 20:34:16 2020
@author: David Stanley
"""
def tobogganTrajectory(slopes):
# Read input text file and store contents
inputText = open("input.txt", "r")
inputContent = inputText.read()
# Close opened file
inputText.close()
# Split i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_sum = -2**31
for head in range(len(nums)):
for tail in range(head+1, len(nums)+1):
pr... |
class Stack():
def __init__(self):
self.items = []
def push(self, items):
self.items.append(items)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def peek(self):
if not self.isEmpty():
return se... |
# BasicCommands.py
# To check Python version (at command prompt)
#1) At command prompt, type python
#python
#2) At command prompt, type python -V (capital V)
# python -V
# -or-
# python --version
#3) in code
import sys
print(sys.version) # Human readable -> 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:14:34) [MSC v.1900 32 ... |
#ReadingWritingCsvFile.py
import csv
#The csv module’s reader and writer objects read and write sequences.
#Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.
# csv.reader(csvfile, dialect='excel', **fmtparams)¶
# csv.writer(csvfile, dialect='excel', **fmtparams)¶... |
# ScopeRulesLEGB.py
'''
LEGB lookup rule
A reference (X) looks for the name X
> first in the current [L]ocal scope (function); then
> in the local scopes of any lexically [E]nclosing functions in your source code, from inner to outer;
(also referred as statically nested scopes), then
> in the current [G]lobal s... |
# IterationsAndComprehensions.py
'''
> Python’s iteration protocol, a method call model used by the for loop,
> list comprehensions, which are a close cousin to the for loop that applies an expression to items in an iterable.
'''
input_numbers = [1,2,3,4]
print(type(input_numbers)) # <class 'list'>
# print uses end=... |
# Tuples.py
# To run from python interpreter
# > cd D:\dev\python\Python101\basics\
# > python
# > exec(open('Tuples.py').read())
# -OR-
# python Tuples.py
'''
Tuples are roughly like a list that cannot be changed
—tuples are sequences, like lists,
but they are immutable, like strings.
tuples are not generally used... |
# Files02.py
'''
>> xDummyFile.txt
This is 1st line without line break This is 2nd line with line break
This is last line
'''
print('\n ----- printing content using for loop')
for line in open('xDummyFile.txt'):
# print(type(line)) # <class 'str'>
# line[0] = 'T'
print(line, end='')
print('\n *** Done pr... |
# MapReduceFilter.py
# map and filter are key members of Python’s early functional programming toolset
# map() function
# => Mapping Functions over Iterables: map
# Syntax : r = map(func, seq)
# The map function applies a passed-in function to each item in an iterable object
# and returns a list containing all th... |
#ClassAttributes.py
'''
Every time we use an expression of the form 'object.attr' (where object is an instance or class object),
Python searches the namespace tree from bottom to top,
beginning with object, looking for the first attr it can find.
This includes references to self attributes in your methods.
'''
clas... |
#!/usr/bin/env python
# Tui Popenoe
# challenge206E.py - Recurrence Relation
import ast
import operator as op
import sys
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
def eval_expr(expr):
"""
... |
#!python2
# Tui Popenoe
# Challenge104E.py - Powerplant Simulation
import sys
def power_plant(n):
l = []
for i in range(1, n+1):
if i % 3 == 0:
pass
elif i % 14 == 0:
pass
elif i % 100 == 0:
pass
else:
l.append(i)
return len(... |
#!python2
# Tui Popenoe
# Challenge28E.py - Duplicates
def detect_duplicate(lst):
hashtable = {}
for i, v in enumerate(lst):
if v in hashtable:
print("Duplicate detected, array[%r] and array[%r] are both equal \
to %r" % (hashtable[v], i, array[i]))
hashtable[v] = i
... |
#!python2
# Tui Popenoe
# Challenge34E.py - Max Squares
from sys import argv
def max_squares(lst):
lst = map(int, lst)
lst.sort(reverse=True)
return (lst[0] ** 2 + lst[1] ** 2)
def main():
if len(argv) > 1:
print(max_squares(argv[1:]))
else:
print(max_squares(list(raw_input())))
... |
#!python2
# Tui Popenoe
# challenge105E.py Word Unscrambler
import sys
def unscramble_words(scrambled_words, word_list):
"""Unscramble the words in a wordfile passed in and match wordlist"""
output = []
for i in scrambled_words:
for k in word_list:
if len(i) > len(k):
i... |
#!/usr/bin/env python
# Tui Popenoe
# challenge198E.py - Words With Enemies
import sys
def battle_words(word1, word2):
winner = bust_words(word1, word2)
if len(winner[0]) > len(winner[1]):
return 'Left: %s' % ''.join(winner)
elif len(winner[1]) > len(winner[0]):
return 'Right: %s' % ''.joi... |
#!python2
# Tui Popenoe
# challenge187E.py - A Flagon of Flags
from sys import argv
def read_flags(filename):
flags = {}
output = []
with open(filename, 'r') as f:
num_flags = int(f.readline().strip())
for i in range(num_flags):
flag = f.readline().strip().split(':')
... |
#!python2
# Tui Popenoe
# Challenge47I.py - Number Translate
from sys import argv
cipher = {
'ze' : 0,
'on' : 1,
'tw' : 2,
'th' : 3,
'fo' : 4,
'fi' : 5,
'si' : 6,
'se' : 7,
'ei' : 8,
'ni' : 9
}
def translate_number(num):
output = list()
#for i in num:
output.append... |
#!python2
# Tui Popenoe
# Challenge38E.py - Line and Word Count
from sys import argv
def counts(filename):
with open(filename, 'r') as f:
x = len(f.readlines())
y = len(f.read().split())
print("Number of lines: ", x)
print("Number of words: ", y)
def main():
if len(argv) > 1:
... |
#!/usr/bin/env python
# Tui Popenoe
# challenge221E.py Word Snake
from sys import argv
def word_snake(lst):
if lst:
print(lst[0])
space_length = len(lst[0]) - 1
turn = False
down = True
for word in lst[1:]:
if not turn and space_length + len(word) > 80:
... |
#!python2
# Tui Popenoe
# Challenge15E.py - Left/right justify
from ast import literal_eval
from sys import argv
import string
def justify(filename, right=False):
with open(filename, 'r+') as f:
text = f.readlines()
f.seek(0)
for i in text:
if right == True:
i =... |
# Tui Popenoe
# Challenge 166b Planetary Gravity
"""Calculate the weight of an object upon the surface of a planet."""
import sys
import math
def calcVolume(r):
return (4/3) * (math.pi * pow(r, 3))
def calcMass(v, d):
return v*d
def calcForce(m1, m2, d):
g = (m1 * m2) / pow(d, 2)
def calcWeight(planet... |
#!python2
# Tui Popenoe
# challenge185E.py - Generated Twitter Handles
from sys import argv
def find_handles(filename):
output = []
with open(filename, 'r') as f:
wordlist = f.read().splitlines()
for i in wordlist:
if i[0:2] == 'at':
output.append(('@' + i[2:] + ' :... |
#!python2
# Tui Popenoe
# challenge190E.py - Webscraping Sentiments
import lxml
import logging
import urllib2
import sys
import lxml.html
def parse_page(url):
try:
# Fetch the url
doc = urllib2.urlopen(url)
if doc:
# parse the tree.
tree = lxml.html.parse(doc)
... |
# Tui Popenoe
# Challenge 161 Blackjack
""" Implementatoin of a simulation of blackjack hands. Calculates the
percentage of hands dealt that are blackjack (21) given a variable number
of decks of cards. Accepts input as a text file or a command line argument.
"""
import random
import sys
deck = [
... |
# Tui Popenoe
# Challenge 163 Probability Distribution of six sided die
"""Simulate various numbers of rolls of a six-sided die, and display the
distribution of the numbers rolled. """
import sys
import random
import math
def printGrid(grid):
print(grid)
def createGrid():
grid = list()
for i in ran... |
#!python2
# Tui Popenoe
# challenge179e.py - Convert Image to Grayscale
from PIL import Image
def grayscale(imagefile='image.jpg'):
"""Convert the image file to grayscale."""
im = Image.open(imagefile)
pix = im.load()
print('Image Size: ' + str(im.size))
for i in range(im.size[0]):
for j i... |
#!python2
# Tui Popenoe
# Challenge55I.py - Validating Input
from sys import argv
def display_sum(user_input):
inp = user_input.split(' ')
if int(inp[0]) >= 0 and int(inp[0]) <= 9:
if int(inp[1]) >= 1 and int(inp[1]) <= 9:
s = int(inp[0]) + int(inp[1])
print(inp[0] + ' + ' + in... |
# basic implementation of music playing functionality!
from os import system
def play_music(commands):
song = raw_input("What song was it that you wanted to hear?\n")
if not 'by' in song:
system('spotify play [' + song + ']')
def main(commands):
print ('Entering DJ mode...')
active = True
current_commands = c... |
print("\nDame un numero del 1 al 100")
Num = int(input())
if Num < 100:
print("\nEse numero es menor a 100")
else:
print("\nEse numero es mayor a 100")
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# import all the required libraries
#Author: Arun Kumar and Rahul Noronha
#Date:
#23/09/2020
#->Encoding function worked for png only, RGB_To_Grayscale and JPEG_To_PNG throwing IOError
#24/09/2020
#->Encoding function worked for png and jpg only RGB_To_Grayscale worked succesf... |
board = [
["_", "_", "_"],
["_", "_", "_"],
["_", "_", "_"]
]
is_x_turn = True
is_valid_move = False
is_still_playing = True
def if_raw(board):
x_won = False
o_won = False
for i in range(len(board)):
x_counter = ''
o_counter = ''
for n in range(len(board... |
from utils import database
USER_CHOICE = """
Your Choices are the following :
- "a" to add a new book
- "l" to list all books
- "r" to mark a book as read
- "d" to delete the book
- "q" to exit
Enter Your Choice:"""
#Defining Function for providing options to theuser
def menu():
database.create_books_table()
... |
import random, sys
print ('ROCK, PAPER,SCISSORS')
#these variable to keep track of the wins
wins = 0
losses = 0
ties = 0
#The main game loop
while True:
print('%s Wins, %s Losses, %s Ties' % (wins,losses,ties))
while True:
print('Enter you move:(r)ock,(p)aper, (s)cissors or (q)uit')
playerMov... |
#fortune ball
import random
def getA(AnswerN):
if AnswerN == 1:
print('you will marry a hottie')
elif AnswerN == 2:
print('you will have a sad life')
elif AnswerN == 3:
print('you will be cool, but your friends won\'t like you')
elif AnswerN == 4:
print('you will die ve... |
import sqlite3
class Connect(object):
def __init__(self,db_name):
try:
self.connection = sqlite3.connect(db_name)
self.c = self.connection.cursor()
except sqlite3.Error:
print("Erro ao abrir o banco.")
def commit_db(self):
if self.c:
... |
import unittest
class NumberTest(unittest.TestCase):
"""
Uses subtest to display all tests within a test method
"""
def test_even_numbers(self):
"""
with subtest, all failures are shown
"""
for i in range(10):
with self.subTest(i=i):
self.ass... |
# 链表机制不明!
from typing import *
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 此段代码只能在leetcode下通过
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res_num = Solution.ln_to_int(l1) + Solution.ln... |
# Importing the module – tkinter, time
# Create the main window (container)
# Add number of widgets to the main window:Button, Entry
# Apply the event Trigger on the wi... |
# PROBLEM DESCRIPTION
#
# An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
# is_isogram("Dermatoglyphics" ) == true
# is_isogram... |
class Stack():
"""堆栈"""
def __init__(self, max_size):
self.max_size = max_size
self.arr = []
def counts(self):
return len(self.arr)
def push(self, item):
if len(self.arr) == self.max_size:
print('数据已满,不能存入')
return None
self.arr.insert(0, item)
print('%s存入成功'%item)
def pull(self):
return s... |
class Stack:
def __init__(self, max_size):
self.max_size = max_size
self.top = None
def push(self, item):
if self.size() != self.max_size:
node = Node(item)
node.next_node = self.top
self.top = node
def pop(self):
if self.top is None:
... |
#Simple neural network with backpropagation learning
#Created by Mark Palenik
#I created this mainly as an exercise in learning python
#it's not necessarily the most efficient python code, as it is
#my first project, but it works.
import random
import math
class Node:
def __init__(self):
self.weights = []... |
import re
def find_repeated_word(text):
"""
Function finds the first repeated word in a string and returns this word.
"""
if not isinstance(text, str):
raise TypeError
word_list = []
text_list = re.findall(r'[A-Za-z]+', text.lower())
for word in text_list:
if word in word_... |
class Node:
"""
Node class initilizing
"""
def __init__(self, value, next=None):
"""
Init node instance with value and next element
"""
self.value = value
self.next = next
def __str__(self):
""" Return an object instance
"""
return f'{... |
class Node:
"""
This is the Node Class
"""
def __init__(self, value):
"""
This is my initialize of the Node
"""
self.value = value
self.next = None
def __str__(self):
"""
return string with the the object instance
"""
return f... |
def multiply(a, b):
return sum([a for _ in range(b)])
def expo_sum(x, y):
if x < 0 or y < 0:
return "Please enter non-negative numbers for both x and y"
result = 1
for _ in range(y):
result = multiply(result, x)
return result
|
string1='a(b(x)d)efghijkl'
string2='(123).)(qw(e)'
def match(str):
count = 0
for i in str:
if i == "(":
count += 1
elif i == ")":
count -= 1
if count < 0:
return False
return count == 0
def match2(input_string):
s = []
... |
#!/usr/bin/python
import sys
import re
# check that a filename argument was provided, otherwise
if len(sys.argv) < 2:
raise Exception("Filename must be first argument provided")
filename = sys.argv[1]
lines = []
# open file in read mode, assuming file is in same directory as script
try:
file = open(filename,... |
#!/usr/bin/python
'''Gathering acutal housing expenses from person and save results
in variables to be called later'''
print('We are going to go over some of your monthly expenses, please answer in all lowercase')
mortgage_rent = input('Do you have a mortgage or rent?')
if mortgage_rent == 'mortgage':
mor... |
#!/usr/bin/python
import sys
# check that a filename argument was provided, otherwise
if len(sys.argv) < 2:
raise Exception("Filename must be first argument provided")
filename = sys.argv[1]
lines = []
# open file in read mode, assuming file is in same directory as script
try:
file = open(filename, 'r')
#... |
"""
1. Идем по списку вниз
2. Открываем форму нажатием enter
3. Ставим мышь в определенную координату экрана
4. Кликаем левой кнопкой
5. Закрываем форму комбинацией ctrl+enter
"""
import pyautogui as pg
import time as t
i = 1
while i <= 100:
t.sleep(5)
pg.hotkey('down')
pg.press('enter')
t.sleep(7)
... |
# -*- coding: utf-8 -*-
import numpy as np
def frontera(rf, r, P, T, M, L):
"""
Magnitudes en la prontera radiativo-convectiva.
Intermpolación lineal para calcular los valores de la temperatura,
presión, masa y luminosidad a un valor específico del radio ('rf').
Los objetos 'r', 'P'... |
#One common use of dictionaries is counting how often we "see" something
'''
ccc = dict()
ccc['csev'] = 1
ccc['cwen'] = 1
print(ccc)
ccc['cwen'] = ccc['cwen'] + 1
print(ccc)
'''
counts = dict()
print(counts)
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
if name not in counts:
... |
'''
Dictionaries are like lists except that they use KEYS
instead of numbers to look up values.
'''
#######LIST#########
print('LIST')
lst = list()
lst.append(12)
lst.append(183)
print(lst)
lst[0] = 23
print(lst)
'''
####LIST=lst####
Key Value
[0] 21
[1] 183
'''
######D... |
#Time Stamp 3:48:56
#Lists
'''
Collections
A list is a kind of a collection
friends = ['Joseph', 'Glenn', 'Sally']
'''
print([1,23,76]) #List
'''
>Lists are surrounded by Square brackets
and the elements in the lists are separated by commas
>A list element can be any Python object-even another list
'''
p... |
#Definite loops
#for i in [5,4,3,2,1]:
# print(i)
#print('BlastOFF!!!!')
friends = ['Joseph','Glean','Sally']
for friend in friends:
print("Happy New Year: ",friend)
print("BlastOFF!!!!") |
#counting lines in file
fhand = open('mbox.txt')
count = 0
for eachline in fhand:
count = count + 1
print("Total number of lines: ",count) |
# Name: Monty Hall Game and Monte Carlo Simulation
# Version: 0.2a3
# Summary: A simple game that replicates the Monty Hall problem, and a Monte Carlo simulator to determine probabilities
# Keywords: Monty Hall, Monte Carlo
# Author: Jacob J. Walker
#
# Header comments based on meta-data specs at https://packaging.pyth... |
import pandas as pd
import json
with open('COUNTRY.json') as f:
data = json.load(f)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
x=pd.DataFrame(data)
print(x) |
import turtle
from typing import List, Tuple, Optional
import math
class Label(turtle.Turtle):
def __init__(self, x, y):
super().__init__(shape='blank')
self.up()
self.goto(x, y)
def msg(self, text):
self.clear()
self.write(text, align="left")
class Checker(turtle.T... |
import turtle
from random import random
car = turtle.Turtle()
car.shape('turtle')
button = turtle.Turtle()
button.goto(x, y)
def create_car(x, y):
turtle.tracer(False)
car_xy = turtle.Turtle()
car_xy.up()
car_xy.goto(x, y)
car_xy.fillcolor((random(), random(), random()))
turtle.tracer(True)
... |
import datetime
import turtle
turtle.tracer(False)
pen = turtle.Turtle()
pen.hideturtle()
pen.goto(0, 100)
t = datetime.datetime.today()
pen.write('Сегодня:', align="center", font=("Arial", 14, "bold"))
pen.forward(65)
pen.goto(0, 70)
pen.write(t, align="center", font=("Arial", 14, "normal"))
pen.goto(0, 50)
p = turt... |
import turtle
player = turtle.Turtle()
def checker(x, y, size, color):
"""
Нарисуем фигуру в нужном месте
:param x: координата Х фигуры
:param y: координата У фигуры
:param color: цвет фигуры
:return: в нужном положении рисуется фигура
"""
player.speed(0)
player.up()
player.goto... |
# Assuming input graph is represented by adjacency list
g1 = {"a": ["b"],
"b": ["c", "d"],
"c": [],
"d": ["c"],
"e": ["c"]
}
g2 = {"a": ["b"],
"b": ["c", "d"],
"c": ["e"],
"d": ["c"],
"e": ["c"]
}
#print(g1)
def isPath(n1, n2, g):
queue = []
seen = {}
... |
import logging
import typing
def logger_config(
prefix: str = 'NULL',
file_level: str = 'INFO',
console_level: str = 'INFO',
log_file: str = 'test.log') -> typing.NoReturn:
"""Set up the log to print to both the log file and the console
:param prefix: Sets the log prefix, which... |
"""Grammar."""
from rule import Rule
# -- coding: utf-8 --
__author__ = 'stepan'
__license__ = 'MIT'
__version__ = '1.0'
class Grammar:
"""Represents grammar with all components."""
def __init__(self):
"""Initialization."""
self.rules = []
self.terminals = []
self.nontermina... |
#Using pandas data reader this program will print a table of close values for a list of stocks from a year from today up until today's date
#Note that I am retrieving the stock data using Yahoo Finance
import pandas as pd
import pandas_datareader.data as pdr
import datetime as dt
#this list may be modified as desire... |
#!/home/sahil/anaconda2/bin/python
import sys
import numpy as np
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from matplotlib import pyplot as plt
from sklearn.utils import shuffle
import math
import optparse
print 'Let\'s do decision tree!!'
#function to create new Table and add the rows... |
import numpy as np
def outer_product(F, G):
b = np.size(F)
r = np.size(G)
W= np.zeros((b,r))
for i in range(b):
for j in range(r):
W[i, j] = F[i] * G[j]
return W
|
#!/usr/bin/python3
import re
import os
class Parser:
"""The parser class is used to parse the episodes and the file for converting the names"""
# hardcoded patterns list to search for
patterns = [
'(?P<Season>S[0-9]{1,2}).*(?P<Episode>E[0-9]{1,3})' # 'S[0-9]{1,2}.*E[0-9]{1,3}'
]
file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.