blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42d56f46cdb8e84ff52ed1118b8ebb97198d36ec | zhou-zhenyi/sicp | /c1_1_elements/s11_block.py | 431 | 3.640625 | 4 | def sqrt(x):
def sqrt_iter(guess):
if good_enough(guess):
return guess
else:
return sqrt_iter(improve(guess))
def improve(guess):
return average(guess, (x / guess))
def average(x, y):
return (x + y) / 2
def good_enough(guess):
return abs... |
fadb969735d518e2ad47ea2aa34eeeaa8450ca55 | 2292527883/Learn-python-3-to-hard-way | /ex15/ex15.py | 844 | 3.5 | 4 | from sys import argv
script, filename, py1 = argv # 从外部获取参数 赋值给script ,filename
txt = open(filename) # 打开 filenmae 文件赋值给txt变量
print(f"Here's your file {filename} :")
print(txt.read()) # 读取txt变量的值
print("script的意思是:", script)
print("Type the filename again :")
file_again = input(">")
txt_again = open(file... |
d4605dcedf034a697a4ccf804f04af1e3ae85f12 | mconchac/Django | /1.py | 978 | 4.25 | 4 | # este es el comando para imprimir en consola
""" esta es otra forma de hacer comentarios en varias líneas
como en este ejemplo
y se cierra con comillas dobles 3 veces
"""
print("hola soy yo, mcc")
print (100)
print ("soy nivelpro")
str("test2")
lista = ["string", 1, [1,2,3], "true"]
# definición de listas
{"name":... |
b875727edfd22560eacdeef3a35d7f8a0165a283 | SongJialiJiali/test | /leetcode_409.py | 655 | 3.515625 | 4 | #leetcode 409. 最长回文串
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
resoult={}
for i in s:
resoult[i]=s.count(i)
num = 0
resoult_q = 0
for keys in resoult:
if resoult[keys] % 2 ... |
3446262a43cfc47aef94c4073f585fd2fa43d88c | IswaryaBaskaran/Python-Programs | /factorial.py | 204 | 4.25 | 4 | '''TO FIND FACTORIAL OF A GIVEN NUMBER'''
n = int(input("Enter a number: "))
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
print(recur_factorial(n)) |
d7c5fc8f4f253d5933902ec0333e9a30f480a39f | sbo97t/BootCamp | /C to F converter.py | 427 | 4.125 | 4 | # C to F converter
print("Enter a temp in Celsius to convert to Fahrenheit")
temp = float(input("Celsius "))
print((temp * 9/5) + 32)
print("Would you like to convert from Farhneheit to Celsius? (Y or N) ")
answer=input()
if answer=="Y":
print("Enter a temp in Fahrenheit to convert to Celsius")
tempF ... |
c8e5fb48af6221d337e58f956bbfab8f490f1d9c | YeomeoR/codewars-python | /well_of_ideas.py | 920 | 3.96875 | 4 | # In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.
def well(x):
good = x.count("good")
re... |
3c94c7256f428461154f03ca144c31a70482c981 | d1rtyst4r/archivetempLearningPythonGPDVWA | /Chapter03/tasks/guests.py | 2,720 | 4.15625 | 4 | guests = ['elizabeth', 'albert', 'peteris', 'jonny']
print("Hi " + guests[0].title() + ", I would like to invite you to my party!")
print("Hi " + guests[1].title() + ", I would like to invite you to my party!")
print("Hi " + guests[2].title() + ", I would like to invite you to my party!")
print("Hi " + guests[3].title(... |
150b41309be6793b942ce188e9e81d74a1be7143 | CFoyer-Portfolio/PyFEA | /pyfea/tools/plotting.py | 1,864 | 3.5625 | 4 | # -*- coding: utf-8 -*-
#Created on Thu Jun 20 23:13:03 2019
#@author: Christophe
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D; _ = Axes3D #hide spyder warning msg
import numpy as np
import pyvista as pv
def scatter3d_mpl(points):
# plot the surface
plt3d = plt.figure().gca(projecti... |
3e253220d9a5e827b6cb7d0245aae9ff889ac9e2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/d9f5e279b7f94c1ab1f5974360770eb7.py | 256 | 3.65625 | 4 | '''
Excercism Problem #2
Iteration 1
'''
def is_leap_year(test_year):
if (test_year % 4 == 0 and test_year % 100 != 0) or (test_year % 400 == 0):
return True
return False
def main():
pass
if __name__ == '__main__':
main()
|
07f46340cce040da895ecdfefdd9c283c412fa13 | laobadao/Machine-Learning-U | /ml_assign/P1_Predicting_Boston_Housing_Prices/boston_housing.py | 6,541 | 3.734375 | 4 | """Load the Boston dataset and examine its target (label) distribution."""
# Load libraries
import numpy as np
import pylab as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
from sklearn import cross_validation
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_erro... |
06cd942275d2508fae26cae6706ae3c60ea0cc18 | timetobye/TIL | /Python/7_Python_utility/dict_union/dict_union.py | 1,127 | 4.1875 | 4 | """
Dict Union 은 Python 3.9 에 추가된 기능(그 이전 버전은 구동 안 됨)
- https://www.python.org/dev/peps/pep-0584/#id18
- https://www.python.org/dev/peps/pep-0584/#specification
병합 연산자 '|' 를 이용하여 Dictionary 를 병합할 수 있다.
- 참고 문서 : https://betterprogramming.pub/new-union-operators-to-merge-dictionaries-in-python-3-9-8c7dbbd1080c
"""
# ... |
151ca6bd31b3227de252e47ecafd2d08a59902b5 | hsl39/PythonTicTacToe | /board.py | 1,044 | 3.9375 | 4 | class Space:
def __init__(self, x, y):
self.value = " "
self.coord = [x,y]
def setValue(self, value):
self.value = value
def printSpace(self):
print("[" + self.value + "]", end = "")
def getXCoord(self):
return self.coord[0]
def getYCoord(self):
... |
991656767c61470b5cde77f5f6037412e3b7a7de | VUW-FAIR/blockchains_web_scraping | /github/jsontocsv_for_github.py | 2,565 | 3.578125 | 4 | import os
import pandas
from pandas.io.json import json_normalize
import json
'''
Make new subdirectory of specified name
'''
def make_dir(name):
newpath = r'.\\' + "json_to_csv" + '\\' + name
if not os.path.exists(newpath):
print("making dir")
os.makedirs(newpath)
'''
Takes you... |
59755ad367ec9d930b24a417f9c0ced30b1191f7 | eugenechung81/coding-java-projects | /distributed-cache-py-analysis/reference/test.py | 343 | 3.515625 | 4 | import csv
from collections import defaultdict
reader = csv.DictReader(open('test.csv', newline=''))
cities = defaultdict(int)
for row in reader:
cities[row["CITY"]] += int(row["AMOUNT"])
writer = csv.writer(open('out.csv', 'w', newline = ''))
writer.writerow(["CITY", "AMOUNT"])
writer.writerows([city, cities[city... |
14c890c289fde88451b0ff25e55af541faace580 | katieunger/hmc-homework | /lesson_3/lesson_3_states.py | 5,459 | 4.15625 | 4 | # Challenge Level: Beginner
# Background: You have a text file with all of the US state names:
# states.txt: See section_07_(files).
#
# You also have a spreadsheet in comma separated value (CSV) format, state_info.csv. See also section_07_(files)
# state_info.csv has the following columns: Popula... |
7ddf0486fdd4b48bda93a08287b5fb6a136b0e9a | BrianWikse/IntegrationProject | /MAIN.py | 6,306 | 4.21875 | 4 | #My name is Brian Wikse
#This is a quiz game.
#This is a function that will print a name and email when it is called, this function is used in Quesion 10.
def info(name, mail):
print(name, mail)
print("Welcome to", end=' ')
print("the Quiz Game!")
#The end= in the print statement combines the two print... |
e60c90b1051b346aa91e51ea974edf56467326c5 | ngsc-py/2020-python-code | /ch6/06-4monthdictonary.py | 275 | 3.90625 | 4 | month={1:'January',2:'Feburary',3:'March',4:'April'}
month[5]='May'
month[6]='June'
month[7]='July'
month[8]='August'
month[9]='September'
print(month)
print()
from random import randint
for i in range(5):
r = randint(1,9)
print('%d: %s' %(r,month[r]))
|
0af610fa59951240f5ee794ef723aa7cd7b85c8f | herozhao/Python-Learning | /Previous/Lab11/exa/school.py | 2,509 | 3.609375 | 4 |
def getStudentInfo():
d = {}
with open("university.txt",'r') as f:
next(f)
coursenames = f.readline()
courseList = coursenames.split()
courseList = courseList[2:]
next(f)
for line in f:
lineList = line.split('|')
personalist = lineList... |
704b1eeaa9dee3b2d1477cce0c0f3d464883a989 | dpk3d/HackerRank | /CheckValidShuffleString.py | 2,667 | 4.4375 | 4 | """
https://www.programiz.com/java-programming/examples/check-valid-shuffle-of-strings
Given strings A, B, and C, find whether C is formed by an interleaving of A and B.
An interleaving of two strings S and T is a configuration such that it creates a new string Y from the concatenation substrings of A and B and |Y| =... |
4ae0f22b870226e9108106390109c098666a97ff | junyechen/Basic-level | /1042 字符统计.py | 1,108 | 3.875 | 4 | '''
请编写程序,找出一段给定文字中出现最频繁的那个英文字母。
输入格式:
输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。
输出格式:
在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。
输入样例:
This is a simple TEST. There ARE numbers and other symbols 1&2&3...........
输出样例:
e 7
'''
###################... |
9b73dbe3f7fefe96457b07166fdcf40b037fadd2 | lilda/likelion_python | /python.py | 1,129 | 3.828125 | 4 | blogs = ["1", "2", "3"]
for blog in blogs:
print(blog)
for i in range(1):
# 0 ~ 9
print("1") #반복할때 숫자(반복된 횟수)와 함께 1 출력
for _ in range(1):
print("HEllo Django") #10번 반복할때 숫자는 보이지 않게
aaa = { "사과" : 1, "배": 2, "포도":3 , "바나나": 234} #dict="key":value
for k, v in aaa.items():
print(k... |
48e5ef0991ee277442e93ce0fad29f7ca56d1436 | ritchereluao/turtle_crossing_game | /road.py | 601 | 3.703125 | 4 | from turtle import Turtle
class Road(Turtle):
def __init__(self):
super().__init__()
self.pensize(width=15)
self.color("white")
# self.penup()
# self.hideturtle()
def draw_middle_line(self):
self.goto(-320, 0)
self.forward(620)
# turtle = Turt... |
fdf3346f2792520bb9d6238bc75f1ba9f335e6b6 | Shubham1744/Python_Basics_To_Advance | /CheckDivisible/Prog4.py | 312 | 4.34375 | 4 | # Accept one number and check whether is is divisible by 5 or not.
def CheckDivisible(No1):
if No1 % 5 == 0:
return True
else:
return False
No1 = int(input("Enter Number :"))
bret = CheckDivisible(No1)
if bret == True:
print("divisible by 5")
else :
print("Not divisible by 5")
|
5cff4ec6f0f61e0514e421024235c5247d571b5e | houstonwalley/Kattis | /Python/IsItHalloween.py | 135 | 3.84375 | 4 | n = list(input().split())
if n[0] == "OCT" and n[1] == "31" or n[0] == "DEC" and n[1] == "25":
print("yup")
else:
print("nope") |
0d823cc7cc1af945423750bb571eb461254d94a2 | theeric80/LeetCode | /medium/reverse_words_in_a_string.py | 365 | 3.6875 | 4 |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])
def main():
inputs = ['the sky is blue', '', 'a']
for s in inputs:
result = Solution().reverseWords(s)
print '{0} = {1}'.format(s, re... |
812aede80a2eab19f4499466141a4d8218f274dc | juliyat/Python | /Python book/Chapter 3.py | 532 | 3.984375 | 4 | cost = 35.27
tip = cost / 15
total = cost + tip
per = total // 3
print " about $", per
print ""
print ""
area = 12.5 * 16.7
perimeter = (12.5 + 16.7) * 2
print "The area is", area
print "The perimeter is", perimeter
print ""
print ""
f = int(raw_input("Enter the temperature in fahrenheit-"))
c = (f - 32) * 5/9
print "I... |
b2814f414ef311ad7cb32dae88b82ec8b42bfd74 | IshchenkoMaksim/lab5 | /ind2.py | 575 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
s = input("Введите слово: ")
m = int(input("Введите номер первой буквы для замены: "))
n = int(input("Введите номер второй буквы для замены: "))
m -= 1
n -= 1
if m > len(s) or n > len(s):
print('Невер... |
89646218ebd98627eb8587bd437a36c80bbc6396 | IsaGher/ANS-unidad1 | /ejercicioUno.py | 518 | 3.71875 | 4 | import math
x = float(input("Ingrese valor de x: "))
cifras = float(input("Ingrese cuantas cifras significativas: "))
es = 0.5*(10**(2-cifras))
ea = es+1
n = 1
ant = 1
while ea>es:
f = 1
for i in range(1,(n+1)):
signo = (-1)**(i+1)
f += signo*round((x**i)/(i*math.exp(i)),6)
ea = round(abs... |
d12c463b935b82891b536b10f969dbe074ea2891 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/mkhnel011/question1.py | 1,441 | 3.9375 | 4 | """ a program that determines which students, according to the marks need to see a student an advisor
nelisile mkhwebane
13/05/2014"""
import math
""" get the text file from the user"""
filename= input("Enter the marks filename:\n")
"""open the file and get it's content"""
f = open(filename, "r")
lines = ... |
9463a140bd35139b8cbda6dd8075a3dc7a0a42bc | Beornwulf/AoC2016 | /day1/puzzle2/puzzle2.py | 2,106 | 3.78125 | 4 | def turn_right(direction):
return {
'north': 'east',
'east': 'south',
'south': 'west',
'west': 'north'
}.get(direction)
def turn_left(direction):
return {
'north': 'west',
'west': 'south',
'south': 'east',
'east': 'north'
}.g... |
e9968c2f032ba3223dd944263fc7e6eaa3074053 | nghiattran/playground | /knapsack.py | 1,847 | 3.6875 | 4 | import time
def knapSack(val, wt, W, n):
# Base Case
if n == 0 or W == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n - 1] > W):
return knapSack(val, wt, W, n - 1)
# return the ... |
797acdc8a5fd330ea163f8d4d993593d0c8a7910 | jiexishede/leetcode-1 | /src/longest_common_prefix.py | 1,230 | 3.59375 | 4 | class Solution:
# @param {string []} strs
# @return {string}
def longestCommonPrefix(self, strs):
if not strs:
return ""
longestIndex = 0
foundNotMatched = False
for index in range(0, len(strs[0])):
if not foundNotMatched:
longestIndex ... |
8437a87ee111cb42e736813766cdd0e00a381b7e | dipanbhusal/Python_practice_programs | /ques6.py | 667 | 4.25 | 4 | # 6. Write a Python program to find the first appearance of the substring 'not' and
# 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor'
# substring with 'good'. Return the resulting string.
def string_manipulation(string):
if 'poor' and 'not' in string:
poor_index = s... |
e4771e3c68b965bf4044b8cd3f02df2bc382f7f9 | Sharko-21/homework-template | /homework2/bubble_sort.py | 992 | 4.15625 | 4 | def input_arr(num):
arr = []
for i in range(0, num):
current_elem = float(input('Введите ' + str(i) + ' элемент массива: '))
arr.append(current_elem)
return arr
def bubble_sort(arr):
for i in range(0, len(arr) - 1):
for j in range(i + 1, len(arr)):
if arr[i] > arr[... |
d6aec33ee3dd56d2aed4be5cfa167bc66da2002a | quocthai200x/NguyenXuanQuocThai-Fundamentals-C4E27 | /session 3/session3.py | 2,456 | 3.90625 | 4 | # # # n = int (input("tổng chữ số cần tính : "))
# # # tong = 0
# # # for i in range (n) :
# # # x = int(input('mời nhập các số : '))
# # # tong = tong + x
# # # print ('tổng các chữ số đó là : ', tong)
# # # n = int(input('mời nhập số : '))
# # # if n%2 == 1 :
# # # print ('abc')
# # # else :
# #... |
0df8749044ab85a4cb855bb3127a5de0253d63cb | moon0331/baekjoon_solution | /programmers/고득점 Kit/네트워크.py | 679 | 3.71875 | 4 | def DFS(n, computers, start_node, visited):
stack = [start_node]
while stack:
node = stack.pop()
for next_node in range(n):
if not visited[next_node] and computers[node][next_node] == 1:
stack.append(next_node)
visited[next_node] = True
def solution(... |
2b392be7b7e9c2faac60e70c6682b2be7ee96d97 | NorthcoteHS/10MCOD-Max-APPELMAN | /modules/u3_organisationAndReources/naming/saysHello.py | 250 | 3.734375 | 4 | """
Prog: saysHello.py
Name: Max Appelman
Date: 2018/03/12
Desc: Says hello to the user.
"""
#gets name of user and displays a personalised greeting
name = input('What is your name? ')
print('Hello ' + name + ', I am Computer! Nice to meet you.')
|
f34bfed9d86499bde96a0a5a7c2c0723e0d31cc7 | Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1- | /Session 2/List/LoopInList.py | 493 | 3.953125 | 4 |
@auther nouran ahmed ibrahim
List = ['a', 1, "b", 2, 'c', 'd']
# display all items in list
for item in List:
print(item)
# find num of small char in list
countChar = 0
for item in List:
if str(item).isalpha(): # convert all items to String then check if it char or not
countChar += 1
print("numb... |
7d05035329c7083cb9dafe6f7647827b40027f6b | wmemon/python_playground | /24_days/Day 24/Question102.py | 493 | 4.03125 | 4 | """Write a Python program that accepts a string and calculate the number of digits and letters."""
def get_digits(string):
digits = 0
for alpha in string:
if alpha.isdecimal():
digits+=1
return digits
def get_letters(string):
letters = 0
for alpha in string:
if alpha.is... |
da45d464210e6287fa0b543fc380751a2f824ae9 | alhanson7210/deploying-working-software | /assignments/a1-unit-tests/test_calculator_one.py | 4,879 | 3.6875 | 4 | from unittest import TestCase
from calculator_one import Calculator
class TestCalculator(TestCase):
def setUp(self) -> None:
self.calculator = Calculator()
def test_default_init_calculation(self):
actual = self.calculator.get_last_calculation()
if type(actual) != int:
self.... |
4daea6f6078e514ad05369a1b5bbd4648ecdcbbd | whelanworkmaster/mta_info_scraper | /scripts/timer.py | 896 | 3.90625 | 4 | import time
class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""
class Timer:
def __init__(self):
self._start_time = None
self._total_time = None
def start(self):
if self._start_time is not None:
return
self._star... |
828ec355176643d361fa0c59558465a2f2058e2f | LukasForst/RPH | /scrabble/scrabble_player.py | 1,862 | 3.65625 | 4 | import config_scrabble
class ScrabblePlayer:
rows = 15
columns = 15
def __init__(self, dictionary_path):
self.halfIDX = int(self.rows / 2) - 1
self.is_first_move = True
self.all_dictionary_words = {}
self.hand_letters = ""
with open(dictionary_path, encoding='u... |
30cdc3c9590c2d777ca7b9ffcf9c3c55b68bccca | Baisal89/Sprint_DS8 | /acme_report.py | 1,330 | 3.671875 | 4 | from random import uniform, randint, choice
from acme import Product
DJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(n: int = 30) -> list:
"""Creating list of new ACME products!"""
products = []
... |
1637fc1e41461375967b440657671116274d28a4 | Batyrsultan/WebDevelopment | /week9/informatics/3/2/30599.py | 72 | 3.953125 | 4 | def power_of_two(n):
sqr=1
while(sqr<=n):
print(sqr,end=" ")
sqr=sqr*2 |
b8f33577646fdf501231475142333986479e110a | zaigr/math-pack | /lab_01/task3/main.py | 422 | 4 | 4 |
import common.input
def get_factorial_loop(number: int):
if not 0 <= number <= 100:
raise ValueError
factorial = 1
for i in range(2, number + 1):
factorial *= i
return factorial
def main():
number = common.input.input_number(int, 'Input int from 0 to 100: ')
factorial = ge... |
7fa0e4e5bc1f6b516fa564ac947444990dfb0e45 | sgalicia/lesson9 | /Lesson 9/problem3.py | 289 | 3.90625 | 4 | print('-'*60)
print('Alien Greeter Bot: ')
print()
planet = input('What planet are you from? ')
if planet == 'Mars':
print('Welcome to Earth, please do not kill us!')
else:
print('Dammmmnnnnn, your face is so ugly I thought you were an alien. Anyways ... have a good day!')
print('-'*60) |
4deba05c3ed97980a76e9ca50be3b119aaeb7254 | vaishnavivm/FINDING-KAREL-GAME | /codeinplace-master/game.py | 7,013 | 3.734375 | 4 | import tkinter as tk
import time
from PIL import ImageTk, Image
"""FINDING KAREL GAME
The player needs to find Karel with the clues provided by Karel.
The player needs to click on the object that matches the clue.
The player has three chances to click on the right object for the whole game.
If the player clicks wron... |
507f32d83c0c15b37a44f7f37700b8fab19673f3 | Elcoss/Python-Curso-em-Video | /Mundo1/desafio3.py | 134 | 3.703125 | 4 | n1=int(input('digite um valor: '))
n2=int(input('digite outro valor: '))
n3= n1+n2
print(f'a soma entre {n1} e {n2} vale {n3}')
|
29a0dfb14231e4bc5c8e2ebab295cc0f1880094d | valleyceo/code_journal | /1. Problems/b. Strings & Hash/0. Template/c. Best Substring - Find All Subset Combination in String.py | 1,029 | 3.9375 | 4 | # Compute All String Decompositions
'''
- Given a input string and array of strings
- Return the starting indices of substrings of the sentence
'''
# O(N*n*m) time, N is length of sentence, m is number of words, n is length of each word
def find_all_substrings(s: str, words: List[str]) -> List[int]:
def match_all... |
a22434d114b2402d95a372c3e95145b2d59b1488 | geon1002/bach | /python/phan tich.py | 168 | 3.8125 | 4 | a = input("so: ")
so = int(a)
sochia = 2
while so >sochia:
if so % sochia==0:
print(sochia)
so /= sochia
else:
sochia +=1
print(so)
|
83a3c8f42faa31328cde36a49f15b776526b3689 | DaniloBP/Python-3-Bootcamp | /nested_lists.py | 779 | 3.90625 | 4 |
matrix1 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
# print(matrix1, end="\n\n")
# print(matrix1[0][1], end="\n\n") # 2
# print(matrix1[1][-1], end="\n\n") # 8
# print(matrix1[2][-4], end="\n\n") # 9
# print(matrix1[-2][-3], end="\n\n") # 6
# for l in matrix1:
# print(" ", end="")
# for val in l:
# print(... |
aef28419d542d53dff30a0e5089ce479c4bff05a | vdpham326/Python_Coding_Exercises | /first_half.py | 303 | 4.125 | 4 | # Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
def first_half(str):
half = int(len(str) / 2)
return str[:half]
#return half
print(first_half('Woohoo'))
print(first_half('HelloThere'))
print(first_half('abcdefg'))
#print(first_half('Woohoo'))
|
d650c4afa97c57556cd0bb8644e347ba7bc52480 | fabiourias/520 | /funcoes.py | 1,821 | 3.640625 | 4 | #!/usr/bin/python3
#encoding: utf-8
from
def boas_vindas(nome='Daniel', idade=24):
nome = input('Digite o seu nome:')
idade = int(input('Digite sua idade:'))
dic = {'nome': nome, 'idade': idade}
return dic
def boas_vindas02(*args):
for x in args:
print('Seja bem vindo: {}!'.format(x))
... |
f1f32d571b20f00ea0e5f1b3ed7095d1375b13c2 | EliRuan/ifpi-ads-algoritmos2020 | /Exercícios Iteração WHILE/f3_q01.py | 172 | 3.984375 | 4 | n = int(input('Digite um número: '))
c = 1
print(f'Os números inteiros entre 1 e {n} são:')
while c <= n:
print(c, end=' ')
c += 1
print('Fim')
|
20761809b8478b6015e51d381edfdb49a65f8f46 | ljZhang416/studypython | /lpthw/day02_3.py | 265 | 3.609375 | 4 | # 1.输入一个季度(1-4表示),输出这个季度有哪几个月
# 如果输入的不是1-4的整数,则提示用户输入错了
while True:
a = int(input("请输入:"))
if a == 1:
print("123")
elif a==2:
print("456")
else:
print("输入错误") |
55fbbe46f95f9084d90913e616f2da348ef297d7 | agentmilindu/IEEExtremes | /IEEExtreme8/Grand-Integer-Lottery/AnonymouZ.py | 557 | 3.59375 | 4 | def remove_repetitions(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))]
params = input().split()
S = int(params[0])
E = int(params[1])
P = int(params[2])
N = int(params[3])
selects = []
for i in range(N):
t = input().strip()
selects.append(t)
LS = ... |
2b8bccea06f840b8701e282b5581b4941b56554e | nkkodwani/arul-naveen-c2fo-2021 | /PracticeProjects/ArulFiles/dp_allocate_mailboxes_partitions.py | 3,375 | 3.5 | 4 | '''
LEETCODE PROBLEM 1478:
Given the array houses and an integer k. where houses[i] is the location of the ith house along a street, your task is to allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
https://leetcode.com/problems/allocate-mailb... |
164c21a4d7cd1fd7720ae37b63b107bb02815857 | daniel-reich/ubiquitous-fiesta | /TCbrjfMm2dPzQDbz5_5.py | 131 | 4 | 4 |
def insert_whitespace(txt):
k = ""
for letter in txt:
if letter.isupper():
k += " "
k += letter
return k[1:]
|
1f60d444cd6c7d8a72a0308e811a714d2deee1ec | emohr44/Coding-Practice | /Variables and Types.py | 404 | 4.1875 | 4 | # This script introduces the concept of data types such as of
# integers and stings. We cast strings as integers and visaversa so
# that we can add integers and concatenate strings.
one, two = 1, 2
three = one + two
four = "4"
seven = int(four) + three
print three
print seven
hello, world = "hello", "world"
hel... |
257bb9507e00ff99d9a75e813c1a015ad142bc46 | jwright0991/RedBlackTree | /RedBlackLeafNode.py | 345 | 3.765625 | 4 | #Black Null Nodes for bottom level of each path of a Red-Black Tree
#data is set to 0 so it will not be counted as odd
class BlackLeafNode:
def __init__(self):
self.isRed = False
self.data = None
self.isLeaf = True
self.isEvenSum = True
self.data = 0
def __str__(self):
... |
12c4e61cd18fa619c19005cc31cdca87f524c9b6 | Vestenar/PythonProjects | /venv/02_Codesignal/02_The Core/066_numberOfClans.py | 1,405 | 3.578125 | 4 | def numberOfClans(divisors, k):
divisors = list(set(divisors))
clans = {k: [] for k in range(1, k + 1)}
ans = []
for i in range(1, k+1):
for div in divisors:
if i % div == 0:
a = clans[i]
a.append(div)
clans[i] = a
for key, val in c... |
604064516088cd6084ffc7b2044d779234e8b5e6 | mrkienls/membership | /mem/test.py | 186 | 3.515625 | 4 | class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
def __str__(self):
return 'a {self.color} car'.format(self=self) |
0f57348d3102007047f8b0458213e3dbaae85a5e | Tang8560/Geeks | /python/bubble_sort.py | 2,072 | 4.125 | 4 | # 泡沫排序
"""
泡沫排序 (Bubble Sort) 想法是這樣的,假設要由小排到大,
左邊為小右邊為大,以左邊第一個為基準點,不斷的跟右邊的值比大小,
比較小的就往左,大的就停住,然後再從這個 礙事的 大的值繼續往右比。
如果到很不幸馬上就遇到更大的,再從更大的往右比,直到最後一個位置。
現在,已經比完第一輪了,接著再從最左邊的頭開始,往下比下去。
我們用比身高來舉例,分為 1 到 10 :
矮 ------------------------------------> 高
8 6 1 10 5 3 9 2 7 4
6 8 1 10 5 3 9 2 7 4
6 1 8 10 5 3 9 2 7 4
可惡,8 碰到 10 ... |
b3d46b19b964721bd8e5f3485b0b0af0122b9fcf | cryptkeypr/python100days | /bmi_calculator2-0.py | 728 | 4.375 | 4 | # 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#BMI = weight/(height**2)
bmi = int(round((weight/(height**2)),0))
if bmi <= 18.5:
print(f"Your BMI is {b... |
68ed39b7a878a791e757d2bcceba64ff1507ad98 | gakawarstone/python | /Head_First_Python/mymodules/vsearch/vsearch.py | 369 | 3.640625 | 4 | def search4vowels(phrase: str) -> set:
"""Return vowels pinned in aforementioned phrase."""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search4letters(phrase: str, letters: str = 'aeiou') -> set:
"""Return array of letters from 'letters',
pinned in aforementioned phrase."""
... |
8d69091e6cded850fa36b495489ba31378f1e3b3 | AndrewParisee/prog1700-cet-ap-master-python- | /tech-checks/Tech_Check3.py | 1,055 | 3.9375 | 4 | # PROG 1700 Tech Check #3 Variables, Operators, Inputs and Output
print ("Tax Withholding Calculator")
print ("")
# Define Variables
weekly_salary = int(input("Please enter the full amount of your weekly salary: $"))
dependants = int(input("How many dependants do you have?: "))
Provincial_Tax = 0.06
Federal_Tax = 0.25... |
8993550dd7cfc2c0dfd5ba07c58710084cfe9f92 | isisisisisitch/python10 | /ca/bytetube/02_processControl/05_Three.py | 135 | 3.53125 | 4 | #x if 条件 else y <===> if else
a = 1
b = 2
d = 10
e = 100
c = a if a > b else b
c = (d if d > e else e) if a < b else b
print(c) |
66b2bc1d905b2b94293e9816f8932f3f623fd78d | isabelsedunko/learn-python | /16_Fibonacci.py | 335 | 3.796875 | 4 | bakery_cache = {}
def carrotcake(n):
if n in bakery_cache:
return bakery_cache[n]
if n == 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = carrotcake(n-1) + carrotcake(n-2)
bakery_cache[n]=value
return value
for n in range(1,101):
print(n,":", carrot... |
26245981248246b9ed362b58addd4e04e9a26df8 | llenroc/LeetCode-28 | /Search/BFS/Abstract_BFS_problems/773_Sliding_Puzzle_hard.py | 3,222 | 3.6875 | 4 | # 这道题和127题word ladder是同一种类型的,即不是在一个matrix或者tree里进行bfs
# 而是每一个node都代表一种状态,127题里每个node是目前单词的拼写,
# 这道题里每个node是board经过这么多次swap以后到现在的排布
# 而这种问题中,两个node是否相连,就看第二个node是不是第一个node经过一次transformation之后就能得到的
# 127题里就是换一个字母能不能从第一个词到第二个词,如果能,那么两个词就是相连的nodes
# 这道题就是在第一种board的排布的基础上做一次0和邻居的swap能不能得到第二种board的排布,如果能,那么
# 这两种board排布的形态就是... |
e8cde086b998ea440b0a06f96f05104ea9397d83 | tnakaicode/jburkardt-python | /prob/runs.py | 8,721 | 3.90625 | 4 | #! /usr/bin/env python
#
def runs_mean ( m, n ):
#*****************************************************************************80
#
## RUNS_MEAN returns the mean of the Runs PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Bur... |
0333fa708c6724a3c379279f2eee381c79297b90 | s-debnath/code-combat | /leetcode/problem_268.py | 383 | 3.734375 | 4 | # 268. Missing Number
# Difficulty: Easy
# https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3659/
class Solution:
def missingNumber(self, nums: List[int]) -> int:
total_nums = len(nums)
expected_sum = (total_nums*(total_nums+1))//2
a... |
d5169a3f4e9fc8cbc2ec0e5e23bb14d169d49748 | gitprouser/LeetCode-3 | /ugly-number.py | 342 | 3.5 | 4 | class Solution(object):
def devide(self, o, d):
while o % d == 0:
o /= d
return o
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
ds = [2, 3, 5]
for d in ds:
num = self.devide(num, d)
return num == 1
... |
2b6cdc8af7dc8940140ce46e307b936836f5877e | Silentsoul04/FTSP_2020 | /MatPlotlib Forsk/PieChart_BarChart_Metplotlib.py | 2,874 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:09:21 2020
@author: Rajesh
"""
"""
Pie chart, where the slices will be ordered and plotted counter-clockwise:
"""
import matplotlib.pyplot as plt
labels = 'CSE', 'ECE', 'IT', 'EE'
sizes = [15, 30, 25, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue... |
75c5b02b5c08847610f561e41e16b84d47fe014a | ErisonSandro/Exercicios-Python | /exercicios/ex012- Calculando descontos.py | 278 | 3.59375 | 4 | #Faça um algoritmo que leia o preço de um produto e mostre seu novo preço
#com 5% de desconto
preço = float(input('Preço do produto? R$'))
desconto = (preço * 5) / 100
total = preço - desconto
print('O valor é {:.2f} e com desconto fica {:.2f}'.format(preço, total))
|
b921185e664cca5a8a129b253d9b71412de26600 | C-CCM-TC1028-111-2113/homework-1-LuisFernandoGonzalezCortes | /assignments/08Caracol/src/exercise.py | 216 | 3.671875 | 4 | def main():
#escribe tu código abajo de esta línea
t=float(input("Dar tiempo en minutos: "))
c = ((t * 60) * (.57))
print("Centimetros recorridos: ", c)
if __name__ == '__main__':
main()
|
a1595d473ed15493b9235b85bd90029b25759cde | jwplante/adventofcode2019 | /day5/part1.py | 5,655 | 3.75 | 4 |
class Computer:
def __init__(self, prog):
self.pc = 0 # Program Counter
self.prog = prog # Program Data
self.debug = False # Debug mode
self.paused = False # Will take in new instructions but will not execute
self.halted = False # Will stop the program
def ha... |
7d2ee3d9ccb97d6477f2556774b5437490ec5aef | prajapatisweta/python-program | /file_handling_1.py | 334 | 3.765625 | 4 | # write a program to read an entire text file
fobj = open("Batch2.txt", "w")
str_1 = "Welcome Batch 2! \nWe are working on Practical 6\nIt is based on File Handling concepts"
fobj.write(str_1)
print("Text Written to the file")
fobj = open("Batch2.txt", "r")
str_2 = fobj.read()
print("Concepts of File are:\n", str_2... |
573d7540b76abc73d1ce3f5f718a0d354bab2039 | simiyukuta/route_distance_checker | /sth.py | 1,927 | 4 | 4 | track=['AB','BC','CD','DC','DE','AD','CE','EB','AE']
track_distance=[5,4,8,8,6,5,2,3,7]
route=raw_input('Enter a route\n')
route_length=len(route)
def check_route_existence(route):
if route in track:
state='Route exists\n'
return state
else:
state='NO SUCH ROUTE\n'
return state
def process_formula(rout... |
900bc6284475b9776734a2bacdc4f831cfcb350f | Hareharan6707/sdet | /python/Activity5.py | 112 | 3.8125 | 4 | n = input("Enter a number : ")
for i in range(1,11) :
num = int(n) * i
print( n , "*" , i, "=" , num) |
4025d8ebe6fc746c94e59d9c7661185922955e98 | alvarogomezmu/dam | /SistemasGestion/Python/2ev/Actividad1/Ejercicio03.py | 597 | 3.734375 | 4 | #_*_coding_utf-8_*_
'''
Escribe una funcion sumador(fichero) que, dado el nombre de un
fichero te texto que contiene numeros separados por espacios
en blanco, devuelva la suma de dichos numeros
'''
import os
def comprobarFichero(f) :
if (f, os.W_OK) :
print 'Fichero OK, Escritura OK'
elif (f, os.R_OK) :
print ... |
7683b7eb8867d7de8f00d4801d52eb608bf7d7b2 | ajdt/udacity_cs212 | /unit7/parking_lot_search.py | 13,170 | 3.59375 | 4 | """
UNIT 4: Search
Your task is to maneuver a car in a crowded parking lot. This is a kind of
puzzle, which can be represented with a diagram like this:
| | | | | | | |
| G G . . . Y |
| P . . B . Y |
| P * * B . Y @
| P . . B . . |
| O . . . A A |
| O . S S S . |
| | | | | | | |
A '|' represents a wall around the p... |
0eae839ff0ca6b3fd016dfc4dda4692c19e333fe | d0iasm/CtCI | /Chapter02/07_find_intersection.py | 2,027 | 3.625 | 4 | import unittest
from LinkedList import LinkedList, Node
def get_length_and_tail(ll):
n = ll.head
count = 0
if n is None:
return None, count
while n.next:
count += 1
n = n.next
return n, count
def find_intersection(ll1, ll2):
t1, c1 = get_length_and_tail(ll1)
t2, ... |
a2af7626ed6c73afb95b5af9d0726c23ca8d7d10 | TebelloX/Screw-pilot | /python3/even't.py | 158 | 3.703125 | 4 | # Checks if a number is even
import random
def even(num):
try:
return [True,False][num%2] if not random.randint(0, 9) else bool(random.randint(0, 1))
|
5ae06265c8b743941c753896030b6dccb5ac6ec3 | Karan-hash/Python_Questions_Hackerrank_Solutions | /Maximum_sum.py | 557 | 3.5625 | 4 | from itertools import product
n, k = map(int, input().split())
N = (list(map(int, input().split()))[1:] for _ in range(n))
results = map(lambda x: sum(i**2 for i in x)%k, product(*N))
print(max(results))
'''
*N goes through all the values of N. So we can write "*N" instead of "N[0],N[1],...,N[K-1]"
N is differ... |
6a19f41d1abf5d14ea260870f2e35739bf9cc0f4 | gadlakha/Binary-Search-2 | /Problem2.py | 1,049 | 3.8125 | 4 | #Problem 2:(https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
#Time Complexity-O(log n)
#Space Complexity-O(n)
#Test Cases passed on Leetcode
#Binary Search Used
class Solution:
def findMin(self, nums):
low=0
high=len(nums)-1
while low<=high:
mid=low+(high-low... |
4c6e820400a82c04fd4499b53e709a35d42d198d | conniec-dev/thinkpython_practices | /chapter17/last_ex_2.py | 1,373 | 4.25 | 4 | class Kangaroo:
"""A Kangaroo is a marsupial."""
def __init__(self, name, contents=None):
"""Initialize the pouch contents.
name: string
contents: initial pouch contents.
"""
# In this version, the default value is None. When
# __init__ runs, it checks the value... |
84fee7978474a2294c5bbfd764802459f54c180d | GuilhermeMenez/Caixa-Registradora | /Caixa_Registradora.py | 689 | 3.65625 | 4 | from functools import reduce
precos = []
inicio = 1
def soma(x, y):
return x + y
def caixa_registradira():
valor_final = reduce(soma, precos)
print(valor_final)
valor_recebido = int(input("digite o valor pago pelo cliente\n"))
troco = valor_final - valor_recebido
print(troco)
receber_pr... |
62915d6e84bc6598c8a2a4cdcbf21f015da44cba | betta-cyber/leetcode | /python/206-reverse-linked-list.py | 1,080 | 3.96875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
... |
3026072d28d1ab702b836637bd88baf155087bca | YiyingW/Individual_Programs | /cluster_algorithms/kruskal.py | 3,172 | 4.34375 | 4 |
class Weighted_graph:
"""
Implement a weighted graph with a 2d list and a corresponding weight list
Vertices are represented by elements (eg. 1,2,3) in the graph list and edges are represented by a list collection of
each 2 vertices (eg. [1,2])
"""
edges = []
weight = []
vertices = []
def __init__(self, ed... |
4866476e5433cebeb86bba509864f61415c8ea6f | Forgotten-Forever/Sword-finger-offer | /ReverseList.py | 1,123 | 4.15625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: forgotten_liu
@projectName: python_study
@file: ReverseList
@time: 2020/12/29 20:04
@IDE: PyCharm
@desc: 反转链表
输入一个链表,反转链表后,输出新链表的表头
输入
{1,2,3}
返回值
{3,2,1}
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 方法一
class... |
cb4a2043b0c57050666df8628f68acab29e67c62 | cloudsecuritylabs/pythonclassaug2021 | /datatypes-class2/13.stringmanupulation.py | 334 | 3.515625 | 4 | # string concatenation
# first_name + last_name
my_string = "Best students ever!"
print(my_string[0])
print(my_string[0:4])
print(my_string[-1])
print(my_string[4:])
splitted = my_string.split(" ")
print(f'here we go :{splitted[0]}')
is_true = (18.0 == 18.0001)
print(is_true)
is_true = (18.0 == 18.0000000000000000... |
2673480a24a1879c2a38df31c2c0683424a04348 | vsdrun/lc_public | /co_twitter/217_Contains_Duplicate.py | 971 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/contains-duplicate/description/
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least
twice in the array,
and it should return false if every element is dis... |
494b9016a2abbec33f78672dd556e703034237a3 | misbaa/python-assignments | /Day2-assign/Q3.py | 671 | 3.640625 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
#Question-3
>>> dict = {"brand" :"Ford","model":"Mustang","year":1964}
>>> x=dict.get("brand")
>>> print(x)
Ford
>>> y=dict.keys()
>>> print(y)
d... |
069c5a2be8ee849ba50697344977e7ca1b709514 | thiago5171/python. | /exercicios/ex040.py | 922 | 3.828125 | 4 | """Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa,
mostre: a média de idade do grupo,
qual é o nome do homem mais velho e
quantas mulheres têm menos de 20 anos.
"""
vinte= 0
maior = 0
maiorn = ""
somaidade = 0
for i in range(1,5):
nome = str(input("digite o nome da {}°pes... |
877a24dbce31099cd3ba89ad41d3a15f461b3d00 | ls-2018/Django_Practice | /others/python从菜鸟到高手/第二章/进一步控制字符串格式参数.py | 1,043 | 3.84375 | 4 | print("{first!s} {first!r} {first!a}".format(first='中'))
"""
字符串
!s 原样输出
!r 调用repr
!a 输出Unicode编码
:f 将十进制数格式化为浮点数, nan\inf 转换为小写
:F 将十进制数格式化为浮点数, nan\inf 转换为大写
c 将一个整数解释为ASCII
!b 十进制数转二进制数
d 将整数格式转换为十进制数
e 将十进制数转换为科学计数法
E 将十进制数转换为科学计数法
:o 将十进制数转换为八进制数
g 根据整数的范围在浮点数和科学计数法之间
G ... |
8ffd09f2d1cacb933d418e5b646169b6ef722063 | Nymrinae/EPITECH-Projects | /Mathematics/200/201yams/combinaisons.py | 1,105 | 3.671875 | 4 | import sys
from maths import *
def buildDicesList(list):
for i in range(1, 6):
list.append(int(sys.argv[i]))
return (list)
def full(dices, a, b):
a = int(a)
b = int(b)
v_a = dices.count(a)
v_b = dices.count(b)
if (v_a == 3 and v_b == 2):
res = 100
else:
if (v_a ... |
494cc6616e60c1be17b8c18307df4edabfa1cdf2 | Kalyvan420/Inf | /ТЯП/Lab2/23.py | 548 | 3.765625 | 4 | N = int(input('Введите кол-во элементов списка(больше 10): '))
sp = []
if N > 10:
for i in range (0, N):
sp.append(int(input('Введите ' + str(i+1) +' элемент списка: ')))
print(sp)
for i in range (5):
sp.append(int(input('Введите новый элемент списка ' + str(i+1) + ': ')))
print(... |
6ee36f6e0496f27988cdd00c2a2013c74931aa7a | issashu/Code-Academy | /Python/20210509/main.py | 323 | 3.9375 | 4 | class EvenOnly(list):
def append(self, integer):
if not isinstance(integer, int):
print("Only integers can be added")
if integer % 2:
print("Only even numbers is recommended to be added")
super().append(integer)
instance = EvenOnly()
instance.append(64)
print(instan... |
0931ce2c3bcd9d0a70417e79d61404ace2f0d41d | AdityaShidlyali/Python | /Learn_Python/Chapter_10/1_intro_dictionary_comprehension.py | 399 | 4.53125 | 5 | # to generate the following dictionary
# {1:1, 2:4, 3:9}
square = {num : num**2 for num in range(1, 5)}
print(square)
# to print the strings as well in the dictionary comprehension is :
square = {f"Square is {num} is {num**2}" for num in range(1, 5)}
print(square)
# word counter using dictionary comprehension :
name... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.