blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3a5af4578d26978a692a7402d763d09e11699ee7 | Rodrigo-Antonio-Silva/ExerciciosPythonCursoemVideo | /Ex0050/ex0050.py | 361 | 3.671875 | 4 | #utf-8
soma = 0
cont =0
for i in range(1, 7):
n = int(input('Digite o {} número: '.format(i)))
if n % 2 == 0:
soma += n
cont += 1
if cont == 1:
print('Você informou {} número par que é o :{} '.format(cont, soma))
else:
print('Você informou {} pares e a soma dos números... |
474b67b537eec745841cb06a437a6eddb047958e | Kabzel55/Codility_Python | /1_BinaryGap.py | 303 | 3.703125 | 4 | def solution(N):
'''
Find longest sequence of zeros in binary representation of an integer.
:param N: Integer
:return: a count of the longest sequence of zeros in the binary representation of the integer
'''
N = bin(N)[2:].strip('0').split('1')
return max(len(i) for i in N) |
c0b8410efc2450cd437d10a557be4fe92daa09f6 | oo363636/test | /ForOffer61.py | 1,725 | 3.6875 | 4 | """从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,
A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14
"""
class Solution:
def is_straight(self, nums: [int]) -> bool:
"""1、若无重复的牌(大小王除外)
2、最大牌 - 最小牌 < 5(大小王除外)
则5张牌可以构成顺子
两种方法:集合+遍历 or 排序+遍历,目的都是一致的
"""
repeat = ... |
16996a072b304229c06424ff7c471e8cf7fd0f55 | thedarkknight513v2/daohoangnam-codes | /Daily studies/26_May_18/Triangle_1_drawing.py | 233 | 4 | 4 | # # Solution
# for i in range (10):
# for j in range(i):
# print("* ", end="")
# #break
# print()
n = int(input("Please input n"))
for i in range(n):
for j in range(i):
print("*",end="")
print() |
2cdfc4e13fa05ed19974d4a562e8d49c8532d895 | mak131/Pandas | /5.replace function/2.replace.py | 1,323 | 4.21875 | 4 | import pandas as pd
df = pd.read_csv("E:\\code\\Pandas\\5.replace function\\Student_data.csv")
print(df)
print()
# this method is used to replace lot of values to different different value using list
# and this method is also used as without parameter
replace_lot_def = df.replace([101,102,103,104,105,106,107,108,109... |
953319de48c1cbbf2f0128f4d226d188682ca2c4 | zzzzx10/AlgorithmExercises | /problems/旋转数组的最小数字.py | 1,212 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 13:48:36 2019
旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
"""
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
... |
39d7a62355cd6ea661636fdba9b855c42a4d909d | decpdx584/recursion_rocks | /coin_flips.py | 419 | 4.09375 | 4 | # You will have to figure out what parameters to include
# 🚨 All functions must use recursion 🚨`
# This function returns an array of all possible outcomes from flipping a coin N times.
# Input type: Integer
# H stands for Heads and T stands for tails
# Represent the two outcomes of each flip as "H" or "T"
def coin... |
378bc96a3ca28edf8be356d3ba8b7d76a5583585 | ALMTC/Logica-de-programacao | /Python/MaiorMenorMatriz.py | 1,197 | 3.953125 | 4 | l=[]
c=[]
MinimoLinha=[]
MaximoLinha=[]
MinimoColuna=[]
MaximoColuna=[]
print 'Digite a qunatidade de linhas da matriz'
linha=input()
print 'Digite a quantidade de colunas da matriz'
coluna=input()
for i in range(linha):
l.append([])
for j in range(coluna):
print 'Digite o eleento',i,j,'da matriz'
l[i].append(inp... |
b54b3963ac51e20930bce6c8424a47405f830b08 | s2t2/example-gui-app-py | /app/my_gui.py | 2,554 | 3.921875 | 4 | import tkinter
#
# INITIALIZE A NEW GUI WINDOW
#
window = tkinter.Tk()
#
# INITIALIZE SOME USER INTERFACE COMPONENTS
#
# MESSAGE
my_message = tkinter.Message(text="Hi. Welcome to my Example GUI Application!", width=1000)
# ENTRY WITH LABEL
my_label = tkinter.Label(text="Input something here:")
entry_value = tkin... |
ffc1ae7860c8e5a58281cadd49126ea57280abc9 | sanketkothiya/python-programe | /code excercise/new11.py | 180 | 4.09375 | 4 | n=int(input("enter the number"))
temp=n
r=0
while(n>0):
d=n%10
r=r*10+d
n=n//10
if(r==temp):
print("its palindrop")
else:
print("its not palindrop")
|
ee9fa866eac12f8024946bd02683d438047a9ee4 | anitrajpurohit28/PythonPractice | /python_practice/Basic_programs/6_area_of_circle.py | 229 | 4.5 | 4 | # 6 Python Program for Program to find area of a circle
from math import pi
def area_of_circle(radius):
return pi * radius * radius
r = float(input("Radius: "))
area = area_of_circle(r)
print(f"Area of circle: {area}")
|
0ff113342df9356e93ec50fe7b6893d7c102c037 | pelekhs/Geo-exercise-5 | /nn_training_evaluation.py | 6,149 | 3.578125 | 4 | import numpy as np
import torch
from sklearn import metrics
import os
import matplotlib.pyplot as plt
def logit_accuracy(logits, y_true):
"""This function computes the accuracy based on the logit outputs
of the neural network (tensor) and the true y labels in integer form"""
max_vals, y_pred = torch.max(... |
73fe5411d93ef3b327d9ef9a162f97074b3f6f32 | redvox27/week-2-python | /opdracht2_w3.py | 673 | 3.96875 | 4 | class stack:
def __init__(self):
self.elements = []
def is_empty(self):
if self.elements == [] :
print("elements is leeg ")
else:
return False
def addToList(self,value):
self.elements.append(value)
def peek(self):
print("last element in... |
129a47d87aee8644ab7d361ee51bf9f06c6d148e | JaniceLove/AutomateTheBoringStuff | /collatzSequence.py | 657 | 4.5625 | 5 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 7 23:32:10 2019
@author: janicelove
"""
import sys
#Function to perform collatz sequence on any number selected by user
def collatz(number):
if number % 2 == 0:
result = number // 2
elif number % 2 == 1:
result = 3 * numb... |
f34df846578e385cadc7b3de1a4581494d6d1627 | hitendrapratapsingh/python_basic | /average.py | 346 | 4.09375 | 4 | #excersize
# number1 = int(input("enter first number1"))
# number2 = int(input("enter first number2"))
# number3 = int(input("enter first number3"))
number1,number2,number3 = input("enter three number comma seprated: ").split(",")
#print(number1+number2+number3/3)
print(f"average of three numbers {(int(number1)+int(n... |
fe384c44a42f99357f008cae64ff27f302253650 | nmessa/Python-2020 | /Lab Exercise 11.12.2020/problem3.py | 363 | 3.890625 | 4 | ## Lab Exercise 11/12/2020 Problem 3
## Author:
## This program replaces all even values in a list with 0
def zeroEvens(lst):
#Add code here
return lst
#Code to test the function
myList = [1,2,3,4,5,6,7,8,9]
print (myList)
print (zeroEvens(myList))
## Output
## [1, 2, 3, 4, 5, 6, 7... |
7e450021f9b4d89756454638fa38f4b6210a747e | xiaoqiangjava/python_basic | /oop/package/case/run_case.py | 1,120 | 4.09375 | 4 | #! /usr/bin/python
# -*- encoding: utf-8 -*-
# 小明爱跑步案例
class Persion:
"""
该类是一个人类,有name和weight两个属性
"""
def __init__(self, name, weight):
"""
初始化对象方法
:param name: 姓名
:param weight: 体重
"""
self.name = name
self.weight = weight
def __str__(se... |
b8c6d68f92ff3ed62639579dad4303f27eb64cd7 | Mitchell-Faas/Q-Learning-tutorials | /Tabular Q-Learning/QLearning.py | 1,162 | 3.78125 | 4 | import gym
import numpy as np
import matplotlib.pyplot as plt
# Define the discount rate
# The reader is encouraged to experiment with this.
GAMMA = 0.9
# Set up the taxi environment
environment = gym.make('Taxi-v3')
# Build the Q-table
NUM_STATES = environment.observation_space.n
NUM_ACTIONS = environment.action_sp... |
15a5b95e961d2a953d39635c319f300a5809a50d | csuwaki/Vamo-AI | /Resilia/Módulo-1/aula06-atividade01.py | 247 | 3.84375 | 4 | comeu_tudo = True
comeu_metade = True
if comeu_tudo == True:
print("Sobremesa liberada!")
elif comeu_metade == True and not comeu_tudo:
print("Você precisa comer tudo para a sobremesa ser liberada.")
else:
print("Nada de sobremesa.") |
7927fff5e516d135c87b984e08beaf00330045c1 | Aasthaengg/IBMdataset | /Python_codes/p02401/s646895351.py | 290 | 3.921875 | 4 | def calc(a, op, b):
if op == "+":
r = a + b
elif op == "-":
r = a - b
elif op == "*":
r = a * b
else:
r = a / b
return r
while True:
a, op , b = raw_input().split()
if op == "?":
break
print(calc(int(a), op, int(b))) |
d1b1c9dc76a6f5aabe29464b875ed1a746123c69 | payne/msebg | /msebg.py | 1,828 | 3.578125 | 4 | #!/usr/bin/env python
#
# Python script for Eric Ligman's Amazin Free Microsoft eBook Giveaway
# https://blogs.msdn.microsoft.com/mssmallbiz/2017/07/11/largest-free-microsoft-ebook-giveaway-im-giving-away-millions-of-free-microsoft-ebooks-again-including-windows-10-office-365-office-2016-power-bi-azure-windows-8-1-off... |
72eba53267e5b15761c8c558434ee444e0a82758 | BandaruRajesh/Assignment | /39_problem.py | 694 | 4.03125 | 4 | """
Write a function that takes an integer n and returns the nth Prime number.
Example 1
Input
n=10
Output
29
Example 2
Input
n=5
Output
11
"""
import unittest
def PrimeNum(nums):
"""
??? Write what needs to be done ???
"""
pass
# Add these test cases, and remove this placeholder
# 1. Test... |
02cf3f0aace3c0616d8ccddaecfdf66b5d59f578 | nimroha/HashCode | /2022/src/common.py | 1,136 | 3.546875 | 4 |
def naive_levelup(project, members, people):
"""only levelup on your own without mentoring"""
for member, skill_req in zip(members, project['skills']):
skill, needed_level = skill_req
member_level = people[member].get(skill, 0)
if needed_level == member_level:
people[member... |
db74fdcede06c95993e57b899db5bed6ee74b200 | MLgeek96/Interview-Preparation-Kit | /Python_Interview_Questions/leetcode/problem_sets/Q49_group_anagrams.py | 1,476 | 4.28125 | 4 | from typing import List
def groupAnagrams(strs: List[str]) -> List[List[str]]:
"""
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the or... |
4194ad3b0279e6da28ea23c2f87de1403e025c3d | jschnab/leetcode | /strings/convert_time.py | 1,077 | 4.125 | 4 | """
We have two strings A and B that represent 24h times, formatted as HH:MM,
such as A is earlier than B.
In one operation we can increase time A by 1, 5, 15, or 60 minutes. We can
perform these operations any number of times.
Calculate the minimum number of operations needed to convert A to B.
"""
def convert_tim... |
f9a82ce3d318b3959dcd7a1fff1baa0ae437526c | mersted/python | /random/baseball.py | 4,419 | 3.796875 | 4 | # Calculates statistics of baseball player
# by inputting stats for each game
def main():
num_games = integer_check("How many games?")
tot_hits = 0
tot_plate_apps = 0
tot_walks = 0
tot_tb = 0
tot_runs = 0
tot_rbi = 0
tot_sb = 0
tot_hr = 0
tot_tr = 0
tot_do = 0
to... |
5f2c1cb005c7e8887067521bbb23da6a64431b5e | KaiyeZhou/LeetCode-repo | /123.买卖股票的最佳时机III.py | 3,211 | 3.546875 | 4 | '''
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:
输入: [1,2,3,4,5]
输出: 4
... |
c271a00d980c8d8f1eec9052f7690d1c6d138d11 | qbingham/Othello | /Game.py | 5,770 | 3.515625 | 4 | from Board import Board
from AIBoard import AIBoard
# from Timer import Timer
from time import sleep
import threading
import random
import Timer as ti
def symbol_toggle(player_symbol):
if player_symbol == "B":
return "W"
elif player_symbol == "W":
return "B"
else:
return True
def ... |
1bace0b1b64489c5f6b1a033c00b6e0aa8869124 | SbasGM/Python-Exercises | /Solutions/E08.M13/Solution-E08.M13.py | 1,096 | 3.890625 | 4 |
# coding: utf-8
# # Solution: Exercise 8.M13
# In[2]:
# Initialize the lists
L1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
L2 = [8, 9, 10, 11, 12, 13]
# ### a)
# In[3]:
# Generate a new list to store object present
# in both lists
intersection = []
# Loop over L2 to check each object and whether it's
# in L1 too
f... |
3f3fc796e9f0af470581bda58d0979d3469e768c | Surmalumi/homework8 | /work3.py | 754 | 3.65625 | 4 | # Создайте собственный класс-исключение, который должен проверять содержимое списка на наличие только чисел.
class Error(Exception):
def __init__(self, numbers):
self.numbers = numbers
total_list = []
while True:
value = input('Введите элемент для добавления в список или stop для завершения: ')
if... |
17bd8d1a649d0da0229fd81b6ed3c514d1c116e3 | mrToad1986/Python | /lesson 1.5.py | 884 | 3.90625 | 4 | revenue = float(input("Ваша выручка составила: "))
cost = float(input("Ваши издержки составили: "))
staff = int(input("Сколько человек на вас работает: "))
profit = revenue - cost
if profit > 0:
efficiency = (profit / revenue) * 100
avg_sallary = profit / staff
print(f"Прибыль вашей компании составил... |
d4d9b5469bc90d13db922db55e45f5a0a745b84b | batumoglu/Python_Algorithms | /LeetCode/sortedSquares.py | 499 | 3.765625 | 4 | class Solution(object):
def sortedSquares(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
B = []
for num in A:
B.append(num * num)
return sorted(B)
class Solution2(object):
def sortedSquares(self, A):
return sorted([x*x for x in... |
e07545299a2d051ff45cced179036f4e6ca4db9d | hackettccp/CSCI111 | /Modules/Module2/Labs/1_variables_lab.py | 559 | 4.46875 | 4 | """
Below are seven variables that reference numbers of different values.
Using the swapping process, assign the values so they are in ascending order.
(Smallest to largest)
Use the temp variable that is provided to help with the swaps.
For example, 10 should be assigned to num1 and 88 should be assigned to num7
Do... |
7d17f3cc8161528be999efe29bbe67041109261c | queryor/algorithms | /leetcode/28. Implement strStr().py | 1,640 | 4.03125 | 4 | # Implement strStr().
# Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
# Example 1:
# Input: haystack = "hello", needle = "ll"
# Output: 2
# Example 2:
# Input: haystack = "aaaaa", needle = "bba"
# Output: -1
class Solution(object):
def strStr(self, ha... |
ffe9eacc4c37813542ebb63202f322ac0fa9bcc4 | aj112358/python_practice | /(1)_The_Python_Workbook/RECURSION/square_root.py | 344 | 4.125 | 4 | # Exercise 179: Recursive Square Roots
def square_root(n: float, guess: float = 1.0) -> float:
if abs(guess**2 - n) < 1e-12:
return guess
new_guess = (guess + n/guess)/2
return square_root(n, new_guess)
def main():
num = float(input("What number to square root: "))
print(round(square_... |
5aad79f24c1daa3535baa20b230c0bb8cc586ab2 | BiT-2/Sorting-Algorithms | /QuickSort.py | 730 | 3.828125 | 4 | from random import randint
def QuickSort(input_array):
if len(input_array) <= 1:
return input_array
less_than, equal, greater_than = [], [], []
pivot = input_array[randint(0, len(input_array) - 1)]
for element in input_array:
if element < pivot:
less_than.append(ele... |
b5d4a2ea9f079bba28d6291fb0787d801d3c0c6a | reo11/AtCoder | /atcoder/hitachi2020/a.py | 106 | 3.734375 | 4 | s = str(input().rstrip())
if s in ["hi" * x for x in range(1, 6)]:
print("Yes")
else:
print("No")
|
8736b2f7a742fbf1726d30ba1e25063705f008bb | lawtherea/Training-Projects-Python | /guess-the-number.py | 506 | 4.03125 | 4 | import random
def guess(x):
random_numb = random.randint(1, x)
guess = 0
while guess != random_numb:
guess = int(input(f"Guess a number between 1 and {x}: "))
if guess < random_numb:
print("You guessed wrong, HAHA! Maybe you're too low...")
elif guess > random_n... |
3d25fa5a4d0860d0dd0ec874f9d728d955b388a0 | WagnerFLL/PAA | /D&C/FreteOBI.py | 809 | 3.515625 | 4 | import heapq
def dijkstra(begin, graph, dist):
dist[begin] = 0
queue = []
heapq.heappush(queue,(0,begin))
while queue:
no = heapq.heappop(queue)
if int(no[0]) > dist[no[1]]:
continue
for v in graph[no[1]]:
if dist[v[1]] > no[0] + v[0]:
... |
b136a022763d43802d0958c687cf39f5aac0d0ec | lifanly000/pythonProject | /pro001/main/classTest.py | 2,997 | 3.625 | 4 | #coding=utf-8
class A:
__instance = None
def __init__(self):
pass
@classmethod
def getInstance(cls):
if A.__instance is None:
A.__instance = A()
return A.__instance
def a(self):
self.b()
def b(self):
print "aaaa"
class TreeNode:
def ... |
be47a8bbaebefa611e9edc1950df2bb7858319b3 | krishnamnuwal/Properties-of-Std-Deviation | /StPer.py | 2,045 | 3.78125 | 4 | ##Importing all the required modules
import plotly
import csv
import plotly.figure_factory as ff
import pandas as pd
import statistics
##storing the data of the file studentPerformance in file var
file=pd.read_csv("StudentsPerformance.csv")
## Graph of score of all three subjects(maths,writing,reading) #... |
a6f9b3a452752018552020ad3de6b5204bb3dde3 | praneethpeddi/Python-Assignments | /san_foundry/merge_and_sort.py | 349 | 4.0625 | 4 | def merge_and_sort(list_1, list_2):
list_1.extend(list_2)
list_1.sort()
return list_1
def main():
list_1 = [2, 4, 5, 8, 10, 9, 40, 78, 0, 1]
list_2 = [4, 6, 6, 6, 6, 8, 0]
sorted_list = merge_and_sort(list_1, list_2)
print(f"Sorted list after merging two lists : {sorted_list}")
if __name... |
3f2e26d11554e1861c9976c4a1d69739b5f37090 | julielaursen/Homework | /Julie_Laursen_Lab7a2.py | 6,264 | 4.28125 | 4 | import sys
QUIT_CHOICE = 6
trys = 10
#Define end program
def endProgram():
print("This program has ended. Goodbye.")
#Define the main function that will call all other functions
def main():
#the choice variable controls the loop and holds the menu choice
choice = 0
conversion_file = open('conver... |
d28e54a8c393aeae7d0d5c44690194c750ed137d | divyaparmar18/python-list | /list/Tlac/bubble_sort.py | 1,579 | 4.15625 | 4 | numbers=[50, 40, 23, 70, 56, 12, 5, 10, 7]
running=0# here we start the counting of how much time sorting will be done
while running < len(numbers):#here we give the condition to run the loop till when
index=0# here we declare the index of the list
while index<len(numbers)-1:# here we give the condiiton to run ... |
9bbc45dee7d151824f40ba995e507b643866b2d5 | baldehalfa/pyScripts | /resize128.py | 458 | 3.578125 | 4 | #!/usr/bin/python
from PIL import Image
import os, sys
path = "C:/Users/images/"
dirs = os.listdir( path )
def resize():
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((1... |
d4d7ded7eca5dac68fc192ea17bb3c85a103a64d | oustella/coding-exercises | /myLinkedList.py | 3,297 | 4.34375 | 4 | # all things LinkedList
class ListNode():
def __init__(self, x):
self.value = x
self.next = None
def print(self):
temp = self
while temp and temp.next:
print(temp.value, end='->')
temp = temp.next
print(temp.value)
# singly linked list
class Li... |
baf31b70fcede914d51d97fe52ceeb47fff5c347 | shajin-sha/python-password-cracker | /di-password.py | 309 | 3.78125 | 4 | from typing import Generator
import wordlist
password = str(input("Password : "))
generator = wordlist.Generator(password)
for each in generator.generate(1,10):
if each == password:
break
print(each)
# if(each == password):
# break
# print(each)
|
96085345556f1e7c9249cb338d474988b56bf629 | IoTLabHNU/i4SC | /Packaging/test.py | 944 | 3.65625 | 4 | import RPi.GPIO as GPIO
import time
LightSensorDigital = 2
LightSensorAnalog = 3
GreenLight = 1
RedLight = 17
def destroy():
GPIO.output(RedLight, GPIO.LOW)
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup... |
a4f351135dd668e7a1bb954641ccf29427c1eb65 | Zahid-Hasan-Jony/Cipher-in-cryptograpy | /Transposition_cipher.py | 596 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zahid
"""
def transposition(text, length):
return [text[i:i + length] for i in range(0, len(text), length)]
def encrypt(key, plaintext):
seg = {
int(val): num for num, val in enumerate(key)
}
ciphertext = ''
for index in sorted(se... |
8bc9cecc649c266dfafa8ff855b7b2a5b0d67e2e | AmRiyaz-py/Python-Arsenal | /All about Looping in python/task2PR1A.py | 217 | 4.4375 | 4 | '''
Program:- Given n as input. Print product of all numbers from 1 to n.
Author:- AmRiyaz
Last Modified:- May 2021
'''
n = 5
a = 1
for i in range(1,n+1):
a = i * a
print(a)
'''
Output:
120
''' |
0337a500938f15a2e0a714d4390024ce0ed6e2df | GeoffreyRe/Project_3_macgyver | /Map.py | 2,222 | 3.640625 | 4 | import pygame
import json
import random
# class that contains methods and attributes linked with the map list
class Map(object):
def __init__(self):
with open("ressource/map.json") as f:
# transform an json file into a python object
self.map_list = json.load(f)
# method that fi... |
ec1db2e933647cccdc5f438f05b18d3265097410 | Ssellu/python_tutorials | /ch01_type/test03_숫자형.py | 2,632 | 4.3125 | 4 | """
1. 숫자형
1) 정수형 - int 형
2) 실수형 - float 형
** 정수/실수의 구분은 소숫점이다.
3 => int
3.0 => float
"""
a = 3
b = 3.0
c = 3.1
print(a) # 3
print(b) # 3.0
print(c) # 3.1
print(f'각 a, b, c의 값 : {a}, {b}, {c}') # 각 a, b, c의 값 : 3, 3.0, 3.1
# type(대상) : 대상의 자료형을 알려줘!
print(typ... |
b06d2fed22eee408bc3e1b58756b3a0e523f68c3 | BLSchaf/small__projects | /Algos/fibonacci_cache.py | 389 | 3.5625 | 4 | cache = {}
def fib(n, cache=cache):
if n in cache:
#print(f'memoization of fib({n})')
return cache[n]
elif n == 1:
cache[n] = 1 #{1:1}
elif n == 2:
cache[n] = 1 #{2:1}
else:
cache[n] = fib(n-1) + fib(n-2)
return cache[n]
for i in ran... |
6659de8c98fd161195cfdc0919f099722513efbc | fangyuan2015/python2018 | /pass1.py | 196 | 3.703125 | 4 | #!/usr/bin/env python
#coding=utf-8
#输出Python的每个字母
for letter in 'Python':
if letter == 'h':
pass
print '这是pass块'
print '当前字母: ',letter
print "Good bye!"
|
c970287bb343db12d039948f2d37f866856777c1 | suvimake/python-tdd-exercises | /exercises.py | 13,844 | 4.34375 | 4 |
def reverse_list(l):
"""
Reverses order of elements in list l.
"""
l_rev = []
for i in range(len(l)-1,-1,-1):
l_rev.append(l[i])
return l[-1::-1]
def test_reverse_list():
assert reverse_list([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
# -------------------------------------------------... |
76ea1084cb991dcffec51f39081d7378a5056e43 | saitcanbaskol/turboard | /module.py | 2,158 | 4.125 | 4 | """
@param is the string word we want to process
@return string pascalized word
"""
def pascalize(word):
if(len(word) == 0 or type(word) != str):
return False
newWord = word.replace('_',' ')
newWord = newWord.title()
return newWord.replace(' ','')
"""
@param is the string word we want to proce... |
0c7355fc0f0d168e9e6ae55a4c76b28b16814f6c | JosephLimWeiJie/algoExpert | /prompt/medium/BinaryTreeDiameter.py | 1,376 | 3.96875 | 4 | import unittest
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TreeInfo:
def __init__(self, diameter, height):
self.diameter = diameter
self.height = height
def binaryTreeDiameter(tree):
... |
734e04369db80997347fa859949a8984368c4f23 | iptkachev/algorithms_methods_part1 | /dynamic_programming/stairs.py | 2,152 | 3.984375 | 4 | from typing import List
def max_value_stairs_recursion(steps: List[int], max_value=0) -> int:
"""
Рекурсия
Вернуть максимальную сумму, которую можно получить, идя по лестнице снизу вверх (от нулевой до n-й ступеньки),
каждый раз поднимаясь на одну или две ступеньки.
:param max_value:
:param s... |
35a6e4282cc36a426e0330efde456a2cad05c9d2 | krniya/ML-Practice | /Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py | 1,253 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 20:04:17 2019
@author: Nitish Yadav
"""
#Simple Linear Regression
#importing libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing dataset
dataset = pd.read_csv('Salary_Data.csv')
x = dataset.iloc[:,:-1].values
y = dataset.iloc[... |
693ae27585951733a10479c2c94673bbc2779dcb | EmineBasheva/Dungeons_and_Pythons | /test_enemy.py | 783 | 3.609375 | 4 | from enemy import Enemy
from weapon import Weapon
import unittest
class TestEnemy(unittest.TestCase):
def setUp(self):
self.enemy = Enemy(health=100, mana=100, damage=20)
def test_damage_negative(self):
with self.assertRaises(ValueError):
enemy2 = Enemy(health=100, mana=100, ... |
10e908868cacdf56e9f6c1398ffa8459a8478ea2 | sbhotika/15112-term-project | /player.py | 958 | 3.9375 | 4 | # handles Player object on screen when maze board is drawn
class Player(object):
# handles Player object, that is, user interactivity
spacing = 5
def __init__(self, cellSize):
# stores cell size, position and radius
self.cellSize = cellSize
self.radius = max(cellSize... |
bdc96615cffc5739f7d0402f3a4f5ec492e1311e | cdamiansiesquen/Trabajo06_Carrillo_Damian | /Damian/simples/ejercicio15.py | 904 | 3.75 | 4 | import os
precio_de_ladrillos, precio_de_cemento, precio_yeso= 0 , 0 , 0
#INPUT
precio_de_ladrillos = int (os.sys.argv[1])
precio_de_cemento = int (os.sys.argv[2])
precio_yeso = int (os.sys.argv[3])
# Processing
total = (precio_de_ladrillos + precio_de_cemento + precio_yeso)
#Verificador
comprobando = (total >= 200)
#O... |
92598f0240e724e4e345f5fc3091264156a0a9db | hulaba/GeeksForGeeksPython | /Sorting/Quicksort.py | 575 | 3.640625 | 4 | class Quicksort:
def quicksort_wrapper(self, a, start, end):
if start < end:
partition_index = self.partition(a, start, end)
self.quicksort_wrapper(a, start, partition_index - 1)
self.quicksort_wrapper(a, partition_index + 1, end)
@staticmethod
def partition(a, s... |
c2de4a5959ac3710deb51d71936b2601ab8d68d8 | Programmable-school/Python-Training | /answer/lessonModulePackage/main.py | 338 | 4 | 4 | """
課題 モジュール分割_パッケージ分割
"""
import hello_world as hw
import util.calc as util
hw.show_hello_world()
x = 10
y = 3
print('%d + %d = %d' % (x, y, util.add(x, y)))
print('%d - %d = %d' % (x, y, util.sub(x, y)))
print('%d * %d = %d' % (x, y, util.multi(x, y)))
print('%d / %d = %f' % (x, y, util.div(x, y)))
|
0d4f009f2979fad6903f3a1809286724ad659fcc | greco380/CodeNames | /game_logic.py | 2,548 | 4.09375 | 4 | import key_of_game
import playing_board
def link_key_with_board():
link = dict()
key = key_of_game.main()
board = playing_board.main()
# print(len(key))
for i in range(len(key)):
for j in range(len(key)):
# dict name[key] = assign
link[board[i][j]] = key[i][j]
... |
8d5d82e1ee6528c99715f52fb8862413ebbb2f55 | daniel-reich/ubiquitous-fiesta | /k2aWnLjrFoXbvjJdb_13.py | 810 | 3.53125 | 4 |
letters = "abcdefghijklmnopqrstuvwxyz".upper()
codes = []
for x in range(len(letters)):
codes.append([letters[i] for i in range(len(letters))])
letters = letters[1:] + letters[0]
def vigenere(text, keyword):
t = "".join([x for x in text if x.upper() in letters]).upper()
key = keyword * (len(t)//len(keyword)... |
dad252d2a873e95428bebbd5490045353eb6df08 | jhesed/learning | /udemy/The Python Mega Course/Section 11 - Creating Leaflet Webmaps with Python and Folium/folium_adding_markers_to_map_from_csv_data.py | 2,064 | 3.765625 | 4 | """
Udemy: The Python Mega Course: Building 10 Real World Applications
Section 11: Creating Leaflet Webmaps with Python and Folium
Adding Markers to the map from CSV Data
Author: Jhesed Tacadena
Date: 2017-01-26
Section 11 Contents:
66. Demonstration of Web Mapping Application
67. Creating an Open Street Ma... |
79e78dbbadd150288e88c74bdc5fb4c8bf62b265 | MrTuesday1020/Algorithms | /Python/KMP Search.py | 1,459 | 3.703125 | 4 | """
http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
"""
def KMPSearch(pat, txt):
"""
:type pat: str
:type txt: str
"""
M = len(pat)
N = len(txt)
# create lps[] that will hold the longest prefix suffix ... |
1543e9707e9ae1484c7321bb72a3dc950a1e0772 | wjddnjs754/Programming-with-Python | /BOJ/#9498 시험성적(if문).py | 285 | 3.828125 | 4 | #Date:2020/09/21
#BOJ 9498 "시험 성적"
A = int(input())
if 100>=A>=90:
print('A')
elif 90>A>=80:
print('B')
elif 80>A>=70:
print('C')
elif 70>A>=60:
print('D')
else:
print('F')
#예제 입력: 1 2
#입력이 띄어쓰기 되어있기 때문에 split 사용 |
bb848b91b5b9a99212533b7d6ff7f654a495e64d | mey1k/PythonPratice | /PythonPriatice/StackQueue_3.py | 740 | 3.875 | 4 |
def solution(bridge_length, weight, truck_weights):
shortestTime = 0
passingTruck = []
waitingTruck = []
waitingTruck = truck_weights
passingTruck = [0]*bridge_length
while passingTruck:
shortestTime += 1
passingTruck.pop(0)
if waitingTruck:
if(sum(pas... |
18f5c972468a34a511a8d6aeb1e98d90ea221281 | Alfonsocastaneda/clase-cinco | /Empleados/Interfaz.py | 4,585 | 3.84375 | 4 | from tkinter import *
from empleado import Empleado
from nomina import Nomina
class Ejercicio1:
def __init__(self):
root = Tk()
frame = Frame(root)
frame.pack()
frame.config(bg="lightblue")
frame.config(width= 500, height= 500)
root.mainloop()
class Ejercicio2:
... |
300158635016d285443ca0ef8e49fa10bcb8ca9e | Amruta329/123pythonnew- | /dictinory.py | 2,354 | 4.4375 | 4 | thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
#Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020 #this will update the value
}
print(thisdict)
... |
b40c3fe9f08861b0f0ef1ddfbee5c0ea9518ee6e | lzh233/Rosalind | /02.Rabbits and Recurrence Relations.py | 313 | 3.625 | 4 | """
斐波那契数列(递归思想):1 1 2 3 5 8 ......
递归: 函数自己调用自己,直到到递归终点,返回值
"""
def fab(n):
if n == 1 or n == 2:
return 1
else:
return (fab(n-1) + fab(n-2))
print(fab(10))
##-------------------output---------------------##
"""
55
"""
|
1fe2955b29af24330112880095c526c90c7d3d6d | TankistVkaske/python-learning | /easy_unpack.py | 440 | 4.125 | 4 |
def easy_unpack(elements):
if len(elements) < 3:
return "Number of elements is less than 3!"
else:
return elements[0], elements[2], elements[-1]
if __name__ == "__main__":
arg1 = ('k', 'e', 'k')
arg2 = ()
arg3 = ('k', 'e')
arg4 = (1, 2, 3, 4, 5)
print(easy_unpack(arg1))
... |
ea1fe92bd4c9f8f238a4764aba47d93f2fc9e4c6 | Iris0609/Leetcode | /Array/88_Merge Sorted Array.py | 982 | 3.984375 | 4 | ## Easy
## 60ms,faster than 76.15%
## The trick is using sort in Python
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.... |
8dd38c06d50e8ba862479eae08b9253b811a4f10 | geokai/Object-oriented-Programming-in-Python | /main_02.py | 1,456 | 3.703125 | 4 | """run file"""
from room_01 import Room
from item_01 import Item, Lantern, Compass
def main():
# creating room objects:
kitchen = Room('Kitchen')
dining_hall = Room('Dining Hall')
ballroom = Room('Ballroom')
# creating item objects:
lantern = Item('Lantern')
compass = Item('Compass')
... |
3e87d6a90e016c9b3d8700c2634ed27edde46fd3 | acoullandreau/geo_rendering_package | /geo_rendering/geo_rendering/point_class.py | 1,609 | 3.578125 | 4 | import cv2
class PointOnMap:
def __init__(self, coordinates, weight, color):
self.x_coord_or = coordinates[0]
self.y_coord_or = coordinates[1]
self.x_coord_curr = coordinates[0]
self.y_coord_curr = coordinates[1]
self.weight = weight
self.color = color
def ren... |
428c5ad96b5096a57f9bb139dd8db349e58f33db | RBaner/Project_Euler | /Python 3.8+/26-50/Problem 041/main.py | 878 | 3.59375 | 4 | from sympy import isprime
from itertools import permutations
import time
digits = [i for i in range(1,10)]
def numFromList(listOfDigits: list) -> int:
output = 0
power = len(listOfDigits)-1
for digit in listOfDigits:
output += digit * (10**power)
power -= 1
return(output)
def main() -... |
58383eaa8d284a762ff98a02020500ae2126dd8a | greenfrog82/DailyCoding | /Codewars/8kyu/8kyu_find_the_smallest_integer_in_array/src/main.py | 222 | 3.75 | 4 | def find_smallest_int(arr):
return min(arr)
print find_smallest_int([78, 56, 232, 12, 11, 43]) == 11
print find_smallest_int([78, 56, -2, 12, 8, -33]) == -33
print find_smallest_int([0, 1 - 2**64, 2**64]) == 1 - 2**64 |
730cb011ae6ba2d0222a4ecf108c393920d85820 | matheus073/projetos-python | /ADS-I/Atividades-na-sala/compra_com_desconto.py | 132 | 3.796875 | 4 | x = float(input("Preço: "))
y = int(input("Quantidade: "))
valor = x*y
if y > 7:
valor *= 0.9
print("Total a pagar:",valor)
|
6fdd768987f0bcbf69298ee7df26a3af76f82843 | ProfessorBurke/PythonObjectsGames | /Chapter1VideoFiles/star_line.py | 709 | 4.375 | 4 | """Draw firework stars with pygame."""
import pygame
# Define some size constants to make drawing easier.
SIZE: int = 480
# Annotate variables
screen: pygame.Surface
star: pygame.Surface
star_num: int
x: float
y: float
# Create a pygame window.
screen = pygame.display.set_mode((SIZE, SIZE))
pygame.d... |
56c13f6e1e4f769e536764d07560fafc75b83387 | Pittor052/SoftUni-Courses | /Python/Fundamentals/0.8-Text-Processing/Lab/substring.py | 93 | 3.65625 | 4 | sub, text = input(), input()
while sub in text:
text = text.replace(sub, "")
print(text) |
3fc8910e398425d88558a930d80287f508b3614f | shshetu/Coursera_Data_Structure_And_Algorithms_Specialization | /1. Algorithmic toolbox/Coding/Week-1/MaxPairWiseProduct/Python/MaxPairWiseProduct.py | 357 | 3.65625 | 4 | # Create an index variable
n = int(input())
# Create an array of int type of length index
a = [int(x) for x in input().split()]
# Create a variable : product
product = 0
# Execute 2 for loop staisfying the condition: numbers[i]*numbers[j]
for i in range(n):
for j in range(i+1,n):
product = max(product,a[i]*... |
f64fede8cd68aa4bc6898f25c1da45de6bf77f05 | evangravelle/AI-projects | /PythonScripts/CodingInterview/sorting.py | 1,035 | 4.21875 | 4 | # Various sorting algorithms are implemented and tested
import random
def merge(left, right):
sorted = []
# while left or right are nonempty
while left or right:
if left and not right:
sorted.append(left.pop(0))
elif right and not left:
sorted.append(right.pop(0))
... |
f33a3c3801dc8c978975b00cf59434f9def250d1 | obviouslyghosts/dailychallenges | /ProjectEuler/042/pe-042.py | 1,614 | 4.03125 | 4 | """
The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1);
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its
alphabetical position and adding these values we form a word value.
For example, ... |
f209e547666504c75cb17b61931307ee5ad41a69 | guoheng/ProjectEulerPy | /p059.py | 2,794 | 4.0625 | 4 |
#Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
#
#A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte... |
cfa5755d9f9154ec1307717fdf32d483eb7c6b55 | aishvarya87/Python_project | /summary.py | 2,746 | 3.765625 | 4 | # This file uses City, Rent and Price_sqft table from mydb.
# Pandas is used in this code to get the operations done.
# This file answers the questions from Question 1 which
# asks to find the summary of the dataset
#Importing Libraries
import mysql.connector
import pandas
from pandas import DataFrame
##Create conne... |
139147f6f1793451a7b6449edec8e5027db21712 | suyash2796/CSCognisanse | /backtracking/python/m_coloring.py | 1,493 | 4.1875 | 4 |
# python program to solve m-coloring problem using backtracking
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
# This function checks if it is safe to color a vertex v with color c
def ... |
2788acac092f263f0dfa4b5ed94abe0028d38805 | Jepps42/calc-mini-project | /calc.py | 977 | 4.125 | 4 | select = int(input("Please select your operation of choice from 1, 2, 3 or 4: "))
num1 = int(input("What is your first number of choice? " ))
num2 = int(input("What is your second number of choice? " ))
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, nu... |
0400307a397071c20be76c42abc68d9e1e120c88 | vikash28-cloud/python_advance | /01 Erros_in_python.py | 722 | 4.0625 | 4 |
'''while (True):
print("enter q to quit ")
a = input("enter a no: ")
if (a=="q"):
break
try:
a = int(a)
if a>6:
print(f"{a} is Grater than 6")
else:
print(f"{a} is smaller than 6")
except Exception as e:
print(f"sorry!\ntr... |
9963191984fd6964380155d93645e9d36dcd023b | tioguil/LingProg | /-Primeira Entrega/Exercicio02 2018_08_21/atv03.py | 508 | 3.953125 | 4 | # 3 Faça um programa que receba duas listas e retorne True se têm
# os mesmos elementos ou False caso contrário
# Duas listas possuem os mesmos elementos quando são compostas
# pelos mesmos valores, mas não obrigatoriamente na mesma ordem.
total_lista = 3
list1 = []
list2 = []
print("Lista 1")
for i in range(total_... |
da06259c5c90eb6bd0ecd7238559bccde328a528 | luongthomas/Python-Mini-Projects | /MadLibs/madLibs.py | 3,591 | 3.921875 | 4 | # Title: Mad Libs
# Author: Thomas Luong
# Purpose: Creates a story based on verbs, adjectives and nouns that the user inputs
# Usage: Practice python functions and reusability
# Notes: Create Mad Libs style game where user inputs certain types of words
# Story doesn't have to be too long but should have some sor... |
5d95f5d65948ffa7bb184774897789e6240973cf | kizs3515/shingu_1 | /11.03파이썬/yesterday.py | 504 | 3.59375 | 4 | f = open("Yesterday.txt", 'r')
yesterday_lyric = ""
while 1:
line = f.readline()
if not line: break
yesterday_lyric = yesterday_lyric + line.strip() + "\n"
f.close()
n_of_yesterday = yesterday_lyric.upper().count("YESTERDAY")
n1_of_yesterday = yesterday_lyric.count("Yesterday")
n2_of_yesterday = yesterday... |
a4aefcb0d9a8dbfefe9eb4c22bce4d598fd0583c | akashmpatil/Python_Programs | /List_crud.py | 187 | 3.875 | 4 | odd = [2, 4, 6, 8] # create the list
print(odd)
odd[0]=1 # updated
print(odd)
odd.append(7) # append
print(odd)
del odd[1] # delete
print(odd)
rev odd
print(odd) |
041d01e1df123d81189f9cf049ef3536b21a7c49 | zd200572/bioinfor-python | /lagest_common_prefix.py | 196 | 3.625 | 4 | def longestCommonPrefix(s1, s2):
i = 0
while i < len(s1) and i < len(s2) and s1[i] == s2[i]:
i += 1
return s1[:i]
print(longestCommonPrefix('ACCATTG', 'ACCAAGTC'))
|
54781ca575397d9649cf54d99b4471e1b733e1ee | iallabs/Data_Preprocessing_ML | /image_pro/utils_data/geotransf/geotransf.py | 2,438 | 3.71875 | 4 | import cv2
import numpy as np
import matplotlib.pyplot as plt
#Let's consider M the translation matrix. Given a translation vector (tx,ty),
# the matrix is defined as follows: M = [1 0 tx]
# [0 1 ty]
##################
# Translation
##################
def translate(fra... |
858b6b21c2da0869acdcf54d897c430a0d3f6b61 | haokaibo/PythonPractice | /leetcode/recursion/unique_binary_tree_ii.py | 2,419 | 4.1875 | 4 | # Definition for a binary tree node.
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
... |
9822413e49b3d007a48552ace4eab7845acea8a8 | sadscv/core_programming | /test.py | 134 | 3.59375 | 4 | import csv
with open('data.csv', 'r') as f:
csv_file = csv.reader(f, delimiter=",")
for line in csv_file:
print(line) |
febad8a3e6e56e97a24939ccc5c14763752cfaac | JiarongYan/cs224n_2017_stanford | /assignment1/q1_softmax.py | 4,116 | 4.34375 | 4 | import numpy as np
def softmax(x):
"""Compute the softmax function for each row of the input x.
It is crucial that this function is optimized for speed because
it will be used frequently in later code. You might find numpy
functions np.exp, np.sum, np.reshape, np.max, and numpy
broadcasting usefu... |
e21692bab0626a6af64dd3dfc81672761435e615 | jvpersuhn/Pythonzinho | /Aula4/Exercicio.py | 891 | 3.796875 | 4 | n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
n3 = float(input('Digite a terceira nota: '))
n4 = float(input('Digite a quarta nota: '))
lista = [n1, n2, n3, n4]
lista.sort()
'''
if n1 >= n2 and n1 >= n3 and n1 >= n4:
print(f'{n1} é a maior nota')
elif n2 >= n3 and n2 >... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.