blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
73a63fb3542c23d1158f750c5a4d14520764a84b | shoroogAlghamdi/test | /Unit3/unit3-challenge4.py | 265 | 3.5 | 4 | # Slide 94
BONUS = 1000
salaryBeforeBonus = input("Please, enter your current salary: ")
salaryBeforeBonus = eval(salaryBeforeBonus)
salaryAfterBonus = BONUS + salaryBeforeBonus
print("Your salary after adding a bonus of ", BONUS, "SR is ", salaryAfterBonus, "SR")
|
85697099c9023bd752fb057e8461f65f543a099a | guidozamora/Data-Structures-Algorithms-Python | /LeetCode Solutions/1480_running_sum_1d_array.py | 353 | 4.09375 | 4 | """
Solution steps:
- Create a sum variable and set it to zero
- Loop thru the array
- Add the value of each element to a the sum variable
- Add each sum to a new list
"""
def runningSum (nums):
sum = 0
sum_nums = []
for number in nums:
sum += number
sum_nums.append(sum)
return sum_nums... |
577300e6a53ea8d2eed2928877c11a0f5ac57a63 | nerunerunerune/kenkyushitukadai | /19.py | 520 | 4.09375 | 4 | #ITP1_5_C: Print a Chessboard
#たてH cm よこ W cm のチェック柄の長方形を描くプログラムを作成
#Draw a chessboard which has a height of H cm and a width of W cm.
#For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.
while True:
H,W = map(int, input().split())
if (H == 0 and W ==... |
b1b464a2e114a253c06a0c2507e9808485d0e6c3 | cedie1/Python_guanabara_100-exerc-cios- | /ex35.py | 632 | 4.09375 | 4 | #Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
#Resolução.
a = float(input('Coloque o valor de um lado: '))
b = float(input('Coloque o valor de outro lado: '))
c = float(input('Coloque o valor de outro lado: '))
if abs(b - c) < a < b + c and... |
47e520361361dd645310e497c14d178046ffcc8a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/9d1365b398d84f7aadc1fbbe766607b1.py | 918 | 3.875 | 4 | from string import digits, punctuation, whitespace
# use sets for quicker lookups
digits = set(digits)
punctuation = set(punctuation)
whitespace = set(whitespace)
def contains_lowercase_letters(text):
for letter in text:
if letter.islower():
return True
return False
def contains_no_letter... |
a26dec60b7b24e18ca7b36f7c4cf70b9895d3609 | tws0002/pop2-project | /Pipeline/the_LATEST/sys_PY/py_MODULES/syncmeister/controller/engine (selecao's conflicted copy 2016-03-06).py | 4,791 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
All methods governing searching within files and lines of strings, determining
rules for how and in what way information should be retrieved, and, to a lesser
extent, defines how to process the retrieved information
.. important::
Currently, the regex that ge... |
ce10fe0187095c2b6af76f192a947fe6b8001598 | hoyeonkim795/solving | /progeammers/튜플.py | 473 | 3.78125 | 4 | import re
def solution(s):
s = re.split('{|}',s)
ans_s = []
for i in range(len(s)):
if len(s[i]) > 0 and s[i] != ',':
mid_s = list(map(int,s[i].split(',')))
ans_s.append(mid_s)
new_s = quickSort(ans_s)
ans = []
for i in range(len(new_s)):
for j in range(... |
54fdc342c2a4cca096af4b64f4ffdd18161fc3e6 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2585/60717/241172.py | 121 | 3.640625 | 4 | list1=list(input())
list2=list(input())
list1.sort()
list2.sort()
if list1==list2:
print(True)
else:
print(False) |
2f5dd8ba01c7d122177539f6e716eacc78170d21 | sandip308/python-program-for-beginners | /HCF with recursion.py | 351 | 3.90625 | 4 | def HCF(f,s):
if s==0:
return f
else:
return HCF(s,f%s)
if __name__ == '__main__':
r = int(input("Enter a first number "))
c = int(input("Enter second number "))
if r >= c:
z = HCF(r, c)
print("The HCF value is=",z)
else:
z = HCF(c, r)
... |
28d84bb855913c1dc28a91eb809142167ae9295e | zhengzhenxing/cookbook | /python/design_patterns/singleton.py | 939 | 4.25 | 4 | """
1. override __new__ method (which is called before __init__) to get or create a class instance
1. add state to track if already initialized in __init__ method - this is only needed if the __init__ method has a side effect.
"""
class Singleton(object):
_instance = None
_inited = False
def __new__(cls,... |
cf5d0719279041256e32fdd587cf2b62db655237 | xuedagong/hello | /pat/1008.py | 1,329 | 3.609375 | 4 | #coding=utf-8
'''
一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A0 A1……AN-1)变换为(AN-M …… AN-1 A0 A1……AN-M-1)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法?
输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。
输出格式:在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。
输入样例:
6 2
1 2 3 4 5 6
输出样例:
5 6... |
a35a7b2af9566f201f0033e198fb937747a67188 | ankithakumari/InformationRetrieval | /bfscrawler.py | 3,137 | 3.625 | 4 | """ Python implementation to perform Breadth first crawling of the web.
Starts from the url https://en.wikipedia.org/wiki/Space_exploration and downloads all
links to other wiki articles in a breadth first manner.
Only downloads english articles, ignores links to sections in the same page, links to images e... |
576184d710e94115f5dee93e2c4a2451c9ca1917 | huiyi999/leetcode_python | /Valid Mountain Array.py | 1,835 | 4.1875 | 4 | '''
Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < A[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Constra... |
84d682bab7fdfb00b7df9851f7e3fdeaacf67633 | dvcolin/Intro-Python-I | /src/14_cal.py | 1,713 | 4.5 | 4 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py month [year]`
and does the following:
- If the user doesn't specify any input, your program should
... |
2e0beb29fcf3ff4015a591714c5d94d9bb1c9aaf | programiranje3/v2020 | /Lab1/lab1.py | 5,491 | 4.28125 | 4 | # Task 1
# Write a function that asks the user for a number, and depending on whether
# the number is even or odd, prints out an appropriate message.
def odd_or_even():
number_str = input("Please enter a whole number\n")
# Option 1:
# if int(number_str) % 2 == 0:
# print("EVEN number")
# else:... |
89a3343de096950f6031477369cf477e3ce10479 | CP-NEMO/Basics-of-python | /Greatest_of_three.py | 205 | 4.125 | 4 | #which number amoung 3 are greatest
x=int(input())
y=int(input())
z=int(input())
if(x>y and x>z):
print(x,"is greatest")
elif(y>x and y>z):
print(y,"is greatest")
else:
print(z,"is greatest") |
f347c72bf9da719ef4c5de208c5bdd2efdd59902 | ShreyasMugali/Leetcode-Solutions | /Python/Longest_Substring_Without_Repeating_Characters.py | 1,051 | 4.0625 | 4 | # Time: O(n)
# Space: O(1)
#
# Given a string, find the length of the longest substring without repeating characters.
# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
# For "bbbbb" the longest substring is "b", with the length of 1.
# Given "pwwkew", the a... |
69b6f46c282013f6da344555b2c78dc74b2e271d | memoizr/python-scratchbook | /compare.py | 864 | 3.671875 | 4 | import time
class Compare:
def compare_n2(self, n):
minimum = None
for i in n:
is_min = True
for j in n:
if j < i:
is_min = False
if is_min:
minimum = i
return minimum
def compare(self, n):
... |
9d0754e0ba371ed5f9ec52fd242ca0cd1adfbd81 | varshajoshi36/practice | /leetcode/python/easy/longestCommonPrefix.py | 592 | 3.90625 | 4 | #! /usr/bin/python
import sys
#Write a function to find the longest common prefix string amongst an array of strings.
#working solution
def longestCommonPrefix(strs):
common_prefix = ""
num_strings = len(strs)
if num_strings == 0:
return common_prefix
shortest_len = len(min(strs, key = len))
for i in rang... |
d693729d68bb3f5a9faa2b5672affa3108e2df22 | sw30637/assignment5 | /lf1414/assignment5.py | 4,224 | 4.03125 | 4 | '''Defining class interval that represents the range of integers between a lower and upper bound. Either of the bounds of an interval can be “inclusive” or “exclusive” and can be positive or negative. The bounds must always meet the requirement that lower <= upper if both bounds are inclusive, lower < upper if one boun... |
820aedf685ecd0d44c961d99bf94ab6d998233f6 | syahn/Problem-solving | /Codewars/python/[6kyu] Multiples of 3 and 5.py | 621 | 4.15625 | 4 | // 1. Reflection
# - solved
# - It's pythonic, but not the best practice
// 2. Problem
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number ... |
596399b611b2dcdd174025036556faf3f6b63d5b | nadiabahrami/Data-Structures-2.0 | /src/bst.py | 13,696 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""Binary Search Tree Module."""
from collections import deque
import random
import io
class Node(object):
"""Define a node class."""
def __init__(self, value=None, parent=None, left=None, right=None):
"""Initialize a Node object."""
self.value = value
self.par... |
3f6088bf3a7198fde18a9854e2c07e104e2c9dfa | CurtisFord1997/Indian-Hills | /Python/Lab4/Challenge.py | 693 | 4.1875 | 4 | #chalange 1
for numRows in range(7,0,-1):
row = "" #starts the row blank
for stars in range(numRows): #concatinates the number of stars equal to the num rows left
row = row + "*"
print(row)
#chalange 2
row = "#" #starts row off with just a lonely hashtag
for numRows in range(7):
if numRows == 0... |
f57c603f6a43d1a9074c88cbe0ab8e2a63feed14 | nottsgeek/py | /examples/readfile.py | 456 | 3.75 | 4 | #!/usr/bin/python
#you should have a file named template in your path
#Read file and store data as a string
'''
f=open('template', 'r')
data=f.read()
f.close()
print data
'''
#Read file line by line and store all lines as a list
'''
f=open("template", 'r')
datalist=f.readlines()
f.close()
print datalist
'''
#Read ... |
8f838966cfa42e63cc2c29135dc8b5761513b1f3 | MahaSabry5/CS50-2020 | /Problem_set6/cash.py | 558 | 3.71875 | 4 | from cs50 import *
from math import *
# make sure that the change not negative just positive number
while True:
n = get_float("Change owed: ")
if (n >= 0):
break
count = 0
coins = round(n * 100)
# calculate cash that will be paid
while (coins != 0):
if (coins >= 25 ):
count += 1
... |
c081568084595ded1928e565c02f97accb6c779f | pushkaraditya/pythonds | /chapter5/exploringMazeProblem.py | 5,377 | 3.84375 | 4 | import turtle
blockCell = 'X'
openCell = ''
startingCell = 'S'
class Maze():
ch = 25 # cell height
cw = 25 # cell width
bc = 'grey' # color for blocked cell
dc = 'white' # color of open cell
wip = 'yellow'
dead = 'red'
path = 'green'
def __init__(self, turtle, maze):
self.m = m... |
399cb6b08bbb9e4d6550098da2af12e1ac4aa987 | mbelalsh/Data_Structures_Algorithms_Specialization_Coursera | /2_Data_Structures/Assignments/week1_basic_data_structures/1_brackets_in_code/Check_brackets_Sub.py | 1,325 | 3.609375 | 4 | # python3
class ArrayStack:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def push(self, e):
self._data.append(e)
def top(self):
if self.is_empty():
raise Empty('Stac... |
714b8d3e2ab85b3d0224d4aea85ecd8db58b9588 | 362515241010/TueyDH | /ChangeDay.py | 675 | 3.96875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[8]:
mm,dd,yyyy = (str(e) for e in input().split())
if mm == "01" :
print(dd, "JAN", yyyy)
elif mm == "02" :
print(dd, "FEB", yyyy)
elif mm == "03" :
print(dd, "MAR", yyyy)
elif mm == "04" :
print(dd, "APR", yyyy)
elif mm == "05" :
print(dd, "MAY", yyyy)
... |
4a85411c612e35b13926471056076c1f43d16a3a | namth2015/python | /1.DataScience/2.BigO/Green18/lec12_symmetrical_number.py | 1,109 | 3.609375 | 4 |
def check_inverse(a):
def inverse(n):
if n == 0:
return 0
step = n // 10
num = str(n % 10)
func = str(inverse(step))
return num + func
if a == int(inverse(a))/10:
return True
else:
return False
class node:
def __init__(self,data = Non... |
b134be7668f89639b9745e63466eae390f138290 | Tuchev/Python-Fundamentals---january---2021 | /05.Lists_Advanced/03.Lists_Advanced_-_More_Exercises/03. Take-Skip Rope.py | 1,117 | 3.859375 | 4 | encrypted = input()
encrypted_list = []
if " " in encrypted:
for char in range(len(encrypted)):
encrypted_list.append(encrypted[char])
else:
encrypted.replace("", " ").split()
for char in range(len(encrypted)):
encrypted_list.append(encrypted[char])
numbers = []
decrypted = []
n... |
f8d86b89f376f496a560ab8891cadb93e5249a89 | gvaldovi/CursoIA2021 | /dia5/PruebaPandas.py | 473 | 3.546875 | 4 | import pandas as pd
#Serie: Columna de una tabla
#DataFrame
a=[1,5,2]
b = pd.Series(a,index=['x','y','z'])
print(b)
print(b['x'])
calorias = {'Lunes':420,'Martes':300,'Miercoles':320}
c=pd.Series(calorias,index=['Lunes','Miercoles'])
print(c)
print(c['Lunes'])
#DataFrame
datos={
'calorias':[420,300,320],
... |
cea0d78c8a8420416e7498fb553bd8fd6befd62d | emersonleite/python | /Introdução a Programação com Python - exercícios baixados do site oficial/Exercícios/exercicio-07-05.py | 962 | 4.40625 | 4 | ##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2014
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - ... |
e1a03c4b1df0f630e5c72808cbcca6e57f80c7a0 | selam-weldu/algorithms_data_structures | /leet_code/python/binary/add_numbers.py | 1,661 | 3.9375 | 4 | class Solution:
def getSum(self, a: int, b: int) -> int:
## RC ##
## APPROACH : BITWISE OPERATIONS ##
## LOGIC ##
# 1. For any two numbers, if their binary representations are completely opposite, then XOR operation will directly produce sum of numbers ( in this case carry is 0 )
... |
08d6a2b740c1b22c711a6b14db16ad96422b58ba | AJ-Walker/DS | /Practical3.a.py | 961 | 4.09375 | 4 | # Implement the following for Stack:
# Perform Stack operations using Array implementation.
class Stack:
def __init__(self,data=[]):
self.data = []
def is_empty(self):
self.len_data = len(self.data)
return self.len_data
def push(self,elememt):
self.data.append(el... |
34d744b7259f2ad82d4fb67de05b7b084c33e9d1 | uu64/project-euler | /problem007.py | 333 | 3.640625 | 4 | # -*- coding: utf-8 -*-
prime_list = [2]
number = 3
while True:
for i in range(len(prime_list)):
if number % prime_list[i] == 0:
break
else:
if i == len(prime_list)-1:
prime_list.append(number)
if len(prime_list) == 10001:
break
number += 2
p... |
b151de83dad84fe34f44aba7e7fbd108a11298c9 | railodain/TaskManager | /Task Manager/module/functions.py | 2,056 | 3.796875 | 4 | from classes import TaskInventory
# Main chat function
def start_working():
"Prints various methods of TaskInventory given input messages."
# An instance of TaskInventory
my_tasks = TaskInventory()
# Variable decides whether work session continues or not
user_working = True
while use... |
eb6cc67aa1d393850cd43bf191c60d5da5fc714f | bj1570saber/muke_Python_July | /cha_5_variable_operator/5-10-member_operator.py | 1,219 | 3.703125 | 4 | '''Summary:
1. compare type:
#can not compare child instance.
type(a)==type(b)
type(a)==int
#compare 'child instance' too.
A better type check: isinstance(a,int):return T F
2. a == b :compare value 1==1.0 True
3. a is b :compare id() 1 is 1.0 False
'''
# isinstance()
a = 'Hello'
b = 1.3... |
7dcadb894621e3c9c183e4000c427882f218872f | zeynepidil/gaih-students-repo-example | /Homeworks/HW3.py | 1,000 | 3.859375 | 4 | #Explain your work
#Day4Homework
def prime_first(num):
num=int(input("Please enter an integer value"))
def prime_second(num):
num=int(input("Please enter an integer value"))
for i in range(0,1000):
for i in range(0,500):
if num>1:
for i... |
8b4ca150fdcdc177493f2690e716fe372d032ef7 | onlinejudge95/materials | /creating-and-modifying-pdfs/source_code/01-extracting-text-from-a-pdf.py | 1,407 | 3.640625 | 4 | # ---------------
# Open a PDF File
# ---------------
from PyPDF2 import PdfFileReader
# You might need to change this to match the path on your computer
from pathlib import Path
pdf_path = (
Path.home()
/ "creating-and-modifying-pdfs"
/ "practice_files"
/ "Pride_and_Prejudice.pdf"
)
pdf = PdfFileRe... |
20361ae5a29ff8f76ab205e34138db60bfd48d31 | gabriellaec/desoft-analise-exercicios | /backup/user_029/ch84_2019_08_28_18_04_57_047001.py | 213 | 3.5625 | 4 | def inverte_dicionario(d):
novo_d = {}
for nome,idade in d.items():
if idade not in novo_d:
novo_d[idade]= [nome]
else:
novo_d[idade].append(nome)
return novo_d |
5d7db16b8b513f6e1916bbc2796567be1b978446 | creatist/neural_network_regression | /regression.py | 1,603 | 3.796875 | 4 | #该代码从https://blog.csdn.net/marsjhao/article/details/67042392 修改得来
import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
# 生成数据
X = np.linspace(-1, 1, 200) #在返回(-1, 1)范围内的等差序列
np.random.shuffle(X) # 打乱顺序
#Y = 0.5 * X + 2 + np.ran... |
59e55fc83c5bf49b88edbe42a2cfdc4736e73ae4 | aditi0330/Codecademy-Python-for-Data-Science | /Web Scraping/Web_Scraping_Beautiful_Soup.py | 3,377 | 3.765625 | 4 | import requests
webpage_response = requests.get('https://s3.amazonaws.com/codecademy-content/courses/beautifulsoup/shellter.html/http-requests')
webpage = webpage_response.content
print(webpage)
#Using Beautiful Soup
from bs4 import BeautifulSoup
webpage_response = requests.get('https://s3.amazonaws.com/cod... |
45898d3feb15cf9243a5dd6be292b0ae0607000e | shayansaha85/pypoint_QA | /set 3/5.py | 196 | 3.828125 | 4 | ask = 'y'
arr = []
while ask.lower()=='y':
el=input('Enter the next element: ')
arr.append(el)
ask=input('Do you want to enter more? (y/n): ')
print(arr)
print('Thanks for entering') |
e20f3fad2a5afddc76e2fd8ea1eb99ed3959e0a7 | Pulsatio/ICC-UTEC-2020-I | /Simulacro-ICC/p3.py | 267 | 3.953125 | 4 | while 1:
lado = int(input("Ingrese el lado del cuadrado: "))
if 5<=lado and lado<=10:
break
for i in range(lado):
for j in range(lado):
if i==0 or j==0 or i==lado-1 or j==lado-1 or i==j or i+j==lado-1:
print("*",end="")
else:
print(" ",end="")
print() |
5200fbcd89b1afce2f20da42b0c8a6352d3b1bf6 | BaoziSwifter/MyPythonLeetCode | /pythonLeetcode/105.从前序与中序遍历序列构造二叉树.py | 1,464 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=105 lang=python
#
# [105] 从前序与中序遍历序列构造二叉树
#
# https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (62.44%)
# Likes: 288
# Dislikes: 0
# Total Accepted: 34K
# Total Submissions: 54K
# Testcase Example: '[3,9,20,... |
1de9d8903f99406e83a0222dae68b4bfb77e4a96 | OyugoObonyo/alx-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 424 | 3.890625 | 4 | #!/usr/bin/python3
"""
Text identation
Contains:
text_identation()
"""
def text_indentation(text):
"""Idents the given text"""
if type(text) != str:
raise TypeError("text must be a string")
s = ""
for i in text:
if i in '.:?':
s += i
print(s.stri... |
bfdd57f543072b232909069416e2b4576ee6d299 | Aasthaengg/IBMdataset | /Python_codes/p03555/s333885211.py | 103 | 3.640625 | 4 | a=input()
b=input()
if a[1]==b[1] and a[0]==b[2] and a[2]==b[0]:
print("YES")
else:
print("NO") |
484933f4d1a30557ad25dbbeb487161f53608b18 | jmontara/become | /Ch2/variables.py | 593 | 3.953125 | 4 | #
# Example file for variables
#
# declare variable and initialize items
f = 0
print(f)
# re-declaring the variabe works
f = 'abc'
print(f)
# ERROR, variables of different types can not be combined
# python is strongly typed, even though you don't need to declare
# the value. The type is inferred by the compiler... |
dfe45a2da92821e2e20155bc4aa0a4e9aa3d8a00 | ShengYg/algorithms | /Leetcode/153 Find Minimum in Rotated Sorted Array.py | 1,262 | 3.578125 | 4 | class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
lo = 0
hi = len(nums)
mini = float('inf')
while lo < hi:
mid = (lo + hi)/2
mini = min(mini, nums[mid])
if nums[lo] <= nums[mi... |
86af59493ad5cc5d80a6634fd715301743ec62ce | madjabal/abstract-algebra-polynomial | /polynomial.py | 2,338 | 3.859375 | 4 | # Rough Draft of Polynomial Object for the purposes of studying and manipulating field polynomials
class Polynomial:
coefficients_d = {}
coefficients_l = []
highest_degree = 0
field = 0
def __init__(self, coefficients, field):
# Checks for input type and edits the corresponding attribut... |
e37671d99fc9ea76e8f4bf0eb9eaecf72d8a7623 | LanderVanLuchene/test | /Lesweek2/Oefening 10.py | 149 | 3.53125 | 4 | def calculate (a, b, c, d):
return a + b - c + d
print (1, 2, 3, 4)
print (calculate(2, 2, 2, 2))
print (calculate(2,2,2,3)==calculate(1,2,3,4)) |
3b0c7b89447aaa2ac8fe685fe0451d7e2d49b38c | abaldeg/EjerciciosPython | /pypart.py | 250 | 3.828125 | 4 | #Alinear un número a la izquierda:
c="*{:<8}*".format(4)
print(c)
"""
*4 *
"""
#Alinear una cadena a la derecha:
c="*{:>8}*".format("Hola") # * Hola*
print(c)
#Alinear una cadena a la centrada:
c="*{:^8}*".format("Hola") # * Hola*
print(c) |
2898abedc3011ff90fc70253d8095cfc5c4385d8 | jinxing-star-design/easy-ppt | /python练习/面向对象/单向链表.py | 984 | 4 | 4 | class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
def __str__(self):
return '<{} -> {}>'.format(self.item,
self.next.item if self.next else 'None')
class LinkedList:
def __init__(self):
self.he... |
79dc270bd9d114f34f8493b9c5a8d24b2ccce6b1 | drewhutchison/dvlp2015 | /code/implementations/target.py | 334 | 3.546875 | 4 | def solution(pirates):
spoken = reduce(lambda spoken, dummy: (
spoken + [pirates[spoken[-1]]]
if pirates[spoken[-1]] not in spoken
else spoken),
pirates,
[0]
)
return len(spoken) - spoken.index(pirates... |
85124e60549709a639c7483ce33f97a96acff648 | Dheerajdoppalapudi/Data-Structures | /linearsearch.py | 378 | 4 | 4 | #linear search python code
def linearSearch(arr, element):
for i in range(len(arr)):
if arr[i] == element:
return True
return False
string = input("Enter the number ")
arr = [int(x) for x in string.split()]
if linearSearch(arr,element = int(input('Enter the number to be search '))):
p... |
3d8400607dca907058cf38ff5cd819d7adbf4e1a | s-mojtaba-a/DS | /DS package.py | 7,212 | 3.9375 | 4 | # A package including BST and LinkedList
# LinkedList
class node:
def __init__(self,data):
self.data=data
self.next=None # points to the next node
self.prev=None # points to the previous node
class linckedlist:
def __init__(self):
self.head=None
self.tail=None
... |
1959160771461fd8f934b83ea160bf8e9bc42235 | HimaniSoni/CtCI | /10.5 Sparse Search.py | 1,685 | 4 | 4 | def search(myList, start, end, target):
if start > end:
return -1
middle = (start + end) // 2
if target == myList[middle]:
return middle
if myList[middle] != '':
if target < myList[middle]:
return search(myList, start, middle - 1, target)
else:
r... |
88fa5d8db82e4a9218bcc41689614ba11d617867 | n3n/CP2014 | /CodePython/pythonDuke/myPython.py | 728 | 3.765625 | 4 | def total_cost(type_car, isHasGPS, days, isSIIT):
return (cars_hire[type_car-1][1]*days + [0,200][isHasGPS]) * [1, 0.9][isSIIT]
cars_hire = [('BMW', 1800), ('Toyota', 1200), ('Honda', 600)]
# Choose car.
for i, car_hire in enumerate(cars_hire):
print str(i+1)+'.', car_hire[0], str(car_hire[1]) + '/day'
type_... |
25c9e1ba1a6bcda1532a5b624f1f00b048389659 | ajinkyad13/LeetCode_For_Interviews | /Python_Solutions/79. Word Search.py | 1,038 | 3.6875 | 4 | class Solution:
def exist(board,word):
nrows = len(board)
ncols = len(board[0])
def backtrack(i, j, idx):
char = board[i][j]
if char != word[idx]:
return False
elif idx == len(word)-1:
return True
... |
149631ce889f74a12f7f06b3c2ff4796747214bd | VitBomm/CSC | /Module1/baikiemtra/bai_3.py | 1,408 | 3.671875 | 4 | # Tạo danh sách nhân viên kiểu dictionary với key là mã nhân viên,
# value bao gồm các thông tin : tên nhân viên, số điện thoại, lương.
# Cho phép người dùng lần lượt nhập các phần tử cho danh sách cho
# đến khi không muốn nhập nữa
# => Chương trình sẽ thực hiện những công việc sau:
# - Hiển thị danh sách nhân viên.
#... |
ac132c19244b9ab6223da25e700f02491b0f23a3 | axeloh/hackerrank | /pythagorean_triplets.py | 1,196 | 4.375 | 4 | """
Given a list of numbers, find if there exists a pythagorean triplet
in that list.
A pythagorean triplet is 3 variables a, b, c where a^2 + b^2 = c^2
Example:
Input: [3, 5, 12, 5, 13]
Output: True
(5^2 + 12^2 = 13^2)
"""
def pythagorean_triplets(nums):
"""
Brute-force solution
Time: O(n^2... |
99eafc14dcf383d24a4c56479c2c596cfcef5fe2 | JIEXUNHE/comp9414 | /searchGeneric.py | 5,923 | 3.53125 | 4 | # searchGeneric.py - Generic Searcher, including depth-first and A*
# AIFCA Python3 code Version 0.8.1 Documentation at http://aipython.org
# Artificial Intelligence: Foundations of Computational Agents
# http://artint.info
# Copyright David L Poole and Alan K Mackworth 2017.
# This work is licensed under a Creative C... |
c66c32278fa834ca34ab3ebc8fb97bbbe5f493e6 | Nikhil-naruto/Phython-project | /WindowGui.py | 325 | 3.703125 | 4 | from tkinter import *
window = Tk()
#widgets = GUI elements : buttons , lables, images
#window = serves as a container to hold or contain these widgets
window.geometry("420*420")
window.title("Hello world")
window.config(background="black")
icon = PhotoImage(file='naruto.jpg')
window.iconphoto(True, icon)
window.mainlo... |
3ad4c330d54847f3788cebf6f8f927ffa3c44cc0 | geniyong/bkj-study | /level001/snail.py | 2,077 | 3.546875 | 4 | def print_result(rs):
for i in rs:
for index_j, j in enumerate(i):
print(j, end=" ")
if index_j % len(i) == len(i) - 1:
print("")
def find_val(arr, val):
n = len(arr)
for i in range(0, n):
for j in range(0, n):
if arr[i][j] == v... |
66dbdca134b28fbaf1c672bd8a6d1878ca537593 | limiyou/Pyproject | /1python基础/class8_func2/d6_函数的作用域.py | 482 | 3.953125 | 4 | #全局作用域
#全局变量:函数外部定义的变量,叫做全局变量
#局部变量:在函数内部定义的变量,仅限函数内部可以使用,函数外部无法使用
def add(a,b):
#局部作用域
c=a+b
return c
#不能直接使用c
#TODO:局部变量不能在全局作用域获取
c=add(4,5)
print(c)
#TODO:局部作用域可以使用全局变量
C=6
def minus(a,b):
d=a+b
print(d-c)
return d-c
minus(3,7)
|
47de11304f81657bd1fb619e387e7ed02faf72ce | alekkswithak/arkera | /q2.py | 1,059 | 3.640625 | 4 | import unittest
def largest_loss(pricesList):
if len(pricesList) <= 1:
return 0
max_value = max(pricesList)
last_max_index = max(i for i, v in enumerate(pricesList) if v == max_value)
if last_max_index == 0:
return 0
min_value = min(pricesList[:last_max_index])
r... |
43cc27f33f0680df5fab3daee8c56af9fbd48bd6 | sushyanthp/fetch-rewards-exercise | /ec2_setup.py | 6,662 | 3.8125 | 4 | #!/usr/local/bin/python3
"""
This exercise takes a YAML configuration file as input and,
- Deploys a Linux AWS EC2 instance
- Configures it with two EBS volumes
- Configures two user accounts on the EC2 instance for SSH
It uses Boto3 which is a Amazon Web Services (AWS) SDK for Python.
"""
import yaml
import boto3
i... |
bb36b785bcdc3f0da89ca78804a9ac2d044f24b5 | HeberCooke/Python-Programming | /Chapter4/exercise6.py | 1,266 | 4.25 | 4 | """
Heber Cooke 10/17/2019
Chapter 4 Exercise 6
This program takes in a message converts the characters to ascii, adds 1, and left shifts the bit and
places it on the other side. It converts the bits back to ascii to print the code
"""
message = input("Enter a message: ")
word = message.split() # splits the mesage ... |
401f36be774e4bfdb4e1ad6c7880d19eb29d0334 | TheManTheLegend1/python_Projects | /heros_inventory2.py | 1,288 | 4.125 | 4 | # Heros Inventory 2.0
# Demonstrates tuples
# create a tuple with some items and diplay with a for loop
inventory = ("sword",
"armor",
"shield",
"healing portion")
print("Your items:")
for item in inventory:
print(item)
raw_input("\nPress the enter key to continue.")
# get ... |
9c8a798549aa9028cfe4f1a4971f7fa253a6d324 | shants/LeetCodePy | /48.py | 753 | 3.84375 | 4 | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
r = len(matrix)
c = len(matrix[0])
for i in range(r):
for j in range(i+1,c):
... |
66bb9bdb591c2376f4a0bdc2dffa208e9e1b3f11 | Welvis3004/Aprendendo-Python | /Aula07aD011.py | 214 | 3.828125 | 4 | largura = float(input('Digite a Largura: '))
altura = float(input('Digite a Altura: '))
area = largura*altura
tinta = area/2
print('A area total é {} m², a tinta necessaria é {} litros.'.format(area, tinta)) |
78e5b6c0330f3fe8acfbacf98850071fffff5a20 | takahi-i/mlbook | /notebook/chapter00/oop.py | 221 | 3.734375 | 4 | class MyObject:
def __init__(self, num):
self.num = num
def add(self, x):
self.num += x
def show(self):
print(self.num)
o = MyObject(3)
o.show()
o.add(2)
o.show()
o.add(5)
o.show()
|
216d70883e60300d0f96e2c47c4306559dc1a14b | khorn89/PyCalc | /PyCalc.py | 2,863 | 4.40625 | 4 | import math
# from tkinter import *
#
# root = Tk()
#
# myLabel = Label(root, text="Hello World!")
# myLabel.pack()
# root.mainloop()
def calc_info():
print("The 'add' option activates addition.")
print("The 'subtract' option activates subtraction.")
print("The 'divide' option activates divis... |
d8dd6f51ee707aa26fc0db0354fe390d92f21c48 | xeon2007/machine-learning | /justin-python-ml/homeworks/hw1.py | 3,083 | 3.71875 | 4 | import numpy as np
import random
from pprint import pprint
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, training_set=None, testing_set=None, weights=None):
# Default weights to [0, 0, 0]
if weights == None:
self.weights = [0., 0., 0.]
else:
se... |
2927d3a6a0845111ae3551b5e4c57cc041f54c4a | kenta-takeuchi/python_design_pattern | /構造に関するデザインパターン/flyweight.py | 1,173 | 3.515625 | 4 | import sys
def main():
h1 = Hoge1()
h2 = Hoge2()
h1.add_att7()
print(h1.att7)
# h2.add_att7() # => AttributeError
# print(h2.att7)
# calc memory size
print(h1.__dict__)
memory_size_h1 = sys.getsizeof(h1) + sys.getsizeof(h1.__dict__)
# print(h2.__dict__) # => AttributeErro... |
2e1e19378d76723b6dc563f648d0d2c1b11d0f04 | mjdecker-teaching/mdecke-1300 | /notes/python/strings.py | 2,938 | 3.96875 | 4 | ##
# @file strings.py
#
# strings in Python based on: https://docs.python.org/3/tutorial
#
# @author Michael John Decker, Ph.D.
#
# What type do you thing this is?
"butterscotch"
# How about this one?
'a'
# Both are strings
'butterscotch'
# Just as in C++, \ can be used to escape characters
'\'escaped\''
# Or use ... |
fb925b1d5220466f09d69592b822a09646f8aa64 | dogancanulgu/arin-python-tutorial | /application1.py | 782 | 3.921875 | 4 | # a = 14
# a = 4.2
# a = 8
# a = 8 / 2
# print(a)
# print(type(a))
# print( (8 - 4) * 5 + (5 % 2))
# r = 5
# pi = 3.14159
# print(round(2 * pi * r, 3))
# print(pi * r * r)
# print(pi * (r**2))
# print(pi * pow(r, 2))
# import math
# r=5
# print(2 * math.pi * r)
# x = 21
# if(x % 2 == 0):
# print('X bir cift sa... |
f1e5f74734329b9c0065cfbcb4e525a69a77417f | tylercrompton/project-euler | /p052/p052.py | 227 | 3.53125 | 4 | def p052():
i = 1
while True:
if sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)):
return i
i += 1
if __name__ == '__main__':
print(p052())
|
279b755197729f18b451e34d7f426241830226c4 | JaredFlomen/LearningPython | /strings.py | 988 | 4.25 | 4 | #Day 4
#\n \t \\ \' \"
first_name = 'Jared'
last_name = 'Flomen'
language = 'Python'
formatted_string = 'I am %s %s. I\'m learning %s' % (first_name, last_name, language)
print(formatted_string)
radius = 10
pi = 3.14
area = pi * radius ** 2
formatted_string = 'The area of a circle with a radius %d is %.2f.' % (radius... |
b142fdc9f75aa0b54d5e7643b1715abd643f4664 | Bobcat1238/HelloWorld-Python | /app.py | 635 | 3.953125 | 4 | import Utils
print('Greg Barth')
print('o----')
print(' ||||')
print('*' * 10)
""" numbers = [5, 1010, 2, 5, 2, 777, 2, 8, -2, 99, 3]
numbers.append(50)
numbers.append(50)
numbers.sort()
largest = numbers[0]
for item in numbers:
if item > largest:
largest = item
print(numbers)
numbers.reverse()
print(num... |
c9deec6ed5d5a2b2df525dc996db85f8876e9b2a | thomasjurczyk/PythonProjects | /AnimalSubclass/animalGenerator.py | 2,268 | 4.1875 | 4 | from Animal import Animal, Mammal, Bird
print('Welcome to the animal generator!\nThis program creates Animal objects.')
animalList = []
while True:
print('\nWould you like to create a mammal or bird?\n1. Mammal\n2. Bird')
while True:
animalType = input('Which would you like to create? ')
... |
86327874f11083f8a97a78487fdc6848df101d8a | mgcarbonell/30-Days-of-Python | /20_map_filter_conditional_comprehension.py | 8,005 | 5.15625 | 5 | # Quick recap of comprehensions
# We only use a comprehension when we want to change something about the values
# when we make this new collection. For example, we might want to turn every
# string in a list to title case:
names = ['tom', 'dick', 'harry']
names = [name.title() for name in names]
# Tom, Dick, Harry
#... |
49254b22232940907e7706a1cd4018fb3a1e62a5 | Shazhul/HJ_FTP_Project | /Assignment3/oldcode/oldserver.py | 1,923 | 3.75 | 4 | # *****************************************************
# This file implements a server for receiving the file
# sent using sendfile(). The server receives a file and
# prints it's contents.
# *****************************************************
import sys
import socket
from cmds import FTP_COMMANDS
# Command line c... |
b3ed7564400394aa041ac8cd66ba57b856eccb7e | georg-remer/python-project-lvl1 | /brain_games/games/engine.py | 2,552 | 3.890625 | 4 | """Game engine.
The flow is the following:
1. Print intro
2. Print game description if game is specified
3. Welcome user
4. Play the game n-rounds (or till first wrong answer) if game is specified:
4.1. Print question
4.2. Get answer from user
4.3. Check if asnwer is correct
"""
import prompt
from brain_games import ... |
56cd8e467e4d94664a57439e49fe2ad397df0c13 | CleitonFurst/python_Blueedtech | /Exercicios_aula_09/Exercicio_07.py | 291 | 3.84375 | 4 | '''5. Faça um programa que mostre os valores numéricos inteiros ímpares situados
na faixa de 0 a 20.'''
lista = list(range(0,21))
lista2 = list()
for i in lista:
if i % 2 != 0:
lista2.append(i)
print(f'Os númeors impares dentro do intervalo de 0 a 20 são {lista2}')
|
14602f68310d1fd85807abf6d8c960e981160cb0 | karlhub/Python-Initial-Programs | /Py01-Initial Programs/Programa_22_Python_Matplotlib_Package_Extended.py | 1,281 | 4 | 4 | # Use of Python package: Matplotlib - Extended
# Import subpackage "pyplot"
# Documentation in internet: https://matplotlib.org/tutorials/introductory/pyplot.html#sphx-glr-tutorials-introductory-pyplot-py
import matplotlib.pyplot as plt
import numpy as np
# Working with multiple figures and axes.
# MATLAB, and pyplot... |
ff609c563a9669104a0c5bc74917159788d2c3db | klmcshane/klmcshane.github.io | /python/places.py | 131 | 3.921875 | 4 | city = ["London", "Reykjavik", "Florence", "Glasgow", "Cairo"]
for item in city:
print("I would like to visit " + item + ".")
|
44727976fee256c0f455db30facb7e20cafb6c4b | Baljot12/training | /operations on list.py | 547 | 3.75 | 4 | #concatenation
IndianBatsman=["VIRAT ","SHIKHAR ","YUVRAJ ","ROHIT "]
print(IndianBatsman+ ["RAINA","JADEJA"])
print(IndianBatsman)
print()
#repetition
print(IndianBatsman*2)
#membership
print("WATSON" in IndianBatsman)
print("A B DEVILLIES" not in IndianBatsman)
#indexing
print(IndianBatsman[2],"",Indian... |
6b12d28524c803afde68b296ff7cfb635df253ae | HONOOUR/Algorithm_Test | /Algorithm_Python/GreedyProgramming_3.py | 1,047 | 3.75 | 4 | import sys
from typing import no_type_check_decorator
# https://leetcode.com/problems/jump-game-ii/
def getJumpToLast(nums):
jump_count = 0
left = right = 0 # start point
while right < len(nums):
farthest = 0
for i in range(left, right+1):
farthest = max(farthest, i + nums[i]... |
bbdfa7242903a494dc52564ece5e8aed8cfd440c | SeungMin-le/grade3 | /정보처리알고리즘/실습과제/ch03_closestpair_v20.py | 6,622 | 3.59375 | 4 | from math import sqrt
import timeit
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "Point(%.2f, %.2f)"%(self.x, self.y)
def __repr__(self):
return self.__str__()
def distPair( p ):
if (p[0] and p[1]):
d = sqrt( (p[1].x - p... |
642e59a72021032956be2940e52550d970ce3bad | TheAlgorithms/Python | /bit_manipulation/binary_and_operator.py | 1,465 | 4.40625 | 4 | # https://www.tutorialspoint.com/python3/bitwise_operators_example.htm
def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
>>> binary_and(25, 32)
'0b000000'
>>>... |
34e136246665689b382cc5292f2d514a8fcffa0a | katsuyamiz/PythonPractice | /sets.py | 242 | 3.640625 | 4 | my_set = set()
print(my_set)
my_set.add(1)
print(my_set)
my_set.add(2)
print(my_set)
my_set.add(2)
print(my_set)
# have to be unique value
# the same value cannot be added twice
my_set2 = set()
my_set2.add('mississippi')
print(my_set2)
|
f459228d2e707acb10133cab2e4cfa456ca5cd52 | kimjieun6307/itwill | /itwill/Python_1/chap01_Basic/exams/exam03.py | 1,101 | 3.875 | 4 | '''
step03 문제
'''
'''
문) 3개의 단어를 키보드로 입력 받아서 각 단어의 첫자를 추출하여 단어의 약자를 출력하시오.
조건1) 각 단어 변수(word1, word2, word3) 저장
조건2) 입력과 출력 구분선 : 문자열 연산
조건3) 각 변수의 첫 단어만 추출하여 변수(abbr) 저장
<<화면출력 결과>>
첫번째 단어 : Korea
두번째 단어 : Baseball
세번째 단어 : Orag
=================
약자 : KBO
'''
word1 = input("첫번째 단어 : ")
word2 ... |
db860a1e84107f294571b2c5738359ae0239456a | Rogan003/Python-vezbe | /vezba3.py | 287 | 3.546875 | 4 | from math import sqrt as koren
import random
def randomLista(x):
lista=[]
for i in range(x):
lista.append(random.randint(5,15))
return lista
unos=int(input("Unesite neki broj: "))
lista=randomLista(unos)
print("Koren iz sume random liste je: "+str(koren(sum(lista)))) |
5c61c271002f42a183df4fff8ee0c3f7b673dc71 | qizongjun/Algorithms-1 | /牛客网/最短子数组.py | 1,281 | 3.78125 | 4 | '''
对于一个数组,请设计一个高效算法计算需要排序的最短子数组的长度。
给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的长度。
(原序列位置从0开始标号,若原序列有序,返回0)。保证A中元素均为正整数。
测试样例:
[1,4,6,5,9,10],6
返回:2
'''
'''
从左到右找最右边一个当前值大于之前最大值的地方
再从右到左找最左边一个当前值小于之前最小值的地方
两个值代表的区间就是需要排序的最短子数组的长度
原理实在不懂...
'''
# -*- coding:utf-8 -*-
import sys
class Subsequence:
def shortestSubsequence... |
76959896dd2adc2694a856849786ed814da80a1e | gabriellaec/desoft-analise-exercicios | /backup/user_179/ch27_2020_03_25_11_40_34_374907.py | 190 | 3.765625 | 4 | duvida = True
while duvida:
resposta = input('Você ainda está com dúvidas? ')
if resposta = 'sim':
print ("Pratique mais")
else:
duvida = False
print ("Até a próxima") |
18842651d19615eb712c6a371a9a29ec417ced34 | kanhu-nahak-au26/attainu_first | /python lecture/input_output.py | 202 | 3.875 | 4 | print("hay!!,Enter some Age")
Age = input ()
print("hay !!, You have enter", "you are" , Age,"year old")
print("Hay !! Please Enter your name")
name = input ()
print("Hi ", name ,"how are you today")
|
045361f47a587b8c14e495583d374375257807ef | lchappellet/leet_code_problems | /Roman_to_integer_leet_code_13.py | 1,410 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 27 17:13:21 2020
@author: cyrilchappellet
"""
#I 1
#V 5
#X 10
#L 50
#C 100
#D 500
#M 1000
roman_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'... |
211f1940ec4d885976b3ac0ba657c89cf03f322b | Hellofafar/Leetcode | /Medium/457.py | 3,035 | 3.703125 | 4 | # ------------------------------
# 457. Circular Array Loop
#
# Description:
# You are given a circular array nums of positive and negative integers. If a number k at an
# index is positive, then move forward k steps. Conversely, if it's negative (-k), move
# backward k steps. Since the array is circular, you may as... |
af231a99969fee2b4d8cd10ace3ad3393a147aff | Roc-J/LeetCode | /300~399/problem345.py | 657 | 3.515625 | 4 | # -*- coding:utf-8 -*-
# Author: Roc-J
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
number1 = []
number2 = []
for item in s:
if item in ['a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U']:
nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.