blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
037c3372719b206f9694da97f36e528b366a037a | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter5/5.1.py | 881 | 4.28125 | 4 | #5.1
#Insertion: You are given two 32-bit numbers, N and M, and two bit positions, i and j.
#Write a method to insert M into N such that M starts at bit j and ends at bit i.
#You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011,
# you can assume that there are at least 5 bit... |
11e1cfd9bd43624f44376b1e300cdf3945114b26 | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter16/16.9.py | 517 | 3.96875 | 4 | # Implement operations with only addition (and negation).
def multiply(a, b):
if abs(a) < abs(b):
s, l = a, b
else:
s, l = b, a
product = 0
for _ in xrange(abs(s)):
product += l
if s < 0:
return -product
return product
def divide(a, b):
if b == 0:
return None
product = 0
quotient... |
cf3fb2b8852de85b47b3aa67a3ae8e48b2607e76 | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter4/4.3.py | 2,560 | 4.125 | 4 | #List of Depths: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth
#(e.g., if you have a tree with depth 0, you'll have 0 linked lists).
from SinglyLinkedList import SinglyLinkedList
class Node():
def __init__(self,value):
self.right = None
self.lef... |
16c9d17f9c4cfd8f8002434d9b810182f4128b1f | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter1/1.4.py | 1,477 | 4.34375 | 4 | #Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome.
#A palindrome is a word or phrase that is the same forwards and backwards.
#A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
#First I need to prep... |
24a50dbd7582b4ff99c3a6c85eaf2b581c2ee60e | EzgiDurmazpinar/CrackingTheCodingInterview-6thEdition-Python-Solutions | /Chapter16/16.4.py | 626 | 3.890625 | 4 | def CheckVictory(board, x, y):
#check if previous move caused a win on vertical line
if board[0][y] == board[1][y] == board [2][y]:
return True
#check if previous move caused a win on horizontal line
if board[x][0] == board[x][1] == board [x][2]:
return True
#check if previous mov... |
4b61ecbe1f448d9018fc62579e42043b667c83a6 | Troy-Wang/LeetCode | /201609_Week1/20160830_1.py | 293 | 4.0625 | 4 | """Write a function that takes a string as input and returns the string reversed."""
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
solution = Solution()
print(solution.reverseString('abcd'))
|
de378556011782346bbaad2e66bd934c9c726fea | Troy-Wang/LeetCode | /201609_Week3/20160912_1.py | 1,148 | 3.78125 | 4 | """
Write a function that takes a string as input and reverse only the vowels of a string.
"""
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
sList = list(s)
st... |
739f897c0de18cdbf808c37f570ac08a9728d0ae | Troy-Wang/LeetCode | /201610_Week2/20161012_1.py | 714 | 3.875 | 4 | """
Longest Palindrome
Given a string which consists of lowercase or uppercase letters,
find the length of the longest palindromes that can be built with those letters.
"""
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
... |
9a514ef2fe5505e656ff953f043d66f32588db7e | Troy-Wang/LeetCode | /201610_Week3/20161023_1.py | 505 | 3.8125 | 4 | """
Remove Duplicates from Sorted Array
"""
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
currentNum = None
currentIndex = 0
for eachNum in nums:
if eachNum != currentNum:
nums... |
d1389d9680a625bbb634d9b99e1310e576103ab0 | Troy-Wang/LeetCode | /201610_Week1/20161009_1.py | 906 | 3.8125 | 4 | """
Given a n x n matrix where each of the rows and columns are sorted in ascending order,
find the kth smallest element in the matrix.
"""
import heapq
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
... |
c3c3fde184da253638c3d2551198d48154dcec03 | Troy-Wang/LeetCode | /201610_Week3/20161020_1.py | 1,219 | 3.828125 | 4 | """
Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
"""
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
num = n
count = 0
while num > 0:
num -= 9 * (10 ** co... |
4131a78e52e8d5e13fc829dc07ae8b9f092728a5 | Troy-Wang/LeetCode | /201611_Week1/20161102_2_todo.py | 947 | 3.828125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {string[]}
def binaryTreePaths(self, root):
if not root:
return
stack = [... |
476c9dfbd0db2cd5c2c8ea07cf0355bd1b620417 | Troy-Wang/LeetCode | /201611_Week1/20161101_2.py | 1,019 | 3.953125 | 4 | """
Minimum Depth of Binary Tree
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
clas... |
566b5f011de1fda1a216c2a07200ea7e405379b6 | benschi11/python | /beispiele/12BMI.py | 451 | 4.09375 | 4 | import math
# Einlesen
weight = float(input("Bitte geben Sie ihr Gewicht in kg ein:"));
height = float(input("Bitte geben Sie ihre Größe in m ein:"));
# Berechnen
#bmi = weight / math.pow(height,2);
bmi = weight / (height*height);
# Ausgabe
print("Ihr BMI ist " + str(bmi));
if bmi < 18:
print("Sie sollten etwas... |
e53cbe6a65fddac374becc7618c8eabb9777ca76 | GlycineASoya/Hangman_Proto | /hm_proto.py | 1,451 | 3.96875 | 4 | from typing import Dict, Any
def isletter(possible_letter: str) -> bool:
#check the letter if it is not a null and/or a string
if len(possible_letter) != 1:
return False #put later an exception
ch = ord(possible_letter)
if (65 <= ch <= 90)\
or (97 <= ch <= 122) \
or ((4... |
bfed011ded4c39ecf628e565bf24fbee36480112 | Matheus-mVilela/POO-python | /pacote /class_abstrata.py | 509 | 3.90625 | 4 | from abc import ABCMeta, abstractmethod
class SuperClass(metaclass=ABCMeta):
@abstractmethod
def fazer_algo(self):
pass
# @abstractmethod
# def fazer_outra_coisa(self):
# pass
class SubClass(SuperClass):
def __init__(self, x, y):
self.x = x
self.y = y
def fa... |
7a63bc773c1cadb01be77008b7d7f6bd1ca7f8d1 | Matheus-mVilela/POO-python | /pacote /decorator.py | 388 | 4.0625 | 4 | """
def modifica(funcao):
def subitrair(a, b):
return a - b
return subitrair
#o decorator esta modificando a função soma
@modifica
def soma(a, b):
return a + b
"""
def modifica(funcao):
def somar_par(a, b):
if a % 2 == 0 or b % 2 == 0:
return a + b
return a - b
... |
576534577c088f5c0b9d1db978fdbd983aba5bd7 | jeffreyj123/beyond-blocks-competition | /q10.py | 357 | 3.59375 | 4 | from functools import reduce
def add(x, y):
return x + y
def prime_sum(n):
k = 0
count = 3
prime = [2]
while count <= n:
for i in range (0, len(prime)):
if count % prime[i] != 0:
k = k + 1
if k == len(prime):
prime.append(count)
count = count + 1
k = 0
else:
k = 0
count =... |
1a21e6163821c46c491ced5e68e542ee074d8707 | olivier987654/python-data-structures-and-algorithms | /dynamic-programming/longest-common-subsequence/script.py | 978 | 3.859375 | 4 | def longest_common_subsequence(string_1, string_2):
print("Finding longest common subsequence of {0} and {1}".format(string_1, string_2))
grid = [[0 for col in range(len(string_1) + 1)] for row in range(len(string_2) + 1)]
for row in range(1, len(string_2) + 1):
print("Comparing: {0}".format(string_2[row - 1]... |
5cb0444544c2474553ecd66970bf6f9d7316994a | khsien/cp2019 | /p01/q2_calc_cylinder_volume.py | 191 | 4.1875 | 4 |
radius = int(input("Enter Radius Here:"))
length = int(input("Enter Length Here:"))
from math import pi
area = radius ** 2 * pi
volume = area * length
print("Volume is " + str(volume))
|
c8c280a877b6c56a9d65ef5793557f15f2761bb7 | khsien/cp2019 | /p01/q4_sum_digits.py | 182 | 4.0625 | 4 |
integer = int(input("Enter Integer:"))
a = integer % 10
b = integer // 10
c = b // 10
d = b % 10
e = c // 10
f = c % 10
print("The sum of the digits are " + str( a + d + e + f) )
|
f8698c3cf058ab16d916d8244306ddce3e01e725 | bocoup/ovc-2016-videos | /analysis/analyze_tfidf.py | 2,514 | 3.515625 | 4 | from utils import tokenize_transcripts, get_files
from collections import Counter
import math
# input: list of tokens
# returns: dict of counts
def get_counts(tokens):
return Counter(tokens)
# input: dictionary of tokens:counts
# returns: sorted list of (token, count)
def sort_counts(counts):
return sorted(co... |
e6d3841489ff392c439beffa8c4ace74b5bfe9d8 | enzomasson25/Proj631 | /Projet1/main.py | 8,580 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 08:19:44 2020
@author: Masson Enzo
"""
import os #utiliser pour connaitre la taille d'un fichier (étape 4)
"""
Etape 1 : Détermination de l’alphabet et des fréquences de caractères
"""
#fichier de départ
fichier_initial=input("Votre fichier txt à compresser :")
phras... |
6fd6268052ce61de5d97fcf138e7ff611fadc1ad | mattfisc/python | /quicksort.py | 1,383 | 4.125 | 4 | # This function takes first element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
import random
def partition(lst, a ,b):
random_index = random.randint(a,b) # pick ra... |
5719a2056cd15bcdb774c9934890e5e4a9aa7dcf | DmytroLukianchuk/Python | /homeTaskTwoNumbers/numbers2.py | 1,164 | 4.03125 | 4 | __author__ = 'dmytrol'
print(
"HomeWork#2: User enters number in range 20 - 99 from keyboard and get correct spelling of this number in console")
dict_units = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five",
6: "six", 7: "seven", 8: "eight", 9: "nine"}
dict_dozens = {1: "ten", 2: "twenty", 3: ... |
1ec1ead705db4e96d2346f79b11da8af41a8c513 | Mturner034/Code-Your-Own-Quiz-Final-Mturner034 | /Project 2_Code_Your_Own_Quiz_With_PEP484_Annotations.py | 4,206 | 3.59375 | 4 |
blanks = ["__1__", "__2__", "__3__", "__4__", "__5__"]
easy_answers = ["browser", "HTML", "moon", "flat", "crazy"]
medium_answers = ["elon musk", "tesla", "spacex", "spacex", "mars"]
hard_answers = ["singularity", "theory", "man", "intelligence", "technology"]
easy_quiz = """We use a __1__ to view web pages. The l... |
73ea014207e3848d5994a1a8c3372fda67a36c0e | LisaVysochyn/hello-python | /7.py | 175 | 3.953125 | 4 | price_of_meal = float(input())
percent = float(input())
tip_amount = price_of_meal*percent/100
total_bill = tip_amount+price_of_meal
print(tip_amount)
print(total_bill)
|
ed5b5431548160088a79d58b1a2952fe3a1fca24 | LisaVysochyn/hello-python | /13.py | 146 | 4.03125 | 4 | from math import *
angle_in_degrees = float(input())
angle_in_radians = radians(angle_in_degrees)
sine = sin(angle_in_radians)
print(sine)
|
251ef584b209b7d35d61c5498a1bbece22345e0e | mihawkeyes/practice-pro | /python/commonchar.py | 415 | 3.859375 | 4 | #PF-Assgn-33
def find_common_characters(msg1,msg2):
common_characters=''.join(a for a in msg1 if msg2.find(a)!=-1 and a!=' ')
if common_characters=='':
return -1
return common_characters
#Remove pass and write your logic here
#Provide different values for msg1,msg2 and test your program
msg1=... |
4ddc6803ef22bf11b850ad801015ed1e07cad14b | mihawkeyes/practice-pro | /python/duplicateinstring.py | 297 | 3.5625 | 4 | #PF-Assgn-60
def remove_duplicates(value):
val=''.join(value[0])
for i in range(1,len(value)):
if value[i] in val:
pass
else:
val+=value[i]
return val
#start writing your code here
print(remove_duplicates("11223445566666ababzzz@@@123#*#*")) |
99d7bceef1cd86093a076d4eba62beb240b06c6b | mihawkeyes/practice-pro | /python/sieveofsundaram.py | 1,101 | 4.625 | 5 | # Python3 program to print
# primes smaller than n using
# Sieve of Sundaram.
# Prints all prime numbers smaller
def SieveOfSundaram(n):
# In general Sieve of Sundaram,
# produces primes smaller
# than (2*x + 2) for a number
# given number x. Since we want
# primes smaller than n, we
# reduce n to ha... |
eb8b103254dbc4af992b1806c733f2d6d6dde861 | mihawkeyes/practice-pro | /python/spelling_checking_dictionary.py | 766 | 3.8125 | 4 | #PF-Assgn-48
def find_correct(word_dict):
contestent_spelling = word_dict.values()
corret_spelling = word_dict.keys()
result=[0]*3
for spelling in corret_spelling:
c=0
c_spell_list=list(spelling)
con_spell_list=list(word_dict[spelling])
for s in range(0,len(c_spell_list)... |
ba50a6c567734780fcfddd9a1f61262bc7f07c19 | arkanalexei/kattis-solutions | /autori.py | 173 | 3.921875 | 4 | string = input()
new_initials = []
for str in string:
if str.isupper() == True:
new_initials.append(str)
result = ''.join(new_initials)
print(result)
|
2ffd5b28f2b27935dcdc2546d3944075bd07363c | arkanalexei/kattis-solutions | /somesum.py | 151 | 4.0625 | 4 | n = int(input())
r = (1+n) * n / 2
if n % 2 == 1:
print("Either")
elif n % 2 == 0 and r % 2 == 1:
print("Odd")
else:
print("Even") |
b417a78c1b4c934851617fbbd4aa890d6df11156 | arkanalexei/kattis-solutions | /tripletexting.py | 324 | 3.890625 | 4 | name = str(input())
firsttext = name[:int(len(name) / 3)]
secondtext = name[int(len(name) / 3):int((len(name)) / 3) + int(len(name) / 3)]
thirdtext = name[int((len(name)) / 3) + int(len(name) / 3):int(len(name))]
if firsttext == secondtext or firsttext == thirdtext:
print(firsttext)
else:
print(secondt... |
798d5d78f6ec617c17ee5d6e779da26c7785a09e | nogumbi/Group-Project | /Calendar/calendar_viewer.py | 874 | 4 | 4 | import calendar_update as check
def check_calendar():
#function to check the calendar is up to date before passing it on to the
#rest of the functions in the program makes use of calendar update to check
#and update the current calendar
checked = False
while 1:
if checked:
con... |
e259ff175419b5160c3246c99750e0380d20e7c6 | diamondman/StatemachineExample | /iter2/statemachine.py | 5,137 | 4.09375 | 4 |
class StateMachine(object):
"""This variable is only used for getting the string names of the
states based on their number. Each stats is just a number below, and
this array lets us check
StateMachine.STATE_NAMES[StateMachine.IDLE]
or
StateMachine.STATE_NAMES[0]
and the result would be th... |
03966e5b0fb50501e67a0567bc925ea3656e12b9 | vesselofgod/Python_Lecture_Note | /Data_analysis/np.py | 745 | 3.765625 | 4 | import numpy as np
import matplotlib.pyplot as plt
#X축 데이터 생성
x=np.linspace(0,2*np.pi,100)
#y축 생성
y=np.sin(x)
#그래프 그리기
plt.plot(x,y)
plt.show()
'''
list1=[1,2,3,4]
a=np.array(list1)
# array의 형태(크기)를 확인할 수 있다.
#이 경우에는 list의 크기가 4이므로 (4,)가 출력됨
print(a.shape)
#데이터의 타입을 확인할 수 있다.
print(a.dtype)
... |
826550ee62029fff7f61bf987598ee0125413a49 | tsamridh86/RSA | /decryptor.py | 1,387 | 4.375 | 4 | # this code converts cipher text into msg & displays it to the user
# this functions converts the cipherText into number format plainText
def decrypt( cipherText, publicKey, divisorKey , blockSize):
i = 0
lenCipherText = len(cipherText)
plainText = []
while i < lenCipherText:
copyBlockSize = blockSize
numArr =... |
55ae87ecccbcd622fb4387d209a5394b6ab71e4e | Jerrydperry/cs114 | /Face.py | 1,215 | 3.8125 | 4 | # face program:
# asks user to pick from a series of faces the face serves as an base image that is loaded from a folder:
def openphoto():
""" this function looks into and pulls a image from a directory."""
def intro():
"""welcomes user, asks user to pick a face type: """
def faces(): """
square, thin, r... |
b733170325793d63b2db089bb0a4a31dd5d36c55 | dimaape/GeekBrains_Python_Course | /Lesson_1/GB_Py_HW_1_1.py | 1,252 | 4.34375 | 4 | # Задание 1.1
# Поработайте с переменными, создайте несколько, выведите на экран
print("Поработайте с переменными, создайте несколько, выведите на экран.\n")
var_a = 0
var_b = "some text"
var_c = 10
var_d = "some text again"
print(var_a, var_b, var_c, var_d, sep='\n')
# Запросите у пользователя несколько ... |
3fe33cc0fbd1fd628e2253899ae0683155cf1feb | Sankowskia/Code | /002AddTwoNumbers.py | 1,329 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
f=0
... |
e6fd95ce117cb9035049aac5bc970dbf7a08f9e3 | icadev/Python-Projects | /ex2.py | 691 | 4.46875 | 4 | print "I will now count my chickens:"
print "Hens", 2.5 + 3.0 / 6.0 #make the operation
print "Roosters", 10.0 - 2.5 * 3.0 % 4.0 #make the operation
print "Now I will count the eggs:"
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 -1.0 / 4.0 + 6.0 #make the operation
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?... |
b1437f271f59cca4f92fb6e111a96f2579bdb93a | icadev/Python-Projects | /my_game.py | 1,628 | 4.40625 | 4 | class Person:
"""Represents a robot, with a name."""
# A class variable, counting the number of robots
population = 0
def __init__(self, name, age, job):
"""Initializes the data."""
self.name = name
self.age = age
self.job = job
print("(Presenting you... |
f6be018185167d1f6dccf6e7eab6b0b86207d9ac | icadev/Python-Projects | /game43.py | 2,651 | 4.09375 | 4 | from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass it and implement enter()."
exit(1)
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self)... |
0f42c3798473b7a5d9f2ce8758c58c7d559425f5 | DANJOCC/inek | /inek.py | 9,333 | 3.703125 | 4 | #LIBRERIA DE FUNCIONES PARA CALCULOS DE INECUACIONES, INEK
#HECHO POR: DANIEL JOSE CARRIZO CONCHO
import math
#INECUACIONES LINEALES DE LA FORMA mx+b<0 Ó mx+b>0
def lineal(x,b,simbolo):
res=-b/x
sim=">"
if simbolo==">":
if x<0:
print("x < ",res)
sim="<"
else:
... |
8610b79b503c8d954b943e1804504d1f0761ac0b | kdeckerpyplus/PyPlus_Class4 | /ex7_show_int_status.py | 1,004 | 3.671875 | 4 | #!/usr/bin/env python
import textfsm
from pprint import pprint
# Create a file handle to the TextFSM Template .tpl file:
template_file = "ex2_show_int_status.tpl"
template = open(template_file)
# Read in the 'show int status' output from a text file:
with open("ex2_show_int_status.txt") as f:
raw_text_data = f.read... |
2011a95fbe2d2ac53b40aa0bf34d804f409496a5 | diaa95/Vending-Machine | /snackMachine.py | 6,717 | 3.953125 | 4 | import time
accepted_coins= [0.10, 0.20, 0.50, 1.00, 20.00, 50.0]
password = 12345678
class Item:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
def add_quantity(self, quantity):
self.quantity += quantity
class Vending... |
47b5e7d992beeeae927c07f8ddfcdbdbefa6d345 | SudheshSolomon1992/Hackerrank_30_days_Coding_Challenge | /Day_7_Arrays.py | 360 | 4.34375 | 4 | #!/bin/python3
def main():
number_of_elements = int(input())
element = [int(n) for n in input().split()[:number_of_elements]]
reverse(element)
def reverse(array):
# reversed function is used to reverse an array in python3
for element in reversed(array):
print (element, end=" ")... |
68f34a9282e9e3650fe2d4f675870057cc5781ca | antonioCC/validar-variables-primitivas | /programa T1.py | 2,603 | 3.703125 | 4 | import re
#patron = re.compile('a[3-5]+')# coincide con una letra, seguida de al menos 1 dígito entre 3 y 5
#print( input("Introduce un texto") );
import re
archivo=open("datosA.txt","r")
mensaje=archivo.read()
p1 = re.compile('(int |long |byte |short )')
p2 = re.compile('(double |float )')
p3 = re.comp... |
d96e7ab8eb529aab4a3a1ad4ef558998928d7e3e | zetwhite/boj | /python_practice/boj2733.py | 2,483 | 3.671875 | 4 | class Stack(list) :
#is empty(), push(), pop(), top()
push = list.append
def is_empty(self) :
if not self :
return True
else :
return False
def top(self) :
return self[-1]
def getCode() :
refinedCode = ""
braceStack = Stack([])
brace... |
120aba6fcedb13eb6c26ff49ba452ba77bd26caa | Gaurank09/FST-M1 | /Python/Activities/Activity_7.py | 163 | 3.859375 | 4 | ListNumbers = list(input("Enter comma separated numbers (without spaces): ").split(","))
Sum = 0
for number in ListNumbers:
Sum += int(number)
print(Sum) |
90c6f4d6db97aba7c3e2e8e8761584312c2c5563 | felix-ogutu/Python-Projects-2 | /calender.py | 376 | 3.625 | 4 | from tkinter import *
import calendar
text = calendar.calendar(2021)
root = Tk()
root.geometry("500x600")
root.title("CALENDER")
label1 = Label(root, text="CALENDAR", bg='dark gray', font=("times", 28, 'bold'))
label1.grid(row=1, column=1)
root.config(background="white")
l1 = Label(root, text=text, font="consolas 10 b... |
d5227746c92f4e347229ef1b38f79cf792d4f654 | JavierEsteban/Basico | /1.- Tipos De Datos/pruebas.py | 574 | 3.984375 | 4 |
def calculo_media():
cantidad_veces = int(input("ingresar la cantidad de números A ANALIZAR: "))
conteo = 0
Sumatotal = 0
while(conteo < cantidad_veces ):
numero = int(input("Ingrese el número a evaluar : "))
Sumatotal = numero + Sumatotal
conteo = conteo + 1
Media = Suma... |
5dc312fc5045a8af800d6cf33ee18baf4acf9464 | sbrady521/coding_resources | /Problems/problem32.py | 2,417 | 3.609375 | 4 | sum = 0
def generate(n, array):
global sum
if n == 1:
#look for pandigital cases
multLeftLen = 1
multRightLen = 1
productLen = len(array) - (multLeftLen + multRightLen)
while multLeftLen <= len(array) - 2:
multRightLen = 1
productLen = len(array) -... |
a0584d95ae10481fdb14b41f49cd0a777b7d3e81 | VadimSquorpikkor/Python_Stepik_2 | /1/1_2/1_object_quantity.py | 1,710 | 3.890625 | 4 | # Реализуйте программу, которая будет вычислять количество различных объектов в списке.
# Два объекта a и b считаются различными, если a is b равно False.
#
# Вашей программе доступна переменная с названием objects, которая ссылается на список, содержащий не более
# 100 объектов.
# Выведите количество различных объекто... |
1190a96ee2c2d89d3680082d05f0e8d6beec1088 | Sadhik0905/Coursera | /Algorithms And Data Structures/Algorithmic Toolbox/Week_2/Fibonacci Number.py | 223 | 3.625 | 4 | def febonacci(n):
lst = list()
lst.append(0)
lst.append(1)
for i in range(2,n+1):
num = lst[i-1] + lst[i-2]
lst.append(num)
return lst[n]
n = int(input())
print(febonacci(n))
|
0b5051386fd85a67cf88c88cabb2d63d1f954bbe | Tbeck202/PythonCourse | /VariablesAndStrings/converter.py | 207 | 4.34375 | 4 | print("Enter a distance in Kilometers, and I'll convert it to miles!")
kms = input()
miles = float(kms)/1.60934
round_miles = round(miles, 2)
print(f"Ok, {kms} kilometers are equal to {round_miles} miles!")
|
22c960b54ebe64b8083645821782ad6852c4436c | Tbeck202/PythonCourse | /Tuples_and_sets/sets.py | 1,202 | 4.15625 | 4 | # cities = ['Los Angeles', 'Boulder', 'Kyoto', 'Florence', 'Santiago',
# 'Los Angeles', 'Shanghai', 'Boulder', 'San Francisco', 'Oslo', 'Tokyo']
# no_duplicates = set(cities)
# # print(no_duplicates)
# no_duplicates.add('Portland')
# print(no_duplicates)
# no_duplicates.remove('Shanghai')
# print(no_dupli... |
b3653e1eb9e951c7b376f8ca241b0df137db962b | Tbeck202/PythonCourse | /BuiltInFunctions/all_any.py | 519 | 3.9375 | 4 | nums = [2, 4, 6, 8]
nums2 = [2, 4, 6, 8, 9]
print(all([num % 2 == 0 for num in nums])) # true
print(all([num % 2 == 0 for num in nums2])) # false
names = ['Jim', 'John', 'Joe']
names2 = ['Jim', 'John', 'Joe', 'Bob']
if all([name[0] == "J" for name in names]):
print("We got a bunch of J holes here!")
if not al... |
bd7669e0818b88e58fe44932a8698299c3aa5b49 | Tbeck202/PythonCourse | /CSV/csv_reader.py | 636 | 3.625 | 4 | from csv import reader
with open("fighters.csv") as file:
# csv_reader is an iterator, NOT a list.
csv_reader = reader(file)
# use "next" to skip the headers in the csv file
next(csv_reader)
for fighter in csv_reader:
print(f"{fighter[0]} is from {fighter[1]}")
print("====================... |
c316e098a15a4859079b77494dd2668200eebe20 | Tbeck202/PythonCourse | /Modules/color_exercise.py | 436 | 3.71875 | 4 | import termcolor
from pyfiglet import Figlet
f = Figlet(font='graffiti')
while True:
text = input("What message do you want to print? \n")
print("What color do you want the text?")
color = input("Green, Magenta, Blue, Cyan, Red or Yellow? \n").lower()
try:
termcolor.cprint(f.renderText(text),... |
cc0cc27653fcbe55bc65ecca72da02037956b473 | DharmilShahJBSPL/DharmilShah | /python/dictionary_ex.py | 620 | 4.5 | 4 | print('using Dictionary example')
print('')
di={'abc':'1','x':'2','jkl':'3'}
print (di)
print(di.keys())
print(di.values())
print('to print particaular value of key then use this ')
print(di['abc'])
print(di['jkl'])
print('')
print('')
print('to print more than 1 key value then use this ')
print((di['abc']),(di['jkl']... |
920bf98098ef7412d8a376e5e06ca20f187562a1 | DharmilShahJBSPL/DharmilShah | /python/Constructor_comparing/Constructor_comparing.py | 500 | 3.5 | 4 | class sdata:
def __init__(self):
self.val1 = val1
self.val2 = val2
def display(self):
print('name :', self.val1)
print('subject :', self.val2)
def compare(self, other):
if self.val2 == other.val2:
return True
else:
return False
val... |
272a9efb9097d1463f2a598d4c1889a320683a22 | DharmilShahJBSPL/DharmilShah | /python/ypdate_mysql/update_data_mysql.py | 1,760 | 3.515625 | 4 | import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", passwd="")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE IF NOT EXISTS userinput")
mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="userinput",buffered=True)
mycursor = mydb.cursor()
# ... |
b978659ff0ab2b6c1189c480efa7accf2aeaa9ed | DharmilShahJBSPL/DharmilShah | /python/forloop_example/forloop_example.py | 452 | 3.890625 | 4 | import sys
import math
print('using For Loop example')
# print('for loop using list')
# d=['hello','hi','welcome']
#
# for i in d:
# print(i)
#
# print('for loop to print single character of string')
# d1='WELCOME'
# for j in d1:
# print(j)
#
# for k in range(11):
# print(k)
#for i in range(1,501):
# y... |
3be4ba4ce2a480e3bce6eec9b78994ef717f1089 | DharmilShahJBSPL/DharmilShah | /python/userinput_mysql/userinput_mysql.py | 786 | 3.640625 | 4 | import mysql.connector
mydb = mysql.connector.connect(host="localhost", user="root", passwd="")
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE IF NOT EXISTS userinput")
mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="userinput")
mycursor = mydb.cursor()
mycursor.execute(... |
18841dec35527dcec7bd7581798614017098d361 | DharmilShahJBSPL/DharmilShah | /python/testing_sqlite/testing_sqlite.py | 367 | 3.765625 | 4 | import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
if c:
print('database created')
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS demo(name TEXT, mno REAL, email TEXT)')
def data_entry():
c.execute("INSERT INTO demo VALUES('xyz', 12345,'SADF')")
conn.commit()
c.close()... |
3ca9429da4f34d34b20e6defd35f682d303d86fb | DharmilShahJBSPL/DharmilShah | /python/exceptional_handling_ex/exceptional_handling_ex.py | 397 | 4.03125 | 4 | print('Using Try and Except for Exception Handling')
val1 = int(input('enter the 1st value : '))
val2 = int(input('enter the 2nd value : '))
try:
val3 = int(input('enter the value'))
except ValueError as e:
print(e)
try:
print(val1 / val2)
except ZeroDivisionError as e:
print(e)
except Exception as... |
cfe60ce0b73f0bedc546ab08510f59cefb03aa4a | Dhamodaran-Nadarajan/Simple-Games | /Snake_Game.py | 5,209 | 3.765625 | 4 | # Simple Snake Game ©Dhamodaran Nadarajan
# Import Statements
import turtle
import time
import random
# Global Declarations - Start
width = 600
height = 600
delay = 0.1
score = 0
high_score = 0
left_border = int(-width / 2) + 10
down_border = int(-height / 2) + 10
right_border = int(width / 2) - 10
to... |
c995c0c43bbacc17b2dec560d80af516fbfe33b2 | odderikf/algdat | /oving4/del2.py | 2,658 | 3.6875 | 4 | #!/usr/bin/python3
class Node:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.value = ""
self.left = None
self.right = None
def depth(self, i=0):
left = self.left
right = self.r... |
96801d522b148f1c7d9c80f44c65552be871ed2a | LinXunFeng/leetcode | /二叉树/_110_平衡二叉树.py | 1,677 | 4.0625 | 4 | """
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.... |
3b08ddaa59983b8883503257442ba44bb3326fbb | LinXunFeng/leetcode | /动态规划/_121_买卖股票的最佳时机.py | 4,053 | 3.546875 | 4 | """
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
来源:力扣(LeetCode)
... |
68dcc231502d22ae030970977ebde8c29ac430a2 | KleyLima/memory_dumper | /utils/enter_data.py | 2,577 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from functools import reduce
from utils.hex import Hex
class Input:
@staticmethod
def enter_data(rows, confirmation=False):
"""
Read the data stream from the input, aggregating in a single list
:param rows: Number of rows that will be read from input
... |
429eb17de14c1bf37e416b008f5826f0389aeb6b | rpao/listaExercicio | /listaQ7.py | 2,132 | 3.609375 | 4 | # -*- coding: utf-8 -*-
## Questão 7
## Construa uma função que receba como parâmetro uma data no formato DD/MM/AAAA e
## devolva uma string no formato "D de mesPorExtenso de AAAA".
## Opcionalmente, valide a data e retorne uma mensagem caso a data seja inválida.
def _verificarAnoBissexto(ano):
if (ano%400 ... |
bece50c41504588f34ed503a2f7a60f4e58456a8 | SabrinaMannan/Python | /mathematicalOperator.py | 364 | 3.96875 | 4 | num1=int(input("Enter a number:"))
num2=int(input("Enter a number:"))
result = num1 + num2
print("The result is",result)
result = num1 - num2
print("The result is",result)
result = num1 * num2
print("The result is",result)
#using functions
from math import *
print(floor(4.54)) #prints the prev lowest integar
print(... |
8fc09527b4ba671fbf04ee8c0811fd803e4bee5a | jimishmrug/Hospital_Database | /Hospital_Management.py | 3,610 | 3.65625 | 4 | from tkinter import *
import sqlite3
import tkinter.messagebox
con = sqlite3.connect('hospital.db')
c = con.cursor()
def call_for_add():
class Application:
def __init__(self,master):
self.master = master
self.heading = Label(self.master, text="ABC Hospital", font=("Ariel 40 bold... |
ba0b4664536839861512d7e1fd9281fc64e94102 | signallogics/MachineLearningProjects | /ECG/src/get_x_y.py | 361 | 3.796875 | 4 | #!/usr/bin/env python
import numpy as np
def get_x_y(sets):
"""
sets is a numpy.array
[
[1,2,...,2000, 1],
[1,2,...,2000, 0],
]
"""
col = sets.shape[1] - 1
x = sets[:, 0:col]
y = sets[:, col, np.newaxis]
"""
print sets.shape
print x.shape
... |
3fa50191aac0be2a049737941c4493d9fa5fcb94 | Robel1992/Python_Basics | /List_Tic_Tac_Toe.py | 14,629 | 4.53125 | 5 | '''#----------------Text Based Version of Tic Tac Toe-------------------------
#First step, break down problem into small pieces, and tackle each problem
#We need some sort of game map, a way to visualize Tic Tac Toe
#Let's keep this simple. We'll be working with 0's 1's and 2's
#We're going to be using a lists, o... |
5b4252a9c0b6cf6fbcf3048d8657dfa9ecdb2673 | bbw7561135/computationalAstrophysics-1 | /metropolis/metropolis_mcmc3_dft.py | 3,964 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# example of the Metropolis algorithm single walker chain
# a difficult distribution: the Rosenbrock “banana” pdf
#
import math
import numpy as np
from numpy import random as rnd
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from tim... |
97ac5cf67bafca3fccbab147bef93e2bb0e4b2cb | bbw7561135/computationalAstrophysics-1 | /integration/seed_ex.py | 1,622 | 3.515625 | 4 | #
# example illustrating how to initialize different random sequences. and that these
# need to be seeding with different seeds.
#
import random
import time
print 'Default initialization:\n'
r1 = random.Random()
r2 = random.Random()
n = 5
for i in xrange(n):
print '%04.3f %04.3f' % (r1.random(),... |
a335d121085618bbef55f2322a50cb31cadded9c | nova0002/DailyCodingProblem | /DailyCodingProblem1 | 566 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 19:21:32 2020
@author: amandanovak
"""
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
def addK(list,k):
if len(list) == 1:
if list[0] == k:
return True;
else:... |
f92ba960ca29a0166e837774c7309224278b8135 | rpicatoste/carnd-term1-project1 | /functions.py | 10,561 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 18 13:55:54 2017
@author: Pica
"""
#%%
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel but NOTE: to see
the returned image... |
b89952c782991c611f977bc7b3d346f471c092f7 | suvoooo/Machine_Learning | /datacleaning/data_cleaning.py | 7,922 | 3.546875 | 4 | #!/usr/bin/python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
movies_df = pd.read_csv("movie_metadata.csv")
#print movies_df.head(3)
#print movies_df.describe()
# check the column names
#print "column names: ", movies_df.columns.values
#print m... |
b05a877197048d7e7d14a33a4117f00c93b83c9f | Patrick-David/MachinePlot | /machineplot.py | 5,862 | 3.671875 | 4 | from matplotlib import pylab as pl
from itertools import cycle
import numpy as np
from sklearn.grid_search import GridSearchCV, RandomizedSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing, metrics
class MLPlot(object):
'''Various plotting functions f... |
05fff5b514a754e4c177e847348b891cb71f8268 | mailmram/Python_Learning | /DataStructures/Graphs/graph.py | 1,284 | 3.859375 | 4 | # class node:
# def __init__(self, data):
# self.data = data
# self.childNodes = []
class Graph(object):
def __init__(self, nodes):
if nodes is None:
self.nodes = {}
else:
self.nodes = nodes
def vertices(self):
return list(self.nodes.key... |
c4da3dc4e8bcaa4a59884affcef4676ef9820185 | mailmram/Python_Learning | /CTCI/List/FindkFromLast.py | 1,273 | 3.9375 | 4 | class node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class linkedList:
def __init__(self):
self.head = None
def printList(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
l... |
2fd6837cb6f45c106124865f7d800c7454d5d696 | DiegoC386/Algoritmos_Diego | /CLASE WHILE_FOR/For.py | 47 | 3.71875 | 4 |
for x in range(0,101):
if(x%3==0):
print(x) |
b2bf3287b925aee709a6520b4d27c8d10094dbf1 | DiegoC386/Algoritmos_Diego | /Taller Estructura Control Secuencial/Ejercicio_11.py | 760 | 3.984375 | 4 | """
Entradas
Nombre-->int--> Nombre
Numero Hijos-->int--> NH
Sueldo Base-->int--> SB
HorasTrabajadas-->int--> HT
HorasExtras-->int--> HE
Salidas
Deducciones-->int--> DEDUC
Asignaciones-->int--> ASIG
SueldoNeto-->int--> SN
"""
#ENTRADAS
Nombre=input("Ingrese su Nombre: ")
NH=int(input("Ingrese numero de Hijos: "))
SB=in... |
e337a7e61eceb73ad55a51696244c143edfab1f8 | DiegoC386/Algoritmos_Diego | /Taller Estructura Control Secuencial/Ejercicio_12.py | 2,312 | 3.84375 | 4 | """
Entradas
ExamenMatematicas-->float-->Mate
ExamenFisica-->float-->Fis
ExamenQuimica-->float-->Quim
NotasTareasMatematicas1-->float-->NotaM1
NotasTareasMatematicas2-->float-->NotaM2
NotasTareasMatematicas3-->float-->NotaM3
NotasTareasFisica1-->float-->NotaF1
NotasTareasFisica2-->float-->NotaF2
NotasTareasQuimica1-->f... |
a8674b4146e7fb058d70e0e1900a14d2b4f0042e | DiegoC386/Algoritmos_Diego | /Taller Estructuras de Control Selectivas/Ejercicio_9.py | 2,123 | 4.3125 | 4 | """
En una tienda efectúan un descuento a los clientes dependiendo del monto de la compra.
El descuento se efectúa con base en el siguiente criterio:
a. Si el monto es inferior a $50.000 COP, no hay descuento.
b. Si está comprendido entre $50.000 COP y $100.000 COP inclusive,
se hace un descuento del 5%.
c. Si está com... |
ff1bba15011d0af4c45520ca0c2e510b617b5ee2 | DiegoC386/Algoritmos_Diego | /Taller Estructura Control Secuencial/Ejercicio_16.py | 277 | 3.765625 | 4 | """
Entradas
Galones-->float-->GAL
Salidas
Litros-->float-->L
PrecioLitros-->int-->PL
"""
#ENTRADAS
GAL=int(input("Ingrese cantidad de Galones: "))
#CAJANEGRA
L=GAL*3.785
PL=L*50000
#SALIDAS
print("La cantidad de litros es: " +str(L))
print("El precio en litros es: " +str(PL)) |
9a9992aff4c47a229cf240ca0724b46127f91153 | Eric3911/Code-with-Life | /Rename1.py | 967 | 3.859375 | 4 | '''
Author:'JungangAn';
_*_ conding: utf-8 -*-
Time: 2019/3/20
'''
#图片文件批量重命名
import os
class ImageRename():
def __init__(self):
self.path = 'D:/ca/'
def rename(self):
filelist = os.listdir(self.path)
total_num = len(filelist)
start = 0
for item i... |
5b4841a57f777204f1a4a2235901b6c0ce723858 | tlofreso/adventofcode2020 | /01/expense_report.py | 1,284 | 4.1875 | 4 |
def values():
"""Reads input, and returns all values as a sorted list of integers"""
with open('input.txt') as f:
lines = f.read().splitlines()
my_input = [int(i) for i in lines]
my_input.sort()
return my_input
def computer():
result = 2020
n1_possible = []
n2_pos... |
adb94761a1fedc70e9e77e6ade231e8ca2028eb8 | amoddhopavkar2/LeetCode-November-Challenge | /05_11.py | 262 | 3.515625 | 4 | # Minimum Cost to Move Chips to The Same Position
class Solution:
def minCostToMoveChips(self, positions: List[int]) -> int:
even, odd = 0, 0
for position in positions:
if position % 2 == 0:
even += 1
else:
odd += 1
return min(even, odd)
|
31c948bf7b49c9f8a11e33a0985326942e17c8cb | amoddhopavkar2/LeetCode-November-Challenge | /01_11.py | 564 | 3.828125 | 4 | # Convert Binary Number in a Linked List to Integer
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
binary = []
while head != Non... |
924ea5455fb5bf4a51d2d9412adfd203b27c1b66 | JamesDevaney1150/Python-Essentials | /test.py | 3,509 | 3.90625 | 4 | #x = float(input("Enter value for x: "))
# Write your code here.
#y=1(x+1/(x+1/(x+(1/x))))
#print("y =", y)
#x = int(input())
#y = int(input())
#x = x / y
#y = y / x
#print(y)
#x = int(input())
#y = int(input())
#x=x%y
#x=x%y
#y=y%x
#print(y)
#x=1 / 2 + 3 // 3 + 4 ** 2
#print(x)
#z = y = x = 1
#print(x,y,z, se... |
64c2c471974ea13afac4cdef5cd02c11de405ea3 | justus-migosi/do-while-loop | /dowhileloop.py | 71 | 3.5625 | 4 | x=1
while True:
print(x)
x=x+1
if(x>10):
break |
00f75399b13208b8b2c648c978fb08065306f427 | OffensiveCyber/Learn_Python_the_practical_way | /T2_List.py | 1,063 | 4.5625 | 5 | cars = ['nissan', 'ford', 'honda','tesla', 'Volkswagen']
#print all cars name from the list
print cars[0]
print cars[1]
print cars[2]
print (cars[3].title()) #title() method displays word with first letter in caps
print "Hello " + cars[0] + ", What is your milage?" #concetation demonstrated
print "Hello " + cars... |
189718bc155949f56b742abc9cb302e5d2b74273 | theLORD97/pynet_test | /file.py | 313 | 3.546875 | 4 | f = open("file.txt")
for line in f:
print(line.strip())
#### WRITE ####
print("\nWriting file.")
f = open("new_file.txt", "w")
f.write('Leon is 2nd best\n')
f.close()
#### APPEND ####
print("\nAppending file.")
with open("new_file.txt", "a") as f:
f.write('Oilers rule\n')
print ("Script Completed")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.