text
stringlengths
37
1.41M
def seslisessiz(cumle): liste = ["a", "e", "ı", "i", "o", "ö", "u", "ü"] seslisayilar = 0 sessizsayilar = 0 for i in cumle: if i in liste: seslisayilar += 1 else: sessizsayilar += 1 print(f"Sesli sayilar : {seslisayilar} \nSessiz sayilar : {sessizsayilar}") ...
# 1 ile 1000 arasindaki tek sayilar ile çift sayilarin toplam adedini ekrana yazdiriniz. i = 1 toplam1 = 0 toplam2 = 0 while (i <= 1000): if (i % 2) == 0: toplam1 += i else: toplam2 += i i += 1 print("Cift sayilarin toplami : ", toplam1) print("Tek sayilarin toplami : ", toplam2)
# Karar yapilari # Karsilastirma Operatorleri # == (esit esittir) soldaki degerin, sagdaki degere esit olma durumu # 1 == 1 => true - if # 1 == 2 => false - else # != (esit degildir) soldaki degerin sagdaki degere esit olmama durumu # 1 != 1 => false - else # 1 != 2 => true - if # > (buyuktur) soldaki degerin sagdak...
# Kullanici disaridan not degerini girecek ve girilen not 0'dan kucukse, 0'dan kucuk not giremezsiniz uyarisi, 100'den buyukse 100'den buyuk not girisi yapamazsiniz uyarisi, girilen no 0'a veya 100'e esit veya kucukse notu gosteriniz. try: x = float(input("Lütfen notunuzu giriniz : ")) if (x < 0): ...
# While control statement x = 1 while x <= 10: print("x = {}".format(x)) x = x + 1 print("**********************************************") # For control statement with range # range(start, stop, increment) r = range(0, 20, 3) # This will print sequence 0, 3, 6,.... 18 for i in r: print("i = {}".format(i))...
#NOTES ON PANDAS LANGUAGE#################################### # Complete cheatsheet at https://elitedatascience.com/python-cheat-sheet ############################################################# import pandas as pd import numpy as np ######################################################################### #BASIC ...
import matplotlib.pyplot as plt def sort_col_to_arrays(jobs_df, column_name): x_counts = [] x_names = [] for name in jobs_df[column_name].unique(): num_counts = len(jobs_df[jobs_df[column_name] == name]) x_counts.append(num_counts) x_names.append(name) # Sort two columns for so...
1 nums = [1, 2, 3, 4, 5 ] my_list = [x ** 2 if x == 5 else x * 2 for x in nums] #2 my_string = "Hello from the otherside" stripped = my_string.strip() #3 new_list = [1,2,3, "text", 7, 10] filtered = list(filter(lambda x: isinstance(x, int), new_list)) #4 def what_to_buy(item, *args, **kwargs): if 'store' in kwa...
import os from copy import deepcopy import random import multiprocessing import numpy as np from PIL import Image,ImageDraw #from IPython.display import display POP_PER_GEN= 50 #number of canvases generated per round, i.e. generation MUTATION_CHANCE=0.04 #self explanatory... this is a threshold, ADD_GENE_CHANCE = 0....
# -*- coding: utf-8 -*- __author__ = 'sebastian kihle' __email__ = 'sebaskih@nmbu.no' from walker_sim import Walker, Simulation class BoundedWalker(Walker): def __init__(self, start, home, left_limit, right_limit): """ Initialise the walker Arguments --------- start : in...
import turtle # bg: window = turtle.Screen() window.title("Pong") window.bgcolor("black") window.setup(width=800, height=600) window.tracer(0) # stops window from updating - speed up game # score score1 = 0 score2 = 0 # paddle 1 paddle1 = turtle.Turtle() paddle1.speed(0) # speed of animation - max paddle1.shape("s...
import csv input_file='week-1-code/stocks.csv' csv_file = open(input_file) csv_row_reader = csv.reader(csv_file, delimiter=',' ) for row_index, row in enumerate(csv_row_reader): row_string = "In Row #" + str(row_index) print(row_string) print(row) if (row_index == 0): continue ...
def main(): for i in generate_numbers(): display_str = handle_number_fizz(i) # display_str = handle_number_nice(i) print(display_str) def generate_numbers(): return range(1,101) def handle_number_nice(input): if is_divisible(input,3 ) and is_divisible(input,5): ret...
def fizzbazz(): for i in range(1, 100): i_mod3 = i % 3 == 0 i_mod5 = i % 5 == 0 if i_mod3 and i_mod5: str = "FizzBuzz" elif i_mod3: str = "Fizz" elif i_mod5: str = "Buzz" else: str = i print(str) def ss(number_...
#!/usr/bin/env python # -*- coding: utf-8 -*- def saut_de_ligne(n): for i in range(0, n - 1): print("\n") def tab(n): result = "" for i in range(0, n - 1): result += "\t " return result infos = ["nom_prenom", "adresse", "code_postal", "num_phone",\ "email"] title = tab(2) + "Obje...
#---------------------------------Stack Time Complexity------------------------------------ # Insertion - O(1) # Removal - O(1) # Searching - O(n) # Access - O(n) class Node(): def __init__(self,val): self.val = val self.next = None class Stack(): def __init__(self): self.firs...
class Node: def __init__(self, val): self.val = val self.left = None self.right = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, val): newNode = Node(val) if not self.root: self.root = newNode ...
#Dp to find no of paths in given array of size n*m def npaths(n, m, memo={}): key = str(n) + "," + str(m) if key in memo: return memo[key] if n == 0 or m == 0: return 0 if n == 1 and m == 1: return 1 memo[key] = npaths(n-1,m) + npaths(n,m-1) return memo[key] print(npaths(2,3)) ...
""" https://www.hackerrank.com/challenges/big-sorting/problem """ def big_sorting_solve(n, x): result = sorted(x, key=lambda x: int(x)) return result if __name__ == "__main__": print("result = ", big_sorting_solve(6, ['31415926535897932384626433832795', '1', '3', '10', '3', '5']))
def solve(a, b): pivot = a if pivot < b: pivot = b max = 0 for i in range(1, pivot + 1): if a % i == 0 and b % i == 0: max = i if i == a or i == b: break return max if __name__ == '__main__': print(solve(280, 30))
"""This is the model class along with other smaller class This is being imported to the main.py file """ import pygame from pygame.locals import * import random import math import time import numpy as np import copy from tree import Tree,Node import aitree import time class Model(object): """ Encodes the game sta...
# This is the structure of the bucketlist from app.bucketlist.bucketlist_item import BucketListItem class BucketList: ''' The bucketlist object ''' def __init__(self, name, details=None, items=None, owner=None): ''' Constructing and instance of the object ''' self.name = name self.d...
# Exercise 03: Numbers and Math - Study Drills. # Prints the message "I will now count my chickens:" print("I will now count my chickens:") # Prints "Hens" and the result of (25 + (30 / 6)) print("Hens", 25.0 + 30.0 / 6.0) # Prints "Roosters" and the result of (100 - (25 * (3 % 4))) print("Roosters", 100.0 - 25.0 * ...
# Exercise 23. Strings, Bytes, and Character Encodings - Study Drills # Download command: # powershell -command "& { iwr https://learnpythonthehardway.org/python3/languages.txt -OutFile languages.txt }" # DBES - Decode Bytes, Encode Strings # bytes.decode() => String # string.encode() => bytes import sys script, encod...
# Exercise 42. Is-A, Has-A, Objects, and Classes - Study Drills ## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): def __init__(self, group): self.group = group def make_sound(self, animal="animal", sound="Muted"): print(f"The {animal} sounds {so...
# Exercise 26. Congratulations, Take a Test! - Original Code print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') # TODO: Close the parenthesis and correct typo print("How much do you weigh?", end=' ' weight = input() # TODO: Define height previously print(f"So, you're {age} old, {heig...
# 1) Implement Python's Range() Function. x= range(3, 20, 2) for n in x: print(n) # 2) Write the generator Function to print prime Numbers. def prime_num(n): prime=True i=2 while(i<n): for a in range(2,i): if(i%a==0): prime=False break if(prim...
'''Escreva um algoritmo que leia dois valores e imprima na tela o resultado da multiplicação de ambos.Entretanto, para calcular a multiplicação, utilize somente operações de soma e subtração (Menezes; Nilo, p. 88). Lembrando que uma multiplicação pode ser considerada como um somatório sucessivo. Utilize essa lógic...
'''Escreva um algoritmo que calcule a média dos números pares de 1 até 100 (1 e 100 inclusos). Implemente o laço usando for''' soma = 0 cont = 0 for c in range(1,101): if c % 2 == 0: soma = soma + c cont = cont + 1 media = soma/cont print('A média dos valores pares de 1 até 100 é: {}....
'''Desenvolva um algoritmo que solicite ao usuário uma quantidade de dias, de horas, de minutos e desegundos. Calcule o total de segundos resultante e imprima na tela para o usuário.''' n1 = int(input('Quantos dias: ')) n2 = int(input('Quantas horas: ')) n3 = int(input('Quantos minutos: ')) n4 = int(input('Qua...
'''Expressões booleanas Escreva as seguintes expressões booleanas em linguagem Python: a) O somatório de 2 com 2 é menor do que 4 b) O valor 7 // 3 é igual a 1 + 1 c) A soma de 3 elevado ao quadrado com 4 elevado ao quadrado é igual a 25 d) A soma de 2, 4 e 6 é maior do que 12 a) 1387 é divisível por 19 b) 3...
#use try-except cycle to show users of your function the limitations #def sqrt(x): # try: # return x**0.5 # except: # print('x must be an int or a float') #n=float(input()) #print(sqrt(n)) #def sqrt(x): # try: # return x**0.5 # except TypeError: # print('x must be a...
# @Time : 2019/6/12 12:48 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseBetween(self, head: ListNode, m: in...
# @Time : 2019/5/16 19:30 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ class Solution: def mySqrt(self, x: int) -> int: low, high = 0, x while low <= high: mid = low + ((high - low) >> 1) if mid ** 2 > x: high = mid - 1 elif...
# @Time : 2019/5/28 14:46 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List from collections import deque class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ if no...
# @Time : 2019/7/20 13:13 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List def radix_sort(nums): n = len(str(max(nums))) for i in range(n): buckets = [[] for _ in range(10)] for num in nums: idx = num // 10 ** i % 10 buckets[i...
# @Time : 2019/6/6 9:15 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import Optional # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next class Solu...
# @Time : 2019/6/23 13:38 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self,...
# @Time : 2019/5/29 9:40 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List from collections import Counter, defaultdict class Solution: # 超时 def groupAnagrams(self, strs: List[str]) -> List[List[str]]: res = [] if not strs: return res cnt = []...
# @Time : 2019/5/28 10:48 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List, Optional # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sortedArray...
# @Time : 2019/6/29 9:24 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: dummy ...
# @Time : 2019/6/6 13:53 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List class Solution: # 使用了额外空间 def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify board in-place instead. """ if not board or n...
# @Time : 2019/5/10 15:49 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ class Solution: def reverseWords(self, s: str) -> str: s = s.strip() words = s.split() return ' '.join(words[::-1]) if __name__ == '__main__': ss = "the sky is blue" s = Solution() pr...
# @Time : 2019/6/6 8:06 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in r...
# @Time : 2019/6/12 12:11 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ class Solution: def lengthOfLastWord(self, s: str) -> int: words = s.split() return len(words[-1]) if words else 0 def lengthOfLastWord1(self, s: str) -> int: length, last = 0, True fo...
# @Time : 2019/6/2 19:00 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ class Solution: # 超时 def canWinNim(self, n: int) -> bool: memo = {} def recur(n: int) -> bool: if n <= 3: return True if n in memo: return memo[n] res = [] ...
# @Time : 2019/5/24 19:13 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import List class Solution: # 日常超时 def maxArea(self, height: List[int]) -> int: if not height: return 0 max_area = 0 for i in range(1, len(height)): for j in range(i):...
# @Time : 2019/6/17 7:40 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import Optional # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def insertionSortList(self, head: ListNode) -> L...
# @Time : 2019/6/1 14:33 # @Author : Xu Huipeng # @Blog : https://brycexxx.github.io/ from typing import Optional # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 愚蠢的写法 def mergeT...
""" Use boolean variables to control program logic between two different code paths. """ import turtle from tkinter import messagebox, Tk if __name__ == '__main__': # TODO) # 1. Use a boolean variable to indicate if it is the weekend. # Display a different message to the user depending on whether it i...
import numbers import re import queue import numpy import stack import operator_calc import function_calc class Calculator: """ Calculates an expression written in text format """ def __init__(self): self.operators = { "add": operator_calc.Operator( numpy.add, 0), "subtrac...
import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('whatsapp-group-data.csv', index_col=0) df1 = df.groupby('date')['date'].count().reset_index(name="messages") df2 = df1.sort_values('messages', ascending=False) print("Busiest days") print(df2.head(10)) print("\n" * 3) print("L...
print('hola') print("son las 8 pm") print("seguimos con los nuevos comandos") a = 23 b = 23 c = a + b print(c) # comandos que se me habían olvidado # if print("escribe galletas") a = input() """es de las cosas que no entiendo apoco se puede hacer eso en serio que no sabía """ print(a)
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- # @Author: yangyuyi # @E-mail: TaroYoung2000@gmail.com # @Date: 2019-08-22 14:56:59 # @Last Modified by: yangyuyi # @Last Modified time: 2019-08-22 15:00:47 sum=0 for i in range(2,100): for j in range (2,int(i**0.5)+1): if (i%j==0): break ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Feb 24 16:46:30 2018 @author: ndanneman """ #%% import numpy as np import copy # Let's play some random games of connect-4 # 6 rows and 7 colums # board is a matrix of zeros. # one color is 1, the other is -1 # an entire game is an array of matrice...
def len_valid_alternates(text, char_one, char_two): mates = {} mates[char_one] = char_two mates[char_two] = char_one is_valid = True expected = None for letter in text: if letter not in mates: continue if expected is None: count = 1 expected ...
def mergesort(arr, start, end): if start >= end: return mid = (start + end) // 2 mergesort(arr, start, mid) mergesort(arr, mid + 1, end) merge(arr, start, mid, end) def merge(arr, left_start, left_end, right_end): right_start = left_end + 1 left = left_start right = right_start res...
#!/usr/bin/python def nextMove(n,row,column,grid): count = 0 for gridRow in grid: princess = gridRow.find('p') if princess != -1: if count < row: nextMove = 'UP' elif count == row: nextMove = 'LEFT' if princess < column else 'RIGHT' ...
def check_binary_search_tree_(root, lower=None, upper=None): if root is None or root.data is None: return False if lower is not None and root.data < lower: return False if upper is not None and root.data > upper: return False if root.left is not None: if root.left.data...
# I am not writing a heap from scratch here... from heapq import heappush, heappop class MinHeap: def __init__(self): self.h = [] def __len__(self): return len(self.h) def push(self, val): return heappush(self.h, val) def pop(self): return heappop(self.h) def peek(self): return self.h[0] def ...
# I could use collections.deque but am using two stacks for demonstration purposes class Queue(): def __init__(self): self._inbox = [] self._outbox = [] def peek(self): if len(self._outbox) > 0: return self._outbox[-1] elif len(self._inbox) > 0: return se...
#!/bin/python3 import sys n = int(input().strip()) arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] ## Recursion solution # def sumArr(arr, n): # return arr[n] if n > 0 else sumArr(arr, n - 1) ## Iterative solution def sumArr(arr): num = 0 for val in arr: num += val return num print(s...
''' 단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다. ''' def solution(s): if len(s)%2 == 0: return s[len(s)//2 -1 : len(s)//2 + 1] else: return s[round(len(s)//2)] # 다른사람 풀이 def string_middle(str): return str[(len(str)-1)//2:len(str)//2+1]
# Name:Lynn Mumia # MIT Username: Lynn Mumia # 6.S189 Project 1: Hangman template # hangman_template.py # Import statements: DO NOT delete these! DO NOT write code above this! from random import randrange from string import * # ----------------------------------- # Helper code # (you don't need to understand this he...
# Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass # class Dog is-a Animal class Dog(Animal): def __init__(self, name): # class Dog has-a __init__ that takes self and name params self.name = name # class Cat is-a Animal class Cat(Animal): de...
import numpy as np import matplotlib.pyplot as plt def func(x): return x ** 2 - 1 def fder(x): return 2 * x def newton_iteration(f, fder, x0, eps=1e-5, maxiter=1000): """ Newton 's root finding method for f ( x )=0 Parameters ---------- f : callable Function f . f...
# Please enter the letters like this: rgyb # Please enter the given questions like this: 1234 # Please enter the question to be solved like this: 1234,2341,3412 # Please enter the answer at the end and the the program will end automatically: ygrb # Setting variable for initial ones start_colour = list(input("Enter: ")...
import turtle import pandas from turtles import Scoreboard screen = turtle.Screen() screen.title("Juego de las Provincias Argentinas") image = "argentina_sin.gif" screen.addshape(image) turtle.shape(image) data = pandas.read_csv("prov_arg.csv") provincias = data["Provincia"].to_list() x_coord = data['x'].to_list() y_c...
# Algo is # divide number by % 2 # push the remainder # use the quotient part as new value # repeat the procedure until the quotient is 0 # pop the from the stack and store result in a string from stacks import Stack s = Stack() def NumberToBinary(value): if value == 0: return remainder = value % 2 ...
numbers = [-5, 23, 0, -9, 12, 99, 105, -43] N = len(numbers) for i in numbers: j = 0 while j <= N-2: if numbers[j] > numbers[j+1]: temp = numbers[j+1] numbers[j+1] = numbers[j] numbers[j] = temp j += 1 summ = 0 for x in numbers: summ = summ + x print...
x = int(input("숫자를 입력하세요:")) if x < 0: x = 0 print('x가 0보다 작아 0으로 변환합니다.') elif x == 0: print('x는 0입니다.') elif x == 1: print('x는 1입니다.') else: print('x는 0보다 큽니다.')
my_list = [] for x in range(10): my_list.append(x ** 2) print(my_list) # my_newlist = my list.append(x ** 2) for x in range(10) # 위의 코드를 한줄로 나타내면 이렇게 되는데 아래와 같이 생략해준다. # for 문을 단순히 한줄로 줄인 것이 아니다. # 시퀀스의 요소를 전부 또는 일부를 처리하고, 그결과를 리스트로 돌려주는 간결한 방법 my_newlist = [x ** 2 for x in range(10)] my_newlist2 = list(x ** 2 ...
# Create your Phrase class logic here class Phrase: def __init__(self, phrase: str): # `phrase` is the phrase given my `game.start`, and is the "answer" the user is trying to guess self.phrase = phrase # `hidden_phrase` is the most important variable in the game. It's printed every ...
# -*- coding:utf-8 -*- class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def FindKthToTail(self, head, k): # write code here if head == None or k == None: return head if k==0: return None listNode = head ...
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if root != None: lst = [] lst2 = []...
# -*- coding:utf-8 -*- class Solution: def FindGreatestSumOfSubArray(self, array): # write code here if len(array)==0: return None value = [] for i in range(len(array)): if i == 0: value.append(array[0]) else: tmp = ...
guess_me = 7 # under 7 is 'too low' # over 7 is 'too high' # equals 7 is 'just right' if guess_me == 7 : print ('just right') elif guess_me < 7 : print ('too low') else: print ('too high')
#!/usr/bin/python3 # Purpose: Crack the password by brute force technique # Author: Deep Patel # LastModified: 16/08/2021 import hashlib import itertools #This function imports in a tuple and returns a string by looping over each character inside a tuple def convertTupleToAString(tuple): stringValue = "" for v...
def counter_effect(hit_count): return [range(int(i)+1) for i in hit_count] ''' Description: Introduction You are the developer working on a website which features a large counter on its homepage, proudly displaying the number of happy customers who have downloaded your companies software. You have been tasked w...
def find_short(s): return min(len(x) for x in s.split()) ''' Description: x Simple, given a string of words, return the length of the shortest word(s). String will never be empty and you do not need to account for different data types. '''
def to_acronym(input): return ''.join(word[0] for word in input.split()).upper() print to_acronym('cascading style sheet') ''' def to_acronym(input): a = input.split(' ') x = [] for i in a: x.append(i[0]) y = ''.join(x) return y.upper() print to_acronym('hello world') ''' ''' Descrip...
from functools import reduce def divisors(n): x = reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)) if len(x) >= 3: return sorted(x[2:]) else: return '%d is prime' % n print(divisors(15)) ''' Description: Create a function named divisors that takes an i...
import random def password_gen(): chars, digits = list('abcdefghijklmnopqrstuvwxyz'), list('1234567890') length = random.randint(6,20) passwrd = [random.choice(chars).upper() for i in range(random.randint(1, length -2))] passwrd += [random.choice(chars) for i in range(random.randint(1, length-len(passw...
def basic_op(operator, value1, value2): return eval(str(value1) + operator + str(value2)) print basic_op('+', 1, 2)
def find_outlier(int): odds = [x for x in int if x%2!=0] evens= [x for x in int if x%2==0] return odds[0] if len(odds)<len(evens) else evens[0] ''' Description: You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely compri...
def binary_array_to_number(arr): return int("".join(map(str, arr)), 2) ''' def binary_array_to_number(arr): strarr = [str(i) for i in arr] binary = ''.join(strarr) return int(binary, 2) ''' print(binary_array_to_number([1,0,1,1,1])) ''' Description: Given an array of one's and zero's convert the equi...
set1=set() set2=set() n=int(input('Enter the size of the first set')) print('Enter the elements of the first set:') for i in range(n): data=input() set1.add(data) print('First set:') print(set1) m=int(input('Enter the size of the second set')) print('Enter the elements of the second set:') for j in r...
class Player: #Creates a new player with the parameters set to the correct #values def __init__(self,firstname,lastname,pt,rb,ass): self._firstname = firstname #Players first name self._lastname = lastname #Players last name self._pt = pt #Points per game self._rb = rb #Rebou...
#!/usr/bin/env python # coding: utf-8 # In[1]: import os rep=os.walk('C:\\Users\\Sujji\\Assignment') d1={} for r,d,f in rep: for file in f: d1.setdefault(file,[]).append(r) file_name=input('Enter the file name:') for k,v in d1.items(): if file_name.lower() in k.lower(): for i in v: ...
# Problem One s = "django" print(s) s[0] s[-1] s[:4] s[1:4] s[::-1] # Problem Two l = [3,7,[1,4,"hello"]] l[2][2] = "goodbye" # Problem Three d1 = {"simple_key":"hello"} d1["simple_key"] d2 = {"k1":{"k2":"hello"}} d2["k1"]["k2"] d3 = {"k1":[{"nest_key":["this is deep",["hello"]]}]} d3["k1"][0]["nest_key"][1][0] ...
#!/usr/bin/env python # coding: utf-8 # In[4]: # 2-1. Simple Message: Store a message in a variable, and then print that message . best_friend ="Symphony" print(best_friend) # In[6]: # 2-2. Simple Messages: Store a message in a variable, and print that message . Then change the value of your variable to a new m...
from time import sleep as s from random import randint def hold(f): def d(*args, **kwargs): s((randint(1, 3) / 100.0)) return f(*args, **kwargs) return d @hold def kth_largest_value_sorted(ls: list, k: int) -> int: """ Return the kth largest value in a list that we sort """ if ...
import numpy as np def load_data(file_name): """Load and shuffle initial data from file and return it""" with open(file_name, "r") as file: data = np.array([line.rstrip().split(",") for line in file.readlines()]) return data def split_data(X, Y, fraction): train = int(len(X) * fraction) ...
def calcularnotafinalFRHH(): #datos de entrada primeraunidad=float(input("ingrese la nota de la primera unidad:")) segundaunidad=float(input("ingrese la nota de la segunda unidad:")) terceraunidad=float(input("ingrese la nota de la tercera unidad:")) trabajofinal=float(input("ingrese el 50% de la n...
# -*- coding: utf-8 -*- ################################################################################################################################ # Project Euler Problem 46 Solution -- GoldBach's Other Conjecture # By Mike Kane # # ...
####################################################################################################################################### # Project Euler Problem 30 Solution -- Digit Fifth Powers # By Mike Kane # # #Surprisingly there are onl...
# -*- coding: utf-8 -*- ######################################################################################################################################## # Project Euler Problem 31 Solution -- Coin Sums # ...
# -*- coding: utf-8 -*- ############################################################################### # # Project Euler Problem 20 Solution # By Mike Kane # # # n! means n × (n − 1) × ... × 3 × 2 × 1 # # For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = ...
# -*- coding: utf-8 -*- ############################################################################################################ # Project Euler Problem 14 -- Longest Collatz Sequence # # # The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n...
"""Basic functionality for reading datafiles line by line using Numpy Description: ------------ Read file formats that contain data in nicely formatted columns in text files. """ # Standard library imports import pathlib from typing import Union # Third party imports import numpy as np # Posetta imports from poset...