text stringlengths 37 1.41M |
|---|
"""
179. Update Bits
Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N start from i to j)
Example
Example 1:
Input: N=(10000000000)2 M=(10101)2 i=2 j=6
Output: N=(10001010100)2
Example 2:
Input: N=(100... |
"""
96. Partition List
中文
English
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example
Example 1:
Input: list = null, x = 0
Output: null
Expla... |
"""
54. String to Integer (atoi)
中文
English
Implement function atoi to convert a string to an integer.
If no valid conversion could be performed, a zero value is returned.
If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Example
Example 1
... |
"""
670. Predict the Winner
中文
English
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues u... |
"""
408. Add Binary
中文
English
Given two binary strings, return their sum (also a binary string).
Example
Example 1:
Input:
a = "0", b = "0"
Output:
"0"
Example 2:
Input:
a = "11", b = "1"
Output:
"100"
"""
class Solution:
"""
@param a: a number
@param b: a number
@return: the result
"""
... |
from typing import List
from cards.card import Deck, GameCard
class Player:
hand: List[GameCard]
id : int
def __init__(self, hand, id):
self.hand = hand
self.id = id
def draw(self) -> GameCard:
return self.hand.pop(0)
def out_of_cards(self) -> bool:
return len(s... |
import requests
import argparse
from bs4 import BeautifulSoup
def scrape(url):
page = requests.get(url)
assert page.status_code == 200
soup = BeautifulSoup(page.content, 'html.parser')
print("Overview: " + soup.article.find_all('h2')[0].nextSibling.text)
print("Symptoms: " + soup.article.find_all('h2')[1].nextSib... |
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 1 11:16:44 2018
@author:
"""
"""
KNN
(1) a description of how you formulated the problem:
Using knn algorithm, we will find n high-dimensional point which is nearst to the point we want to classify.Then, we will find out the label of most point we... |
'''
This program provides something....
* 1. draw a box around a region-of-interest (ROI) to crop
* 2. roi is stored to disk (./cropped/)
* 3. x, y, w, h coordinates of ROI are stored in a txt file (./labels/)
Usage:
crop.py [<some_args>, here]
v - view cropped ROI (separate window)
c - close ROI window
r - refresh ... |
def merge_sort(array, array_size):
# array list to be sorted
# buffer temporary space needed during merge
buffer = [None] * array_size
n_if_statements = 0
return merge_sort_helper(
array,
buffer,
0, array_size-1,
n_if_statements
)
def me... |
#Assignment 2: Algorithm Implementation and Analysis
#Abrie Halgryn
#Student number: 10496171
import time
#Question 1, 1(c):
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
n = len(arr)
#This will iterate through each item of the array - 1 the last element as it does no... |
#code adapted from http://automatetheboringstuff.com/2e/chapter10/
#import library
import os
#Enter '.' to specify current directory
#Otherwise enter directory_name/subdirectory_name
directory = input("Enter directory:")
#create text file
fname = "all_listings.txt"
fhandle = open(fname,'w')
#loop using os.walk()
for... |
import pandas as pd
import json
# you can use this as a script with a json response stored as a file, or can just use same indexing on raw JSON resonse from YNAB server
# if you wanted to do this as a function just declare function and include parameter 'json' that must be passed into the function
# read in json fil... |
#!/usr/bin/env python3
# created by: Ryan Walsh
# created on: January 2021
# this program calculates the volume of a hexagonal prism
import math
def calculate_volume(base_edge, height):
# calculates volume
# process & output
volume_of_hexagonal_prism = ((3 * (math.sqrt(3))) / 2 * (base_edge) ** 2 *
... |
#Suppose you want to put all your functions into a module for organization purposes
class Math:
@staticmethod #dont need self because it only defines functions within the class
def add5(x):
return x+5
print(Math.add5(10))
from inheritance import Pet
s = Pet("Joe", 30)
print(s.name) |
import numpy as np
board_setups = [
'random',
'magnetised',
'checkerboard',
'stripes',
'two sides'
]
class Ising:
board_setups = board_setups
def __init__(self,
N: int = 32,
T: float=1,
M: float=0,
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
... |
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
start, stop = 1, n
mid = (start + stop) // 2
... |
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
elif n == 2:
return 2
first, second, third = 1, 2, 3
for i in range(3,n+1):
third = first + second
first, second = second, third
re... |
class Solution:
def isValid_replacements(self, s: str) -> bool:
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('()','').replace('[]','').replace('{}','')
return s == ''
def isValid_stack(self, s: str) -> bool:
stack = []
hashmap = ... |
class Deque:
def __init__(self):
self.container = []
self.count = 0
def push_front(self, value):
self.container.insert(0, value)
self.count += 1
def push_back(self, value):
self.container.append(value)
self.count += 1
def pop_front(self):
... |
words = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ']
string = input()
cnt = 0
for i in range(len(string)):
for idx, j in enumerate(words):
if string[i] in j:
cnt += idx + 3
print(cnt) |
T = int(input())
for t in range(1, T+1):
N = int(input())
lst = [int(n) for n in input().split()]
lst = sorted(lst)
print(f"#{t} ", end = "")
for n in range(N):
print(lst[n], end = " ")
print() |
from collections import deque
def bfs(start, numbers, target):
q = deque([start])
cnt = 0
while q:
value, idx = q.popleft()
if idx == len(numbers):
if value == target:
cnt += 1
else:
q.append([value + numbers[idx], idx + 1])
... |
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado un numero real R, intercambiar la parte entera por la parte decimal,
Desplegar ambos números.
'''
nroReal = float(input("Introduzca un número(Real): "))
# Separamos la parte entera de la parte decimal utilizando la funcion parte entera
entera = int(nroReal)
# Mult... |
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado un número X hallar su cuadrado con la suma de sus X numeros impares,
desplegar los números impares y su cuadrado.
'''
import sys
x = int(input("Introduzca un número: "))
imp = 1
cx = 0
for ca in range(1, x + 1, 1):
cx = cx + imp
sys.stdout.write(str(imp)... |
# -*- coding: utf-8 -*-
'''
@author: Hector Cortez
Dado tres números A, B, C determinar y desplegar cual es el mayor.
'''
a = int(input("Introduzca el primer número: "))
b = int(input("Introduzca el segundo número: "))
c = int(input("Introduzca el tercer número: "))
if a > b:
if a > c:
print a, " es el may... |
#!/usr/bin/python
#Learning things about dictionary.
address = {
"Pincode":"272-0112",
"Country":"Japan",
"State":"Chiba",
"City":"Ichikawa",
"Street":"Shioyaki 2-1-35",
"Other":"Copo-Sunrse 105"
}
print address["Pincode"],
print addre... |
#!/usr/bin/python
#we can access nth element of list l
#by l[n]
#we can find lenght of list using len function
element = [1,2,3,4]
print "0th element is ",element[0]
string = "ABCDEFGH"
print "second char in string is ",string[2]
|
#!/usr/bin/python
#This time we explore more functions from file
#seek -> to move to position
#readline -> to read one line
#read -> read all data
#open -> to open a file
#and we user all this in functions
from sys import argv
script,filename = argv
def printAll(f):
print f.read()
def printOneLine(count,f):
print... |
#!/usr/bin/python
#Lets work with some pure logical statments
#and operators
#each print statment prints logic result of following statments
print True and False
print True and (0 == 0)
print True or (0 == 0)
print 1 == 1 and True
print 1 == 1 and False
print "test" == "test"
one = "test"
two = "test"
print one ... |
def display(hash_table):
for i in range(len(hash_table)):
print(i, end = " ")
for j in hash_table[i]:
print("->", end = " ")
print(j, end = " ")
print()
def hash(key):
return key % len(hash_table)
def insert(hash_table, key, value):
hash_key = hash(key)
... |
# Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
def __init__(self):
self.head = None
def deleteNode(self, data):
temp = self.head
prev = self.head
if temp.data == dat... |
def parse_years(years):
years_list = years.split(",")
for year in years_list:
if "-" in str(year):
start, end = year.split("-")
years_list.remove(year)
years_list.extend(range(int(start),int(end) + 1))
years_list = list(map(int, years_list))
return years_lis... |
name = input("Enter Name : ").strip()
with open("name.txt","w") as fname:
fname.write(name)
print("--------")
print("Reading file : name.txt")
namefound = open("name.txt","r").read()
print("Your name is : %s" % namefound)
print("--------")
print("Writing 17 & 42 inside number.txt")
with open("numbers.txt","w") a... |
"""
taylor expansion examples
https://en.wikipedia.org/wiki/Taylor_series
taylor approximation of exponential function
exp(x) ≅ x^0 / 0! + x^1 / 1! + x^2 / 2! + x^3 / 3! + ...
taylor approximation of logarithmic function
log(1 - x) ≅ -x - x^2/2 - x^3/3 - ...
"""
import numpy as np
def taylor_exp(x, k=3):
ap... |
#Variables allow us to add trainable parameters to a graph. They are constructed with a type and initial value
import tensorflow as tf
W = tf.Variable([.3], dtype=tf.float32)
b = tf.Variable([-.3], dtype=tf.float32)
x = tf.placeholder(tf.float32)
lenear_model = W * x + b
#variables are not initialized when you cal... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
cnt = 0
def countUnivalSubtrees(self, root: TreeNode) -> int:
#print(root.val)
if (root==None) :
return 0
s... |
class Solution:
"""
@param source: the input string
@return: the number of subsequences
"""
def countSubsequences(self, source):
# write your code here
blist = []
# first B
acnt, ccnt = 0,0
foundB = False
firstbindex = 0
for i in ran... |
class QuickSort:
def quicksort(self,arr):
self.sort(arr,0,len(arr) - 1)
return arr
def sort(self,arr,left,right):
if right <= left:
return
low = left
high = right
pivot = arr[low]
while left < right :
while left < right and arr[rig... |
#!/usr/bin/python3
from MySameTree import TreeNode;
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findBottomLeftValue(self, root):
"""
:type root: ... |
import numpy as np
# Create a range with min, max, and step
a = np.arange(10, 30, 5)
print(a) # [10 15 20 25]
b = np.arange(0, 2, 0.3)
print(b) # [0. 0.3 0.6 0.9 1.2 1.5 1.8]
# Create a evenly spaced numbers
c = np.linspace(0, 2, 9)
print(c) # [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2.]
# Function evalua... |
import math
def soma(x: float, y: float) -> float:
return x + y
def main() ->None :
num = input('Entre com o numero: ')
try:
raiz = math.sqrt(int(num))
except (ValueError, EnvironmentError, SyntaxError, NameError) as E: # catch multiple exception
print(E)
print('Erro: Somente ... |
sum = lambda x, y: x + y
print(sum)
print(sum(4, 5))
can_vote = lambda age: True if age >= 18 else False
print(can_vote)
print(can_vote(17))
print(can_vote(19))
powerlist = [lambda x: x ** 2,
lambda x: x ** 3,
lambda x: x ** 4]
for func in powerlist:
print(func(4))
####... |
courses = ['History', 'Math', 'Physics', 'CompSci']
teste = list(['Gato', 'Macaco', 'Leao', 'Zebra'])
# print(type(courses))
# print(courses)
# print(type(teste))
# print(teste)
# print(courses[0])
# print(courses[1])
# print(courses[2])
# print(courses[3])
# print(courses[-1]) # ultimo registro
# pri... |
import random
l = [0, 1, 2]
new = zip("ABC", l)
print(new) # [('A', 0), ('B', 1), ('C', 2)]
new = map(lambda x: x * 10, l)
print(new) # [0, 10, 20]
new = filter(None, l)
print(new) # [1, 2]
# um gerador eh um objeto iteravel:
for par in zip('ABC', l):
print(par)
# para criar a lista, basta... |
def greet_me(**kwargs):
if kwargs is not None:
for key, value in kwargs.iteritems():
print("%s == %s" % (key, value))
greet_me(name = "yasoob", idade = 30)
def table_things(**kwargs):
for name, value in kwargs.items():
print('{0} = {1}'.format(name, value))
table_... |
#Import necessary module
from termcolor import colored
#Initialize a text variable
text = "Colored text using Python"
#Print the text with font and background colors
print(colored(text, 'red', 'on_cyan'))
|
""" DECORATORS
Nested Decorators
Class decorators
Note: Using functools.wraps retains original function's name and module
"""
from functools import wraps
def ex_decorator(func):
""" Decorator pattern """
@wraps(func)
def wrapper_decorator(*args, **kwargs):
# Do something before
... |
/* Task 1 */
def SomeFunction(n):
y = n**2 + 3*n + 1
return y
acc=0
for i in range(2, 6):
print(SomeFunction(i))
if i < 5:
print('+')
else:
print('=')
acc = acc + SomeFunction(i)
print(acc)
/* Task 2 */
import math
def taylor(x):
series = 0
for n in range (16):
... |
"""
Clone of 2048 game.
"""
import poc_2048_gui
from random import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1, 0),
LEFT: (0, 1),
... |
"""
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
class Puzzle:
"""
Class representation for the Fifteen puzzle
"""
def __init__(self, puzzle_height, puzzle_width, initial_... |
#to generate the text character by character after training the model
#importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import config as cf
import models as md
#importing tenserflow libraries
import tensorflow as tf
from tensorflow.keras.models import Sequential
... |
from abc import ABC, abstractmethod
import requests
class HTTPRequestor(object):
"""The goal of the requestor object is to enable communication with a service in different ways.
The requestor needs to implement the CRUD methods.
Then the use would be as follows:
req = Requestor()
service = Service... |
import turtle
def drawSun():
"""
Draws a square, a circle, and then a triangle.
"""
def drawSquare(squareTurtle):
"""
Draws a white, filled square 100 pixels long with a white square cursor
"""
#color squareTurtle, its lines, and the filling of its square white, and mak... |
def most_prolific(albums):
"""
Takes a dictionary with values formatted {'title': year} and returns
the year that occurs most often among the elements. IF there are years
that occur the same number of times, it returns a list of years.
years: dictionary. Holds the years albums were published and the... |
import re
def create_cast_list(filename):
"""
Takes a cast list from IMDB and pulls a string up to the first comma
(actors' names), and puts that string into a list, which gets returned.
filename: txt file. The file containing the cast list
"""
cast_list = []
#use with to open the file fil... |
class Node:
def __init__(self, x):
self.value = x
self.children = None
class Queue:
def __init__(self):
self.internal_ds = []
def enqueue(self, x):
if x is not None:
if isinstance(x, list):
self.internal_ds = self.internal_ds + x
elif isinstance(x, NodeLevel):
self.internal_ds = self.internal... |
if __name__ == "__main__":
string = input()
parts = input().split()
string_as_list = list(string)
index = int(parts[0])
print("".join(string_as_list[:index] + [parts[1]] + string_as_list[index+1:]))
|
tuple = (4, 'one item', -8)
def print_all(t):
for item in t:
print(item, end=' ')
print()
# sort() doesn't work on tuple
def sort_tuple(t):
t.sort()
print_all(tuple)
print(len(tuple))
print(tuple[0])
print(tuple[len(tuple)-1])
print_all((1, 2, 3, tuple))
print(tuple[0])
# sort_tuple(tuple)
... |
if __name__ == "__main__":
command_cnt = int(input())
lst = []
while command_cnt:
parts = input().split()
cmd = parts[0]
if cmd == "insert":
index = int(parts[1])
element_to_insert = int(parts[2])
lst = lst[:index] + [elemen... |
def sort_by_first_element_then_by_():
q = [[1, 'd'], [0, 'b'], [1, 'c']]
print(q)
print(sorted(q, key=lambda x: (x[0], x[1])))
if __name__ == "__main__":
# sort_by_first_element_then_by_()
stdnt_cnt = int(input())
stdnt_list = []
while stdnt_cnt:
stdnt_list.append([input(), f... |
import os
def write_to_file(lines, file_name):
if lines:
with open(file_name, 'w+') as f:
new_line = '\r\n'
for x in lines:
f.write(x + new_line)
f.write(new_line)
def copy_and_remove(file_to_copy):
import shutil
im... |
from collections import deque
if __name__ == "__main__":
n = int(input())
dq = deque()
for _ in range(n):
parts = input().split()
op, v = parts[0], int(parts[1]) if len(parts) == 2 else None
if op == "append" and v is not None:
dq.append(v)
elif op == "pop":
... |
import copy
class GoodBus():
def __init__(self, passengers):
self._passengers = copy.deepcopy(passengers) if passengers else []
def pick(self, p):
if p:
self._passenger.append(p)
def drop(self, p):
if p:
self._passengers.remove(p)
def __repr__(self):... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
# 9
# 1 2 3 4 5 6 7 8 9
# 10 11 21 55
# 1 2 3 4 5 6 7 8 9 10 11 21 55
input()
list_one = set(input().split())
input()
list_two = set(input().split())
unioned = list_one.union(list_two)
print(len(unioned))
|
import collections
def convert_to_collection(iterator):
if iterator:
return collections.Counter(iterator)
def find_uniqueness(seq):
if seq:
for _, count in collections.Counter(seq).items():
if count > 1:
return False
return True
return None
def find_... |
class Solution(object):
def getConcatenation(self, nums):
if nums:
i = 0
l = len(nums)
while i < l:
nums.append(nums[i])
i = i + 1
return nums
s = Solution()
assert s.getConcatenation([1]) == [1, 1]
assert s.getCon... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def traverse_leaf(self, tree_root):
if not tree_root:
return None
else:
left_ret = self.traverse_leaf(tr... |
class MyQueue:
def __init__(self):
self.internal_stack = []
def push(self, x):
self.internal_stack.append(x)
def pop(self):
popped_element = self.internal_stack[:1]
self.internal_stack[:] = self.internal_stack[1:]
return popped_element[0] if popped_element else No... |
def loop(n):
if n is not None:
return [x * x for x in range(n)]
if __name__ == "__main__":
n = int(input())
for x in loop(n):
print(x)
|
class Solution:
def is_alphanumeric(self, c):
c = c.lower()
return (ord(c) >= 97 and ord(c) <= 122) or (ord(c) >= 48 and ord(c) <= 57)
def isPalindrome(self, s):
if s is not None:
s = list(s)
head = 0
tail = len(s) - 1
while head < tail:... |
'''
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
'''
class Solution(object):
... |
'''
Converts various weightings between 0 and 100 to an actual amount to stress particular resource to
ALL UNITS IN BITS
All functions accept:
1.) Current allocation of resource
2.) Percentage to change resource.
- A positive number means to increase the resource provisioning by a certain amount.
- A negative numb... |
from random import *
import os
def enemy_score_gen():
enemy_score = randint(1,21)
return enemy_score
def random_card_picker():
card_value = randint(1, 11)
return card_value
def game_starting():
global decision
print("Hello in blackjack! Your goal in blackjack is to get higher sco... |
import sys
#print "Nbr args : %d" % (len(sys.argv))
if len(sys.argv)>=3:
readfrom=sys.argv[1]
writeto=sys.argv[2]
else:
print("Syntax: python %s <file_to_read> <file_to_write> [<id_label> <rest_of_cols> ['<char_sep>'] ]" % sys.argv[0])
print(" <rest_of_cols> : columns to include in output file (ex: 1,2,3), starti... |
v=[[1, 1], [2, 2], [1, 2]]
v2=[[1, 4], [3, 4], [3, 10]]
def solution(v):
x=list()
y=list()
for i in range(len(v[0])):
for j in range(len(v)):
if i==0:
x.append(v[j][i])
elif i==1:
y.append(v[j][i])
print(y)
result=list()
try:
... |
triangle=[[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]
def solution(triangle):
sum=[[0]*len(line) for line in triangle]
for i in range(len(triangle)):
for j in range(len(triangle[i])):
if(j==0):
sum[i][j]=sum[i-1][j]+triangle[i][j]
elif(i==j):
... |
def fibo(num):
F=[0]*num
if num>0:
F[1]=1
for i in range(2,num):
F[i]=F[i-1]+F[i-2]
return F
if __name__ == "__main__":
max_num=15
Fibo_num=fibo(max_num+1)
for i in range(max_num+1):
print("Fibo( {}) = {}".format(i,Fibo_num[i]))
|
import turtle as t
import random as rd
height=300
width=300
def draw_screen():
screen=t.Turtle(visible=False)
screen.speed("fastest")
screen.penup()
screen.goto(-width,-height)
p=screen.pos()
screen.write(str(p),False)
screen.pendown()
screen.goto(width,-height)
p=screen.pos()
... |
def Divisors(num):
divisors=list()
# 항상 범위 생각할것
for i in range(1,num+1):
if num%i==0:
divisors.append(i)
return divisors
def Perfect_Numbers(num):
perfect_nums=list()
for i in range(2,num):
temp=Divisors(i)
if temp.pop()==sum(temp):
... |
## These are the steps that need to be followed
## Write out the pairs and singles
## Put the pairs above the single column
## If this is a valid partition, you're done, otherwise
## Shift the stuff below the pairs that are less than (3, 4, 6 ... 2, 5)
## the greatest left element of the pairs upwards, pushing stu... |
class Stack:
def __init__(self):
self.stack = []
self.top = -1
def push(self, data):
self.stack.append(data)
self.top += 1
def pop(self):
temp = self.stack[self.top]
del self.stack[self.top]
self.top -= 1
return temp
def __str__(... |
def fib(index):
if index in {0, 1}:
return index
else:
return fib(index-1) + fib(index-2)
print([fib(i) for i in range(10)][::-1])
|
import datetime
import jarvis as jv
import smtplib # this module is used to send email through gmail but for that you have to
import json
import pywhatkit
def wishMe():
'''
This function can greet you as per time
'''
hour = int(datetime.datetime.now().hour)
if hour >= 0 and hour <12:... |
# Solved HW Budget Data
# Approach is to create a third list with the monthly delta in Profit/Losses
import csv
month_date = []
monthly_profit = []
monthly_delta =[0]
with open('budget_data.csv','r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
csv_header = next(csvreader)
print(f"CSV Hea... |
# https://www.youtube.com/watch?v=iV-4F0jGWak&list=PLU8oAlHdN5BlvPxziopYZRd55pdqFwkeS&index=10
print("Programa de evaluacion de notas de alumnos")
nota_Alumno=input("Introduce la nota del alumno: ")
def evaluacion(nota):
valoracion="aprobado"
if nota<5 :
valoracion="Suspendido"
return valoracion... |
#Libreria de matematicas match
import math
def calculaRaiz(num1):
if num1 <0:
raise ValueError("El numero no puede ser negativo")
else:
return math.sqrt(num1)
op1= int(input("Digite un numero: "))
try:
print(calculaRaiz(op1))
except ValueError as ErrorDeNumeroNegativo:
... |
import random
def numAleatorio(num1,num2):
resultado = random.randint(num1,num2)
return resultado
respuesta = input("¿Quieres un numero de la suerte? S/N --> ")
while respuesta != "S" and respuesta != "N" and respuesta != "s" and respuesta != "n":
respuesta = input("ERROR: debes digitar 'S' o 'N':")
... |
from collections import deque
from random import shuffle
def max_window(arr, k):
dq = deque()
out = []
for i in range(len(arr)):
if dq and dq[0] <= i - k:
dq.popleft()
while dq and arr[dq[-1]] < arr[i]:
dq.pop()
dq.append(i)
if i >= k - 1:
... |
"""
compute running median
"""
import heapq
def balance(bottom_half, top_half):
if len(bottom_half) > len(top_half):
promote = -1*heapq.heappop(bottom_half)
heapq.heappush(top_half, promote)
if len(bottom_half) < len(top_half):
demote = heapq.heappop(top_half)
heapq.heappush(bo... |
"""
Saya Sudirman Nur Putra mengerjakan Tugas Praktkm 3 dalam Praktikum Desain dan Pemrograman Berorientasi Objek untuk
keberkahan-Nya maka saya tidak melakukan kecurangan yang seperti yang telah dispesifikasikan. Aamiin
"""
# mengimfor library
from Biodata import Biodata
from tkinter import *
data = ... |
#!/usr/local/bin/python3
import sys
from Field import Field
from queue import Queue
class MineSweeper():
def __init__(self, num_cols, num_rows, num_mines):
self._num_cols = num_cols
self._num_rows = num_rows
self._field = Field(num_cols, num_rows, num_mines)
self._image = []
... |
import socket
import string
import secrets
def string_to_binary(parametru):
res = ''
for x in parametru:
aux = format(ord(x), 'b')
while len(aux) < 8:
aux = '0' + aux
res += aux
return res
def binary_to_string(parametru):
rezultat = ''
for i in range(0, len(para... |
#mayor_menor
i = 1
mayor=0
menor=0
suma=0
while i<=3:
numero = int(input(" ingresen un numero " + str(i) + "= "))
if numero >= 0:
if numero > 0:
if numero> mayor:
mayor =numero
if numero < menor or i == 1:
menor = numero
if i==1:
... |
#hdg
numero=int(input("ingrese un numero ="))
print("los numeros son:")
for n in range(1,numero,2):
print(n)
for i in range(0,numero,2):
print(-i) |
#ecuacion cuadratica
a=float(input("ingrese el valor de a = "))
b=float(input("ingrese el valor de b = "))
c=float(input("ingrese el valor de c = "))
discriminante= b**2-4*a*c
if discriminante < 0 :
print("no tiene soluciones reales")
elif discriminante==0:
x = -b / (2 *a)
print ("la solucion unica es x = "... |
#indicar ciertas cantidades
suma=0
suma2=0
suma3=0
suma4=0
suma5=0
i=1
n=int(input("ingrese la cantidad de numeros que quiere digitar = "))
while i<=n:
numero = int(input(" ingresen un numero " + str(i) + "= "))
if numero <=0:
suma= suma+1
if numero >=0:
suma2= suma2+1
if numero%2 ==0:
... |
#cadena invertida utilizando la posicion
frase=str(input("ingrese la frase que desee invertir = "))
print(frase [::-1 ]) |
kj#numero por cual es divisible
numero=int(input("ingrese un numero = "))
if numero%2==0:
print("el numero es divisible por 2")
if numero%3==0:
print("el numero es divisible por 3")
if numero%5==0:
print("el numero es divisible por 5")
if numero%7==0:
print("el numero es divisible por 7")
if numero%9==0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.