blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
e3008db9a96ba334d407c6c7de1c689660c80cc7 | snowdj/cs_course | /Algorithms/challenges/lc121_best_time_to_buy_and_sell_stock.py | 2,148 | 3.984375 | 4 | """
Time: O(n)
Space: O(1)
Say you have an array for which the ith element is the price of a given stock
on day i.
If you were only permitted to complete at most one transaction (ie, buy one
and sell one share of the stock), design an algorithm to find the maximum
profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output... |
6915c0a2cceb84609c8826616798dfaa1f885c45 | moonso/magister_kth | /code/Individual.py | 7,494 | 4.0625 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Sequences.py
This is a class with the information about an individual.
So I would like to re write the find allele section in such a way that we divide the sequences into TWO groups.
The alleles are then built in a way such that in every variable position each of the groups... |
caefa672164daa47bbfecf2f5e5d51e6fa3fcdd7 | Verneriv9/HackerRank-30-Days-of-Code-Python-2018 | /Day 25: Running Time and Complexity - O(Sqrt(n)).py | 565 | 3.828125 | 4 | ### Name: Verneri Kalviainen (dryicefox)
### Date: 12/31/2018
### Day 25: Running Time and Complexity
import math
# Enter your code here. Read input from STDIN. Print output to STDOUT
def isPrime(n):
if n <= 1:
return False
sqrt_n = math.sqrt(n)
if sqrt_n.is_integer():
return False
for... |
e14b5e2b3dc903fd7200373c9cb6c71c002ce22d | mottaquikarim/pydev-psets | /pset_basic_data_types/typecasting/p3.py | 708 | 4.3125 | 4 | """
Booleans I - Typecasting w. Numbers
"""
# A) Use typecasting to turn these variables into boolean values. Print the result and the datatype of the result.
one = 1
zero = 0
# B) Use typecasting to turn the resultant variables from part A into floats. Print the result and the datatype of the result.
# C) Use t... |
390a735f17ec469aedbebb1e4086f58ba72bcfc1 | gaodelade/MachineLearning_at_FLT | /02_Supervised/02_Classification/01_Logistic_Regression/source.py | 4,010 | 4.125 | 4 | ''' Logistic Regression Classification '''
# ***** Logistic-Regression Intution *****
# This is a regression type algo that we use for classifcation problems (i.e., 0 or 1), either we perform this action or
# that action. For this we calculate the probability or likelihood of happening any event on the basis of the tr... |
d2e3905322f2f6ee19c3478f995683495d7e8eaf | hermetikos/algorithms-python | /trees/connect_all_siblings.py | 1,347 | 4.34375 | 4 | # "Given the root to a binary tree where each node has an additional pointer called sibling (or next),
# connect the sibling pointer to the next node in the same level.
# The last node in each level should point to the first node of the next level in the tree."
# taken from:
# https://www.educative.io/m/connect-all-sib... |
063c7828557518fb2fba68232ab922c63a25c82d | superSeanLin/Algorithms-and-Structures | /139_Word_Break/139_Word_Break.py | 703 | 3.515625 | 4 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
## bottom-top DP; O(n^2)
wordDict = set(wordDict)
return self.dp(s, wordDict)
def dp(self, s, wordDict): # phraseDict store ... |
652ba78f54bbc5626fe391f56720a51aca6917f1 | kidbytes/pdsa | /python/util.py | 989 | 3.71875 | 4 | import random
def generate_rand_list(numItems=10, start=0, allowDuplicates=True):
out = []
if (allowDuplicates):
for _ in range(numItems):
x = random.randrange(1,numItems)
out.append(start + x)
else:
uniq = set()
while (True):
x = random.rand... |
686bb1d29fe247b247c34e3fefaa986747b48be6 | shehryarbajwa/Algorithms--Datastructures | /algoexpert/freq_count.py | 352 | 3.828125 | 4 |
def check_frequency(s1, s2):
count = {}
for char in s1:
if char in count:
count[char] += 1
else:
count[char] = 1
for char in s2:
if char in count:
return "YES"
else:
continue
return "NO"
print(check_frequency('wouldyouli... |
3c14f44b69679d8dc9810dd65e69a734f7134b4c | alesalsa10/python_course | /workingfiles.py | 128 | 3.75 | 4 | with open('text.txt', mode='r+') as my_file: # r+ is read and write
text = my_file.write('hey, it is me!')
print(text)
|
12f74894368fdd013b7fec633c947eb135f63ab5 | abekthink/leetcode | /python3/0031_Next_Permutation.py | 961 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: abekthink
from python3 import List
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
for i in range(length - 1, 0, -1)... |
7077a8b378dcf4f42fab8f395fea2e4cd9474f68 | sitakantapanda/scraping-automation-visualization | /automation_examples/lecture2_example6.py | 504 | 4.40625 | 4 | '''
lecture2_example6.py. This example imports the threading and time modules. It
then demonstrates how threads can be used to schedule tasks that are not
executed sequentially.
'''
import threading
import time
def doSomething():
for j in range(100):
time.sleep(1)
print('Something.')
def doSomethingElse():
... |
e32147ee3ad8593b43b546fb091e4c3db3c40328 | ConnorMattson/Misc-Scripts-and-Challenge-Solutions | /challengeSolutions/NZPC/2013/nzpc2013e.py | 484 | 3.78125 | 4 | #Problem E 2013 - Connor Mattson
def subtractionFunction(data, n=0):
if data == [0, 0, 0, 0]: return n
else: return subtractionFunction([abs(data[0]-data[1]), abs(data[1]-data[2]), abs(data[2]-data[3]), abs(data[3]-data[0])], n + 1)
data = [int(x) for x in input("Enter the initial sequence or '0 0 0 0' to exit: ").... |
cf1f3f8d244ccda994600d27c5a0b10c68d9c919 | socialpanic/cs121 | /ch3.5prob2.py | 226 | 4.3125 | 4 | a = input("what is the length of side a? ")
b = input("what is the length of side b? ")
c = input("what is the length of side c? ")
if a**2 == b+c:
print "this is a right triangle"
else:
print "this is not a right triangle"
|
df7119cb1cd469f1270891a7ed5428b926b7474b | gonzalob24/Learning_Central | /Python_Programming/PythonUhcl/hello.py | 553 | 4 | 4 | """
import sys
print(sys.version)
x = 'Hello World'
s = 'This is my first program'
print(x + s)
# value = [5, 4, 3, 2, 1]
for i in range(1, 11):
print (i, end=' ')
w = 100 / 3
z = 23 / 3
# formatted output
print("\nThe float rounder is %8.2f %8.2f" % (w, z))
"""
current_time_str = input("What is the current t... |
1b0b0f767699411f5d4cad35f363dc689261724e | mjaitly/LeetCode | /Algorithms/Easy/20_Valid_Parentheses.py | 1,077 | 4.125 | 4 | ''''
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
... |
fa73c2a33a20d6a64b0fd7f21e46ed3c484d70ed | b-andrew-yang/Cracking-the-Coding-Interview | /Chapter 1/zeroMatrix.py | 637 | 3.78125 | 4 | def main():
test_matrix = [[0, 1, 2, 3], [2, 3, 4, 5],
[3, 4, 5, 0], [1, 1, 1, 1]]
print(test_matrix)
print(zeroMatrix(test_matrix))
def zeroMatrix(matrix):
zero_indices = []
counter = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if(mat... |
bdd3d0229d6dcd118ef044426de074c37f88fefc | Gerrydh/MPP-Recursion | /filter2.py | 436 | 3.5 | 4 | class StringIterator:
def __init__(self, string):
self.string = string
self.index = 0
self.length = len(string)
def __iter__(self):
return self
def next(self):
if self.index >= self.length:
raise StopIteration
else:
s... |
6987c1c8dea80f47b9cdd7725548219336bc7eb5 | bibinvasudevan/PythonExercises | /ProjectEuler/Problem3/problem3.py | 855 | 4.1875 | 4 | #Solution for the problem no-3
#Find the largest prime factor of our input
# Eg:- largest prime factor of 13195 among 5,7,13,29 is 29
import logging
def largest_pfactor(n):
i = 2
while i * i < n:
while n % i == 0:
n = n / i
i = i + 1
return n
def main ():
logging.basicCo... |
8148ac90885ff1eb247b0e35cc8537d780bdfe2d | juanpablorp96/Analisis-de-algoritmos | /(6,2)Hotel.py | 734 | 3.578125 | 4 |
def hotel(array):
hotels = array
best_path = [0] * len(hotels)
stop = [0] * len(hotels)
for i in range(0, len(hotels)):
best_path[i] = pow((200 - hotels[i]), 2)
stop[i] = 0
for j in range(0, i):
if (best_path[j] + pow(200 - (hotels[i] - hotels[j]), 2)) < best_path[i]... |
a6bf5c1d1892325dad85ae8dc8a2a0b3dfc49cb1 | sebassands/551-Applied-Machine-Learning | /Project 1/processResults.py | 2,651 | 3.5625 | 4 | # Functions to process results of machine learning models
# COMP 551 mini project 1
# Feb. 8, 2020
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def evaluate_acc(y_true, y_prediction):
accuracy = np.sum(y_true.T.ravel()==y_prediction)/len(y_true.T.ravel())
#accuracy=np.mean(y_true==y_... |
48c993bb697d4d85e6b0f531e5b602afddeee2c9 | aditya-doshatti/Leetcode | /count_good_nodes_in_binary_tree_1448.py | 1,237 | 3.78125 | 4 | '''
1448. Count Good Nodes in Binary Tree
Medium
Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.
Return the number of good nodes in the binary tree.
Example 1:
Input: root = [3,1,4,3,null,1,5]
Output: 4
Explanation: Node... |
f9661e89c8ee09861e1dc0ceec14a37ec181f922 | itsrbpandit/fuck-coding-interviews | /problems/search_in_a_binary_search_tree.py | 1,304 | 3.703125 | 4 | # coding: utf-8
"""
https://leetcode.com/problems/search-in-a-binary-search-tree/
"""
class TreeNode: # pragma: no cover
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def searchBST(self, root: TreeNode, val: int)... |
0b472c8c3f4090037750ddb9f8ab5f409c922758 | mohmutho/fund_python | /exercise lambda.py | 207 | 3.84375 | 4 | my_list = [5, 4, 3]
print(list(map(lambda item: item**2, my_list)))
a = [(0, 2), (4, 3), (9, 9), (10, -1)]
# pengurutan pada key ke 2
b = []
a.sort(key = lambda item: item[1])
b.append(a)
print(a)
print(b) |
65962fe08054f4f0213287a32aee6df3e2bdbfb2 | LeanC100/ejercicios-de-python | /PIP/index.py | 212 | 3.890625 | 4 | from camelcase import CamelCase
import os
c = CamelCase()
print(' Normal to CamelCase \n')
s = input('Enter the text: \n')
os.system('cls')
print('Text normal: ',s)
print('Text Camelcase: ', c.hump(s))
|
053f13856ba656c9a93cb43e3e107148f4185dd9 | hvijaycse/HacktoberFest_2K20 | /Starter/Python/lineCount.py | 180 | 4.09375 | 4 | #! /usr/bin/python3
filename = input("Enter the file name: ")
lines = 0
with open(filename, 'r') as f:
for line in f:
lines += 1
print("Number of lines:")
print(lines)
|
693cc1392c97db1bad279e3e23de789ea53fa6f1 | teco-kit/CNN_LSTM | /quaternion.py | 1,886 | 3.671875 | 4 | class Quaternion:
def __init__(self, s, x, y, z):
"""构造函数"""
self.s = s
self.x = x
self.y = y
self.z = z
self.vector = [x, y, z]
self.all = [s, x, y, z]
def __str__(self):
"""输出操作重载"""
op = [" ", "i ", "j ", "k"]
q = self.all.copy()
result = ""
for i in range(4):
if q[i] < -1e-8 or q[i] >... |
39fa4e03799059d5b93237fc6964d4acddf7fe74 | Sreerag07/bankproject | /flowcontrols/functions/recursion.py | 293 | 3.546875 | 4 | #function call inside a function
def recur_fibo(n):
if n<=1:
return n
else:
return recur_fibo(n-1)+recur_fibo(n-2)
nterms=10
if nterms<=0:
print("Enter positive number")
else:
print("Fibinocci series:")
for i in range(nterms):
print(recur_fibo(i))
|
1b0fcc447b81b5ee00c14a93b8d87802997c3593 | green-fox-academy/Unicorn-raya | /week-01/day-3/Functions/Sort_that_list.py | 992 | 4.21875 | 4 | # Create a function that takes a list of numbers as parameter
# Returns a list where the elements are sorted in ascending numerical order
# Make a second boolean parameter, if it's `True` sort that list descending
def bubble(arr):
arr_length = len(arr)
if arr_length == 0:
return -1
for i in rang... |
41186bd5165234122744f3c062d2ea7db3067cdf | josiahdavis/project-skeleton | /src/visualization/plit.py | 6,912 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""Base functionality for three different types of charts.
Includes plot (for line chart and scatter), hist, and bar.
"""
from functools import partial
import matplotlib.pyplot as plt
import numpy as np
_COLORS = ["g", "b", "r", "k", "c"]
def hist(x, title, xlab, ax=None, bins=10, grid=Fa... |
0c2451af4ff01dd16a3b8bbf60b3cd2d4b9797ee | sindhudp1/project3 | /char.py | 99 | 3.875 | 4 | n=int(input("enter number"))
if n>0 or n<128:
print(chr(n), end= " \t")
print("\n")
~
|
ad34c2bdb4602ad5fbf2cb1a5f1a4c8bdeba903b | jleine02/Python_Workout | /guessing_game.py | 797 | 4.1875 | 4 | #! usr/bin/env python3
""" A guessing game that uses user input """
import random
def main():
"""Function to run the program."""
guessing_game()
def guessing_game():
"""Guessing game where user tries to guess random int between 0 and 100"""
number_to_guess = random.randint(0,100)
user_guess = int... |
6ce2cf332c137ed0e26e03b838d84c7fe03b0918 | JaxYoun/TensorFlow-study-cn | /study-code/pyplot-code/pyplot_animation_2.py | 704 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
####### 另外一种动图的写法
fig, ax = plt.subplots()
x = np.linspace(0, 2 * np.pi, 200)
y = np.sin(x)
line = ax.plot(x, y)
dot, = ax.plot([], [], 'ro')
def init_dot():
... |
d11f9c5360c6933e938b103e9bc64d95ee8533f4 | escofresco/makeschool_fsp2_realtweets | /grams/linkedlist.py | 6,665 | 4.09375 | 4 | #!python
__all__ = []
class Node(object):
__slots__ = ("data", "next")
def __init__(self, data):
"""Initialize this node with the given data."""
self.data = data
self.next = None
def __repr__(self):
"""Return a string representation of this node."""
return 'Node(... |
7ff91bcaff30b06e76f75ceb4c69e6d9ab99bfde | Tarelkinal/python-practice | /Lab_1/task252.py | 943 | 3.78125 | 4 | # Написать функцию array_diff(a, b), которая возвращает разность списков a и b.
# Т.е. из спсика a должны быть удалены все значения, которые встречаются в списке b.
#
# Пример:
# array_diff([1,2,2,2,3],[2]) == [1,3]
import traceback
def array_diff(a, b):
try:
for j in range(len(a)):
... |
b8b3edd981def2b2dc11ef746643fe07173ca029 | AnthonyChupin/homework2 | /HW2/02_5.py | 240 | 3.78125 | 4 | my_list = [7, 5, 3, 3, 2]
request = input('Vvedite ')
for index, number in enumerate(my_list):
if int(request) < int(number):
continue
my_list.insert(index, request)
break
else:
my_list.append(request)
print(my_list) |
739cebfc9b02242be0c65d012343648fbdbc6ebc | meng-z/leetcode | /20_valid_parentheses/v2.py | 787 | 3.921875 | 4 | '''
Runtime: 24 ms, faster than 94.35% of Python3 online submissions for Valid Parentheses.
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Valid Parentheses.
'''
class Solution:
def isValid(self, s: str) -> bool:
if not s:
return True
if len(s) % 2 !=... |
fbf0cd9e983c171b92fe5789c4ebc3ba066e836c | alu-rwa-prog-1/final_project_part1-diane | /main_program.py | 6,215 | 4.15625 | 4 | #Author: Niyibaruta Diane
from typing import ValuesView
from work import Work
from school import School
from family_friends import Family_Friends
print()
contacts = {'work': {}, 'school': {}, 'family and friends': {}}
print('PhoneBook')
print()
while True:
try:
action = int(input("""Please choose an ac... |
458fcb1633e2258d2f610b9515404c2ad2174c93 | buxuele/algo_snippet | /junk/5470.py | 463 | 3.765625 | 4 | # author: fanchuangwater@gmail.com
# date: 2020/8/8 下午11:36
# 目的:
#
# s = "(()))"
#
# # 栈的思想
#
#
# left = 0
# right = 0
#
# for i in s:
# if i == "(":
#
# else:
# # i == ")"
#
import re
s = "))())("
while "())" in s:
s = s.replace("())", "", 1)
print(s) # ))(
left = 0
right = 0
fo... |
5106c58b472211c38790e0936598b01788c84c79 | suyeony0/AlgorithFromNoteBook | /DP/피보나치/for문.py | 156 | 3.765625 | 4 | N=int(input())
if N == 1 : print(1)
elif N==2 : print(2)
result=[1,2]
for i in range(2,N):
result.append(result[i-1]+result[i-2])
print(result[-1])
|
e2356fa35e2e51ecd7cbc1fce175a8242bd29277 | romulovieira777/Programacao_em_Python_Essencial | /Seção 04 - Variáveis e Tipos de Dados em Python/Exercícios da Seção/Exercício_05.py | 194 | 3.6875 | 4 | """
5) Leia um número real e imprima a quinta parte deste número.
"""
number = int(input('Enter the number: '))
share = round((number / 5), 2)
print(f'The fifth part of {number} is {share}')
|
cefee398d25ffd8f14d3f68b496680500de19908 | Adam-Banderker/Calculator.py | /Calculator.py | 1,300 | 4.3125 | 4 | #Create a calculate having different options such as Addition/Subtraction/multiplication/Division/Exit
#Define every option in functions
def add(x,y):
return x + y
def sub(x,y):
return x - y
def div(x,y):
return x/y
def multi(x,y):
return x * y
def exit(x):
return x
#Display the options for user t... |
7696ab47f2f65eb574aa31bc4d7ebbd772faff92 | yucehasan/NYT-Crossword-Puzzle-Solver | /wikipedia_search.py | 804 | 3.59375 | 4 |
import wikipedia
import nltk
from nltk.corpus import stopwords
import datetime
import string
import word_eliminator
def wikipedia_search(input_string, word_length):
print("Wikipedia is searching for {} with length {}".format(input_string, word_length))
try:
list = wikipedia.search(input_string)
... |
46c262b0af3a5299d1dbecfc4e21438ed7b8d72c | mcgurck164/Lyrics-Database | /DataTable.py | 7,238 | 3.84375 | 4 | import tkinter as tk
import pandas as pd
import numpy as np
import re
class DataTable(tk.Frame):
"""
A custom tkinter widget for a sortable and searchable data table.
A single (double) click on a column header will sort the data ascending
(descending) with respect to that column.
The e... |
1f7c66cb041736ffd743b58a876a0da546e4a986 | HuichuanLI/play-with-data-structure-python | /Chapter31RandomAlgo/lc382.py | 657 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import random
class Solution(object):
def __init__(self, head):
"""
:type head: Optional[ListNode]
"""
self.head = head
... |
a75ea41399be20a4084e38437f5a583aeff3d6dd | visw2290/Scripts-Practice | /Scripts-Sublime/strFormat.py | 103 | 3.609375 | 4 | def sum (*args):
sum = 0
for i in args:
sum += i
print('sum is {}'.format(sum))
sum(9,10,11,12,13) |
9a8914a54a594c3b96480081ba4292aadccec102 | PaulMacDonald/Spaceship_Simulator | /Spaceship_Simulator_2.0.py | 851 | 3.625 | 4 | from Crew import Crew
def main():
# TESTING CRAP
# TODO TEST ALL SHIP FUNCTIONS AND WHATNOT!!!
myCrew = Crew(5) # construct a crew of size 5
myCrew.startRepairing()
print(myCrew.getBusyRepairing()) # TRUE
print(myCrew.getRepairTimeLeft()) # 2
print(myCrew.getSize()) # 5
... |
3cced43ce5693e7232d8afdf149cc9531a72289b | shanthivimalanataraajan01/Beginner | /recursively_div_by2.py | 55 | 3.625 | 4 | n=int(input())
if n%2==0:
print(n//2)
else:
print(n)
|
dded8f01a1547e667aa2b6142924876e0d877dca | Izaack-B97/Ejercicios-en-python | /Practica16-CreacionBD.py | 2,118 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 09:33:32 2020
@author: Isaac Bustamante
Objetivo: Aprender a crear bases de datos, crear tablas e insertar registros usando MySQL en Python.
"""
# Importamos MySQL connector
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
... |
9486b8d65be98481c6255d5b2e058f0a36a75b09 | f1amingo/leetcode-python | /分治算法/23. 合并K个排序链表.py | 2,209 | 3.890625 | 4 | # Definition for singly-linked list.
import heapq
from typing import List
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 使用堆
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# heap = []
# heapq.heapify(heap... |
8144b82896d7a54186052a819dc964e900766599 | TianCccc/Leetcode | /3_Longest Substring Without Repeating Characters/3_1.py | 697 | 4 | 4 | #Longest Substring Without Repeating Characters
"""
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
"""
def lengthOfLongestSubstring(s):
# 滑动窗口
left, right = 0, 0
res = 0
window = list()
l = len(s)
while (right < l) :
c1 = s[right]
window.... |
3375903c3542cc5281222736f4a5b062a4f4bca6 | kiranrubavathy/problem-solving1 | /alphabet or not.py | 69 | 3.5 | 4 | s=(input())
if s.isalpha():
print("alphabet")
else:
print("not")
|
28ca68a10750eee92832a83d0aeeee3789cfef10 | Daylen-Mackey/ECE491 | /GUI/numpadtest.py | 1,398 | 3.515625 | 4 | from tkinter import *
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.set_active_entry('entry_1_var') # set initial active entry
self.entry_1_var = StringVar()
self.entry_2_var = StringVar()
self.entry_1 = Entry(self, width=10, font='Helvetica 32', textvariable=se... |
3850442685b5fa7fda8f9027a6ce6578860deb93 | aiiilii/py_code | /merge_intervals.py | 674 | 3.9375 | 4 | from typing import List
class MergeIntervals:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# sort based on the starting time
intervals.sort(key = lambda x: x[0])
merged = []
for interval in intervals:
# if merged is empty
# or if the cur... |
d9d8a22c17bd0d917384d72e96c6bb31b53a781d | CelsoAntunesNogueira/Phyton3 | /ex050 - somando par com par e impar com impar.py | 373 | 3.8125 | 4 | s = 0
co = 0
ss = 0
coo = 0
for c in range(6):
num = int(input('Digite um número:'))
if num % 2 ==0:
s += num
co += 1
elif num % 2 !=0:
ss += num
coo += 1
print("Você informou {} números pares .A soma dos números é {}.". format(co, s))
print("Você informou {} números impares... |
ff43aa36a8b1d056ff06803449be3bc445d67a5c | Sandeep-Joshi/python_crawlers | /getUsers.py | 2,995 | 3.875 | 4 | """
This script retrieves the urls that correspond to user profiles on freelancer.com
Here is an example url:
https://www.freelancer.com/u/zhj11651.html
On the website, freelancers are viewed in pages (10 per page). For example,
page 1 is https://www.freelancer.com/freelancers/skills/all/1
page 2 is https://w... |
4dd95b25c13723ef805a5ac63ef1442e54a398b2 | mnaberez/f2mc8dasm | /f2mc8dasm/scripts/lst2bin.py | 2,558 | 3.8125 | 4 | '''
Parse an ASF2MC8 listing file and create a binary file from it.
Usage: python lst2bin.py <file.lst> [<file.bin>]
'''
import os
import sys
def parse_listing(lines):
'''Parse listing lines into a dict of address: value'''
bytes_by_address = {}
last_address = 0
for line in lines:
# ignore he... |
81022152798447d5793f1c289da519f785e615fc | MaxiVargas78/DesafioLatamPython | /Desafios Modulo III/Opcional - CasoChileno/CasoChileno.py | 778 | 3.90625 | 4 | import pandas as pd
df = pd.read_csv('athlete_events.csv')
subset = df.loc[:, ["Name","Team", "Year", "Medal"]]
subset2 = subset[subset["Team"] == "Chile"]
#Año con la participación más alta
subset3 = subset2["Year"].value_counts().head(1)
print("El año con la participación más alta es: ")
print("Año Cantidad")
pri... |
d681d5edd7d8712e6f7f9bc265a0678e3408462c | SelvorWhim/competitive | /Codewars/TribonacciSequence.py | 194 | 3.8125 | 4 | def tribonacci(signature, n):
if n <= len(signature):
return signature[:n]
for i in range(n-len(signature)):
signature.append(sum(signature[i:i+3]))
return signature
|
a16d9b7526207ee1de464b016de70cc78baeece0 | yashasvi128/Assignments | /databases-SQL/QUES2.py | 613 | 4.03125 | 4 | import sqlite3
try:
con = sqlite3.connect('yashasvi.db')
cursor = con.cursor()
for i in range(0,10):
sname = input("enter the name of the student :")
smarks = int(input("enter the marks obtained by the student in the range 0 to 100 :"))
cursor.execute('insert into students (sname, sm... |
933a1584da23b0f6e6165c61d42dcdaada4fea62 | Expert37/home_work_lesson_5 | /divisor_master.py | 3,904 | 4.21875 | 4 | '''
Необходимо реализовать модуль divisor_master. Все функции модуля принимают на вход натуральные числа от 1 до 1000. Модуль содержит функции:
1) проверка числа на простоту (простые числа - это те числа у которых делители единица и они сами);
2) выводит список всех делителей числа;
3) выводит самый большой простой дел... |
359ed5d20e30d7de8a15268f6308e231edee9731 | BJNick/APCS-Practice | /unit3_lesson0/coding_test_part_a.py | 886 | 4.09375 | 4 | """
Mykyta S.
coding_test_part_a.py
Contains Part A of the AP CSP 20 Coding Test A
"""
def count_vowels(word):
"""Returns the number of vowels in a given word"""
vowels = "aeiouAEIOU"
vowel_count = 0
for letter in word:
if letter in vowels:
vowel_count += 1
return vowel_count
... |
886494f1fa00d769ef00db7ff121691c18699e43 | marakon/zajecia_python | /Zajecia_9/exercise_email.py | 245 | 3.78125 | 4 | def search_email(email_list, email):
for email in email_list:
if email == email_input:
return True
return False
email_list = ["Elo", "Gitara siema", "Cześć"]
email = input("Podaj mail: ")
search_email(email_list, email) |
eaf016502853d2fee8943eee71a8b02ca2c45075 | tranphibaochau/LeetCodeProgramming | /Easy/roman_to_integer.py | 709 | 3.9375 | 4 | """Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999."""
def romanToInt(self, s: str) -> int:
rti_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} #create... |
e4c3c3d9f7c488370fb48d23d9140002d001b7a9 | mirandarevans/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/3-my_safe_filter_states.py | 620 | 3.65625 | 4 | #!/usr/bin/python3
"""
script to print states with a name given from input
"""
import MySQLdb
import sys
def main():
"""
calls db fuctions in order to select and print states
"""
db = MySQLdb.connect("localhost", sys.argv[1],
sys.argv[2], sys.argv[3])
... |
df1e5e440d5ed8515e4d7953e22a537e2d76e1c4 | AaronWendell/MIS3640 | /Session 15/Exercise2.py | 6,347 | 4.5625 | 5 | import math
class Point:
"""Represents a point in 2-D space.
attributes: x, y
"""
class Circle:
"""Represents a point in 2-D space.
attributes: center, radius
"""
class Rectangle:
"""Represents a rectangle with corner as bottom left point.
attributes: width, height, corner.
"""... |
d9d0082f599f5f6c682df2b347d5c2f7fe50d828 | qmnguyenw/python_py4e | /geeksforgeeks/python/easy/23_19.py | 1,755 | 4.1875 | 4 | Python | a += b is not always a = a + b
In python a += b doesn’t always behave the same way as a = a + b, same
operands may give the different results under different conditions.
**Consider these examples for list manipulation:**
**Example 1**
__
__
__
__
__
__
__
list... |
703f65253f123ad0158c29c2817d4063c9cb3253 | mattwright42/Cache-demos | /lru_cache.py | 1,951 | 3.765625 | 4 | import collections
class LRUCache:
def __init__(self, limit=10):
self.limit = limit
self.cache = collections.OrderedDict()
"""
Retrieves the value associated with the given key. Also needs to move the key-value pair to the top of the order such that the pair is considered most-recently used... |
859ced1c90ee468a6b3855a006b507be4ff5d53a | waikei1917/PythonBeginnerTube | /T28Exception.py | 313 | 3.96875 | 4 |
while True:
try:
number = int(input("what is the number? \n"))
print(18/number)
break
except ValueError:
print("Make sure you input the number.")
except ZeroDivisionError:
print("No Zero")
except:
break
finally:
print("loop completed") |
0aedefaa4a8fb55c479133dda1eae84f69f06bdf | zz-zhang/some_leetcode_question | /source code/283. Move Zeroes.py | 805 | 3.515625 | 4 | from typing import List
from random import randint
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
faster, slower = 0, 0
while faster < len(nums):
nums[slower] = nums[faster]
... |
5dca1873f420b9158de3ee0e9584c376f4efe38c | Ajay2521/Python | /INTERMEDIATE/List/List.py | 900 | 4.0625 | 4 | # In this lets see more about "List Datatype" in Python.
# A list in Python is used to store the sequence of various types of data.
# Lists in Python are mutable.
# That is it can modify its element after it created.
# The most common and reliable datatype to store the sequences is "List".
# List can be... |
02bac3c45d5987a13f16be8268e1d44f72fb6afb | mnoga07/CPE551 | /SwimFinder.py | 4,996 | 3.515625 | 4 | import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
import sys
if (len(sys.argv) == 1):
print('Please specify a team code as an argument. For example run "python3 SwimFinder.py 313". Team codes can be found from the URL in a specific team page on www.collegeswimming.com. Here are some exa... |
0474cc2c1c93fbf84eca091708be5457058559ea | adreena/DataStructures | /Arrays/RotateImage.py | 232 | 3.546875 | 4 |
def rotateImage(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
row.reverse()
return matrix
|
300fe2af969c3ec5ca97f2a1386e1a5a3f9fe65a | wisesky/LeetCode-Practice | /utils/count-decorator.py | 572 | 3.546875 | 4 | import time
from functools import wraps
def timethis(func):
'''
Decorator that reports the execution time.
'''
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
r = func(*args, **kwargs)
end = time.perf_counter()
print('{}.{}:{} s'.format(func.__... |
0e2c02c5b27da80d7fdcbf44d2027a6dba79de39 | IvayloSavov/Fundamentals | /dictionaries_exercise/count_chars_in_a_string.py | 269 | 3.765625 | 4 | from _collections import defaultdict
string = input()
occurrences = defaultdict(int)
for character in string:
if character == " ":
continue
occurrences[character] += 1
for character, count in occurrences.items():
print(f"{character} -> {count}")
|
3fa3b47182e012930aaef8dcc0a1be87dd3c6af4 | AliceHincu/FP-Assignment06-10 | /TextRepo/StudentTextRepo.py | 2,023 | 3.8125 | 4 | """
- Implement a new repository that is able to persist data to text files
- Keep the functionalities from Repository class (code reuse, don't write things twice,
swap the memory-repo with the text-repo) -> modules are independent and interchangeable
- Learn about inheritance
"""
from domain.Student import Student... |
f9ab8d330409eea2728eb857d704a955aedd9489 | iziumska/Softserve_tasks | /file_parser/task4_file_parser/work_with_file.py | 810 | 4.15625 | 4 | # !/usr/bin/env python
def counting_string(file_name, sourse_text):
with open(file_name, 'r') as file:
data = file.read()
words = data.count(sourse_text)
print('{} lines in the file {}'.format(words, file_name))
return words
def replace_string(file_name, sourse_text, replace_text... |
45e900439a527ac5265302530a16844aa0150924 | andylampi/esercizi_workbook_python | /capitolo_1/esercizio_4.py | 661 | 3.96875 | 4 | #!/bin/python3
def conversione_metri(a,b):
a /= 3.28
b /= 3.28
return print("Ecco i valori convertiti in metri: \n" + str(a) +" " + str(b) + "\n")
def conversione_acri(area):
area /= 4047
return print("ecco l'area in acri\n" + str(area))
def main():
try:
lunghezza = float(input("I... |
b02c47af64b0495be7f85d168198138e24315157 | Taoge123/OptimizedLeetcode | /LeetcodeNew/Trie/LC_692_Top_K_Frequent_Words.py | 2,405 | 4.03125 | 4 |
"""
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest.
If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Outp... |
a7cd3ebc7b361745f85f443f75483c2d40c3c4ae | erick00denner/processadorDeArquivos | /classesFuncoes/log.py | 1,584 | 3.609375 | 4 | '''
CLASSE: Log
Classe desenvolvida para criação de Logs de Arquivo e Logs de Sistema
'''
class Log:
#Recebe nome do arquivo e mensagem de erro e gera log
def geraLogArquivo(self,nomeArquivo,msg):
from datetime import datetime
from classesFuncoes.diretorios import Diretorios
di... |
8c5953d3584ac7f2e60a75025b8df2540e8acc3f | henrydaleywhite/tfb-recipes | /run/src/models/spoonacular_api.py | 3,283 | 3.59375 | 4 | import json
import requests
from pprint import pprint
filename = "spoonacular_key.txt"
test_ing_list = "apples%2Cflour%2Csugar"
test_list = ['basil', 'garlic', 'tomato', 'olive oil', 'pasta', 'thyme', 'parsley', 'lemon', 'rosemary']
def get_api_key(filename):
"""get the api key from a seperately stored... |
f04460795b031ec4d2882d572c13a1ff863791e7 | parmalatinter/ai | /math/mode.py | 714 | 3.875 | 4 | #!/usr/bin/env python
# 最頻値の求め方 最も頻度が高い値(一番多く出現している値)
# 参考 https://bellcurve.jp/statistics/course/19014.html
# 最頻値
def Mode(numList):
print(numList)
nowNum = 0
nowCount = 0
maxCount = 0
maxNum = 0
for num in numList:
if (nowNum != num):
nowNum = num
nowCount = ... |
b9ff6a803100a9760e01a2a4b492b047b91ae44f | oscarhscc/algorithm-with-python | /程序员面试经典/面试题 08.10. 颜色填充.py | 1,567 | 3.703125 | 4 | '''
颜色填充。编写函数,实现许多图片编辑软件都支持的“颜色填充”功能。给定一个屏幕(以二维数组表示,元素为颜色值)、一个点和一个新的颜色值,将新颜色值填入这个点的周围区域,直到原来的颜色值全都改变。
示例1:
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出:[[2,2,2],[2,2,0],[2,0,1]]
解释:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
说明:
image... |
057f8cb86599677e9049988a65f550de9661dfcc | 22yuu/Python | /Exam3/q1.py | 484 | 4 | 4 | '''
날짜 : 2021/05/14
이름 : 이진유
내용 : 수행 평가 문제 1번
다음과 같이 2차 방정식을 파이썬 수식으로 코딩하고, y의 결과를 출력하시오.
<처리조건>
2차 방정식 : y = 2.5 x X**2 + 3.3 x X + 6 ( X = 2)
<출력 결과 예시>
2차 방정식 결과 x = 2 일 때 : 22.6
'''
y = 0
def equation(x) :
return 2.5 * (x**2) + 3.3 * x + 6
print(f'2차 방정식 y = 2.5 x X**2 + 3.3 x X + 6 ( 단, X = 2)의 결과는? {equa... |
eac8bbf8b7227cda70478cc82c78b78107a0438f | jain-aayush1123/Machine-Learning | /week2.py | 2,181 | 3.625 | 4 | import sklearn
from sklearn import linear_model
from sklearn.utils import shuffle
import numpy as np
import matplotlib.pyplot as pyplot
import pandas as pd
import os
from sklearn.utils import shuffle
import statistics
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'home_da... |
256978939b546508675ec98f230e36dc14fd9b27 | sudarshananjanamandal/Discount | /discount.py.py | 1,014 | 4.125 | 4 | price=int(input("Enter the price: "))
quantity=int(input("Enter the quantity: "))
amount=price*quantity
if amount>=10000:
print("Eligible for 10% discount")
discount=int(amount*10/100)
print ("discount amount is : ",discount)
amount=amount-discount
elif amount>=5000:
print("5% discount is a... |
c671307a3bb52771b39e53ba8d03b50e89236121 | robinscreech/startingPython | /conditional.py | 198 | 4.21875 | 4 | number = int(input('Enter a number : '))
if number > 10:
print('The number is greater than ten')
elif number < 10:
print('the number is less than ten')
else:
print('the number is ten')
|
d8586db22313c61b61c818123a947d887a482988 | peltierchip/the_python_workbook_exercises | /chapter_1/exercise_28.py | 339 | 4.5 | 4 | ##
#Compute the body mass index (BMI)
#Read the value of the height and weight
height=float(input("Enter the value of height in meters:\n"))
weight=float(input("Enter the value of weight in kilograms:\n"))
#Compute the BMI
BMI=weight/(height*height)
#Display the result
print("The body mass index (BMI) is: %.3f "%BMI)
... |
b79ace6c4c683b08a103e9ef078f158f27b0f9b2 | tatsw10/aedb_ds | /lists/nodes.py | 714 | 3.546875 | 4 | class SingleListNode:
def __init__(self, element, next_node):
self.element = element
self.next_node = next_node
def get_element(self):
return self.element
def get_next(self):
return self.next_node
def set_element(self, element):
self.element = eleme... |
64bb56c7ec38a39cfa8112658df43b1bf1de807b | Jbeltrann/MIS3640 | /Bi_inclass/Data Analysis.py | 946 | 3.8125 | 4 | #Import Python Libraries
import numpy as np
import scipy as sp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Read csv file
df = pd.read_csv("C:/Users/jbeltran1/Documents/GitHub/MIS3640/Bi_inclass.csv")
#Display a few first records
#Display first 10 record
#Display first 20 records
#D... |
c24cd64a7f3964ec250b47ad9a5069ba46371a7c | Rachel-commits/python-playground | /game_of_chance.py | 2,314 | 4.03125 | 4 | import random
#Write your game of chance functions here
def coin_flip(choice,bet):
num=random.randint(1,10)
if num<6 :
outcome ='heads'
else:
outcome = 'tails'
print(outcome)
if choice == outcome:
return bet
else:
return -1*bet
def cho_han(choice,bet):
dice1=random.randint(1,6)
dice2... |
602b1a05057e9aa6e839ac6ceac6f77f2fcceba7 | firtanaelif/PancakeProblem | /pancake.py | 6,129 | 3.5625 | 4 | from search import *
from random import shuffle
from datetime import datetime
#Problem Class
class PancakeProblem(Problem):
def __init__(self, initial):
super().__init__(initial)
self.initial = tuple(initial)
self.goal = tuple(sorted(initial))
self.size = len(initial)
... |
eb385ae2be338bd3d0cf8bd48808e85e605bb114 | Womens-Coder-Community-2020/30-Days-Coding-Challenge-WCC | /Day 1/Find_the_Duplicate_Number.py | 1,303 | 3.765625 | 4 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
#Phase1
tortoise = hare = nums[0] #starting from 0th index
while True: #Running loop till tortoise and hare meet
tortoise = nums[tortoise] #tortoise moves 2x faster than hare
... |
18d5dd502edd4991e536c7784fb26db1493229b5 | RaiLinKey/EREMEEV-BSBO-08-17-LAB-PYTHON | /laba1/t3.7.py | 660 | 3.90625 | 4 | a = input('Введите трёхзначное число: ')
b = list(a)
v_max = float(b[0])
v_min = float(b[0])
if v_max < float(b[1]):
v_max = float(b[1])
if v_max < float(b[2]):
v_max = float(b[2])
if v_min > float(b[1]):
v_min = float(b[1])
if v_min > float(b[2]):
v_min = float(b[2])
half_sum = (v_min + v_max) / 2
if... |
d9a03c55b2d77af8acb49fd5866145a4f40be424 | Dragonink/ISEP_A2-GTFS | /src/clustering.py | 4,726 | 3.765625 | 4 | from pathfinding import Pathfinder
def clustering(DIJKSTRA: Pathfinder, nodes, n, display_all=False):
"""
Clustering method (first try)
"""
print("\nCreating", n, "clusters...")
clusters = [] # Content of the clusters
n_nodes = len(nodes) # Number of nodes
iteration = 0
while len(clusters) < n: # As long as... |
e21163f6293e6ad6119ccd080a95c629b89d410c | jerome1213/EveryBodyTensorFlow | /lab1_randomwalk.py | 1,056 | 3.765625 | 4 | '''
#------------------------------------------------------------
filename: lab1_randomwalk.py
This is an example for random walk problem using numpy ndarray
written by Jaewook Kang @ Aug 2017
#------------------------------------------------------------
'''
import numpy as np
position = 0
next_pos = 0
step = 1... |
27baf2dfe479c34d0f9d8ada668d17ef39fab6f3 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/Programs/Ways to create a dictionary of Lists.py | 1,851 | 4.125 | 4 |
def ex1():
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
myDict["key2"] = ["Geeks", "For", "Geeks"]
print(myDict)
def ex2():
# Creating an empty dictionary
myDict = {}
# Adding list as value
myDict["key1"] = [1, 2]
# creating ... |
1938883febfd0ecf10e1c6ae2fe3cab10c69f62e | AnanyaMaruthi/CollegeCourseWork | /5th semester/PythonLab/1BM17CS015/brackets.py | 1,453 | 4.34375 | 4 | # Write a Python class to find validity of a string of parentheses, '(', ')', '{', '}', '' and '.
# These brackets must be close in the correct order, for example "()" and "()[]{}" are valid
# but "[)", "({)" and "{{{" are invalid.
def checkBrackets(expression):
stack = []
for bracket in expression:
... |
509ef8330525203a5741b0d88ca317d50056e1df | arkhipowasilii/Vasilii_tasks | /add_binary.py | 906 | 3.640625 | 4 | def add_binary(left: str, right: str) -> str:
result = list('_' * len(left if len(left) > len(right) else right))
left, right = left[::-1], right[::-1]
mem = False
for index in range(len(result)):
right_val = False
if index < len(right):
right_val = right[index] == '1'
... |
48249e1f5d4ab57aa652062eda31111ac02ed908 | Aasthaengg/IBMdataset | /Python_codes/p02400/s254108305.py | 102 | 3.96875 | 4 | import math
r = float(input())
pi = float(math.pi)
print("{0:.8f} {1:.8f}".format(r*r*pi,r * 2 * pi)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.