text stringlengths 37 1.41M |
|---|
import crypt
import argparse
def crack_pass(ctext, pw_dict):
salt = ctext[0:2]
with open(pw_dict, 'r') as pw_dict:
for word in pw_dict.readlines():
word = word.strip()
crypt_word = crypt.crypt(word, salt)
if crypt_word == ctext:
return word
retur... |
def main():
count = 1
answer = 0
while count < 1000:
if count % 3 == 0:
answer += count
if count % 5 == 0 and count % 3 != 0:
answer += count
count += 1
print(answer)
main()
|
"""
These are the basic image-stack processing commands. They aren't really filters as they don't change
the data in the image slices but instead work on changing which slices we are using. They generally
create ImageStackCollection image stacks.
"""
from __future__ import absolute_import
from __future__ import divisio... |
# -*-coding:utf-8-*-
# Link: https://leetcode.com/problems/insert-interval/
# Problem Description:
# Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
# You may assume that the intervals were initially sorted according to their start times.
# Example:
# Input: i... |
# -*-coding:utf-8-*-
# Link: https://leetcode.com/problems/jump-game/
# Problem Description:
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
# Each element in the array represents your maximum jump length at that position.
# Determine if you are able to reach t... |
# Example based on:
# https://towardsdatascience.com/building-a-deep-learning-model-using-keras-1548ca149d37
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
from helpers import create_f... |
import pyglet
from character import *
from Map import *
GRAVITY = 2
class Player(Character):
def __init__(self, x, y, path, BG, win, spdx = 0, spdy = 0):
Character.__init__(self, x, y, path, BG)
self.mid = (win[0]/2-100, win[1]/2, 100)
self.onGround = False
self.jumping = False
... |
'''
Problem 2.6 Determine if a LinkedList is a Palindrome
September 4, 2017
Kevin Chen
'''
from datastructures import LinkedList
import unittest
def isLinkedListPalindrome(ll):
'''
Add first half as stack, then compare reversed first half with second half.
time: o(n)
space: o(n)
where n is the #... |
'''
Problem 2.5 Sum two linked lists whose contents represent an integer's digits in reverse order
August 27, 2017
Kevin Chen
'''
from datastructures import LinkedList
import unittest
def sumLists(list1, list2):
'''
time: o(n)
space: o(n)
where n is the # of elements in the greater list
'''
c... |
'''
Problem 3.2 Create a stack that keeps the minimum
September 8, 2017
Kevin Chen
'''
import unittest
import math
class StackMin(object):
'''
A stack that holds the minimum (retrieved in O(1)).
Returns infinity for minimum of empty list.
time: o(1)
space: o(1)
'''
def __init__(self):
... |
class bst:
def __init__(self, parent=None, val:int =None, left=None, right=None):
self.parent = parent
self.val = val
self.left = left
self.right = right
# ouh my god you dingdong
# be careful about putting commas after stuff in your constructor
# you're thinking JS objects or somet... |
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 1
# 2 3
# 6
# 7 8
#
#
l = [1,2,3,None,None,None,6,7,8]
def generate_tree_from_list(l):
if not l:
return None
nodes = [None if i is None... |
def has_balenced_parens(parens_string):
i=0
for letter in parens_string:
if i<0:
return False
elif letter=="(":
i+=1
elif letter==")":
i-=1
if i==0:
return True
else:
return False |
#question1
import numpy
def vectorpi(n):
v=numpy.arange(0,n)
#lists numbers 1 to n
v=0.5*v*numpy.pi/(n-1)
return v
# question 2
import numpy
from tutorial2 import vectorpi #assignment is the file containing the module called vector
def integrate(n):
dx=numpy.pi/2/n
vec=vectorpi(n)
tot=nump... |
#def print_formatted(number):
# your code goes here
# for i in range(1,number):
# print(tohex(i))
#print_formatted(6)
def fun(N):
width = len(bin(N)) - 2
for i in range(1,N+1):
print "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i,width = width)
n = input()
fun(n) |
import csv
with open("data.csv",newline="") as f:
reader= csv.reader(f)
file_data= list(reader)
numbers = 0
numberofnumbers = len(file_data)
for sum in file_data:
numbers = numbers+ float(sum[1])
mean= numbers / numberofnumbers
print("mean is: "+ str(mean))
import math
diffrence= 0
... |
# -------------------- Менеджеры контекста ---------------------------------------
# Как работает оператор with?
# with open('test', 'w') as f:
# f.write('Stroka')
# Оператор with использует интерфейс менеджера контекста объекта.
# Создадим свой класс, реализующий интерфейс менеджера контекста.
... |
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
# Пример:
# Дано: ["яблоко", "банан", "киви", "арбуз"]
# Вывод:
# 1. яблоко
# 2. банан
# 3. киви
# 4. арбуз
# Подсказка: воспользоваться методом .format()
fruits ... |
import random
class Card:
def __init__(self, title='', rows_amount=3, cols_amount=9, nums_per_row=5, max_num=90):
self._rows_amount = rows_amount
self._cols_amount = cols_amount
self._nums_per_row = nums_per_row
self._max_num = max_num
self._title = title
... |
# print('Hello' + ' ' + 'world')
# print('Hello' ' ' 'world')
# print('Hello! ' * 3)
#
# url = 'http://yandex.ru'
# index = url.find('yandex')
# print(url.find('yandex'))
# print(url[index:])
# name = 'ivAn peTrov'
# print(name.title())
# print(name.upper())
# print(name.lower())
# print(len(name))
#... |
import csv
with open('data.csv') as f_n:
f_n_reader = csv.reader(f_n)
for row in f_n_reader:
print(row)
print()
with open('data.csv') as f_n:
f_n_reader = csv.reader(f_n)
print(f_n_reader)
print()
with open('data.csv') as f_n:
f_n_reader = csv.reader(f_n)
print(list(f... |
# class Colors:
# def __init__(self, colors):
# self.colors = colors
#
# def __iter__(self):
# i = 0
# while True:
# yield self.colors[i]
# i += 1
# if i == len(self.colors):
# i = 0
#
# class Colors2:
# def __init__(se... |
import data_import as data
import matplotlib.pyplot as plt
import model.two_layer as two_layer
import model.l_layer as l_layer
import prediction.post_function as pdt
# Loading Data and knowing Dimension
train_x_origin, train_y, test_x_origin, test_y, classes = data.load_data()
m_train, num_px, m_test = data.gettingDim... |
'''
4. Пользователь вводит строку из нескольких слов, разделённых пробелами.
Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове.
'''
user_str = (input('Введите слова через пробел: ')).split(' ')
i = 1
for word in user_str:
if len(word... |
'''
1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
'''
def divisions(a, b):
return a / b
a = input('Введите делимое: ')
b = input('Введите делитель: ')
if not a.isdigit() or not b.... |
n = input('Введите целое положительное число: ')
# короткий вариант
max_d = max(map(int, n))
print(max_d)
# вариант с while
i = 0
max = n[0]
while i < len(n) - 1:
if n[i] < n[i+1]:
max = n[i+1]
i +=1
print(max) |
import turtle
# creatring a turtle-object
tu = turtle.Turtle()
# hide cursor
tu.hideturtle()
# set up the window as full
turtle.setup(width=1.0, height=1.0, startx=None, starty=None)
screen_height = turtle.screensize(canvwidth=None, bg=None)
screen_height = float(screen_height[0])
print(screen_height)
... |
# Team member: Hanna Magan and Kristine
# Course: CS151, Dr.Rajeev
# Date: 22 September 2021
# Programing Assignment 1
# import math
# Program Inputs: ask user for population (births,deaths and migration by year)
birth = float(input("Enter_births"))
deaths = float(input("Enter_death"))
migration = float(input("Enter _m... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Justin Dano 10/23/2016
# Design inspired by articles on Quantstart.com
from abc import ABCMeta, abstractmethod
class Portfolio(object):
"""
Abstract Base class for a portfolio. Currently it includes logic to generate positions
based on the Strategy cla... |
# Based on this
# https://www.youtube.com/watch?list=PLQVvvaa0QuDfju7ADVp5W1GF9jVhjbX-_&time_continue=6&v=jA5LW3bR0Us
# Pretty simple one buuuuuut
names = ['Jeff', 'Gary', 'Jill', 'Samantha']
##for name in names:
## #print('Hello there, ' + name)
## print(' '.join(['Hello there', name]))
#print(', '.join(names... |
import sys
class Justify(object):
def __init__(self, text, maxWidth):
self.words = text
self.maxWidth = maxWidth
def fullJustify(self):
"""
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
"""
text_len = len(self.words)
dp = [0... |
import dfs
def dfs_connected(graph):
connected_components = list()
discovered_nodes = set()
for node in graph.keys():
if node not in discovered_nodes:
connected = dfs.dfs(graph, node)
connected_components.append(connected)
discovered_nodes = discovered_nodes.union... |
def find_kth(A, B, k):
# Stopping condition is when only k elements are left in both the array
# return the max of the last elements
if len(A) > len(B):
A, B = B, A
if not A:
return B[k]
if len(A) + len(B) - 1 == k:
return max(A[-1], B[-1])
# invariant k = i + j
# se... |
import time
def dfs_recusive(graph, start):
visited = set()
def _dfs(node):
visited.add(node)
for next_node in set(graph[node]) - visited:
_dfs(next_node)
_dfs(start)
return visited
if __name__ == '__main__':
test_graph = {1: [2, 3, 4, 7],
2: [1, 3, ... |
import unittest
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.datastack = []
self.minstack = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
# insert into min stack
i... |
class Employee:
raise_amount=1
num_of_emps=0
def __init__(self,first,last,pay):
self.first=first
self.last=last
self.pay=pay
Employee.num_of_emps += 1
def fullname(self):
return'{}{}'.format(self.first,self.last)
def apply_raise(self):
self.pay=int(... |
class Employee:
pass
emp1=Employee()
emp1.first='satyam'
emp1.last='kumar'
emp1.job='sonus'
emp1.salary=60000
emp1.email='satyam.kumar@sonus.com'
print(emp1.first)
print(emp1.last)
print(emp1.job)
print(emp1.salary)
print (emp1.email)
print(emp1)
emp2=Employee()
print(emp2)
emp2.first='Shivam'
emp2.last='kuma... |
import sqlite3
app_senha="senha123@"
senha=input("Insira a senha: ")
if senha !=senha:
print("senha invalida ! encerrando...")
exit()
conn= sqlite3.connect("senhas.db")
cursor= conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
servico text not null,
usuario text not null,
senha interger n... |
_sum = 0
number = 0
while number < 20:
number += 1
if number == 10 or number == 11:
continue
_sum += number
print(number, end = " ")
print(_sum, end = " ")
|
# File: Goldbach.py
# Description: This is a program that displays all pairs of prime numbers that sum to equal a user defined number for a user defined range of numbers
# Student Name: Derek Orji
# Student UT EID: dao584
# Course Name: CS 303E
# Unique Number: 51845
# Date Created: 3/24/2017
# Date Las... |
s = input("Enter a string: ")
if len(s) % 2 == 0:
print(s, "contains an even number of characters")
else:
print(s, "contains an odd number of characters")
|
pay = eval(input("What is your pay? "))
score = eval(input("What is your score? "))
if score > 90:
pay = 1.03 * pay
print("For your efforts, your new pay is", round(pay, 3),"!")
|
year = 1
tuition = 10000
for year in range(0, 10):
year = year + 1
tuition = 1.05 * tuition
tuition10 = tuition
print(tuition10)
tuitioninitial = tuition10
year = 0
_sum = tuitioninitial
while year < 3:
year = year + 1
tuitioninitial = 1.05 * tuitioninitial
_sum += tuitioninitial
print(_sum)
|
# File: Benford.py
# Description: This program counts the frequency of the leading digit of a population sample
# Student Name: Derek Orji
# Student UT EID: dao584
# Course Name: CS 303E
# Unique Number: 51845
# Date Created: 4/29/2017
# Date Last Modified: 4/29/2017
def main():
# create an empty dict... |
def main():
filerandom = open("randomfile.txt", "w")
filerandom.write("I am the greatest basketball player that ever lived because I love to play basketball and basketball loves me, I love basketball basketball you dont love me basketball you hate me basketball lets rock and roll basketball yes")
filerandom.close()... |
import turtle
import math
line_size = 150
wn = turtle.Screen()
wn.bgcolor("lightgreen")
t = turtle.Turtle()
t.speed(1)
t.shape('turtle')
t.color('blue')
t.penup()
t.left(90)
t.stamp()
t.right((360/12)/2)
t.forward((line_size * 2 * math.pi)/12)
#t.forward(line_size/2)
t.stamp()
for i in range(9):
t.stamp()
t.... |
# count = 2
# while count<=15:
# print(count)
# count+=3
# print(count)
invalid_number = True
while invalid_number:
user_value = int(input("Enter a number above 10: "))
if user_value>10:
print("Thanks,thats wrks! is a great choice")
invalid_number = False
else:
print("ok")
... |
# def calculator(operation,a,b):
# if operation=="add":
# return a+b
# elif operation == "subtract":
# return a-b
# elif operation == "multiply":
# return a*b
# elif operation == "divide":
# return a/b
# else:
# return "Not sure about the answer"
# print(c... |
# 2016, Day 1.
# Input is a single line consisting of movement instructions separated by commas.
# Start facing north, each movement instruction dictates whether to turn left or
# right and then walking a certain distance on a manhattan grid.
#
# Part 1: Calculate final distance from starting point.
# Part 2: Determine... |
# 2016, Day 16.
# We fill a disk with non-random bits. This sequence of bits is constructed from
# a pattern that grows by reversion and inversion, using a method similar to the
# growth of the binary dragon curve.
#
# Approach: we don't need to expand the string, only generate its checksum. Each
# letter in the checks... |
# 2016, Day 3.
# Input is a table of numbers with 3 columns.
#
# Part 1: Count the rows that form a possible set of triangle numbers.
# Part 2: For each group of three lines, count the number of columns
# (of size 3) that form a possible set of triangle numbers.
NAME = "Day 3: Squares With Three Sides"
def triangli... |
"""
Problem Statement : https://www.hackerearth.com/practice/data-structures/hash-tables/
basics-of-hash-tables/practice-problems/algorithm/exists/
"""
from collections import deque
from sys import argv, stdin
def hash_insert(element, hash_table, size):
index = element % size
if hash_table[index] is not None:
ha... |
# Programma PERMUTAZIONI in Python
# Figura 10.8 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
def esamina(p):
print p
def permutazioni(p, k):
"""
Permutazioni degli elementi di un sottovettore p[k:n-1], estremi inclusi... |
# Programma ALBERTI in Python
# Figura 6.6 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
def alberti():
"""
Trasforma un messaggio nel relativo crittogramma
applicando il metodo di Leon Battista Alberti,
ove k e' la ... |
# Programma RICERCA_BINARIA in Python
# Figura 2.8 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
# carica le funzioni matematiche
import math
def ricerca_binaria(insieme, dato):
"""
Ricerca binaria di un elemento dato in i... |
# Programma TH_ITER in Python
# Figura 10.5 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
def th_iter(n, p):
"""
Algoritmo iterativo per risolvere il problema della Torre di Hanoi
L'ordine in cui si considerano i pioli e'... |
# Programma CARICA_RICERCA in Python
# Figura 2.6 del libro "Il Pensiero Computazionale: dagli algoritmi al coding"
# Autori: Paolo Ferragina e Fabrizio Luccio
# Edito da Il Mulino
# copia il programma ricerca2 dal file precedente
from ricerca2 import ricerca2
def carica_ricerca():
"""
Programma per interro... |
for value in range(0,5):
print(value)
#list将range转换为列表
numbers=list(range(1,6))
print(numbers)
squares=[]
for value in range(1,9):
square=value**2
squares.append(square)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))
##元组的元素不可更改,但是元组可以重新赋值
dimensions=(1,2)
#dimensions[0]... |
# Electronic Phone Book
# =====================
# 1. Look up an entry
# 2. Set an entry
# 3. Delete an entry
# 4. List all entries
# 5. Quit
# What do you want to do (1-5)?
# If they choose to look up an entry, you will ask them for the person's name, and then look up the person's phone number by the given name and pri... |
# Inheritance!
class Car(object):
def __init__(self, make, model, mpg):
self.make = make
self.model = model
self.mpg = mpg
def startCar(self):
print "%s goes vroom!" % self.make
myCar = Car('Ford', 'Fpics', 40)
myCar.startCar()
class Electric_Car(Car):
# call this obje... |
from tkinter import *
class App:
def __init__(self,master):
frame=Frame(master)
frame.pack()
self.button=Button(frame, text="Quit",fg="green",command=quit)
self.button.pack(side=LEFT)
self.slogan=Button(frame, text="hello Button", command = self.write_slogan)
self.s... |
from tkinter import *
import os
creds ="tempfile.txt"
def signup():
global pwordE
global nameE
global roots
roots = Tk()
roots.title("Sign Up")
instruction = Label(roots,text="Please enter your credentials\n")
instruction.grid(row=0,column=0,sticky=E)
namel = Label(roots,text="New ... |
# coding=utf-8
import sys
class SelfListNode(object):
def __init__(self,value,next_node):
self.node_value = value
self.next = next_node
def self_print(head):
while head != None:
print head.node_value
head = head.next
def self_revert(head):
... |
accounts = open("Usernamelist.txt", "r+")
print("Hello human!")
username = input("insert your username and password ")
if username in accounts:
print("Access completed")
else:
error = input("Username not found, if you are new, type \"sign up\" if you want to try login again, type \"login\" ")
i... |
from math import *
#Calculating range until inputed number
num = int(input("Input a number: "))
sum = 0
for i in range(num+1):
sum = sum + i
print("The sum is ", sum) |
#Apartments price
apartments_price = 1
apartments = []
sum_apartments = 0
while apartments_price > 0:
apartments_price = int(input("Apartment price: "))
if apartments_price > 0:
sum_apartments = sum_apartments + 1
apartments.append(apartments_price)
print("Apartment ", sum_apartments, ... |
#Garage company
drivers = 0
earnings = 0
while drivers >=0:
member = input("Are you a member? (yes/no): ")
if member == "yes":
cost = 1.5
elif member == "no":
cost = 3
hours = int(input("How many hours you have been parked?: "))
if 0 < hours <= 1:
hours_cost = 2
elif ... |
# This function set two values.
def main():
print('The sum of 12 and 45 is')
n1 = 12
n2 = 45
total = sum(n1, n2)
print(total)
# This function accepts two values and return the sum.
def sum(x1, x2):
result = x1 + x2
return(result)
# Calling the main program.
main()
|
# Simple I/O Program
# Name: Deborah Barndt / pgm1
print("Welcome to Python Programming!")
print("I'm here to assist\n")
FullName = "Jane Doe"
num1 = 88.581
print(format(num1, '7.2f'))
print(format(num1, '15.2f'))
amount_due = 5000.0
monthly_payment = amount_due / 12 # Divide the amount due by 12
print('The monthly ... |
'''
This program demonstrates Python GUI.
Name: Deborah
'''
import tkinter as tk
win = tk.Tk()
win.title('Python GUI')
tk.Label(win, text = 'A Label').grid(column = 0, row = 0)
def click_me():
action.configure(text = '*** I have been clicked! ***')
action = tk.Button(win, text = 'Click Me!', command = click_m... |
'''
Deborah Barndt
4-3-19
TestMain.py
hw9: Coffee Vending Machine
This program will create a vending machine that will tell the user how many
cups of coffee are available, the cost of one cup of coffee, and the total
amount of money that the user inserted into the machine. The machine will
require exact change.
Writt... |
'''
Deborah Barndt
2-6-19
CreditCardNumberValidation.py
hw3: Financial: Credit Card Number Validation
This program will ask the user to input their credit card number, then will
use Hans Luhn's algorithm to check if the card is valid or not valid. Once the
result is displayed, it will ask the user if they would like t... |
'''
Deborah Barndt
2-20-19
AlgebraMatrix.py
hw5: Question 2 Algebra Matrix
This program will prompt a user to enter two 3 x 3 matrices and display their
product.
Written by Deborah Barndt.
'''
# Function that will multiply two matrices given by the user.
def multiplyMatrix(a, b):
rowA = len(a)
colA = len(a[0... |
'''
These are just storing some basic data structure and algorithms.
After I practice leetcode, I'll add more to here.
'''
import numpy as np
# find x, or find the last element that is smaller than x
def BinarySearch(array,x):
l = 0
r = len(array)-1
while l < r:
mid = l+(r-l)/2
if array[mi... |
#!/usr/bin/python3
for character in range(97, 123):
if character is 113 or character is 101:
continue
else:
print("{}" .format(chr(character)), end="")
|
#!/usr/bin/python3
def uppercase(str):
for character in str:
if ord('a') <= ord(character) <= ord('z'):
character = chr(ord(character) + (ord('A') - ord('a')))
print("{:s}" .format(character), end="")
print("")
|
#!/usr/bin/python3
"""
mod 1-my_list contains class MyList
"""
class MyList(list):
""" define Mylist Class """
def __init__(self):
""" init the object """
super().__init__()
def print_sorted(self):
""" prints sorted list """
print(sorted(self))
|
#coding:utf-8
import time
def usetimeDecorate(fun):
def wrapper(num_list):
start_time = time.time()
num_list = fun(num_list)
print "Time:",time.time() - start_time
return num_list
return wrapper
def insertionSort(num_list):
"""
插入排序
思想:首先认为第一个数已经排好序,我们应该从第二个数开始,和前边排... |
import pytest
class TestList:
# Проверка метода len
def test_list_len(self):
a = list()
assert len(a) == 0
# Проверка создания списка
def test_list_create(self):
a = list()
assert a == list()
# Негативный тест умножения списков
def test_list_multiple(self):
... |
def calculator(num1, num2, cal):
if cal == "+" :
return num1 + num2
elif cal == "-":
return num1 - num2
elif cal == "/":
return num1 / num2
elif cal == "*":
return num1 * num2
num1 = int(input("숫자1 :"))
num2 = int(input("숫자2 :"))
cal = input("사칙연산 :")
print(calculator(nu... |
n = int(input("숫자를 입력하세요:"))
for i in range(n, 0, -1):
print(' '*(n -i), end ='' )
print('*'*(2*i-1)) |
inputed_star=int(input("별역삼각형 높이를 입력해주세요 -> "))
for i in range(inputed_star) :
print(" "*i+("*"*(inputed_star*2-1-2*i))) |
a = int(input("줄 수를 입력해주세요: "))
for i in range(a-1, -1, -1):
print(" "*(a-i-1)+("*"*(2*i+1)))
|
class calculator:
def sum(self, num1, num2):
return num1 + num2
def sub(self, num1, num2):
return num1 - num2
def mul(self, num1, num2):
return num1*num2
def div(self, num1, num2):
return num1/num2
class can_div_zero(calculator):
def div(self, num1, num2):
... |
most_add = None
most_count = None
results = dict()
filename = input('Enter a file name:')
try:
file = open(filename)
except:
print('Could not open file: ', filename)
quit()
for line in file:
if line.startswith('From:'):
words = line.split()
print(words)
results[words[1]] = results.get(words[1] , 0... |
def сollatz(n):
if n % 2 == 0:
return(n // 2)
else:
return(3 * n + 1)
number = int(input('Введите целое число\n'))
print()
list_number = []
while number != 1:
сollatz(number)
number = сollatz(number)
#print(number)
list_number.append(number)
print(list_number)
print('Число итер... |
from list import *
import random
class Implant:
def __init__(self):
self.implantParams = Stats()
self.implantName = 'Default Implant Name'
def get_name(self):
return self.implantName
def get_params(self):
return self.implantParams.get_params()
def create_by_random(self):
self.implantName = ""
self.... |
from controller import ControllerCadastro, ControllerLogin
while True:
print("========== [MENU] ==========")
decidir = int(input('Digite 1 para cadastrar\nDigite 2 para Logar\nDigite 3 para sair\n'))
if decidir == 1:
nome = input('Digite seu nome')
email = input('Digite seu email')
... |
# Use logistic regression to predict if a credit card application will be approved
# Project taken from DataCamp
# Data taken from http://archive.ics.uci.edu/ml/datasets/credit+approval
# Achieve a best score of 85.07%
# Import necessary modules
import pandas as pd
import numpy as np
from sklearn.preprocessing... |
print("hello world")
#this will not appear when executed
print("hello")
print(' hi ')
print("2 + 2")
print(2+2)
#variables
daniel = "Handsome"
print(daniel)
print("this guy is",daniel)
apple = 10
orange = 15
basket = apple + orange
bill = basket * 10
print("we've bought",apple,"apples")
#text names integer value
pri... |
# #FUNCTIONS
#
# def say_hi(name):
# """
# This function say hi to the name
# """
# print("Hi, {}".format(name))
# #
# say_hi("Don")
#
#
# print(say_hi.__doc__) # the doc is giving the text in quote marks inserted
# #the doc string exists even if nothing is inserted specifically for it
#
# #ANNOTATIONS
... |
import time
from numpy import matrix
def fib_con_matrice(n):
return (matrix(
'0 1; 1 1' if n >= 0 else '-1 1; 1 0', object
) ** abs(n))[0, 1]
def fibonacci(n):#la funzione calcola anche l'ennesimo negativo mediante la formula F -n = (-1)^(n+1) F n dove Fn e' l'ennesimo numero positivo di fibonacci... |
def row_sum_odd_numbers(n):
num = 0
a = ((n-1)*n)/2
for i in range (0, n):
num += 2 * a + 1
a += 1
print(num)
row_sum_odd_numbers(5)
|
import string
def rot13(message):
alfa_min = string.ascii_lowercase
alfa_max = string.ascii_uppercase
stringa = ""
for car in message:
if car not in alfa_min and car not in alfa_max:
stringa += car
else:
if car in alfa_min:
stringa += alfa_min[(alf... |
"""
Three 1's => 1000 points
Three 6's => 600 points
Three 5's => 500 points
Three 4's => 400 points
Three 3's => 300 points
Three 2's => 200 points
One 1 => 100 points
One 5 => 50 point
"""
from collections import Counter as ct
def score(dice):
a = ct(dice)
a1 = list(a)
a2 = list(a.v... |
def Kapracane(num):
iterazioni = 0
while(num != 6174):
stringa_1 = str(num)
stringa_2 = str(num)
stringa_1 = sorted(stringa_1, reverse = True)
stringa_2 = sorted(stringa_2)
stringa_1 = ''.join(stringa_1)
stringa_2 = ''.join(stringa_2... |
"""
Тестируется реакция нескольких объектов на нажатия одновременно,
в том числе и когда объекты пересекаются в момент нажатия
"""
from state import *
COUNT = 2000
BUTTON_NUM = 4
PAUSE = 1
RUN_TIME = 10
BUTTON_SETTINGS = {"lower_w": SCREEN_WIDTH/16, "lower_h": SCREEN_HEIGHT/16, "upper_w": SCREEN_WIDTH*3/16, "upper_... |
"""
В процессе разработки были выявлены некоторые сложности в навигации различных меню
Все эти сценарии были проанализированы и упрощены
Ниже рассматриваются различные сценарии пользовательских действий, а также дизайнерские решения, их покрывающие
"""
"""
Цель: пользователь не должен тратить более трёх нажатий мышкой... |
# -*- coding: utf-8 -*-
# import logging
# logging.basicConfig(level=logging.INFO)
# import pdb
# s = '0'
# n = int(s)
# # logging.info('n = %d' % n)
# pdb.set_trace()
# print(10/n)
def fact(n):
'''
Function to calculate n!
Example:
>>> fact(0)
Traceback (most recent call last):
...
Value... |
# -*- coding: utf-8 -*-
# class Student(object):
# def __init__(self, name):
# self.name = name
# def __call__(self,value):
# print('My name is %s %s ' % (self.name,value))
# s = Student("Michael")
# import debug.py
# fact(0)
# from collections import deque
# q = deque(['a','b','c'])
# q.append('x')
# q.app... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.