blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
68d12b010096e7154930b87aec7a101b505ad37b | danisebastian9/Ciclo1MinTIC | /Semana6/exerList01.py | 301 | 3.90625 | 4 | '''
Pide un numero por teclado y guarda en una lista su tabla de
multiplicar hasta el 10.
Por ejemplo, si pide el 5 la lista tendra:
5,10,15,20,25,30,35,40,45,50
'''
num = int(input('Digite un numero -> '))
tabla = []
for i in range(1,11):
mult = num * i
tabla.append(mult)
print(tabla)
|
5bbbe57c31952c4e04e8ab5739e04cc3fb678474 | danisebastian9/Ciclo1MinTIC | /Semana5/funcExternas04.py | 903 | 4.125 | 4 |
'''
Definir una función inversa() que realice la inversión de una cadena.
Por ejemplo la cadena "estoy probando" debería devolver la cadena "odnaborp yotse"
Definir una función que diga si una cadena es palindrome "Sometamos o matemos" "oso" "radar" ""
'''
# def inversa(palabra):
# reversa = ''
# for i in ... |
dffe7657c2da8a724882f64e3e79ec15ddd47019 | BhuviRaj/sdet | /python/Activity11.py | 201 | 3.84375 | 4 | dct={
"apple":{
"price":10
},
"banana":{
"price":16
}
}
name=input("Enter Fruite Name").lower()
if(name in dct):
print("Available")
else:
print("Not Available")
|
a9ffe52abd1bb85f0b8e44f1ddcf036f90822aea | riyag283/Leetcode-July-20-Challenge | /quest1-2.py | 340 | 3.515625 | 4 | import math
def findRoots(s):
a = 1
b = 1
c = -2*s
d = 1 - 4 * c
sqrt_val = math.sqrt(abs(d))
if d > 0:
x = (-1 + sqrt_val)/2
elif d == 0:
x = -1/2
else:
x = -1
if x > 0:
return math.floor(x)
else:
return -1
# Driver Program
su... |
2e6e4b448dbcf3b19b58b109ac1508f37dc1ffa8 | mdadil98/Python_Assignment | /24.py | 565 | 3.90625 | 4 | class Employee:
def __init__(self, emp_id=0, name="", salary=0):
self.Employee_ID = emp_id
self.Name = name
self.Salary = salary
def get(self):
self.Employee_ID = int(input("Enter the Employee ID:-"))
self.Name = input("Enter the Employee Name:-")
self.Salary = i... |
11d89be606e71e8c71a665be2b1b349ef63a2968 | mdadil98/Python_Assignment | /5.py | 157 | 3.75 | 4 | a=int(input("Enter Start Number: "))
b=int(input("Enter End Number: "))
c=int(input("Enter Step Number: "))
for i in range(a,b,c):
print(i, end=" , ") |
c961c1845e80e88496fefbb12ff75ab957c59e1a | mdadil98/Python_Assignment | /21.py | 323 | 4.53125 | 5 | # Python3 program to print all numbers
# between 1 to N in reverse order
# Recursive function to print
# from N to 1
def PrintReverseOrder(N):
for i in range(N, 0, -1):
print(i, end=" ")
# Driver code
if __name__ == '__main__':
N = 5;
PrintReverseOrder(N);
# This code is contributed by 29AjayKum... |
987ff58fecc2605230ae21fb6d3bd7bb63102b8a | seanoughton/python_flask_test | /hello_puppies/hello.py | 867 | 3.671875 | 4 | from flask import Flask #import flask class
app = Flask(__name__) # creates an app object as an instance of the class Flask
## __name__ is a python predefined variable, which is then set to the name of the module in which it is used
# this tells us ... are we running this script directly, or within another script where... |
4c7cd2043057bef063b9acaf1ed81291e738a323 | derekli66/Algorithm-In-Python | /LeetCode/152_Maximum_Product_Subarray/solution.py | 1,339 | 3.78125 | 4 | import typing
from typing import List
import pdb
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
maxProd = nums[0]
cMax = nums[0] # cMax == contiguousMax
cMin = nums[0] # cMin == contiguousMin
for value in nums[1:len... |
3cec4d50e4712190ba6353c15c84367bc641ebff | brohum10/python_code | /guessingdg.py | 717 | 3.921875 | 4 | import random
input("Ready to start? Hit the 'Enter' Key to continue\n")
user_score = 0
computer_score = 0
#Random numbers between 1 and 10
user_value = random.randint(1, 6)
computer_value = random.randint(1, 6)
print("User's turn to roll: ")
print("User first roll: [", user_value, "]\n")
print("Computer's turn... |
5e318ed167d013af2b96898b84ee384037c9fe28 | brohum10/python_code | /daniel_liang/chapter02/2.15.py | 164 | 4.25 | 4 | import math
side = float(input("Enter the side: "))
root_3 = math.sqrt(3)
area = (((3*(root_3))*(side**2))/2)
print("the area of the hexagon is %.4f" %area)
|
8e2bcf9cb452423e29381afbf2e30bfab5bc633e | brohum10/python_code | /daniel_liang/chapter06/6.8.py | 365 | 3.640625 | 4 | f = 120
def ctof(f):
print("Celsius \t Fahrenheit")
for c in range(40, 30, -1):
f = ((9/5) * c) +32
print(c ,"\t %.1f" %f)
def ftoc(f):
print("Fahrenheit \t Celsius")
for f in range(120, 20, -10):
c = (5/9) * (f - 32)
print(f ,"\t %.3f" %c)... |
bd7b188ddcb0026ce6c83a6ac7323b441ccc42a5 | brohum10/python_code | /daniel_liang/chapter06/6.12.py | 1,190 | 4.40625 | 4 | #Defining the function 'printChars'
def printChars(ch1, ch2, numberPerLine):
#y is a variable storing the count of
#elements printed on the screen
#as we have to print only a given number of characters per line
y=0
#Running a for loop
#'ord' function returns the ASCII value o... |
f94b21431f98543fcd4b42e2d0e812413c6b0245 | brohum10/python_code | /daniel_liang/chapter01/1.10.py | 120 | 3.609375 | 4 | kilometers = 14
miles = kilometers / 1.6
min = 45.5
miles_min = miles/min
print("The mph is ", miles_min * 60)
|
f272b784d1bb79bf1830c6aff3a8146c41d86a64 | brohum10/python_code | /daniel_liang/chapter04/4.33.py | 118 | 3.703125 | 4 | decimal_number = eval(input("Enter a decimal value: "))
print("The hex value is", str(format(decimal_number, "X")))
|
a7e12235441d595783104cf1c2b0f73d0d6bbf31 | brohum10/python_code | /daniel_liang/chapter06/6.14.py | 828 | 4.0625 | 4 | def sum_series(x):
#total is a variable storing the sum of the series
total=0
#running a for loop for 'x' number of times
for i in range(1, x+1):
#computing the sum by the given formula in the question
total=total+(-1)**(i+1)/(2*i-1)
#returning the ... |
704cf2839b37179cc5e097ef655cda8095ba6ff3 | brohum10/python_code | /daniel_liang/chapter02/2.26.py | 344 | 3.921875 | 4 | import turtle
import math
t = turtle.Turtle()
x1, y1 = eval(input("Enter x and y coordinate for the center of the circle: "))
radius = eval(input("Enter the legnth of the rectangle: "))
area = (radius**2)*(math.pi)
t.penup()
t.goto(x1, y1)
t.write(area)
t.fd(radius)
t.lt(90)
t.pendown()
t.circle(r... |
bba7b4798f9ed92e4e4d7e1e1752db1af69d915e | brohum10/python_code | /daniel_liang/chapter02/2.19.py | 367 | 3.984375 | 4 | investment_amount = float(input("Enter investment amount: "))
annual_interest = float(input("Enter annual interest rate: "))
num_years = float(input("Enter number of years: "))
#1200 is for percentage and divided by 12 for months
future_value = ((investment_amount)*((1+(annual_interest/1200))**(num_years*12)))
pri... |
02977e335e34fcd444d16dc649cd906a3a57fa9f | brohum10/python_code | /vector_magnitude.py | 2,020 | 3.859375 | 4 | import math
def mag_comp():
x1, y1 = eval(input("Enter first x and y coordinates to calculate vector distace : "))
x2, y2 = eval(input("Enter second x and y coordinates to calculate vector distace : "))
x_disc = x2 - x1
y_disc = y2 - y1
d = math.sqrt(((x_disc)**2) + ((y_disc)**2))
... |
089777885452d5c25f586f7d738106fd6df0864c | brohum10/python_code | /daniel_liang/chapter05/5.5.py | 387 | 3.625 | 4 | kilogram = 1
pound = 20
print("Kilorgams \t Pounds \t | \t Pounds \t Kilorgams")
while (kilogram in range(1, 200)) or (pound in range(20, 520)):
pounds = kilogram * 2.2
kilograms = pound / 2.2
print(str(format(kilogram, "<4.0f")) + str(format(pounds, "20.1f")) + " \t |"+ str(format(pound, "20.0f")) ... |
e0577b2374eac90b70d9b16b9271ce31e9e891e8 | thanhpn7/PyLearn | /py_introduction/pylearn_list.py | 1,009 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 7 09:02:38 2017
@author: THANHPN7
"""
"""Define list"""
li = ["a", "b", "c", 1, 2]
print(li)
"""Access list's elements"""
print("\r\n**** Access list ****")
print(li[1])
print(li[-1])
"""Slicing list"""
print("\r\n**** Slice list ****")
print(li[0:3]... |
927000de15de97588c91bbb6327fa0a462e74c4e | MurtazaMoiyadi/MovieDatabase-Queries | /get_best_pics.py | 665 | 3.8125 | 4 | import sqlite3
db = sqlite3.connect('movie.sqlite')
cursor = db.cursor()
start = int(input('Enter the start year: '))
end = int(input('Enter the end year: '))
command = '''SELECT O.year, M.name, M.runtime
FROM Movie M, Oscar O
WHERE M.id = O.movie_id
AND O.type = 'BEST-PICTURE... |
ce00e3e7e30332081cc1dfce94f1713d092f0584 | amiterez/holidays-flights | /h_flights/scanner/holidays.py | 4,722 | 3.515625 | 4 | import requests
import datetime
from datetime import datetime
from datetime import timedelta
HOLIDAYS_REST_API_URL="https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=off&mod=off&nx=off&year={year}&month=x&ss=off&s=off&mf=off&c=off&geo=none&m=50&s=on"
TOTAL_MONTHS_IN_YEAR = 12
SEARCH_FLIGHTS_MONTHS = 11
AVG_DAYS_I... |
7bbecf05287d5a11f158524c18c01143f42d534c | MantaXXX/python | /6- while/6-1.py | 205 | 4.28125 | 4 | # For a given integer N, print all the squares of positive integers where the square is less than or equal to N, in ascending order.
n = int(input())
i = 1
while i**2 <= n:
print(i**2, end=' ')
i += 1 |
b6b2adcf3a32878705f22edab530f7e8074da936 | MantaXXX/python | /7- list/7-3.py | 219 | 3.984375 | 4 | # Given a list of numbers, find and print all its elements that are greater than their left neighbor.
a = [int(s) for s in input().split()]
for i in range(1, len(a)):
if a[i-1] < a[i]:
print(a[i], end=' ')
|
4a902e6c95a8b980fbcf6ca3193bbc2af259988c | MantaXXX/python | /3- if else /3.A.py | 392 | 4.15625 | 4 | # Given three integers. Determine how many of them are equal to each other. The program must print one of the numbers: 3 (if all are same), 2 (if two of them are equal to each other and the third one is different) or 0 (if all numbers are different).
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
... |
a4ced4ca30dd28fd83d94da1123f05c28f7c5c99 | MantaXXX/python | /8- 2D list/8-3.py | 396 | 3.828125 | 4 | # Given an integer n, create a two-dimensional array of size n×n according to the following rules and print it:
# On the main diagonal put 0.
# On the diagonals adjacent to the main put 1.
# On the next adjacent diagonals put 2, and so forth.
n = int(input())
a = [[0] * n for i in range(n)]
for i in range(n):
fo... |
4b671215713fa3d2423859f89f49358db3de9beb | MantaXXX/python | /2- numbers/2-6.py | 156 | 4.03125 | 4 | # Given a positive real number, print its first digit to the right of the decimal point.
number = float(input())
a = int(number * 10)
b = a % 10
print(b) |
ffdde8654e3bb4ca62a566d19147d737e376fa35 | MantaXXX/python | /7- list/7-1.py | 215 | 3.96875 | 4 | # Given a list of numbers, find and print all its elements with even indices (i.e. A[0], A[2], A[4], ...).
a = [int(i) for i in input().split()]
print(a[::2])
# 另外寫法
for i in a[::2]:
print(i, sep=' ')
|
a0f99ae2bbfb5ad16f609d365dd9010725f7b02c | MantaXXX/python | /5- string/5-7.py | 313 | 3.84375 | 4 | # Given a string in which the letter h occurs at least twice. Remove from that string the first and the last occurrence of the letter h, as well as all the characters between them.
s = input()
# 找出第一位 h 索引值
a = s.find('h')
# 找出最後一位 h 索引值
b = s.rfind('h')
print(s[:a] + s[b+1:]) |
11e2fdf60d3ca31ddb10d1b042f3e2deb0600502 | MateuVieira/hackerrank | /10 Days of Statistics/Day 1 Standard Deviation/Program.py | 268 | 3.796875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
size = int(input())
numbers = list(map(int, input().split()))
mean = sum(numbers)//size
standard_deviation= sum([((a - mean) ** 2) for a in numbers])/size
print(round(standard_deviation ** 0.5,1)) |
6c8b2745c7e34271a007e2ecaaf634938cd3b851 | johnmarcampbell/concord | /concord/member.py | 956 | 4.25 | 4 | class Member(object):
"""This object represents one member of congress"""
def __init__(self, last_name='', first_name='', middle_name='',
bioguide_id='', birth_year='', death_year='', appointments=[]):
"""Set some values"""
self.last_name = last_name
self.first_name = first_nam... |
edd62710a5ae5ae17009b97d29296f58ad99f849 | sogouo/notes | /python/mydailydate.py | 1,625 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""关于命名不规范灰常👏走过路过大神瞬时指出
官方文档: https://docs.python.org/2/library/datetime.html
日常项目或者练习关于 datetime 模块的总结与Demo
"""
from datetime import timedelta, datetime, date
class MyDailyDate():
def get_day_of_each_month_in_datetime(self, *args):
""" 通过 datetime 对象获取上个月1号零时或者任何x号datet... |
42d30de9b33fe51fb789746fad7da4d252f3fca7 | htunctepe/7.hafta-odevler | /PhoneBook.py | 4,098 | 4.21875 | 4 | import time
message = """
Please select an action from the following menu
{}
1-Add a person to the phone book
2-Delete a person from the phone book
3-Update a name or a number
4-Show the phone book
Press q to quit: """
phoneBook = {}
action = ''
while str(action).lower() != 'q':
try:
action = input(messag... |
d0d9be92bad43c6a0f081bcb6d8f991e198c5847 | harshagarwal94/python-class- | /9-9-2020 classes.py | 920 | 3.984375 | 4 | #1
class person:
def __init__(self,fname, lname):
self.fname=fname
self.lname=lname
p1=person("Harsh","Agarwal")
print(p1.fname,p1.lname)
#2
class Dog:
kind="cannie"
def __init__(self,name):
self.name = name
d=Dog("fibo")
e=Dog("Buddy")
print(d.kind)
print(e.... |
b76f946e328807d32a03b6e0c8fc00e1ee084066 | Thejoker2012/ExerciciosPython | /Desafio005.py | 252 | 4.0625 | 4 | print('========================================Desafio005============================================')
n1 = int(input('Digite um numero: '))
a = n1 - 1
s = n1 + 1
print('O numero digitado foi {}\nO antecessor é {}\nO sucessor é {}'.format(n1, a, s)) |
3b04eb0ef999f9f76b4486becaa6a762c0d40394 | pradityabagus/analisis-sentimen | /ngramGenerator.py | 2,091 | 3.515625 | 4 | # N-gram generator based on nltk module
# K-most frequent words in a class od tweets
import nltk
import operator # for sorting dictionnares
# getting word frequencies from training data for a given class
def getTweetWords(tweet):
all_words = []
sTweet=tweet.split()
return sTweet
def get_word_features(wor... |
56617aabf6a6fd288a52423725fac951f1271003 | MohamedMurad/Computer-Vision-Exercises | /Image Cartoobifier/Image Cartoobifier.py | 4,042 | 3.5 | 4 |
# coding: utf-8
# # Image Cartoonifier
# ## Applying Image Processing Filters For Image Cartoonifying
# In[1]:
# import needed libraries
import cv2
import matplotlib.pyplot as plt
import glob
# ---
# ## 1. Generating black and white sketch and Noise Reduction Using Median Filter
#
# In[2]:
# default color i... |
269f012a02a5d731a08f30a9ad90548208c0bd81 | lofues/programer_code_interview_guide | /2.链表问题/向有序的环形单链表中插入新节点.py | 1,710 | 4.0625 | 4 | """
向有序的环形单链表中插入新节点
注意:若该节点值大于所有节点要插入到最后一个位置
若该节点值小于所有节点,需要更换新的头结点
若链表为空则返回单个的环形链表
"""
import random
class Node(object):
def __init__(self,val = None):
self.val = val
self.next = None
def print_list(head):
if head is None:
return
dummyhead = head
pri... |
19914fe1ec81faa970e660f20aac5dccb905333c | lofues/programer_code_interview_guide | /2.链表问题/环形单链表的约瑟夫问题.py | 1,497 | 3.75 | 4 | """
一个循环链表,每次遍历到第m个节点时便删除该节点,之后从该节点之后循环遍历到第m个节点并删除
返回最后剩余的一个节点,并自成循环链表
"""
import random
class Node(object):
def __init__(self,val = None):
self.val = val
self.next = None
def print_list_circle(head):
if head is None:
return
cur = head
print(cur.val, end=' ')
wh... |
099d46132be05529140e38f9b1bf456559304bd8 | lofues/programer_code_interview_guide | /3.二叉树问题/1.分别使用递归和非递归方式实现前序、中序、后序遍历.py | 3,119 | 3.96875 | 4 | """
使用不同方式实现二叉树的前中后序遍历
"""
import random
class TreeNode(object):
def __init__(self, val = None):
self.val = val
self.left = None
self.right = None
def make_tree(num):
arr = [random.randint(0,9) for _ in range(num)]
return _list_make_tree(None, arr, 0)
def _list_make_tree(ro... |
96b81904b3b745ec24922bb44fca799f3cd18439 | anpoon430/Personal-projects | /scrapedatajobpostings.py | 4,922 | 3.640625 | 4 | """
Created on Sat Mar 10 23:36:40 2018
This program scrapes jobsdb.com for job listings.
It gathers all the links on each page to each posting,
then scrapes each listing for all the relevant information and
stores it in a dictionary. Finally, a CSV file containing the date,
title, company name, company information an... |
0eb70f5bceb57d197e98983ad95f1f2bee6d2da2 | JSagueFlo/pythonsnippets | /resize_image.py | 1,842 | 3.6875 | 4 | # Using Python 3.6.8
from PIL import Image
'''
Resize image keeping aspect ratio
'''
print("Resize image keeping aspect ratio")
print("-" * 50)
img = Image.open('image.jpg')
width, height = img.size
new_width = 1200
if new_width > width:
print("augmenting, this can cause blur effect")
else:
print... |
4915d79911ebc4908da3b3f5598f7a2f6df3b800 | weifanhaha/leetcode | /python3/q1-50/3_longest_substring_without_repeating_characters.py | 526 | 3.5625 | 4 | class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
l = r = 0
max_len = 0
chars = set()
while l <= r and r < len(s):
if s[r] not in chars:
chars.add(s[r])
max_len = max(max_len, r - l + 1)
r += 1
e... |
3602d26bda7b7625140e2ec01d2dc0edcfd306bf | weifanhaha/leetcode | /python3/q1-50/46_Permutations.py | 438 | 3.515625 | 4 | class Solution:
def permute(self, nums):
if not nums:
return []
if len(nums) == 1:
return [nums]
sol = []
for i in range(len(nums)):
res = nums[:i] + nums[i+1:]
for p in self.permute(res):
sol.append(p + [nums[i]])
... |
3cc977367bd8242b7bd754ab0b1ca283f21ff9da | weifanhaha/leetcode | /python3/q1-50/23_Merge_k_Sorted_Lists.py | 1,188 | 3.609375 | 4 | # class Solution(object):
# def mergeKLists(self, lists):
# """
# :type lists: List[ListNode]
# :rtype: ListNode
# """
# l = []
# for list_node in lists:
# next_one = list_node
# while next_one:
# l.append(next_one)
# ... |
ef53445f1e0a6216d3352fac9b8312e6feb0c215 | weifanhaha/leetcode | /python3/q101-150/143_Reorder_List.py | 1,047 | 3.9375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head... |
7d642594c4a60b5949461ed7f3219d59555a5402 | weifanhaha/leetcode | /python3/q50-100/83_Remove_Duplicates_from_Sorted_List.py | 943 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
while curr:
while curr.next and curr.val == curr.next.val:
... |
482af67eb3871c0c5aa66ad8ad26992e90c3c290 | weifanhaha/leetcode | /python3/q1-50/11_Container_With_Most_Water.py | 499 | 3.65625 | 4 | from typing import List
class Solution:
def maxArea(self, height: List[int]) -> int:
l = 0
r = len(height)-1
max_area = 0
while l < r:
max_area = max(max_area, (r-l) * min(height[l], height[r]))
if height[l] <= height[r]:
l += 1
... |
3e948af632813384edc5b7f6e64a84beeb36e02d | weifanhaha/leetcode | /python3/q50-100/86_Partition_List.py | 1,113 | 3.828125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
h1 = l1 = ListNode(0)
h2 = l2 = ListNode(0)
h1.next = l1
h2.next = l2
whi... |
036d80086c7882f991cecc0c82fbdaa28e317c1c | weifanhaha/leetcode | /python3/q1-50/31_Next_Permutation.py | 1,437 | 3.625 | 4 | class Solution:
def nextPermutation(self, nums):
i = len(nums) - 2
while i >= 0 and nums[i+1] <= nums[i]:
i -= 1
if i >= 0:
j = len(nums) - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
... |
62cd51f8869cda6893e815f3508fc07b61f7e91f | andelgado53/interviewProblems | /order_three_colors.py | 971 | 4.15625 | 4 | # Problem Statement:
# You are given n balls. Each of these balls are of one the three colors: Red, Green and Blue.
# They are arranged randomly in a line. Your task is to rearrange them such that all
# balls of the same color are together and their collective color groups are in this order:
# Red balls first, Green... |
4fffd0870f81f9d7504f95a4e8f1ad9cd55ccf1c | andelgado53/interviewProblems | /graph_cycle.py | 1,385 | 3.546875 | 4 | import pprint
class GraphNode:
def __init__(self, label):
self.label = label
self.neighbors = set()
with_cycle = []
a = GraphNode('a')
b = GraphNode('b')
c = GraphNode('c')
d = GraphNode('d')
e = GraphNode('e')
f = GraphNode('f')
g = GraphNode('g')
h = GraphNode('h')
a.neighbors.add(b)
a.neighbors... |
b83844de875d0191e1a71552917e525b10b6ebf1 | andelgado53/interviewProblems | /find_cycle_in_array.py | 524 | 3.796875 | 4 |
data = [ 1, 2, 1, 3, 4, 8]
data1 = [1,2,3,4,5]
def find_cycle(array):
p = 0
q = 0
while True:
if p >= len(array) or q >= len(array):
return False
p = array[p]
if p == q:
return True
if p >= len(array)-1:
return False
p = array[p]
... |
931caf9121a7ec9e6b6e478470f120791089e7bd | andelgado53/interviewProblems | /reverse_nodes_in_k_groups.py | 2,240 | 3.921875 | 4 | # https://leetcode.com/problems/reverse-nodes-in-k-group/
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
#
# k is a positive integer and is less than or equal to the length of the linked list.
# If the number of nodes is not a multiple of k then left-out nodes in the... |
fa39e07ae10c3368d33c9d17d7971afece313160 | andelgado53/interviewProblems | /palindrome_permutations.py | 724 | 4 | 4 |
def is_palindrome(word):
start = 0
end = len(word) - 1
is_palindrome = True
while start < end:
if word[start] != word[end]:
return False
start +=1
end -=1
return is_palindrome
def get_letter_frequencies(word):
letter_freq = {}
for letter in word:
... |
276e38bf3598e557e47b7513fdbca2c9b1eb5691 | andelgado53/interviewProblems | /reverse_string_in_place.py | 382 | 3.5625 | 4 | input = ['a', 'b', 'c', 'd', 'e', 'f']
def reverse_in_place(input):
start = 0
end = len(input) - 1
while start < end:
new = input[start]
input[start] = input[end]
input[end] = new
start +=1
end -=1
return input
# print(reverse_in_place([ 'c', 'a', 'k', 'e', ' ... |
217a5453ea804bd4f712fe2c1ddaa3b38d0ca94d | andelgado53/interviewProblems | /is_single_riffle.py | 1,888 | 3.8125 | 4 | from random import shuffle
deck = [1,2,3,4,5,6,7,8,9,10,11, 12,13,14,15,16,17,18,19, 20]
shuffled_deck = [1,2,3,4,5, 12,13,14, 15, 6,7,8,9,10,11, 16,17,18,19,20]
def is_single_riffle2(shuffled_deck):
half1 = [1,2,3,4,5,6,7,8,9,10,11]
half2 = [12,13,14,15,16,17,18,19, 20]
index1 = 0
index2 = 0
... |
ac2752d651fd1f78118357e504f5fc58e2d4b712 | andelgado53/interviewProblems | /day_trade.py | 1,311 | 3.6875 | 4 | stock_prices = [10, 7, 5, 8, 11, 9]
def get_max_profit(stock_prices):
max_profit = -10000
already_seen = set()
for index, purchased_value in enumerate(stock_prices):
for sell_value in stock_prices[index+1: ]:
if (sell_value, purchased_value) not in already_seen:
pro... |
e5376089499f5bce5631b85ee1581a57451f0cb2 | andelgado53/interviewProblems | /zig_zag_conversion.py | 2,140 | 4.15625 | 4 | import pprint
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
# (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a ... |
f51cbb356a1899216c3ad8ba4abad6b819e176df | andelgado53/interviewProblems | /single_value_trees.py | 1,557 | 3.75 | 4 | # Single Value Tree
# Problem Statement:
# Given a binary tree, find the number of unival subtrees
# (the unival tree is a tree which has the same value for every node in it).
class Node:
def __init__(self, val):
self.val = val
self.left_ptr = None
self.right_ptr = None
def num_of_single... |
9e84a0156febb09375208e2f1be5d4b3b30ae95e | andelgado53/interviewProblems | /set_matrix_zero.py | 1,956 | 4.28125 | 4 | # https://leetcode.com/problems/set-matrix-zeroes/
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
#
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
# Example 2:
#
# Input:
# [
# [0,1,2,0],
# ... |
f099fe4a9a928d3e45192e9e23e728f12057674d | gotarazo/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-write_file.py | 261 | 4.0625 | 4 | #!/usr/bin/python3
"""Defines a file-writing function"""
def write_file(filename="", text=""):
"""Write string to text file and returns number characters written"""
with open(filename, "w", encoding="utf-8") as _file:
return _file.write(text)
|
fe1225c79fcd50fe5382b92b6b9f0f7236b5e508 | gotarazo/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 408 | 4.03125 | 4 | #!/usr/bin/python3
"""Defines a text indentation function"""
def text_indentation(text):
"""prints a text with 2 new lines after '.', '?', and ':"""
if not isinstance(text, str):
raise TypeError("text must be a string")
string = ""
specials = ['.', '?', ':']
for ch in text:
string ... |
c52682029f4bfeb8ded75c3a06ecce396a888468 | gotarazo/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 425 | 4.03125 | 4 | #!/usr/bin/python3
"""Defines a text file insertion function"""
def append_after(filename="", search_string="", new_string=""):
"""Inserts line of text to file line containing specific string after"""
txt = ""
with open(filename) as r:
for line in r:
txt += line
if search_s... |
cb9d8450cc3101de16179244df039c3d6b00ca4a | MisakaRxyh/architects-teach-deep-learning | /1-2/step7.py | 2,251 | 3.875 | 4 | # 重写Network 新增 gradient 函数 求每个参数梯度
# 寻找损失函数更小的点
import numpy as np
from step2 import load_data
# 将计算 w 和 b 梯度的过程,写成Network类的gradient函数
class Network(object):
def __init__(self, num_of_weights):
# 随机产生 w 的初始值
# 为了保持程序每次运行结果的一致性,此处设置固定的随机数种子
np.random.seed(0)
self.w = np.random.randn... |
68e9352f3b5001a5c86795423ab51f28b2bc2296 | GuiJR777/5-IDEIAS-DE-PROJETOS-EM-PYTHON-PARA-INICIANTES | /desafios/simulador_dado.py | 4,615 | 3.796875 | 4 | '''1. SIMULADOR DE DADO
Objetivo: Seu script deve gerar um valor aleatório entre 1 e 6(ou uma faixa que você definir) e permitir que o usuário rode o script quantas vezes quiser.
Habilidades praticas a aplicar:
Tratamento de exceções
Condicionais If/Else
Input de dados
Geração de valores
Print
Detalhes e boas Prática... |
b7e826eea2cb2bc38d5989eb99e2c835d009930c | sanket-qp/IK | /5-DP/coin_play.py | 3,651 | 4.03125 | 4 | """
Consider a row of n coins of values v , . . ., v .
We play a game against an opponent by alternating turns.
In each turn, a player selects either the first or last coin from the row,
removes it from the row permanently, and receives the value of the coin.
Determine the maximum possible amount of money we can d... |
16c125fbe1b7e1dfeba8515f38a5e88cf73e5380 | sanket-qp/IK | /16-Strings/longest_repeating_substring.py | 6,042 | 4.125 | 4 | """
Longest repeating substring
Approaches:
(1) Brute force: Generate all substrings and count their occurrence
Time Complexity: O(N^4) = O(N^2) for generating all substrings
+ O(N^2) for num_occurrence (string compare also takes O(N))
Space Complexity: ... |
a9ca7660d5daf407247efa3219bde5714591e492 | sanket-qp/IK | /4-Trees/invert_binary_tree.py | 1,141 | 4.3125 | 4 | """
You are given root node of a binary tree T. You need to modify that tree in place,
transform it into the mirror image of the initial tree T.
https://medium.com/@theodoreyoong/coding-short-inverting-a-binary-tree-in-python-f178e50e4dac
______8______
/ \
1 __16
... |
df7b73944b7b1d4676d64edafeb1c3cbc976d483 | sanket-qp/IK | /3-Recursion/power.py | 1,109 | 4.1875 | 4 | """
The problem statement is straight forward. Given a base 'a' and an exponent 'b'. Your task is to find a^b.
The value could be large enough. So, calculate a^b % 1000000007.
Approach:
keep dividing the exponent by two pow(2, 8) will be handled as follows
2x2x2x2 x 2x2x2x2
... |
73601e344b62ecc1b895c7485c0654c73927cb81 | sanket-qp/IK | /3-Recursion/strings_from_wildcard.py | 2,544 | 4.34375 | 4 | """
You are given string s of length n, having m wildcard characters '?', where each wildcard character represent
a single character.
Write a program which returns list of all possible distinct strings
that can be generated by replacing each wildcard characters in s with either '0' or '1'.
Any string in returned list... |
8aa76c6fc8ce909d602ab20db646afb81c54dcce | sanket-qp/IK | /4-Trees/postorder_without_recursion.py | 738 | 3.765625 | 4 | from bst import Tree as BST
def process(node):
print "%s" % node
def postorder(root):
if not root:
return
if root.is_leaf():
process(root)
return
stack = []
stack.append(root)
while stack:
top = stack[-1]
if top.is_leaf():
stack.pop()
... |
7d8f85173a4b68d9c43e3e13393f6fc5469854e2 | sanket-qp/IK | /1-sorting/merge_sort.py | 1,876 | 3.984375 | 4 | """
Implementation of merge sort
"""
import math
import random
def _merge(arrA, startIdxA, endIdxA, arrB, startIdxB, endIdxB):
mergedArr = []
idxA = startIdxA
idxB = startIdxB
while idxA <= endIdxA and idxB <= endIdxB:
if arrA[idxA] <= arrB[idxB]:
mergedArr.append(arrA[idxA])
... |
731e4f31afeb97b0881aaef9044ba77833e79e36 | sanket-qp/IK | /5-DP/word_break.py | 5,189 | 4.1875 | 4 | """
You are given a dictionary set dictionary that contains dictionaryCount distinct words and another string txt.
Your task is to segment the txt string in such a way that all the segments occur in a continuous manner in the original
txt string and all these segments (or words) exists in our dictionary set dictionary.... |
7fdc67d441054d5930aa8a0bbc309a8fc87c6338 | sanket-qp/IK | /6-Graphs/alien_dictionary.py | 3,407 | 4.0625 | 4 | """
https://leetcode.com/problems/alien-dictionary/
Given a sorted dictionary of an alien language, you have to find the order of
characters in that language.
There is a new alien language which uses the latin alphabet. However, the order among letters are unknown to you.
You receive a list of non-empty words from th... |
447c50394bc0ec745ca4c1be84f7be5d454d1893 | sanket-qp/IK | /3-Recursion/target_sum.py | 1,582 | 3.796875 | 4 | """
Given an integer array arr of size n and a target sum k,
you have to determine, whether there exists a non-empty group of numbers
(numbers need not to be contiguous) in arr such that their sum equals to k.
"""
def __target_sum(arr, idx, K, taken, result):
if K == 0:
result.append(taken[:])
... |
b582309ce92aec4b604110253b8bbf346de29af1 | sanket-qp/IK | /4-Trees/binary_tree_printer.py | 7,830 | 3.671875 | 4 | import sys
from copy import deepcopy as deepcopy
class Queue(object):
def __init__(self, items=None):
if items is None:
self.a = []
else:
self.a = items
def enqueue(self, b):
self.a.insert(0, b)
def dequeue(self):
return self.a.pop()
def isEmp... |
b3a55b4092420b2891aa680c49222ef7bbfeaa47 | MikeM711/PO-Script | /z_SampleExample.py | 1,830 | 3.859375 | 4 | #
import xlwt # Writes Files
import xlrd # Reads Files
# xlrd documentation - http://xlrd.readthedocs.io/en/latest/api.html
# We will be opening input.xlsx with xlrd to read. Using "xlrd" in the beginning of the python file allows us to use xlrd of its entirety!
workbook = xlrd.open_workbook('input.xlsx')
# We wi... |
d293ee5901966c6a373bc0b36517b1992bfc42f5 | sorenmulli/graph-of-thrones | /src/build.py | 1,630 | 3.609375 | 4 | from __future__ import annotations
import re
import os
import json
def get_names(path: str = "data") -> dict[str, list[str]]:
"""
Reads the character data base characters.json.
"""
with open(os.path.join(path, "characters.json"), "r") as f:
characters = json.load(f)
return characters
def... |
a8d8936a66c30d62e3a341a0c7549c12ee875992 | iJohnMaged/Huffman-Coding | /HuffmanTree.py | 4,243 | 4.0625 | 4 | from BinTree import Node
from heapq import heappop, heappush, heapify
from collections import Counter
class HuffmanTree(object):
def __init__(self, root=None):
self.heap = []
self.root = root
def calculateFrequency(self, text):
"""Calculates how many times a character appears in text... |
6f2334d301ab329321ee6f4626fc4c680bf8343a | SARIKAYA77/Airline-Management-System | /airline/flights/models.py | 1,877 | 3.53125 | 4 | from django.db import models
# Create your models here.
# models are python classes which represent each table
# Airport model
class Airport(models.Model):
# below are the rows for Airport tabel
# there'll be a id row by default which is PK and AI
code = models.CharField(max_length=3)
city = models.C... |
959b2bd0682a091c7f1ffccd29f0b9137361b745 | chennqqi/bigdata-fortune-telling | /02_mapreduce/square_sum.py | 1,431 | 3.90625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
#. 任务:求数组 [1, 8, 9, 20, 3, 9] 每个元素的平方和
ldemo = [1, 8, 9, 20, 3, 9]
def fun_map(l):
"""映射,平方
"""
return (i**2 for i in l)
def fun_reduce(l):
"""化约, 相加
"""
return sum(l)
def mapreduce():
"""map-reduce程序演示
"""
mapout = fun_map(ldemo)
reduceout = fun_reduce(mapout)
... |
fdaf5f312dd7b3f0f1d3c67c2e111517bb6f0c98 | nimomaina/Password-locker | /credential.py | 1,472 | 3.71875 | 4 |
class Credentials:
"""
Class that generates instances of credential data
"""
credentials_list = []
def __init__(self, acc_name, acc_username, acc_password):
self.acc_name = acc_name
self.acc_username = acc_username
self.acc_password = acc_password
def save_credential... |
310580a11e81d83443b0ca1dccdad332056b916a | deepitapai/Coding-Interview-Prep | /Leetcode solutions/find-first-last-range-sorted-array.py | 522 | 3.703125 | 4 | def searchRange(nums,target):
def searchRangeLeft(nums,target):
l,h = 0,len(nums)-1
while l<=h:
mid = (l+h)//2
if nums[mid] < target:
l = mid+1
else:
h = mid -1
return l
def searchRangeRight(nums,target):
l,h = 0,len(nums)-1
while l<=h:
mid = (l+h)//2
if nums[mid] <= target:
l = m... |
e6191091fd60aee1d060c9eea8dba86b37b80085 | deepitapai/Coding-Interview-Prep | /Leetcode solutions/containter-most-water.py | 237 | 3.515625 | 4 | def containerMostWater(arr):
maxArea = 0
l,r = 0,len(arr)-1
while l<r:
maxArea = max(maxArea,min(arr[l],arr[r])*(r-l))
if arr[l] <= arr[r]:
l +=1
else:
r -=1
return maxArea
print(containerMostWater([1,8,6,2,5,4,8,3,7])) |
932ab39ad360bddc5a9c0786588cacc8a2ff9e42 | deepitapai/Coding-Interview-Prep | /Leetcode solutions/wildcard-matching.py | 432 | 3.53125 | 4 | def wildcardMatching(s,p):
dp = [[False for f in range(len(p)+1)] for i in range(len(s)+1)]
for i in range(1,len(p)+1):
if p[i-1] != '*':
break
dp[0][i] = True
dp[0][0] = True
for i in range(1,len(dp[0])):
for j in range(1,len(dp)):
if p[i-1] == s[j-1] or p[i-1] == '?':
dp[j][i] = dp[j-1][i-1]
... |
4fd59d2ddc015458df5c19288a693428d75a5f73 | deepitapai/Coding-Interview-Prep | /Leetcode solutions/valid-sudoku.py | 971 | 3.625 | 4 | def validSudoku(board):
def isUnitValid(unit):
unit = [i for i in unit if i!='.']
return len(set(unit)) == len(unit)
def checkRow(board):
for row in board:
if not isUnitValid(row):
return False
return True
def checkCol(board):
for col in zip(*board):
if not isUnitValid(col):
return False
... |
d5b76414a156ed71ea35dafe416840bf1980b07b | sandro93/praxis | /util/anagrama.py | 364 | 3.953125 | 4 | import os
import itertools
vocab = open("vocabulary.txt", "r")
wordlist = set()
for word in vocab.readlines():
wordlist.add(word.strip())
def anagram(letterset):
for word in itertools.permutations(letterset):
word = ''.join(word)
if word in wordlist:
print(word)
anagram(in... |
91acc9bd925f21654d1992dc9048232b8a8482c6 | duhjesus/practice | /hackerrank/countingInversions.py | 2,916 | 4.25 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# function: helper function
# merges left and right half arrays in sorted order
# input:nums= array to be sorted
# temp= place holder array, hard to do inplace sorting
# leftStart = start index of the left half array
# ... |
2866fde079a6ef9881df498c653db42f338d85c4 | erigler-usgs/pyLTR | /pyLTR/Graphics/Encoder.py | 1,455 | 3.75 | 4 | import glob
class Encoder(object):
"""
Abstract base class for movie encoder. See ffmpeg.py and mencoder.py for sample implementations
"""
def __init__(self):
"""
Raises EnvironmentError if encoder is not installed.
"""
raise NotImplementedError
def _isInstall... |
64825315d30fcafceea46f3346bbbb00f04157c5 | gnclmorais/interview-prep | /recursion/04april/02complete.py | 248 | 3.6875 | 4 | def max(numbers, largest_so_far=0):
if numbers == []:
return largest_so_far
next_num = numbers[0]
if next_num > largest_so_far:
return max(numbers[1:], next_num)
else:
return max(numbers[1:], largest_so_far)
|
d3f911d5937815913e7c8b4fa10e1ce68ea821ab | Miryu-PS/2021_DGUalgocamp | /코드리뷰/장문주(jmj2359)/5일차/코드리뷰_좌표압축.py | 153 | 3.515625 | 4 | n=int(input())
l=list(map(int,input().split()))
sort=sorted(set(l))
d={a:b for b,a in enumerate(sort)}
for i in l:
print(d[i], end = " ")
print("")
|
3a64b7a08e77c9d4b7a512b03a4683f26d56ed9a | borntofrappe/python-scripts | /binary-tree/maze.py | 3,190 | 3.75 | 4 | from cell import Cell
from random import choice
class Maze:
def __str__(self):
return self.format_maze()
def __init__(self, size):
self.size = size
maze = []
for i in range(size ** 2):
column = i % size
row = i // size
cell = Cell(column, ro... |
71ffe3400a40df8ca2d9688d5973c1926bf2ec43 | RutRabinowitz/pokemons_project | /add_pokemon_to_owner.py | 1,545 | 3.53125 | 4 | import pymysql
connection = pymysql.connect(
host="localhost",
user="root",
password="towr678",
db="pokemon",
charset="utf8",
cursorclass=pymysql.cursors.DictCursor
)
def owner_name_by_id(owner_id):
with connection.cursor() as cursor:
owner_id_query = f"""select name... |
682bd465ab3f5c7cdad1ace2e54b41c1f5ad29c4 | Cdt12233344446/ichw | /pyassign3/wcount.py | 2,264 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: <utf-8> -*-
"""wcount.py: count words from an Internet file.
__author__ = "Cai Danyang"
__pkuid__ = "1700011774"
__email__ = "1700011774@pku.edu.cn"
"""
import sys
from urllib.request import urlopen
def alnumify(word):
"""convert freshly split words to ones containing onl... |
c393f87657b09fc9fb90621ef0d6ffe8eef1c47d | ErikBrany/python-lab2 | /Lab 2_Exercise 2.py | 914 | 4.125 | 4 | from sys import task_list
print(sorted(task_list))
index = int(input("1. Insert new task, 2. Remove task, 3. Show all existing tasks, 4. Close program, Choose an action 1-4: "))
while index != 4:
if index == 1:
new_list = input("What task would you like to add: ")
task_list.append(new_list)
... |
ec36860320bee6e6f6a7055f10f9b7fbd58f5404 | abdulalikhan/Image-Compression-with-RLE | /PNG to RGB Grid/PNGToGrid.py | 1,149 | 3.8125 | 4 | # you need the PILLOW Image Processing library
# type "pip install Pillow" to install this Python Library
from PIL import Image
print("######## ###### ########")
print("## ## ## ## ## ##")
print("## ## ## ## ##")
print("######## ## #### ########")
print("## ## ## ##... |
d1a2bbabbb8fbd9469c88f39f0f083db8dbc4636 | dowlandaiello/selection-sim | /ssim/test_actor.py | 3,283 | 3.6875 | 4 | import unittest
from actor import Condition, InputModifier, ModificationOperation, ResponseNetNode
class TestCondition(unittest.TestCase):
'''A class used to test the functionality of the Condition helper type'''
def test_is_active(self):
cond = Condition.EQ
# The condition must be true if tw... |
3a8a59d2c938946a8c91a90bad12dd7189f174c0 | neu-spiral/iROPASSISTPackage | /code/loadImages.py | 1,245 | 3.546875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 10 12:51:53 2018
@author: veysiyildiz
"""
from keras.preprocessing import image
import numpy as np
import os.path
def readImages(image_names, path_to_folder):
'''
read images in the image_names list, write them to an array. if an image does... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.