text stringlengths 37 1.41M |
|---|
numbers = [1, 3, 4, 2, 9, 45, 32, 89]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)
|
import numpy as np
import pandas as pd
class MultilabelPredictionEvaluater(object):
"""
Class for evaluation and comparison of multi-label classifiers.
Most methods of this class take an ndarray of predictions as input and compare them (in some way) to the
correct multi-labels which the constructor m... |
# Quiero Retruco
# El Truco es un juego de cartas muy popular en Argentina. Se suele jugar con naipes españoles de 40 cartas, las cuales tienen 4 palos (basto, oro, espada y copa) y 10 números, 1,2,3,4,5,6,7,10,11 y 12. Si bien en esta ocasión no vamos a programar un juego de truco, sí vamos a resolver uno de los probl... |
# Dr. Chaos, el malevolo semiótico
# "Chaos es caos en inglés" te diría Dr. Chaos, charlando con una taza de té Chai en la mano. En verdad no es tán malo como su nombre lo hace aparentar... si es que tenés un buen manejo de los idiomas.
# Dr. Chaos esta armando un diccionario. Este diccionario tiene la particularidad ... |
import math
n = int(input())
for i in range(0,n):
args = input().split(' ')
a = int(args[0])
b = int(args[1])
root_a = math.sqrt(a)
root_b = math.sqrt(b)
square_numbers = int(math.floor(root_b)) - int(math.ceil(root_a)) + 1
print(square_numbers)
|
hours_in_words = ['one', 'two', 'three','four','five','six','seven','eight','nine','ten','eleven','twelve']
minutes_in_words = ['zero','one', 'two', 'three','four','five','six','seven','eight','nine','ten','eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen','sixteen','seventeen','eighteen','nine... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p=q=head
f=False
... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
# ʼ
if not l1... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
... |
class MyHashSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.lst=[[] for i in range(10000)]
def add(self, key):
"""
:type key: int
:rtype: void
"""
index=key%10000
if key not in self.lst[index]:
... |
class Stack:
def __init__(self):
self.list = []
self.top = -1
def push(self,data):
self.top += 1
self.list.insert(self.top,data)
def pop(self):
if (self.top == -1):
print("Invalid to perform Pop operation !!!")
return False
top = sel... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 10:53:57 2019
@author: ottil
"""
word_counter = {}
def wordcount(words):
for word in words.split():
if word not in word_counter:
word_counter[word] = 1
else:
word_counter[word] +=1
return(word_counter)
#print(wordco... |
class Queue(object):
def __init__(self):
self.queue = list()
def enqueue(self,value):
self.queue.insert(0,value)
def dequeue(self):
if self.is_empty():
return None
return self.queue.pop()
def peek(self):
if self.is_empty():
return None
... |
"""
Logic : Do BFS traversal. At each level start with previous set as None
Then if previous, set node.next as previous
Set node as previous and continue with BFS
TimeComplexity : BFS traversal; O(N)
Space complexity : O(2^log(N)) -> O(2 to the power h where h is hte height of the tree)
"""
cla... |
"""
Bruteforce: Find all indices for the first alphabet of B in A.
Then for all indexes in indices,
check if B to end matches with A[index]->A[len(A)]->A[0]->A[index-1]
Time complexity : Finding indexes O(N)
Checking for match O(N)
Space complexity : O(N)-> Storing the in... |
"""
Bruteforce : For a given string, iterate over the indexes, taking the index as the middle point
of the palindrome. From the middle point, check if left and right
Time complexity : O(n^2)
Space complexity : O(1)
Other approaches:
"""
class Solution(object):
def longestPalindrome(sel... |
"""
Solution : Convert to binary. Store indexes of 1's.
Find maximum distance between the adjacent differences
return
Time complexity : O(N), N being the number of bytes needed to represent the number
Space complexity : O(N), depends on the number indexes stored.
"""
class Solution(objec... |
"""
Algorithm - Single stack
We use one stack only and a variable to store min element.
If the element to be inserted is less than or equal to(equal to because duplicate elements which can be same min) min element, then we push the current min element to stack, then
update the min element to new element and then pu... |
"""
With division, bruteforce soln
time complexity: O(N)
space: O(N)
"""
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
ans = []
prod = 1
non_zero_prod = 1
zero_flag = False
... |
"""
To find min element, do binary search on all the unsorted parts.
If there is no unsorted part, return nums[low]
When searching in second subarray, include the mid also in the search
Time complexity - O(log(N))
Space complexity - O(1)
"""
class Solution(object):
def findMin(self, nums):
"""
... |
from Tkinter import *
class sketcheCanvas(Canvas):
"""Inherits from tk.Canvas. Additional methods for mouse click callbacks.
e.g. drawing lines, curves, etc."""
def setVals(self):
"""Sets attributes needed in sketcheGui."""
self.click = False
self.items = []
self.tool = sel... |
def to_2(num, bits):
ans=""
bits-=1
while bits>=0:
if 2**bits <= num:
num-= 2**bits
ans+='1'
else:
ans+='0'
bits-=1
return ans
palendromes = 0
nth = int(input())
nth-=1
n = 0
length = 1
while n+2**((length-1)//2) <= nth:
n += 2**((length-1)... |
import heapq
class Node:
def __init__(self, idx):
self.idx = idx
self.dist = -1
self.edges = []
self.visited = False
self.pot = False
def set_dist(self, new_dist, heap):
if new_dist > self.dist:
self.dist = new_dist
def __lt__(self, other):
... |
"""Project Euler problem 3"""
def sqrt(number):
"""Returns the square root of the specified number as an int, rounded down"""
assert number >= 0
offset = 1
while offset ** 2 <= number:
offset *= 2
count = 0
while offset > 0:
if (count + offset) ** 2 <= number:
count... |
"""Project Euler problem 22"""
def calculate(name_list):
"""Returns the sum of the alphabetical value for each name
in the list multiplied by its position in the list"""
return sum(
(i + 1) * (ord(c) - ord("A") + 1)
for i, name in enumerate(sorted(name_list))
for c in name.strip('"... |
"""
Written by Abdullah Al-Hajjar
"""
import unittest
import pandas as pd
class test(unittest.TestCase):
@classmethod
def setUpClass(self):
try:
df3 = pd.DataFrame()
df = pd.read_csv('canadianCheeseDirectory.csv')
search_word = 'Bufflo Cow Creamy and fresh, this... |
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
# Добавление строки в текстовый блок
def insertText(s):
textDiary.insert(INSERT, s + "\n")
textDiary.see(END)
# Расположение лошадей на экране
def horsePlaceInWindow():
horse01.place(x=int(x01), y=20)
horse02.place(x=int(x02)... |
number_of_months = int(input("Number of months: "))
k = int(input("Number of pairs every pair produces: "))
n1,n2 = 1,1
counted = 0
while counted < number_of_months:
print(n1)
new_number = k*n1 + n2
n1 = n2
n2 = new_number
counted += 1
|
arr = []
def push(data):
arr.append(data)
def pop():
arr.pop()
def printAll():
for i in range(0,len(arr)):
print arr[i]
push(1)
push(2)
push(3)
push(4)
pop()
printAll()
|
date=input("enter the date in dd/mm/yyyy:")
day,month,year = date.split("/")
day = int(day)
month = int(month)
year = int(year)
if month==1 or month==3 or month==5 or month==7 or month==8 or month==10 or month==12:
max_days=31
elif month==4 or month==6 or month==9 or month==11:
max_days=30
elif y... |
def meetsCriteria(number):
doub = False
previous = -1
st = str(number)
for i in range(len(st)):
if previous == int(st[i]):
doub = True
elif previous > int(st[i]):
return False
previous = int(st[i])
return doub
def meetsMoreCriteria(number):
previo... |
fname = input("Enter file name: ")
han=open(fname)
count=0
for line in han:
line=line.rstrip()
wds=line.split()
if len(wds) < 3 or wds[0] !='From':
continue
count=count+1
print(wds[1])
print('There were',count,'lines in the file with From as the first word')
|
def are_anagrams(*words: str) -> bool:
"""
Checks whether all words passed are anagrams of each other
This will return True for the cases where less than 2 words are passed.
i.e. Nothing and a single word are considered anagrams of themselves
:param words: The words to compare against each other
... |
from adventofcode.common import Solution
import re
class Day11(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._s = self._load_input_as_lines()[0]
def _is_valid(self, s):
# must be 8 characters
if re.match('^[a-z]{8,8}$', s) is None:
... |
from adventofcode.common import Solution
import re
class Day25(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self.input = self._load_input_as_string()
r = re.match('To continue, please consult the code grid in the manual\. Enter the code at row (\d+), col... |
from adventofcode.common import Solution
import re
class Day19(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._transformations = []
lines = self._load_input_as_lines()
self._final_molecule = lines[-1]
for t in lines[0:len(lines)-3]... |
from itertools import cycle
from adventofcode.common import Solution
from typing import Set
class Day03(Solution):
def __init__(self, year: str, day: str):
super().__init__(year, day)
self._directions = self._load_input_as_string()
def _journey(self, directions) -> Set:
x = 0
... |
# Faça um programa que leia o nome e peso de várias pessoas, [ X ]
# guardando tudo em uma lista. No final, mostre:
# A) Quantas pessoas foram cadastradas [ X ]
# B) Uma lista com as pessoas mais pesadas, [ X ]
# C) Uma lista com as pessoas mais leves [ X ]
temporal = list()
principal = list()
leve = pesado = ... |
dias = int(input('Quantos dias alugados? '))
quilometros = float(input('Quantos Km rodados? '))
precoDias = 60.0
precoQuilometro = 0.15
resultado = (dias * precoDias) + (quilometros * precoQuilometro)
print('O preço a pagar é: R${}{:.2f}{}'.format('\033[33m', resultado, '\033[m'))
|
numero = int(input('Digite um número: '))
unidade = numero // 1 % 10
dezena = numero // 10 % 10
centena = numero // 100 % 10
milhar = numero // 1000 % 10
print('unidade: {}{}{}'.format('\033[35m', unidade, '\033[m'))
print('dezena: {}'.format(dezena))
print('centena: {}'.format(centena))
print('milhar: {}'.form... |
metros = int(input('Digite um valor: '))
metros1 = (metros) * 10 ** 0
centimetros = (metros) * 10 ** -2
milimetros = (metros) * 10 ** -3
print('Esse número em metros é = {}{}{}m\nEm centímetros é = {}cm\nEm milímetros = {}mm'.format('\033[31m', metros1, centimetros, milimetros, '\033[m'))
|
soma = 0
count = 0
for i in range(1, 7):
valor = int(input('Digite um valor: '))
if i % 2 == 0:
soma = soma + valor
count = count + 1
print('A soma de todos os {} números PARES é igual a {}'.format(count, soma))
|
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print('A média desse aluno foi: {}{}{}'.format('\033[34m', media, '\033[m'))
|
from datetime import date
ano_de_nascimento = int(input('Digite o ano de nascimento: '))
atual = date.today().year
idade = atual - ano_de_nascimento
print('Sua idade é: {}'.format(idade))
if idade <= 9:
print('Até 9 anos, MIRIM')
elif idade <= 14:
print('Até 14 anos, INFANTIL')
elif idade <= 19:
... |
# RGB color table
# based on http://en.wikipedia.org/wiki/File:1Mcolors.png
def draw_square(steps, pos, b):
color_step = 1.0 / steps
x, y = pos
for i in range(steps):
for j in range(steps):
r = j * color_step
g = i * color_step
fill(r, g, b)
stroke(r... |
# Emily Simon
# Assignment - Lab4
# Aug 4 2019
# Imports the turtle graphics module
import turtle
# creates a turtle (pen) an sets the speed (where 0 is fastest and 10 is slowest)
# The colors can be set through their names or through hexadecimal codes, use hex for accuracy
turtle.screensize(200, 200, bg="#... |
# importing random int maker module
from random import randint
# class defines what happens when a player dies.
# in this case, it has a list of phrases to be displayed
# randomly, and returns the string 'died' to let the engine know.
class Death(object):
quips = ["You died. You kinda suck at this.",
"You... |
# interpolation between 2D cartesian points
# visualize this example here: https://www.desmos.com/calculator/lkyi2y4kbx
# tuples are a good way to represent point coordinates, since they cannot change
# these are in the format (x, y)
point_A = (20, 16)
point_B = (24, 8)
# now compute the slope of the line connecting ... |
# a string which contains both lower and upper case letters.
# notice the extra letter 'a' at the end of each alphabet. This is to make shifting easier.
caesar_alphabet = 'abcdefghijklmnopqrstuvwxyzaABCDEFGHIJKLMNOPQRSTUVWXYZA'
def caesar_cipher(original_string):
"""
Returns the caesar cipher for a given stri... |
#!/usr/bin/python3
from shape3 import *
N = 50
LINE = '=' * N # It's used in drawing a line between
# individual segments.
"""
This external routine is to print out certain parameters of
some of the two- or three-dimensional geometric shapes.
"""
def Print ( name, shape, flag = True ):
print ( ... |
#!/usr/bin/env python3
"""
CSCI 503 - Assignment 5 - Spring 2019
Author: Sneha Ravi Chandran
Z-ID: z1856678
Date Due: May 02, 2019
Purpose: This API implements various 3D shapes
and provides for means to determine their area,
volume and by extension allow for changes.
"""
from shape2 impo... |
def collatz(n):
dictCollatz, keyMaxTraject = {}, 1
for i in range(n):
chisloK, pathLength = i + 1, 0
while chisloK:
if not chisloK in dictCollatz and chisloK != 1:
if not chisloK % 2:
chisloK //= 2
else:
chisloK... |
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
... |
# Btree data structure and methods for manipulating same to be find unique
# subsequences and their successors.
class BNode:
# Canonical key order
KEY_ORDER = []
##########################################################################
def __init__(self, key_in_parent=None):
# Key in parent is used to find th... |
import pyhop
"""
HELPER FUNCTIONS
"""
def is_done(state, a):
"""Checks current state of domain for whether the player has reached the goal"""
if state.x[a] == state.goal_x[a] and state.y[a] == state.goal_y[a]:
return True
else:
return False
def is_dead_end(state, a):
"""Checks curre... |
# Task 1
if __name__ == "__main__":
# Number of test cases
test_cases = int(input())
# Iterate through each of the test cases
for i in range(test_cases):
# Get the number of patients in the case
noPatients = int(input())
# Iterate through each patient
# Create an array t... |
print('Programa que muestra todos los numeros pares positivos hasta el numero introducido por el usuario',end='\n')
numero = int(input('Ingrese N >>> '))
for i in range(numero):
if i%2==0:
print(i,end=' ') |
# Common Ground
#
# Consider the strings "Tapachula" and "Temapache", both of which name
# towns in the country of Mexico. They share a number of substrings in
# common. For exmaple, "T" and "pa" can be found in both. The longest
# common unbroken substring that they both share is "apach" -- it starts
# at positi... |
# ----------
# User Instructions:
#
# Create a function compute_value() which returns
# a grid of values. Value is defined as the minimum
# number of moves required to get from a cell to the
# goal.
#
# If it is impossible to reach the goal from a cell
# you should assign that cell a value of 99.
# ------... |
# -----------------
# User Instructions
#
# Write a function, bsuccessors(state), that takes a state as input
# and returns a dictionary of {state:action} pairs.
#
# A state is a (here, there, t) tuple, where here and there are
# frozensets of people (indicated by their times), and potentially
# the 'light,' ... |
#Spelling Correction
#Double Gold Star
#For this question, your goal is to build a step towards a spelling corrector,
#similarly to the way Google used to respond,
# "Did you mean: audacity"
#when you searched for "udacity" (but now considers "udacity" a real word!).
#One way to do spelling correct... |
#Lecture 5: Clustering Coefficient Code
def make_link(G, node1, node2):
if node1 not in G:
G[node1] = {}
(G[node1])[node2] = 1
if node2 not in G:
G[node2] = {}
(G[node2])[node1] = 1
return G
flights = [("ORD", "SEA"), ("ORD", "LAX"), ('ORD', 'DFW'), ('ORD', 'PIT'),
... |
# Writing Reductions
# We are looking at chart[i] and we see x => ab . cd from j.
# Hint: Reductions are tricky, so as a hint, remember that you only want to do
# reductions if cd == []
# Hint: You'll have to look back previously in the chart.
def reductions(chart, i, x, ab, cd, j):
# x -> ab * cd fr... |
#Complete the median function to make it return the median of a list of numbers
data1=[1, 2, 5, 10, -20]
def median(data):
#Insert your code here
m = len(data) / 2
return sorted(data)[m]
print median(data1) |
print("*********************************************\n")
print(" "*10+"\033[1;96;40mRemoving Punctuations\033[0m \n")
print("*********************************************\n")
usr = input("\033[1;34;40mEnter a string with punctuatuions: \033[0m").lower()
punc = ['!','/','(',')',',','-','[',']','{','}',';',':','\\','<'... |
print("***********************************",'\n')
print(" "*10+"\033[1;34;40mPalindrome Test\033[0m\n")
print("***********************************")
#header with allignment and coloured text
usr = input("Enter a string: ")
#accepting user string
rev = ''
#initailising a rev variable(to store reverse) to null
flag =... |
# this code is showing comment and print basic variable
"""
this is docstring i don't know how to
use it properly i will learn about it
"""
first = 3
second = 5
sum_of_both = first + second
print(sum_of_both)
name = 'anshul'
surname = 'gera'
fullname = "my name is " + name + " "+ surname
print(fullname)
def uniqu... |
import re
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
if re.match(r'^\d{3}\-\d{3,8}$', '010-12345') :
print 'ok'
else:
print 'failed'
print re.split(r'\s+', 'a b c')
print re.split(r'[\s\,]+', 'a,b, c d')
print re.split(r'[\s\,\;]+','a,b;c d')
#Group regex
m = re.match(r'^(\d{3})-(\d{3,8})$', '01... |
from collections import Iterable
age=20
if age >= 6:
print 'teenager'
elif age >=18:
print 'adult'
else:
print 'kid'
names=['a','b','c']
for name in names:
print name
sum=0
for x in range(101):
sum = sum + x
print sum
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print sum
def m... |
from collections import deque
def solution(priorities, location):
# 대기목록의 중요도와 인덱스를 튜플로 같이 저장한다
order = deque([(n, idx) for idx, n in enumerate(priorities)])
q = [] # q = 최종 인쇄 순서
while len(order) != 1: # 마지막 한개만 남을 때까지
# 만약 현재 중요도보다 더 큰 중요도가 있으면 뒤로 넘기고, 아니면 q에 추가
now = order.poplef... |
import numpy as np
X = np.array([3,1,8,6,0])
def softmax(X):
Y = np.exp(X)
return Y/np.sum(Y)
print("argmax :",np.argmax(X))
p = softmax(X)
for i in range(len(X)):
print("p[{:d}] = {:.4f}".format(i,p[i]) )
|
import numpy as np
import matplotlib.pyplot as plt
# ----------------------------------------------------
# 1. Un exemple
def f(x):
return np.exp(-x**2)
a,b = -3,3
X = np.linspace(a,b,num=100)
Y = f(X)
plt.plot(X,Y)
# plt.savefig('pythonx-gauss.png')
plt.show()
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#------------------------------------------
# Newton
#------------------------------------------
# La fonction f(x)
def f(x):
return x**3 - 100
# La fonction dérivée f'(x)
def df(x):
return 3*(x**2)
# Méthode de Newton
# x0 est le terme initial, n est le nomb... |
#!/usr/bin/python3
# Descente de gradient classique -- 2 variables
from descente import *
from descente_stochastique import *
from descente_lot import *
def exemple1():
# fonction de 2 variables
def f(x, y):
return x**2 + 3*y**2
# gradient calculer par nos soins
def grad_f(x, y):
... |
import numpy as np
import matplotlib.pyplot as plt
# ----------------------------------------------------
# 5. Fonctions mathématiques de numpy
print("\n\n--- 1. Fonctions mathématiques de numpy ---\n")
X = np.array([0,1,2,3,4,5])
print(X**2)
print(np.sqrt(X))
print(np.exp(X))
print(np.cos(X)) # en radians
prin... |
#!/usr/bin/env python
# coding: utf-8
# # Applying Stereo Depth to a Driving Scenario
# Now that you've reviewed the algorithms behind stereo vision and cross correlation we can begin to tackle real-world examples (Actually, we'll use images from the Carla simulator, so I suppose real-world-like would be more appropri... |
# -*- coding: utf-8 -*-
## @package guided_filter.util.timer
#
# Timer utility package.
# @author tody
# @date 2015/07/29
import time
class Timer(object):
def __init__(self, timer_name="", output=False, logger=None):
self._name = timer_name
self._logger = logger
self._outp... |
def get_and(i, j):
if i is False or j is False:
return False
elif i is None or j is None:
return None
else:
return True
def get_or(i, j):
if i is True or j is True:
return True
elif i is None or j is None:
return None
else:
retur... |
# Determine the threshold of distance
# Method 1. Look at the distance when its coefficient in the Hedonic regression function approaches 0
# Method 2. Look at the distance when the Pearson correlation coefficient approaches 0
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklear... |
# Project will be continued to find best combination for area message
# TODO: Implement Area Message
import math
import random
import sys
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'This is a Project for {name}') # Press Strg+F8 to toggle the breakpoint.
... |
demo_list =[1, 'hello', 1.34, True,[1, 2, 3]]
colors = ['red', 'green', 'blue']
numbers_list = list((1, 2, 3, 4)) #Uso una tupla que generar 1 variable en vez de 4
print(numbers_list)
print(type(numbers_list)) #Tipo de la lista
r = list(range(1, 10)) #Enumera del 1 hasta el 9
print(r)
print(... |
myStr = "Hello World"
#Para ver las propiedades
# #print(dir(myStr)) #"Quitar el '#'para visualizar" <-
# | ctrl + 'k+ctrl' + c = comment
#-----------------------------------------------------------------------------------------
print("Mood " + myStr) #Lo agrupa sin espaciado, por eso uno debe de separarlo con espa... |
import threading
# uses a set for the queue. Duplicates are therefore discarded, and results popped() at random
class SetQueue:
def __init__(self):
self.items = set()
def push(self, item):
self.items |= set([item])
def push_group(self, items):
self.items |= set(items)
def po... |
#class_of_python
#class_name: TWP030 Declarando nossas primeiras variáveis
#link_class: https://www.youtube.com/watch?v=qHx8SRYqW2E&list=PLUukMN0DTKCtbzhbYe2jdF4cr8MOWClXc&index=4
#some basic calculus to learn some thins about python lenguage
# print(type('abacate'))
# print(dir('abacate'))
# help('abacate'.upper)
# ... |
# Find the char that is not repeated in a string. if more than, return the first repeated char
# if empty or too few return -1
# one by one, check the charcaters in dictionary. If found, add the count. Else add the char to dictionary
# Now iterrate thru the dictionary. Return the first char with count == 1
# if i... |
#from collections import namedtuple
#from typing import AsyncGenerator
print((2+10)*(10+4))
a=5
print(a)
print(a+a)
a=a*5
#print a
print(a)
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)
#strings (use "double quotes and single quote'' ")
mystring ='abcdegh'
print(mystring[::])
#slicin... |
# TO RUN THIS SCRIPT COPY THIS COMMAND INTO THE TERMINAL -----> index_list.py
packages_setup = ['''
conda create -n stocks-env python=3.7 # (first time only)
conda activate stocks-env
pip install -r requirements.txt
pip install pytest # (only if you'll be writing tests)
python index_list.py
''']
# Examples (cli... |
# TO RUN THIS SCRIPT COPY THIS COMMAND INTO THE TERMINAL -----> crypto_ticker.py
packages_setup = ['''
conda create -n stocks-env python=3.7 # (first time only)
conda activate stocks-env
pip install -r requirements.txt
pip install pytest # (only if you'll be writing tests)
python crypto_ticker.py
''']
# Examples... |
# from math import *
# a = int(input("son kirit= "))
# b = int(input(" yana son kirit= "))
# if a > 0 and b > 0:
# x1 = sqrt(a+b)
# x2 = sqrt(a-b)
# print(f"x1 = {x1}, x2 = {x2}")
# elif a < 0 or b < 0:
# y = ((a) + (b))*-1
# u = ((a) - (b))*-1
# x1 = sqrt(y)
# x2 = sqrt(u)
# print(f"x1... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 11:14:41 2019
@author: Matthew Mulhall
"""
import os
def rename(path = ''):
#Set old dir to the path up until your char folder . Something like: "C:\Users\yourname\Documents\OCR-Handwriting\bin\data\char"
#Created more generality in the script, rather than nee... |
Pizzas=['Ks bakers','dominos','pizza hut']
print(Pizzas)
for item in Pizzas: # In For Loop item is a variable which takes items from List
print("this is "+item.title()+" pizza")
print("I really love pizza..!!\n")
# indendations are important in the loop
# variables are declared and definied at a time in the for loop
... |
class Ejercicios:
def __init__(self):
pass
def num_cuadrado11(self):
suma = 0
for i in range(1, 101):
suma = suma + i * i
print('Suma:', suma)
print('-'*6 + '-'*len(str(suma)))
def numero12(self):
i = 1
while i <= 100:
print(i... |
def print_board(board):
for i in range(len(board)):
for j in range(len(board[0])):
print(board[i][j],end=" ")
print("")
# checks if a given row contains the given number,if it contains the function returns False
def is_row_valid(board,row,number):
for i in range(len(board)):
... |
civilization_world = [
#0 1 2 3 4 5 6 7 8 9 10
[0,0,0,0,0,0,0,0,0,1,0], #0
[0,0,0,0,1,0,0,0,0,0,0], #1
[0,0,0,0,1,0,0,0,1,0,0], #2
[0,0,0,0,1,1,0,1,1,0,0], #3
[0,0,0,1,1,1,0,1,0,0,0], #4
[1,1,1,1,1,1,1,1,0,0,0], #5
[0,0,0,0,1,0,0,0,0,1,0], #6
[0,0,0,0,1,0,0,0,0,1,0], #7
[0,0,0,0,... |
#segun los números digitados, se escoge en las
#condicionales y los muestra en pantalla
def matriz(n):
if n=="1":
lista=[" ","#"," "," ","#"," "," ","#"," "," ","#"," "," ","#"," "]
for i in range(len(lista)):
if i==2 or i==5 or i==8 or i==11 or i==14:
... |
import unittest
from app.models import News,Articles
News = news.News
class NewsTest(unittest.TestCase):
'''
Test Class to test the behaviour of the News class
'''
def setUp(self):
'''
Set up method that will run before every Test
'''
self.new_news = News(1234,'Ineos 1... |
import time
import numpy as np
import pandas as pd
from pandas.core.algorithms import value_counts
from pandas.core.tools.datetimes import to_datetime
def city_list():
return
CITY_DATA = {
"chicago": pd.read_csv("chicago.csv"),
"new york": pd.read_csv("new_york_city.csv"),
"washington": pd.read_csv... |
while True:
print "Type in a month's number and learn what month that is."
month = raw_input()
if month == "1":
print "January"
print "Happy New Year!"
elif month == "2":
print "February"
print "Celebrate the loved ones in your lives on Valentines Day!"
elif month ==... |
from flask import Flask
from flask import render_template
from flask import request
# The parameter static_url_path tells Flask where to look for the "static" directory.
# Requests for paths not explicitly listed with @app.route() directives below will be
# interpreted as requests for files from the "static" director... |
def recurse(a):
a.append(a[len(a)-1]+1)
for x in a:
print 1
print x
if a[len(a)-1]<8:
recurse(a)
a = [2]
recurse(a)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.