blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3b633fb9d6b644e254c2334ec53fd8dba8c68fef | daniel-reich/ubiquitous-fiesta | /oCe79PHB7yoqkbNYb_5.py | 168 | 3.546875 | 4 |
def break_point(num):
nums = [int(num) for num in str(num)]
for i in range(1, len(nums)):
if sum(nums[:i]) == sum(nums[i:]):
return True
return False
|
885c94edb21c3597df8e550d0f2bf29d97319336 | NisaSource/python-algorithm-and-data-structure | /dataStructure/BinaryHeap.py | 1,523 | 3.90625 | 4 | class Heap:
def __init__(self, sz):
self.list = (sz + 1) * [None]
self.heapSz = 0
self.maxSz = sz + 1
def heap_peek(root):
if not root:
return
else:
return root.list[1]
def heap_size(root):
if not root:
return
else:
return root.heapSz
def... |
950c60c32ccbe5ca50191be5502c8ff9cbed992a | Dharanikanna/Python | /FIND FIRST AND LAST NUMBER IN A DIGIT.PY | 208 | 3.703125 | 4 | def fdigit(A):
while (A>=10):
A=A//10
print(A)
#--------------------
def ldigit(A):
A=A%10
print(A)
#--------------------
A=int(input())
count=0
fdigit(A)
ldigit(A)
|
c10ab96915c6b68e4cc3f139befbda31486f1a48 | luismvargasg/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 474 | 4.34375 | 4 | #!/usr/bin/python3
"""Module to read n lines text file"""
def read_lines(filename="", nb_lines=0):
"""function that reads n lines of a text file (UTF8)
and prints it to stdout.
Args:
filename: text file to read.
nb_lines:
"""
with open(filename) as myFile:
lines = myFil... |
b2652bdd386f12d07d8d186299f1a9473e10fa8a | Brunocfelix/Exercicios_Guanabara_Python | /Desafio 011.py | 559 | 4.0625 | 4 | # Desafio 011: Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área e a
# quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m^2;
L = float(input('Digita a Largura da parede, em metros: '))
A = float(input('Digite a Altura da parede, em... |
e5852f031ba1f1d5667a08f34eba59abd06e6545 | linoor/Euler | /Python/PentagonNumbers44.py | 1,117 | 3.78125 | 4 | import unittest
import math
import time
def isPentagonal(n):
return ((math.sqrt(24*n+1)+1) / 6).is_integer()
def pentagonal(n):
return (n*(3*n-1))/2
start_time = time.time()
i = 1
found = False
while not found:
second = pentagonal(i)
for j in range(i-1, 1, -1):
first = pentagonal(j)
if i... |
280efdf97721da73b2234a5f66329b7d140b800f | mikiotada/LeeCode_exercises | /palindrome.py | 575 | 3.984375 | 4 | """
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
"""
def isPalindrome(s):
"""
0(n)
"""
store = []
s = s.lower()
for char in s:
if char.isalnum():
store.append(char)
if len(store) == 0:
return ... |
38c2ff423aaaee904cb25efbc7c78bb2c3d2965f | finlayg/colloidsoncones | /checkoverlaps.py | 915 | 3.625 | 4 | #checks if any particles in coords file are overlapping
inputfile = input('Coords Input Filename: ')
from math import sqrt
#generating particle coordinate list
particlelist = []
with open(inputfile, 'r') as stream1:
for line in stream1:
values = line.split(' ')
splitline = lin... |
f3c187d9234d48ebaa1b6607af5f1d82c083ef54 | TPALMER92/HWFin5350 | /main.py | 589 | 4.09375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 4 17:15:56 2017
@author: courtenaenielson
"""
from nuggets import is_nugget_number
def main():
small, medium, large = 6, 9, 20
count = 0
largest = small - 1
candidate = small
while count != small:
if(is_nugget_num... |
373b8ca41aa840298d488649d5e545ad5b6a589f | FukurouMakoto/GBF-SparkCalculator | /SparkCalculator.py | 1,285 | 3.765625 | 4 | def totalDraws(crystals, tix, tenrolls):
totalDraws = ((int(tix)*300) + (int(tenrolls)*3000) + int(crystals)) / 300
return totalDraws
def how_many_rolls(total):
if total == 300:
return "You can spark a character!"
elif total > 300:
leftover = total - 300
return f"You can spark a character and have {str(int(... |
5c720c9a9a2622590177f603a20c260c25f1f0a1 | WALL-EEEEEEE/interview | /design_pattern/singleton_1.py | 679 | 3.71875 | 4 | #
# Singleton
# Based by shared properties
#
#
#
class singleton(object):
_state = {}
def __new__(cls,*args, **kwargs):
ob = super(singleton,cls).__new__(cls,*args,**kwargs)
ob.__dict__ = cls._state
return ob
class MyClass(singleton):
name = "MyClass"
myclass = MyClass()
myclass.na... |
399a30313581f0067145e93c129e4e8ff38ed937 | fd-facu/termodinamica | /radiobutton.py | 1,141 | 3.5 | 4 | import sys
if sys.version_info[0] < 3:
import Tkinter as tk
import tkFont as tkfont
else:
import tkinter as tk
from tkinter import font as tkfont
def sel():
print("entro")
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = tk.Tk()
var = tk.IntVar... |
8e1ea7800a2275cc4a066878cf836ac54d07fe8d | IhsanE/Algorithms | /bfs.py | 336 | 3.640625 | 4 | G={"A":["B","C","D"],"B":["A","E","F"],"C":["A","F"],"D":["A"],"E":["B"],"F":["B","C"]}
def bfs(G,v):
node=0
parent={v:None}
q=[v]
for v in q:
for i in G[v]:
if i not in parent.values():
parent[i]=v
q.append(i)
return parent
print (bfs(G... |
441f257c43d758a2b3b30a58126dd73c88b47219 | idanSoudry/pinkFloyd | /data.py | 7,205 | 3.890625 | 4 | import collections
import datetime
PATH = r"Pink_Floyd_DB.txt"
def dbase():
"""
This function organise the data base to a difficult build
:return: the difficult build
"""
albums_data = {}
song_dict = {}
songs_list = []
with open(PATH, 'r') as f:
data = f.read()
... |
146a2598d42742a1a86c662e42413e6a8a1b6021 | xintao0202/Gatech_Machine-Learning-for-Trading | /m3p3/mc2_p2/marketsim.py | 6,418 | 3.53125 | 4 | """MC2-P1: Market simulator."""
import pandas as pd
import numpy as np
import os
from util import get_data, plot_data
from portfolio.analysis import get_portfolio_value, get_portfolio_stats, plot_normalized_data
def compute_portvals(start_date, end_date, orders_file, start_val):
"""Compute daily portfolio value ... |
0f662d24569e16f7b59220235dd21e243733d2d7 | krivacic/homework1 | /example/algs.py | 2,499 | 4.25 | 4 | import numpy as np
import time
def pointless_sort(x):
"""
This function always returns the same values to show how testing
works, check out the `test/test_alg.py` file to see.
"""
return np.array([1,2,3])
def bubblesort(x):
"""
Describe how you are sorting `x`
"""
#Bubble sort for i... |
7ee3e769b37470bedfde91ebbbb9ccd8432bbc40 | SnehankaDhamale/Python-Assg-WFH- | /Assignment6/ex20.py | 172 | 4.25 | 4 | #Write a Python program to print all ASCII character with their values
for i in range(1,255): #ascii range is 1-254
ch=chr(i) #typecast int to char
print(i,"=>",ch) |
862e50bcd279acf307f269fbf79493ddd42e4bd7 | HenriquedaSilvaCardoso/Exercicios-CursoemVideo-Python | /Exercícios em Python/PythonExercícios/ex036.py | 472 | 3.640625 | 4 | vcasa = float(input('Qual o valor da casa a ser comprada? R$'))
sal = float(input('Qual o seu salário? R$'))
tem = (int(input('Em quantos anos você pretende pagar essa casa? ')))
par = vcasa/(tem*12)
print(f'Uma casa de R${vcasa:.2f} sendo paga em {tem} anos terá uma prestação de {prest:.2f}')
if prest > 0.3*sal:
p... |
61a89fea69950a42ce39ffcfd562f6b529dbde25 | strongliu110/offer | /51_InversePairs.py | 2,234 | 3.6875 | 4 | """
// 面试题51:数组中的逆序对
// 题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组
// 成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
"""
import copy
# 归并排序(分治)。时间O(nlogn),空间O(n)
def merge_sort(nums):
if len(nums) <= 1:
return nums
num = len(nums) // 2
left = merge_sort(nums[:num]) # 左边有序
right = merge_sort(nums[num:]) # 右边有序
... |
6ae0835e1381e2172d1e9548e01eb0257a95343b | nikhil2195/pythonprojects | /bubblesort/bubblesort.py | 457 | 4.1875 | 4 | def bubblesort(sortlist):
l=len(sortlist)
for i in range(l):
for j in range(i+1,l):
if sortlist[i]>sortlist[j]:
sortlist[i],sortlist[j]=sortlist[j],sortlist[i]
return sortlist
def main():
print("Enter the list cof numbers to be sorted.Keep a space between the numbe... |
1211abc8d56ba0bca7a163f3c87990edeedf7eb4 | AndGasper/code_playground | /simple_line_chart_ch3.py | 399 | 3.78125 | 4 | from matplotlib import pyplot as plt
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
# create a line chart, years on x-axis, gdp on y-axis
plt.plot(years, gdp, color='green', marker='o', linestyle='solid')
# title for plot
plt.title("Nominal GDP")
#... |
adfeac03977dd1fbe1518655d4b8bb7504c84dfc | meoweeb/Pricing-Project | /pricetoolscript-fixing.py | 2,551 | 4.5625 | 5 | """
This tool is designed to take user input of cost and determine the range of
pricing needed to make a profit greater than their desired value.
"""
#shipping function - determines if we pay shipping and returns true or false
def ship_true(shipping_bool):
has_shipping = input("Do we pay shipping on... |
7857e3db5217411ead0ea5c95cde7be0e9b32260 | JaiHindocha/Combat-Game | /main.py | 9,868 | 3.578125 | 4 | import random
class PlayerClass:
def __init__(self, attack, speed, health, heal):
self._AttackIncrease = attack
self._SpeedIncrease = speed
self._HealthIncrease = health
self._HealIncrease = heal
#self._Special = special
def returnAttackIncrease(self):
return self._AttackIncrease
def returnSpeedIncrease... |
4d5f420d62a3c5b26dfef1d59576b9646caa5900 | davendiy/ads_course2 | /subject5_trees/3358.py | 5,206 | 3.703125 | 4 | #!/usr/bin/env python3
# -*-encoding: utf-8-*-
# by David Zashkolny
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
class Heap:
""" Клас структура даних Купа """
__slots__ = ('mItems', 'mSize')
def __init__(self):
""" Конструктор """
self... |
1a8052b8b2d5406cf6fa8feaa2f91a6b4133c943 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2452/58586/236423.py | 446 | 3.5625 | 4 | lines=int(input())
matrix=[]
for i in range(lines):
row=list(map(int,input().split(",")))
matrix.append(row)
start=0
end=len(matrix)*len(matrix[0])-1
width=len(matrix[0])
target=int(input())
while start<end:
mid=(start+end)//2
if matrix[mid//width][mid%width]==target:
break
elif matrix[mid/... |
c08633a8c506ad17fc1d6a6a787cd2703722a7d3 | lishulongVI/leetcode | /python/397.Integer Replacement(整数替换).py | 2,275 | 3.84375 | 4 | """
<p>
Given a positive integer <i>n</i> and you can do operations as follow:
</p>
<p>
<ol>
<li>If <i>n</i> is even, replace <i>n</i> with <code><i>n</i>/2</code>.</li>
<li>If <i>n</i> is odd, you can replace <i>n</i> with either <code><i>n</i> + 1</code> or <code><i>n</i> - 1</code>.</li>
</ol>
</p>
<p>
What is the... |
65cf921783e0f4b82e7f60dd2744aeb879eac326 | zaimeali/Data-Structure-and-Algorithms | /LCO Competitive/Day14.py | 803 | 3.53125 | 4 | def printAllCombination(arr):
if len(arr) == 0:
return []
if len(arr) == 1:
return [arr]
I = []
for i in range(len(arr)):
m = arr[i]
remLst = arr[:i] + arr[i+1:]
for p in printAllCombination(remLst):
I.append([m] + p)
return I
def fourPairComb... |
776d1668db4fce1c212f1300280ef1ceb2955554 | rgokhale31/ClassNameParser | /parser.py | 3,736 | 3.828125 | 4 | import json
#reads the file and extracts json components
def jsonReader(filename):
with open(filename, encoding='utf-8') as data_file:
jsonData = json.loads(data_file.read())
return jsonData
#outputs the relevant json data based on the word given by the user
def promptOutput(jsonData, inputWord):
... |
1fe0675192a2438deaf0dbc92c331f71c50180e1 | tsaxena/Master_Thesis | /NetAdapt/utils/compute_table/wideresnet_tf.py | 1,005 | 3.71875 | 4 | """functions used to create smaller models that are to be used in the tables in tensorflow"""
from tensorflow.keras.layers import BatchNormalization, Conv2D, AveragePooling2D, Dense, Activation, Flatten
from tensorflow.keras.models import Model
def make_conv_model(inputs, out_channels, stride, kernel_size=3):
"""... |
693d94d5c82e62f57ce463bc89c2aa58b98673ce | wael20-meet/meetyl1201819 | /final_stage.py | 8,753 | 3.609375 | 4 |
import time
import turtle
from turtle import *
import random
turtle.tracer(0)
turtle.hideturtle()
import math
import sys
colormode(255)
turtle.setup(950,534)
class Ball(Turtle):
def __init__(self, x, y, dx, dy, radius, color):
Turtle.__init__(self)
self.pu()
self.goto(x,y)
self... |
ed86f635bc719b608cc89eef1552ff2f66277d89 | efreeman15/gwc | /object pseudocode no lecture.py | 2,377 | 4.75 | 5 | # how to define a cat object.
# THIS IS NOT VALID PYTHON CODE!!!!!!!!!!!!!!!!!!!!!
# THIS IS JUST AN EXAMPLE OF HOW CODE MIGHT LOOK.
# defining the Cat object
object Cat:
# this function is called automatically
# when we define a new instance of our class
def __init__(whiskers, color, size):
# sa... |
200d679ccb698ca8e919f9a57c61137a796e82dd | CallumGasteiger/dec2bin | /dec2bin.py | 195 | 3.578125 | 4 | def dec2bin(num):
list = []
while num >= 1:
if num % 2 == 1:
list.insert(0, 1)
num = num - 1
num = num/2
else:
list.insert(0, 0)
num = num/2
print list |
273d1c161d7ae047e847b4fdaa9339abac2fb0e2 | syurskyi/Python_Topics | /125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/508 Most Frequent Subtree Sum.py | 1,489 | 3.953125 | 4 | #!/usr/bin/python3
"""
Given the root of a tree, you are asked to find the most frequent subtree sum.
The subtree sum of a node is defined as the sum of all the node values formed by
the subtree rooted at that node (including the node itself). So what is the most
frequent subtree sum value? If there is a tie, return al... |
28548c0a5a58c5377ee4a03fc726d436040c4ad3 | caiopg/random-text-generator | /wordgenerator.py | 574 | 3.75 | 4 | import random
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
LETTERS = VOWELS+CONSONANTS
def assemble_word(user_options):
generated_word = ""
for option in user_options:
if option == 'v':
generated_word = generated_word + random.choice(VOWELS)
elif option == 'c':
... |
8496fdc4a044df128b3c1857dbd8e37250739b1c | atg-abhijay/LeetCode_problems | /hamming_distance_461.py | 522 | 4 | 4 | """
URL of problem:
https://leetcode.com/problems/hamming-distance/description/
"""
def main(x, y):
xor_result = x ^ y
# converting result to binary
# and getting rid of the '0b'
# at the beginning of the number
xor_result = bin(xor_result)[2:]
hamming_dist = 0
for digit in xor_result:
... |
30e58c361ab33acb6fd20a43ad357c6a6c222e55 | ectky/PythonProjects | /Loops/Min-Number.py | 124 | 3.796875 | 4 | n = int(input())
Min = int(input())
for i in range(1, n):
num = int(input())
Min = min(Min, num)
print(Min)
|
24cdf92d04f733851006f1dbf66ba037ebf06934 | Pythonyte/lc | /misc/misc_codes/reorganize_string.py | 723 | 3.578125 | 4 | def reorganize_string(S):
from collections import Counter
import heapq
# for aab => pq = [(-2,a),(-1,b)]
# DOING NETAGIVE FOR MIN HEAP USAGE OF HEAPQ
pq = [(-value, key) for key, value in Counter(S).items()]
heapq.heapify(pq)
prev_freq, prev_char, result = 0, '', ''
while pq:
fr... |
174d33540f0ae4b4e197a074f4dbb223574b2c27 | mws19901118/Leetcode | /Code/Maximum Twin Sum of a Linked List.py | 1,019 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def pairSum(self, head: Optional[ListNode]) -> int:
fast, slow = head, head #Use fast and slow pointers to find t... |
89eea1e6ab5b7e4e80fa834a72c8ff7f27336756 | ZX1209/gl-algorithm-practise | /leetcode-gl-python/leetcode-437-路径总和-III.py | 2,739 | 3.65625 | 4 | # leetcode-437-路径总和-III.py
# 给定一个二叉树,它的每个结点都存放着一个整数值。
# 找出路径和等于给定数值的路径总数。
# 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
# 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
# 示例:
# root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
# 10
# / \
# 5 -3
# / \ \
# 3 2 11
# / \ \
# 3 ... |
4ab9eed249842f1a25c5832c66c492a1c5c70235 | gaohaoning/leetcode_datastructure_algorithm | /LeetCode/HashMap/290.py | 1,939 | 3.78125 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
290. 单词模式
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。
这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str... |
0cb706fdd05cdbfb8310255ba9bced03dc5fcac9 | yuju13488/pyworkspace | /m10_class/overridding.py | 511 | 3.9375 | 4 | class Parent:
def m1(selfs):
print('Parent:m1()')
def m2(selfs):
print('Parent:m2()')
class Child1(Parent):
def m3(self):
print('Child1:m3()')
def m2(self):
print('Child1:m2()') #覆寫、改寫父類別的方法
class Child2(Parent):
def m4(self):
print('Child2:m4()')
def main():... |
50f7d3d74363c7024f704113962255f67e9a88d9 | JSYoo5B/TIL | /PS/BOJ/4673/4673.py | 338 | 3.609375 | 4 | #!/usr/bin/env python3
def d_func(num):
for d in str(num):
num += int(d)
return num
if __name__ == '__main__':
gen_numbers = set()
for i in range(10000 + 1):
gen_numbers.add(d_func(i))
self_numbers = [ i for i in range(10000 + 1) if i not in gen_numbers ]
for n in self_numbers:... |
8f394c528cc3d285fbc58d49690753cb254bb8f2 | Mateus-Silva11/AulasPython | /Aula_4/Aula4_1.py | 1,286 | 3.984375 | 4 | # Aula 4_2 13-11-2019
# Booleanas
#--- Variável booleana simples com True ou False
validador = False
#--- Substituição do valor inicial
validador = True
#--- Criação de variável booleana através de expressão de igualdade
idade = 18
validador = ( idade == 18 )
print(validador)
#--- Criação de variável booleana através... |
377b293f98399186492f014a772258b4d9c209aa | rrwt/daily-coding-challenge | /daily_problems/linked_list.py | 717 | 3.71875 | 4 | from typing import Optional, Union, List
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.next: Optional[Node] = None
def print_ll(head: Node) -> None:
runner = head
while runner.next:
print(runner.data, end="->")
runner = runner.next
if runn... |
08ce988bb8b10a78507c29948c0e5b65a5a993ba | alialmhdi/SmartCalculator | /Problems/CapWords/task.py | 241 | 4.09375 | 4 | user_input = input()
user_input_list = user_input.split("_")
words = []
if len(user_input_list) >= 2:
for word in user_input_list:
words.append(word.capitalize())
print("".join(words))
else:
print(user_input.capitalize()) |
ff9e691ba0f2dbedcffb7fb31e555c6ff399f70d | EinarK2/einark2.github.io | /Forritun/Forritun 1/Verkefni 1/Vísa 22.08.18.py | 407 | 3.515625 | 4 | #Höfundur Einar
# Forrit um vísu
print("halló")
karl=input("hvað heitir karlinn? ") #Les inn það sem er skrifað
kona=input("hvað heitir konan?? ")
drykkur=input("hvað drekka þau??? ")
#útskrift vísa
print("----------------------------------------------")
print(karl+" og "+kona+" eru hjón")
print("Óttalega mikil flón")... |
1b2ca7051a7c1aba1b08cc89871d1306a4aee035 | CrashLaker/HabitsID | /red2.py | 925 | 3.578125 | 4 | import random, time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
# Set GPIO to Broadcom system and set RGB Pin numbers
RUNNING = True
GPIO.setmode(GPIO.BCM)
red = 26
green = 20
blue = 27
# Set pins to output mode
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green, GPIO.OUT)
GPIO.setup(blue, GPIO.OUT)
Freq = 100 #Hz
#... |
e956a96e0c3926f1930bebcdee63cdd470b174a2 | PrashilAlva/Programs | /Practice/Data Analytics (Heraizen)/Assignment/Set 2/q3.py | 346 | 3.71875 | 4 | n=int(input())
prime=list()
for i in range(2,n+1):
flag=0
for j in range(2,i//2+1):
if i%j==0:
flag=1
break
if flag==0:
prime.append(i)
print(prime)
sum=0
for ele in prime:
sum=sum+ele
print(sum)
squareprime=list()
for ele in prime:
squareprime.append(el... |
b458144c5bb94e8e08f5041393bbe057fab24acc | IvanciuVlad/PbInfo | /Clasa a IX-a/Algoritmi elementari/Cifrele unui număr/suma_cifrelor.py | 93 | 3.53125 | 4 | n = raw_input("")
n = int(n)
s = 0
while(n > 0):
s += n % 10
n = n // 10
print(str(s))
|
e8c0b19395e35fb42374404d56e830962b145d74 | GitAj19/Python-is-easy | /Homework Assignment #3: "If" Statements/main.py | 602 | 4.0625 | 4 | """Python Homework #3 - If Statements"""
import functions
# Print details
print("Check equal numbers 9, 8, 8")
print(functions.checkEqual(9,"8",8))
print("Check equal numbers 101, 101, 450")
print(functions.checkEqual(101, 101, 450))
print("Check equal numbers 10, 1.01, 10")
print(functions.checkEqual(10, 1.01, 10)... |
27925a43687cbc09034903eb2e2bc86b8d021cb9 | coderkhaleesi/Data-Science-Interview-Preparation | /DataStructuresAndAlgorithms/RecursionAndBacktracking/searchKeyInArray.py | 409 | 3.921875 | 4 | #Given an array of elements A, and a key k, search for k in A. If the key is present in the array A, return the index of key in A, else return -1
def searchElement(A, i, j, k):
if (i <= j):
if A[i] == k:
print(i)
return i
else:
return searchElement(A, i+1, j, k)
else:
return -1
if __name__=="__... |
d62b2ebf517e9a704341f760bc6d68e5b6bec517 | kiryeong/python_intermediate_study | /p_chapter02_02.py | 2,738 | 3.625 | 4 | #Chapter 02-02
#객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지, 유지보수, 대형프로젝트
#규모가 큰 프로젝트(프로그램) -> 함수 중심 -> 데이터 방대 -> 복잡
#클래스 중심 -> 데이터 중심 -> 객체로 관리
#class Car(object):와 같은 거임 object를 상속받은 것
class Car():
"""
Car class
Author : Nam
Date : 2020.09.28
"""
#클래스 변수(모든 인스턴스가 공유)
car_count = 0
... |
c793cb680e139ffc713b694da0fd054fd1d769f3 | 2020ayao/Word_Ladder | /word_ladder_astar.py | 6,477 | 4.0625 | 4 | import math, random, time, heapq
class PriorityQueue():
"""Implementation of a priority queue
to store nodes during search."""
# TODO 1 : finish this class
# HINT look up/use the module heapq.
def __init__(self):
self.queue = []
self.current = 0
def next(self... |
5f1572201b52a35d996bc31b1a483b695dcb93cb | rlan/pyml | /pyml/RunningVariance.py | 1,865 | 3.75 | 4 | from __future__ import division
from __future__ import print_function
class RunningVariance:
"""Compute running variance using Welford's algorithm
https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
Example
-------
>>> from RunningVariance import RunningVariance
>>> s = RunningVariance()
... |
640ca376db03a7c1e58901014c02c1c3e212bfe1 | anupamsharma/algo | /math_util.py | 2,605 | 3.765625 | 4 | import math
import sys
def get_binomial_coeffs_matrix(n):
"""
It returns the matrix a[n+1][n+1] containing binomial coefficient for a[i][j] for i>=j.
"""
max_n = n + 1
b_coeff = [range(0, max_n) for i in range(0, max_n) ]
b_coeff[0][0] = 1
b_coeff[1][1] = 1
b_coeff[1][0] = 1
for i... |
3d0d9e2df948e64a8ffcf38d253e672e0d5aaea9 | kunalkhandelwal/Python-Projects | /movie.py | 510 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 12 14:20:34 2021
@author: kkhan
"""
import imdb
hr = imdb.IMDb()
movie_name= input("Please enter the name of the Movie: ")
movies = hr.search_movie((str()))
index =movies[0].getID()
movie = hr.get_movie(index)
title= movie['title']
year= movie['year']
cast... |
09dde4093ac3df809a011908102d6cc0e133e4b7 | AZAZAZAZ1/first_re-pository | /EXCELLL.py | 1,668 | 3.59375 | 4 |
#C:\Users\E.H.PAUE\Desktop\python lessons
import openpyxl
import os
os.chdir('C:\\Users\\E.H.PAUE\\python lessons')# change the directory of where the file is Excell sheet saved # dont forget to put \\ in the path
workbook = openpyxl.load_workbook('example.xlsx') # to open the excell sheet that saved in the abo... |
b96ca824dc22a9e3547f49f6e18976a70b579bce | wendelsilva/Python | /exercicios/exe028.py | 478 | 3.796875 | 4 | from random import choice
lista = [0,1,2,3,4,5]
escolher = choice(lista)
print("loading...")
print("O computador escolheu um número")
opcao = int(input("Escolha um número entre 0 e 5: "))
if opcao == escolher:
print("Parabens, você venceu!!")
print("O número escolhido pelo computador foi {} e o seu {}".format(e... |
33271bf2a9273093db3b29be5ddaf37536e17209 | manickaa/CodeBreakersCode | /Strings/Worksheet/checkValidSubstitutions.py | 824 | 3.984375 | 4 | class Solution:
def isValid(self, s: str) -> bool:
#O(N) time
#O(N) space if all characters are expect 'c'
if len(s) < 3:
return False
stack = []
for char in s:
if char != 'c':
stack.append(char)
elif char == 'c':
... |
349bfcc0e1cc16b4ebcff7cb94abf9f78820c4f4 | andersoncardoso/dump | /pypp4gamers/examples/animation.py | 807 | 3.546875 | 4 | #! /usr/bin/env python
# animation
from pypp4gamers import *
#setings
set_background_color(BLACK)
#initialize
pypp_init()
# defines main loop
def mainLoop():
x=10
y=20
vx = 5
vy = 5
width, height = get_screen_width(), get_screen_height()
while True:
#gets display and clean the s... |
6d2d6a3832b60162365331cdebc0ee4a818b5964 | zalefin/sneruz | /sneruz/connective.py | 274 | 3.71875 | 4 |
def NOT(p):
return not p
def AND(p, q):
return p and q
def OR(p, q):
return p or q
def XOR(p, q):
return (p and not q) or (not p and q)
def IMPLIES(p, q):
return (not p) or (p and q)
def IFF(p, q):
return ((not p and not q) or (p and q))
|
89dd2b3b39962f1634bb4b52b810796b5deee60c | alexangupe/clasesCiclo1 | /P45/Clase4/interfaz.py | 884 | 3.75 | 4 | def bienvenida():
print("-------------------------------------------")
print("Bienvenido: Aplicación Cálculo de Impuestos")
print("-------------------------------------------")
def recogerPrecio4Productos():
producto1 = float(input('Ingrese el valor del primer producto: '))
producto2 = float(input(... |
47a8e08acf10ce7eb47b5635eefdf65e299a3868 | muniri92/microsoft-interview-study | /src/find_rotation_point.py | 1,717 | 4.09375 | 4 | """
Write a function for finding the index of the "rotation point," which is where I started working from the beginning of the dictionary. This list is huge (there are lots of words I don't know) so we want to be efficient here.
words = [
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepi... |
0eb1e2f0f465e1e49b2cf133aac365d823749e48 | xtompok/prg2 | /list/list.py | 1,317 | 4.03125 | 4 | class ListNode(object):
def __init__(self,data):
super(ListNode,self).__init__()
self.data = data
self.next = None
class LinkedList(object):
def __init__(self):
super(LinkedList,self).__init__()
self.head = None
def append(self,data):
if self.head is None... |
78ebb43397fa6506299cb46b6a4317b05ed0423e | Ariana1729/ariana1729.github.io | /writeups/2022/GreyCTF/Permutation/perm.py | 785 | 3.515625 | 4 | class Perm():
def __init__(self, arr):
assert self.valid(arr)
self.internal = arr
self.n = len(arr)
def valid(self, arr):
x = sorted(arr)
n = len(arr)
for i in range(n):
if (x[i] != i):
return False
return True
def __str__... |
22a46ad25d160525a0137a0ef1833d2845b89aff | AmrEsam0/HackerRank | /python3/2d_Array_DS.py | 709 | 3.609375 | 4 | #!/bin/python3
def list_sum(l):
total = 0
for i in range(len(l)):
total = total + l[i]
return total
def hourglassSum(arr):
max = -1000
s= []
sub_array = []
for m in range(4):
for col in range(4):
for row in range(3):
s... |
f3b68660ea0e593638260247729a8ba20c8b1321 | jaewilson07/course-material | /exercices/230/solution.py | 312 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 23 17:37:53 2014
@author: Catherine
"""
def is_prime(n):
x = True
if n > 1:
for i in range(2, int(n ** .5)):
if (n % i) == 0:
x = False
return x
x = 100000000
while is_prime(x) is not True:
x = x + 1
print(x)
|
fae39f809f9202288cfe12ab7de8e63a05fd6341 | Rayban63/Coffee-Machine | /Problems/Calculator/task.py | 583 | 4 | 4 | first_num = float(input())
second_num = float(input())
operation = input()
no = ["mod", "div", "/"]
if second_num == (0.0 or 0) and operation in no:
print("Division by 0!")
elif operation == "mod":
print(first_num % second_num)
elif operation == "pow":
print(first_num ** second_num)
elif operation == "*":
... |
40371230eb5f3a5b3e98e5fbc12624d681e52dbf | OmarMWarraich/Assignments | /32-Least_Common_Multiple.py | 238 | 4.09375 | 4 | # Ai Assignment 32 - Compute the Least Common Multiple of Two Positive Integers
n1 = int(input("Input Integer # 1 : "))
n2 = int(input("Input Integer # 2 : "))
x = n1
y = n2
while(y):
x, y = y, x % y
print("LCM is : ", (n1 * n2) / x)
|
7f2dcfb60194dfac2ad1cced431813d4eafa47a8 | B-Assis-O/Bernardo | /fibonacci.py | 275 | 3.890625 | 4 | n = int(input("Digite o número de termos desejado para a sequência de Fibonacci: "))
i = 1
b = 0
c = 1
a = 0
lista_fib = [0,1]
while i <= (n - 2):
a = c + b
b = c
c = a
lista_fib.extend([int(a)])
i = i + 1
print(lista_fib)
|
0730c1aa623b22523739dd3f0ff5d9943337ed10 | nikozhuharov/Python-Basics | /Introduction/08. Fish Tank.py | 381 | 3.671875 | 4 | # 1. Дължина в см – цяло число
# 2. Широчина в см – цяло число
# 3. Височина в см – цяло число
# 4. Процент зает обем – реално число
length = int(input())
width = int(input())
height = int(input())
percent = float(input())
print(((length*width*height)/1000)*(1-percent/100))
|
fddd0efebf80b9ffeff11cc2515fa385886edc29 | vitaliytsoy/problem_solving | /python/medium/reverse_words.py | 1,833 | 4.40625 | 4 | """
Given an input string s, reverse the order of the words.
A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.
Return a string of the words in reverse order concatenated by a single space.
Note that s may contain leading or trailing spaces or multiple sp... |
6b0f9a6268da0577ce7fac4e6447bd8bc669fc23 | rafaeljordaojardim/python- | /regex/regex.py | 3,032 | 4.40625 | 4 | mystr = "YOu can learn any programming language, whether it is Python2, Python3"
import re
# a = re.match(pattern, string, optional flags)
# Try to apply the pattern at the start of the string,
# returning a match object, or None if no match was found.
a = re.match("You", mystr)
# entire method returned
a = re.matc... |
e49e5a94fc26bb536a0fd225448cd16654dcd941 | vishnia92/algo.python | /l2_3.py | 493 | 4.15625 | 4 | # 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
# Например, если введено число 3486, то надо вывести число 6843.
num = int(input('Введите целое число: '))
invers = 0
while num % 10 != 0 or num // 10 != 0:
invers = invers * 10 + num % 10
num //= 10
print(f'Обра... |
5707c0985e9f1bbd412a1d4bcb5895e2337eb9d5 | haoonkim/python-challenge1 | /PyPoll/main.py | 1,860 | 3.703125 | 4 | #import csv dependencies
import os
import csv
#read csv and make the path for file
data_output = os.path.join('/Users/haoonkim/Desktop/election_data.csv')
#variables to count votes
total_vote = 0
khan_vote = 0
correy_vote = 0
li_vote = 0
otooley_vote = 0
#read data
with open(data_output, newline = '') as csvfile:
... |
c72e1d6a0ed995152d71a315dd8d2e5702a4de12 | bpuderer/python-snippets | /general/function_args.py | 901 | 3.953125 | 4 | # args=tuple, kwargs=dict
def ftn(a, b=0, *args, **kwargs):
print(f"a={a} b={b} args={args} kwargs:{kwargs}")
ftn(1)
ftn(1, 2)
ftn(1, 2, 3)
ftn(1, c=42)
# unpack list or tuple
# https://docs.python.org/3.7/tutorial/controlflow.html#unpacking-argument-lists
# PEP 448 added unbounded number of * and ** unpackings... |
0296343e8410032a44f1a72235d0e0e5c6e93aee | Fluffhead88/mystery-word | /normal.py | 1,305 | 4.03125 | 4 |
# Word guessing game, similar to hang man
import random
with open('/usr/share/dict/words') as infile:
word = infile.readlines()
answer = random.choice(word).lower().replace("\n", "")
used_letters = []
game_word = []
len_word = len(answer)
def display():
for char in answer:
game_word.append('_')
... |
e03fc44540f70eda9f57b3d046674fab2494102b | lexust1/algorithms-stanford | /Course2/02c03w.py | 2,500 | 4.09375 | 4 | # Download the following text file:
# Median.txt
# The goal of this problem is to implement the "Median Maintenance" algorithm
# (covered in the Week 3 lecture on heap applications). The text file
# contains a list of the integers from 1 to 10000 in unsorted order;
# you should treat this as a stream of numbe... |
96380019ffe0fa14a4d120b5561c11fb75534d15 | joaopauloaramuni/python | /desafio_python/logica.py | 1,224 | 4.40625 | 4 | '''
Lógica de programação
Pensando em todos os números naturais inferiores a 10 que são múltiplos de 3 ou 5, temos 3, 5, 6 e 9. Somando esses múltiplos obtemos o valor 23.
Utilize um algorítimo para calcular a soma de todos os múltiplos de 3 ou 5 abaixo de 1000
'''
def e_multiplo(numero=None, multiplos=None):
"""... |
71e231d9c5f7155ca2bcf06393f4b8ae8199bf2b | YiHerngOng/leetcode_practice | /python/Longest_Panlindromic_substring.py | 1,278 | 3.625 | 4 | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
p = 0
ans = ""
# define the start of longest substring
start_of_longest = 0
max_length = 1
# two pointers for b... |
358db80d72bc7e80516cc1b52bd90c7ff67b6375 | vrsilva17/fichas_aula | /fa_3/ex2.py | 152 | 3.9375 | 4 | inicio = int(input('Introduza o inicio do ciclo: '))
fim = int(input('Introduza o fim do ciclo: '))
for item in range(inicio, fim, 1) :
print(item) |
c4b74032ef3283c28fc88850d74061bba4e30405 | alextanhongpin/project-euler | /python/49-prime-permutations.py | 1,523 | 3.640625 | 4 | # 1487, 4817, 8147
# step: 3330
import math
def is_prime (n):
"""
Checks if a number is a prime number
"""
if n <= 1:
return False
elif n == 2:
return True
elif n == 3:
return True
else:
square_root = int(math.ceil(math.sqrt(n)))
for i in range(square_root + 1, 2, -1):
if n % i... |
3e95c1ebd79235cd18ef20d4ba1b441c63fd11cb | JakeTux8/Movie-Trailer-Website | /media.py | 679 | 3.6875 | 4 | import webbrowser # module needed to open url links in browser
class Movie():
""""This class allows the creation of movie objects that include movie
title, synopsis, poster, and trailer"""
# Movie class constructor.
def __init__(self, movie_title, movie_storyline, poster_image,
tra... |
7ed2f00c05eb1fe27e686c35fa4d5a8e303b38fb | dheerajs0346/PYPL | /regular_expressions/py/re_special_char_matches.py | 2,326 | 4.21875 | 4 | #!/usr/bin/python
################################################
## matching special characters
## author: vladimir kulyukin
############################################
import re
txt_01 = '12345'
txt_02 = 'abcde'
txt_03 = ' .;!?\\'
txt_04 = ' .;!?\\_'
txt_05 = ' .;!?\\_\n';
txt_lst = (txt_01, txt_02, txt_03, txt... |
b2cdda436876d39e4bc01b582ac43b7e579ce1d2 | NivruthaBalaji/guvi11 | /power.py | 213 | 4 | 4 | base=int(raw_input("Enter base: "))
exp=int(raw_input("Enter exponential value: "))
power=1
i=0
if exp==1:
print "Power=",base
else:
for i in range(0,exp):
power=power*base
print"Power=",power
|
7878bf85678ac50926c92721576054df35ace74e | QuaziBit/Python | /demo/user_input.py | 143 | 3.984375 | 4 | name = input("Uer input your name: ")
age = input("Uer input your age: ")
age = int(age)
print("\n%s you are %d years old!\n" % (name, age) ) |
5a44d1307a3166b45ee4523ab9c330e4dbe5f5b1 | Amruta-Pendse/Python_Exercises | /TempCoversion.py | 496 | 4.34375 | 4 | #Program to covert Temperature from/to Celsius to Farenheit
n1=input("Enter 'C' to enter Temperature in Celsius and 'F' for Farenheit:")
if(n1=='C' or n1=='c'):
ctemp= float(input("Enter Temperature in Celsius:"))
ftemp=(ctemp*1.8) +32
print("Temperature in Farenheit is:", ftemp)
elif (n1=='F' or n1=='f'... |
5ac52a60fa2924f1751632c69aab8cc16cdbf911 | stephenroche/COMP2041---Software-Construction | /lab08/shortest_path.py | 1,104 | 3.890625 | 4 | #!/usr/bin/env python3
import sys, re
(start, end) = (sys.argv[1], sys.argv[2])
roads = {}
visited = {}
for line in sys.stdin:
matches = re.findall('(\S+)\s+(\S+)\s+(\d+)', line)
frm = matches[0][0]
to = matches[0][1]
length = matches[0][2]
visited[frm] = 0
visited[to] = 0
if (frm not in roads... |
f50064774f2f4e86e99689493ef1b888dfcafcfa | pranav165/nasa | /utils/location.py | 785 | 4.09375 | 4 | from enum import Enum
class Direction(Enum):
NORTH = 'N'
SOUTH = 'S'
EAST = 'E'
WEST = 'W'
class Location:
"""
Locations class to define location type object
"""
def __init__(self, latitude=None, longitude=None, name=None):
self.lat = latitude[:-1]
self.lat_direction... |
6c142c8780b4e1e89f8e3dbb569e64bb832173ba | Poolfloaty/Python-Projects | /multi_dimensional_array.py | 3,071 | 4.1875 | 4 | #Program: multi_dimensional_array
#Author: Brent Lang
#Date: 09/15/20
#Purpose: Program tests the function main and the functions as commented below.
inStock = []
alpha = []
beta = []
gamma = [11, 13, 15, 17]
delta = [3, 5, 2, 6, 10, 9, 7, 11, 1, 8]
#setZero function initializes any one-dimensional list to 0.
def set... |
d271103e3b130a0bf1b5a564fe8b743cbb16f5e7 | kmtos/InsightDataEngineeringCodingChallenge | /src/prescription_drug_class_def.py | 7,735 | 3.890625 | 4 | import csv
import string
class prescription_drug_class(object):
def __init__(self, drug_list, index_last_name, index_first_name, index_drug_name, index_drug_price):
self.full_list = drug_list
self.INDEX_LNAME = index_last_name
self.INDEX_FNAME = index_first_name
self.INDEX_DNAME = index_dr... |
a424fa6e2522258e80d0284526a841202ed0a2d9 | Vaishnavi02-eng/InfyTQ-Answers | /PROGRAMMING FUNDAMENTALS USING PYTHON/Day2/Exercise7.py | 809 | 3.84375 | 4 | #PF-Exer-7
def calculate_total_ticket_cost(no_of_adults, no_of_children):
total_ticket_cost=0
final=0
#Write your logic here
Rate_per_Adult=37550.0
Rate_per_Child=Rate_per_Adult/3
service_ad = (Rate_per_Adult*7)/100
service_ch = (Rate_per_Child*7)/100
ticket_cost1=Rate_per_Adult... |
0cb94a6782ceed0709216733f95d1581c5ebc821 | ao9000/tic-tac-toe-ai | /run_game.py | 7,054 | 3.796875 | 4 | """
Pygame based version of tic-tac-toe with minimax algorithm artificial intelligence (AI) game
"""
# UI imports
import pygame
import sys
from game_interface.color import color_to_rgb
from game_interface.templates import game_board, selection_screen, board_information, highlight_win
# Game logic imports
import r... |
aff8ce16d908f8ebbc80cee09b0440206568ff1e | vinod-boga/019-check-key-existence | /build.py | 164 | 3.65625 | 4 | def solution(d1,Key1):
for key in d1:
if key == Key1:
return True
else:
return False
print solution({'abc':20,'efg':10},'efg')
|
27437bc7e6230065b6038d7e962dbd3b959564e5 | mini-monstar/Array-practises | /remove_duplicates.py | 94 | 3.859375 | 4 | A = [1, 2, 1, 2, 3, 4, 5]
B = []
for i in A:
if i not in B:
B.append(i)
print(B)
|
6e1f8b00a781dcafe8be6d0062be68a5712b517b | evorontsova/LeetCode | /028/code.py | 1,418 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 11 2021
@author: Evgeniya Vorontsova
LC Problem 28 Implement strStr()
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question... |
da31e7c75c044753f357a497550740616b68a3e0 | renatanesio/guppe | /heranca.py | 2,002 | 3.921875 | 4 | """
POO - Herança (Inheritance)
A ideia de herança é reaproveitar código, e também extender as classes.
OBS: Com a herança, a partir de uma classe existente, extende-se outra classe
que passa a herdar atributos e métodos da classe herdade.
Cliente
- nome
- sobrenome
- cpf
- renda
Funcionário
- ... |
a8357393cad296fb8be3c7b041a90209e7a65301 | nathanlo99/dmoj_archive | /done/ccc12j2.py | 313 | 3.78125 | 4 | import sys
data = []
for _ in range(4):
data.append(int(input()))
if data[0] > data[1] > data[2] > data[3]:
print("Fish Diving")
elif data[0] < data[1] < data[2] < data[3]:
print("Fish Rising")
elif data[0] == data[1] == data[2] == data[3]:
print("Fish At Constant Depth")
else:
print("No Fish") |
e690e2ca91eb042557c0d36e8a67cc181aa4842a | vitdanilov/python_devops | /dev/4/task4_6.py | 1,344 | 4.03125 | 4 | # 6. Реализовать два небольших скрипта:
# а) итератор, генерирующий целые числа, начиная с указанного,
# б) итератор, повторяющий элементы некоторого списка, определенного заранее.
#
# Подсказка: использовать функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечны... |
8083cd108e9d0bfe05c9b3fd8c37fbcfb151b590 | Akhilesh09/MS_Projects | /Deep Learning - Individual Projects/DL_HW2/ResNet/Network.py | 8,381 | 3.5625 | 4 | import tensorflow as tf
"""This script defines the network.
"""
class ResNet(object):
def __init__(self, resnet_version, resnet_size, num_classes,
first_num_filters):
"""Define hyperparameters.
Args:
resnet_version: 1 or 2. If 2, use the bottleneck blocks.
resnet_size: A positive integer (n).
nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.