blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3a006077064739b1922593aa0ac6ca11767f1994 | mackhack321/python | /tommyUnitConv.py | 310 | 4.15625 | 4 | unit = input("Millimeter or Centimeter? m or c\n")
amt = float(input("Give the measurement.\n"))
if unit == "m":
inch = float((1/25.4)*amt)
print("{} millimeters is {} inches.".format(amt,inch))
if unit == "c":
inch = float((1/2.54)*amt)
print("{} centimeters is {} inches.".format(amt,inch))
|
1066d8cc2f5406ca7b8ec33d053955188408d53e | Chris0935/udacity | /功課4.py | 93 | 3.5 | 4 | for i in range (1, 6):
for j in range (1, i + 1):
print(j,end = " ")
print()
|
1b8c3ad304c9478daf208505eed345b9d69f430b | rickblanco3/exercism.io-python | /bob/bob.py | 345 | 3.59375 | 4 | import re
def hey(sentence):
response = "Whatever."
if re.search("[A-Z]+",sentence) and not re.search("[a-z]",sentence):
response = "Whoa, chill out!"
elif re.search("\?\s*$", sentence):
response = "Sure."
elif re.search("^\s*$", sentence):
response = "Fine. Be that way!"... |
cb857696e47cc084d901fbef7a06db7e78dc1dfb | vrampal/codingame-public | /python/src/training/easy/temperatures.py | 579 | 3.765625 | 4 | from sys import stderr
def main():
temper_count: int = int(input()) # the number of temperatures to analyse
best_temper: int = 0
smallest_norm: int = 999999
for temper_str in input().split():
# t: a temperature expressed as an integer ranging from -273 to 5526
temper: int = int(tempe... |
337780136601f35e91b216115e0e5708c644ac85 | touhiduzzaman-tuhin/python-code-university-life | /Telusko/6.py | 185 | 3.59375 | 4 | tpl = (1, 2, 3, 4, 5)
print(tpl)
print(tpl[0])
print(tpl[4])
print(tpl[-1])
print(tpl[-5])
print(tpl[2:])
print(tpl[:3])
s = {5, 7, 3, 4, 1}
print(s)
s = {5, 7, 9, 2, 5}
print(s)
|
19e43a4fcce8f486ee9b673c6fa9c15d8d05ea1b | Riezzie/Pi-zzaBot | /UI/RC/flask_show_events_v3.py | 3,163 | 3.53125 | 4 | # imports are program code that is needed to run your program
from flask import Flask, render_template # to run Flask
import datetime
import os # needed to check if events file exists
'''
Source file: flask_show_events_v1.py
Start: sudo flask_show_events_v1.py
(v1) This code starts a Flask webserver. The user can re... |
1f1534852a9db2607c992b78f5f809ec4e1e99fa | ctc316/algorithm-python | /Lintcode/G_Practice/Tag_Hash/1225. Island Perimeter.py | 706 | 3.59375 | 4 | class Solution:
"""
@param grid: a 2D array
@return: the perimeter of the island
"""
def islandPerimeter(self, grid):
if not grid or len(grid) == 0 or len(grid[0]) == 0:
return 0
n = len(grid)
m = len(grid[0])
perimeter = 0
for i in range(n):
... |
07b98d2942551ded27e857d143270f7fa23e1000 | kwasnydam/python_exercises | /CodeWarsKata/IQtest/iqtest.py | 1,313 | 4.4375 | 4 | '''
Bob is preparing to pass IQ test.
The most frequent task in this test is to find out which one of the given
numbers differs from the others.
Bob observed that one number usually differs from the others in evenness.
Help Bob — to check his answers, he needs a program that among the given numbers
finds one that is di... |
04990a91f2e907188696e5e23d4c32f060e47d0e | MaximFirsoff/infa_2020_Titov | /lab1/ex1.py | 182 | 3.5625 | 4 | import numpy as np
import math
for i in range (3):
x = int(input())
z = np.e**(1/np.sin(x)+1)
a = 1.25 + (1/(x**15))
y = np.log(z/a) / (np.log(1 + x**2))
print(y, ' for ' , x) |
47240c8884c2c9702919a16f2cd84d1cdca5c43e | christopher-burke/python-scripts | /cb_scripts/collatz_conjecture.py | 1,267 | 4.59375 | 5 | #!/usr/bin/env python3
"""Collatz Conjecture."""
import sys
def handle_even(n: int) -> int:
"""If n is even, divide it by 2.
returns int
"""
return n // 2
def handle_odd(n: int) -> int:
"""If n is odd, multiply it by 3 and add 1.
returns int
"""
return ((n * 3) + 1)
def collat... |
65c2311684dd5c702c8703a5a71058cd0efff0c7 | eliyanovva/elantris_game | /state_class_item.py | 3,665 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 8 08:29:15 2021
@author: Teodora
"""
# item_arr: food, book, clothes
# items are stored as bools in the Character class, each new state acts in a certain way to an object.
# add empty stuff / check if key exists in line 32
class Character:
"""
The... |
f7cacd36d9d19bd81f356ade7aef523875026226 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3/snv2/jamcoins.py | 1,514 | 3.71875 | 4 | __author__ = 'snv'
from random import randint
UPPER_LIMIT = 2000000 # до какого числа ищем простые
def get_primes(n):
""" Создание списка простых чисел меньших n
:param n: верхняя границаб до которой ищем простые числа
:return: отсортированный список простых чисе от 2 до n
"""
numbers ... |
0039c4165277448793fee006f8868fcfc5fc2a60 | turbo-moniak/ProjectEuler | /Problem_16.py | 436 | 4.03125 | 4 | # Power digit sum
# 2^15 = 32768 and the sum of its digis is 3 + 2 + 7 + 8 + 8 = 26.
# What is the sum of the digits of the number 2^1000?
from math import pow
def power_digit_sum():
power = 1000
base = 2
power_result = int(pow(base, power))
sum_of_digits = 0
for i in range(len(str(power_result... |
98807d7a11a4aa02d7eaa56fea26e99b6d16a944 | osamamohamedsoliman/Competitive-Coding-9 | /Problem-2.py | 1,400 | 4.03125 | 4 | # Time Complexity :O(1)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
class PeekingIterator(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
... |
7a3dfe75eaacaeb23698c889014cf2cd1b46d414 | Aasthaengg/IBMdataset | /Python_codes/p02843/s450136978.py | 84 | 3.6875 | 4 | N = int(input())
x = N // 100
y = N % 100
if y <= 5 * x:
print(1)
else:
print(0) |
33218faaa5217b7e3bbded00eccb01275145ef69 | xerces/exercise-2 | /13prog.py | 202 | 3.578125 | 4 | def remove_item(l,s):
l.remove(s)
return l
food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print( remove_item(food_staff, 'Mango'))
numbers = [2, 3, 7, 9];
print(remove_item(numbers, 3)) |
658579ef31f8baeeef6e39d91404b8b0dd0b9560 | ilovejnote/PythonProgrammingTutorial | /Py_02_00_AdvancedFeatures.py | 391 | 3.671875 | 4 | # -*- coding: utf-8 -*-
# Advanced features for python
# If you master python's data type; statement; function; In basic you can write lots of usefull programmings.
# In class example :
L= []
n = 1
while n <= 99:
print(n)
L.append(n)
n = n + 2
# this is a 1,3,5,....99. List.
# But in python the code is the ... |
0d05ac48caa3be87329131023325ca12fa3f633f | Adi0704/Team-Titan | /Feedback.py | 542 | 3.859375 | 4 | def feedback():
print("We hope you have got all the required information that you were looking for.\n\n")
c=int(input("We would love to hear some feedback from you..Please rate our following project from 1-5: "))
if c<3:
print("\n\nWe regret the inconvenience caused ..We will look to make the re... |
82227eae94d6d8dd20b09ebaf0433ce0bece8cd7 | dzolotusky/advent-of-code | /2015/8/8.2.py | 540 | 3.5 | 4 | with open("input8.txt") as f:
content = f.readlines()
total_chars = 0
total_encoded_chars = 0
for cur_line in content:
cur_line = cur_line.strip()
total_chars = total_chars + len(cur_line)
encoded_chars = len(cur_line) + 2
encoded_chars = encoded_chars + cur_line.count("\\") + cur_line.count("\"")... |
ea45b314c6fb8f11f960068c29c1a29f03886ae6 | Kireetinayak/Python_programs | /Programs/Basic_Programs/Sum of squares of first n natural numbers.py | 115 | 4 | 4 | num=int(input("Enter the number:"))
sum=0
for i in range(1,num+1):
if (i!=0):
sum=sum+i*i*i
print(sum)
|
0ed34809b02555c60f46e414d560cbfa9a82f64d | JerryHu1994/Linkedin-2019-OA | /bit_count.py | 221 | 3.765625 | 4 | def bitcount(arr):
pairs = []
for num in arr:
count = bin(num)[2:].count("1")
pairs.append((num, count))
pairs = sorted(pairs, key = lambda x: [x[1], x[0]])
return [p[0] for p in pairs]
print bitcount([3,2,4,5,3]) |
e7581ae817a1d113d7321226d9428177fac90cb8 | RishabhK88/PythonPrograms | /5. DataStructures/MapFunction.py | 562 | 4.71875 | 5 | # Map function is used to get a new list of elements from original list
items = [
("Product1", "10"),
("Product2", "9"),
("Product3", "12")
]
prices = []
for item in items:
prices.append(item[1])
print(prices)
# The above can also be done elegantly with map function as follows
x = map(l... |
34966b64a827740657952e37fb40ca35902f1929 | yangzongwu/leetcode | /20200215Python-China/0896. Monotonic Array.py | 1,078 | 3.859375 | 4 | '''
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Outpu... |
7fdc92ca5393386f2e4691bbcca56df332a476a8 | uxlsl/leetcode_practice | /longest-palindromic-substring/solution.py | 717 | 3.609375 | 4 | # leetcode
# https://leetcode-cn.com/problems/longest-palindromic-substring/
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
def pal(s, i,j,r):
"""
返回回文
"""
while 0<=i<len(s) and 0<=j<le... |
4d23187029c89a66fa00f67be01b33c7c1424f17 | samueleagan/Programming-Contest | /SevenWonders.py | 444 | 3.5 | 4 | userInput = input()
cards = []
score = 0
bonusScore = 0
for i in userInput:
cards.append(i)
for i in cards:
if i == 'T':
score += 1
elif i == 'C':
score += 1
elif i == 'G':
score += 1
if "TCG" in userInput or "GCT" in userInput or "CGT" in userInput or "TGC" in userIn... |
df08953ddb65b29e39cb50754e45d7c2c4c4880f | Pu-Blic/PruebasPython | /Excepciones_I.py | 1,261 | 4.125 | 4 | def Sumar(a,b):
return int(a)+int(b)
def Restar(a,b):
return int(a)-int(b)
def Multiplicar(a,b):
return int(a)*int(b)
def Dividir(a,b):
try:
return int(a)/int(b)
except ZeroDivisionError2:
print("No se puede dividir entre 0. Operación errónea")
except:
print("Error al ... |
73f5b207d80aa7874e16972e1f339c1e23523330 | rafaelperazzo/programacao-web | /moodledata/vpl_data/38/usersdata/74/15376/submittedfiles/decimal2bin.py | 341 | 3.703125 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
n = input('Digite o numero binario: ')
j = 10
cont = 0
d = n
while n>=2:
if n>=j:
cont = cont+1
n = n/j
dec = 2**cont
d = d-j
j = 10
cont = 0
if d>=10:
while d>=2:
if d>=j:
cont = cont+1
d = d/j
else:
dec = de... |
2e4ec5c25fc14d3a5b3aa22f8bf29771ba4ddc40 | anuragmukherjee2001/test | /Python Assignment 8/Duplicate_keys.py | 505 | 4.03125 | 4 | def duplicate_present(dict1, key):
if key in dict1.keys():
return True
else:
return False
dict1 = {}
key = ''
n = int(input("Enter the number of elements: "))
for i in range(n):
key = int(input("Enter the key "))
value = int(input("Enter the value"))
dict1[key] = value
key = int... |
124732da564ef970d566d3e44a849900aff31a94 | SujanMaga/Python-prac-for-ref. | /test/Basic/prac4_string.py | 206 | 3.6875 | 4 | letter = "Dear Sujan, This python course is awesome. Thanks!"
print(letter)
formatted_letter = "Dear Sujan,\n\tThis python course is awesome.\nThanks!"
print(formatted_letter)
# Escape squences charactere |
674ce5ec5ba11481b0b825a22202955b7e4d0883 | kangshuaibo/My-Python-Learn | /chapter15/15.2.4绘制一系列点.py | 563 | 3.625 | 4 | #coding=utf-8
#使用scatter()绘制一系列点
import matplotlib.pyplot as plt
x_value = [1,2,3,4,5]
y_value = [1,4,9,16,25]
plt.scatter(x_value,y_value,s=100)
#设置图表标题并给坐标轴指定标签
plt.title("Square Numbers",fontsize=24)
plt.xlabel("Value",fontsize=14)
plt.ylabel("Square of value",fontsize=14)
#设置刻度标记的大小
plt.tick_params(axis='both'... |
04e494143ce9ff778dce511307c7e86648ae9156 | gitcheol/MyGit | /Algorithms/python/7785.py | 332 | 3.796875 | 4 | import sys
n = int(input())
employees = set()
for i in range(n):
name, status = sys.stdin.readline().split()
if status == 'enter':
employees.add(name)
elif status == 'leave':
employees.remove(name)
list_employees = list(employees)
list_employees.sort(reverse=True)
print('\n'.join(list_... |
b90f01753f248cc9175117428b9c983c2cb731b0 | 1lch2/PythonExercise | /leetcode/string/151.py | 1,182 | 4.0625 | 4 | # 给定一个字符串,逐个翻转字符串中的每个单词。
# 示例 1:
# 输入: "the sky is blue"
# 输出: "blue is sky the"
# 示例 2:
# 输入: " hello world! "
# 输出: "world! hello"
# 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
# 示例 3:
# 输入: "a good example"
# 输出: "example good a"
# 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
# 说明:
# 无空格字符构成一个单词。
# 输入字符串可以在前面或者后面包含多余的空格... |
cec68568f871c87794f47f62c6520a2855d12d88 | rsln-s/SMMailCoreKit | /Carthage/Checkouts/MailCore/Scripts/BuildScripts/projectutils.py | 1,078 | 4.03125 | 4 | import os, fnmatch, glob, re
def expandArchive(directory, archiveName):
""" Given a directory, it will try and find an archive that
has name that begins with archiveName and will then expand it """
for path, subdirs, files in os.walk(directory):
for filename in files:
pattern = archiveName+"*.tar.gz"
if(f... |
22c0ea1e2f5c94a02c6b8a57c5167f226b37cb10 | vignek/CodePractice | /Interview-Practice/Python-Solutions/Basics/Basic_Swap.py | 455 | 4 | 4 | """
Basic 25 Programming Questions warm up
"""
"""
Swap 2 Numbers
"""
num1 = 1
num2 = 10
num1,num2 = num2,num1
print(num1)
print(num2)
print('-------------------------------')
a_list = list(range(1,101))
a_list[0],a_list[-1] = a_list[-1],a_list[0]
print(a_list)
print('-------------------------------')
b_list =... |
c88703da7c48db80b632f731d6ff857d6ba80dbd | hardwindus/class1 | /dialogs-rep.py | 2,085 | 3.546875 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
import codecs
myFileTypes = [
("Text",".txt"),
("All type", "*")
]
currentFile = ""
def selectFile():
global currentFile
filepath = filedialog.askopenfilename(filetypes=myFileTypes)
# messagebox.showinfo("Selected... |
51a6bc89007e84092c1ceddc9315e14ff11e9e9d | meatripoli/PythonSandbox | /reverse_list.py | 131 | 3.75 | 4 | def reverse_list(A):
y=len(A)
new_list=[]
for n in range(0,y):
new_list.append(A[(y-1)-n])
return new_list
|
4d3cb248653f5600ebffb484cbd5c5028e1dced3 | fyzx92/Python-Projects | /Projects/NN_dense.py | 3,825 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
NN From scratch
"""
import numpy as np
# initialize
def __init__(input_size, layer_sizes):
"""
Create arrays of weights and biases for each layer
Parameters
----------
input_size : TYPE
DESCRIPTION.
layer_sizes : TYPE
DESCRIPTION.
Returns... |
914248ec03e3e36e587935f9463964cc60d03f6a | Droxef/ML2017 | /rendu/build_polynomial.py | 924 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""implement a polynomial basis function."""
import numpy as np
def build_poly(tx,degree):
"""
polynomial basis function up to degree
"""
poly = np.ones((len(tx), 1))
for deg in range(1, degree+1):
poly = np.c_[poly, np.power(tx, deg)]
return poly
def buil... |
eee72bcd7b171d221d7f1ecc169e89743fbf4868 | hongdaepyo/eduPython | /codingProb/problem1.py | 196 | 3.796875 | 4 | # multiples of 3 and 5 // https://projecteuler.net/problem=1
def getSum():
sum = 0
for x in range(1000):
if x % 3 == 0 or x % 5 == 0:
sum += x
return sum
getSum() |
dc3e3d8e206646bd9883ed028abdc112f09b5f11 | athletejuan/TIL | /Algorithm/BOJ/5554.py | 88 | 3.53125 | 4 | total = 0
for _ in range(4):
total += int(input())
print(total//60)
print(total%60) |
e70faa0ca4e2f2d56aa01de7e44170f0a8f899f8 | j-217/python | /codewars/57_RGB_to_hex_conversion.py | 283 | 3.6875 | 4 | def rgb(r, g, b):
def check(x):
# if x < 0:
# return 0
# elif x > 255:
# return 255
# return x
return 0 if x < 0 else 255 if x > 255 else x
print('{:0>2X}{:0>2X}{:0>2X}'.format(check(r), check(g), check(b)))
rgb(1,2,3) |
da4e38e05f80762afda153dd1735ab1b0b5c901f | COOLIRON2311/normalg | /src/Substitution.py | 922 | 3.625 | 4 | from .Entry import Entry, Word
class Substitution:
pair: 'list[Word]'
final: bool
def __init__(self, value: str, sep: str = ' ') -> None:
self.final = '.' in value
self.pair = []
for i in value.split(sep):
self.pair.append(Word(i.strip(' .')))
if len(self.pair)... |
29469adeccc0923dd2c4d5733c7060b9d29e1b56 | flbdx/AoC_2019 | /day_06.py | 2,400 | 3.546875 | 4 | #!/usr/bin/python3
#encoding: UTF-8
import fileinput
import sys
if len(sys.argv) == 1:
sys.argv += ["input_06"]
class Object(object):
def __init__(self, name):
self.name = name
self.center = None
def set_orbit(self, obj):
self.center = obj
def get_orbit(self):
return s... |
171c2c4f3f5f1e46f1f62a8de8445129ce45a79f | mottledZebra/Exercises | /Python/The for loop/The sum of the factorials.py | 823 | 3.921875 | 4 | # По данному натуральном n вычислите сумму 1!+2!+3!+...+n!.
# В решении этой задачи можно использовать только один цикл.
# Пользоваться математической библиотекой math в этой задаче запрещено.
# For the given natural n calculate the sum 1!+2!+3!+...+n!.
# In this task, you can only use one cycle.
# To use the math li... |
16702840aacb9850a01a433054d97929eb1d8698 | chantigit/pythonbatch1_june2021data | /Python_9to10_June21Apps/project1/listapps/ex10.py | 150 | 3.703125 | 4 | listA=[]
listA=listA+[10,20,30,40,50]
print(listA*3)
print(listA[1]) #20
print(listA[-3])#30
print(listA)
listA[0:4]= [11 ,22,33,44,55]
print(listA) |
6e49369c17ae8cf4b445728c30acca90907ce944 | Mazumsad/Python-Programs | /Hash_Table_Class.py | 2,375 | 3.546875 | 4 | """
A hash table (dictionary) class that uses
linear probing to make sure no collisions occur.
Author: Oscar A. Nieves
Updated: August 9, 2021
"""
class HashTable:
def __init__(self,MAX=10):
self.MAX = MAX
self.arr = [None for i in range(self.MAX)]
self.keys = [ [], [] ]
def get_hash(s... |
ecfe537d81d960b5f007893c8c5889491779359e | StyLishPoor/python-practice | /2.py | 2,411 | 3.53125 | 4 | from operator import itemgetter
def CelebrityCount(time):
arrive_celeb = []
maxcount = 0
best_time = time[0][0]
for i,c in enumerate(time):
arrive_celeb.append(i)
for j in arrive_celeb:
if(c[0] >= time[j][1]):
#帰った有名人を削除
arrive_celeb.remove(j)... |
e06d4389563d924b718f6b6ea31b76fd59269488 | timpark0807/self-taught-swe | /Algorithms/InsertionSort.py | 430 | 4.1875 | 4 | def insertion_sort(arr):
"""
Basic Insertion Sort
Time : O(n^2)
Space : O(1)
"""
for index in range(1,len(arr)):
current_value = arr[index]
compare_index = index-1
while compare_index >= 0 and current_value < arr[compare_index]:
arr[compare_index + 1] = arr... |
8df245c5c4de0f7655fffcb29496f491630b6980 | kz/compsci-homework | /1. AS Level/5. Encryption Exercise/Task 1.py | 2,046 | 4.75 | 5 | # Task 1
# Author: Kelvin Zhang
# Date Created: 2016-03-22
# This program takes in a word and makes it uppercase (e.g., "computing" -> "COMPUTING". It then takes in a keyword.
# An encrypted message is generated by adding the alphabet value of the message to the value of the keyword.
# If the word is longer than the ke... |
81fdf47c0cd9af4fcc58cf852fc061018aada9b6 | Roozbeh-web/darage2 | /app.py | 1,793 | 3.65625 | 4 | from flask import Flask, render_template, request
import math
app = Flask(__name__)
@app.route("/")
def index():
# first_number = float(input("Enter first number: "))
# second_number = float(input("Enter second number: "))
# third_number = float(input("Enter third number: "))
#
# if(delta < 0)... |
9d0c8408c38d042a51961eabc00d5c81cb171b98 | sumedh105/Python-Programs | /GeeksForGeeks/Operators/anyAllOperator.py | 452 | 3.84375 | 4 | # Usage of any operator in Python
print(any([False, False, False, False]))
# Usage of any operator in Python
print(any([False, True, False, False]))
# Usage of any operator in Python
print(any([True, False, False, False]))
print()
# Usage of all operator in Python
print(all([True, True, True, True]))
# Usage of al... |
ff040a33861ee3bde747d2a862df49d51b52f39f | heron2014/Learning_Python_The_Hard_Way | /ex20_functions_and_files.py | 1,351 | 4.28125 | 4 | from sys import argv
script, input_file = argv
#f = current_file = input_file
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
#this function takes ... |
bc98f7142d565d2ae272698b052eb1c61016453d | shubhamjante/python-fundamental-questions | /Programming Fundamentals using Python - Part 02/Assignment Set - 07/Assignment on list APIs - Level 3 (puzzle).py | 1,726 | 4.1875 | 4 | """
Use Luhn algorithm to validate a credit card number.
A credit card number has 16 digits, the last digit being the check digit. A credit card number can be validated
using Luhn algorithm as follows:
Step 1a: From the second last digit (inclusive), double the value of every second digit.
Suppose the credit card num... |
82c9d2c2a58669a292e3a8d45d63c2d66e36904c | OleksandrLozinskyy/Hillel_Python_Lessons | /Lesson7/word_weight_in_some_strings.py | 3,157 | 3.828125 | 4 | """
1. Дан текст состоящий из нескольких строк. Выведите слово, которое в этом
тексте встречается чаще всего. Если таких слов несколько, выведите последнее.
Задачу необходимо решить с использованием словаря.
Данная задача - частный случай предыдущей. Так как input() в Python не позволяет получить
о... |
f9a85aee28f569c22a9ff6842a592b2f3e6c3fac | nmaue/number-converter | /number_program_input.py | 3,038 | 3.921875 | 4 | def word_to_number(word):
if word == 'one':
return(1)
elif word == 'two':
return(2)
elif word == 'three':
return(3)
elif word == 'four':
return(4)
elif word == 'five':
return(5)
elif word == 'six':
return(6)
elif word == 'seven':
return... |
26898b7ec5848cd2944831d86b1dac044eeea409 | anis-byanjankar/python-leetcode | /contains_duplicate.py | 1,377 | 3.78125 | 4 | # https://leetcode.com/problems/contains-duplicate/
# 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 distinct.
# has_key() vs in : http://stackoverflow.com/questi... |
bef9e0688646e70be526bb66edd839e5a7df6e26 | Graziele-Rodrigues/100-exercicios-resolvidos-em-python | /19_SorteioNomes.py | 213 | 3.546875 | 4 | # leia 4 nomes e sorteie um #
import random
n1 = input('')
n2 = input('')
n3 = input('')
n4 = input('')
lista = [n1, n2, n3, n4]
escolhido = random.choice(lista)
print('O aluno escolhido foi {}'.format(escolhido)) |
63af0c400f99f51ae8c353a97cf12065416df972 | martin-martin/python-crashcourse | /02_25_mon/contains.py | 357 | 4.0625 | 4 | locations = ["indonesia", "spain", "thailand", "mexico", "usa"]
# membership operators
# in
# not in
print('bali' not in locations)
my_list = [1, 2, 3, 5, 42]
even = []
for num in my_list:
if num % 2 == 0:
even.append(num)
print(even)
not_even = []
for num in my_list:
if num not in even:
n... |
e55dc7c8a4d710ddd18626ce7bce96a2d4f9f98f | DishaCoder/Data-Structures-in-Python | /stack_by_ll_op.py | 1,148 | 4.125 | 4 | # Stack implementation using linked list
class node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self, head = None):
self.head = head
def traverse(self):
current = self.head
while current.next:
print(current... |
45a723d96e9a1059649f125b02f92b530ad87fac | elenamoglan/Tipul-de-date-String | /Problema3_String.py | 290 | 3.71875 | 4 | cuvant1=str(input('Introduceti cuvintul 1: '))
cuvant2=str(input('Introduceti cuvintul 2: '))
cuvant3=str(input('Introduceti cuvintul 3: '))
cuvant4=str(input('Introduceti cuvintul 4: '))
fraza = cuvant1 + " " + cuvant2 + " " + cuvant3 + " " + cuvant4 + "."
print('Fraza este:', fraza) |
0b628f01b0672d6a4b8c4090d7244f307a5d695c | zzydshh/sql_class.py | /sql/sql_class.py | 12,922 | 3.671875 | 4 | #python数据库,函数class形式
#姓名:章宗扬
#日期:2021.5.17
import pymysql
import pandas as pd
class MySQLServer(object):
def __init__(self, host, port, user, password, database):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
def cre... |
24af935dfb0529169bd60acd8becc88e8720e42c | lfishRhungry/PythonStudy | /数据分析Pandas(实用主义学python)/幸福指数等级分析.py | 2,877 | 3.546875 | 4 | # 为幸福指数添加对应的等级
# pandas中的apply()函数 pandas中的cut()函数 透视表pd.pivot_tablt()深化 numpy表示正无限
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_path = 'C:\\Users\\shine小小昱\\Desktop\\data_pd\\happiness_report.csv'
save_path = 'C:\\Users\\shine小小昱\\Desktop\\'
def collect_data():
"""
... |
5a12c3ed53e4fce2dbfc4688ee6dd0ab49e10d2b | ivan77mi4x/HW | /HW_0602.py | 436 | 3.59375 | 4 |
#https://www.codewars.com/kata/5265326f5fda8eb1160004c8/train/python
def number_to_string(num):
return str(num)
#https://www.codewars.com/kata/57a55c8b72292d057b000594/train/python
def reverse(st):
spisok = st.split()
spisok.reverse()
return " ".join(spisok)
#https://www.codewars.com/kata/55225023e1b... |
b784e9c35b88013939b20718d636b07be05edace | ronshuvy/IntroToCS-Course-Projects | /Ex9 - Rush Hour/board.py | 4,863 | 4.21875 | 4 |
class Board:
"""
This class represents board in "rush-hour" game
"""
__ROW_SIZE = 7
__COL_SIZE = 7
__TARGET_LOC = (3, 7)
def __init__(self):
self.__board = [['_'] * self.__COL_SIZE for i in range(self.__ROW_SIZE)]
self.__cars = dict()
self.__car_in_target = None
... |
1f74711d0d389e96bb7dbf7a8b6855e422ce5868 | Josh551/Kamikaze | /rock.py | 1,763 | 4 | 4 | import random
comp=0
ply1=0
compcount=0
ply1count=0
L=("Rock","Scissor","Paper")
while(compcount<=5 and ply1count<=5):
comp=random.choice(L)
print("1.Rock 2.Scissor 3.Paper")
ply1=input("Enter your choice:")
if(comp==ply1):
print("Tie,No one wins this round")
elif(comp=="Rock" and ply1=... |
ec8b6edceb906b76dae4cbf5c92c78c940692cda | pandiyan07/python_2.x_tutorial_for_beginners_and_intermediate | /samples/conceptual_samples/remaining/executing_string_operation_module.py | 1,220 | 3.65625 | 4 | # this piece of python script is to get the string operation module imported and perform operations
# by using the functions that are defined inside that module and performing their specified operaitions in thid file
import string_operation_module
# ->" from string_operation_module import * "<- can also be writ... |
5696307308942ad10b5b17c590ba1f0753da10e6 | alexrrobbins/Challenge-Response-Simulator | /Server.py | 2,671 | 3.75 | 4 | # COSC 316-001 Assignment 1
# Written by Alex Robbins, 2019
# For educational purposes only.
from User import User
import re
import csv
import random
import hashlib
from zlib import crc32
class Server():
# First open password file and initilize an array (simulating a database)
def __init__(self):
fil... |
1dd15b9f822170005cee31e474e51ac22462b49f | dstorer2/Bank_Account | /associations.py | 3,275 | 3.84375 | 4 | class BankAccount:
all_accounts = []
def __init__(self, acct_name, int_rate = 0.02, balance = 0):
self.acct_name = acct_name
self.int_rate = int_rate
self.balance = balance
BankAccount.all_accounts.append(self)
def deposit(self, amount):
self.balance += amount
... |
50b969e5a6b6595ce48d55fe631bdf993d20b0de | Joshua-Benfell/ECEN321 | /Lab1/NormalDensity.py | 1,814 | 3.5625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# Ensure we are using tkinter for matplotlib
from scipy import special
# matplotlib.use("TkAgg")
N = 1000
mean = 2.5
variance = 16
sigma = variance ** 0.5
bins = 30
nums = sigma * np.random.randn(N) + mean
# Need Mean and Variance
sampleMean = np.mean(nums)
sampleVa... |
b60b10a0129a8e03db516d1e61ee2a1d5db03a99 | mhetrick29/COS429_Assignments | /A4_P2/logistic_backprop.py | 907 | 3.921875 | 4 | import numpy as np
def logistic_backprop(dLdy, y):
# Computes the partial derivative of the loss with respect to the input to
# the logistic function, given it with respect to the output.
#
# dLdy: a scalar double that is the partial derivative of the loss with
# respect to y, the output of the lo... |
0f3f20115603d11a1c7811301d4f433da4357145 | bigdata-i523/hid336 | /assignments/iterate.py | 604 | 4.28125 | 4 | """Usage:
iterate.py -n [NUM]
Arguments:
NUM Number to iterate
Options:
-h --help Shows these options
-n Specify the number to iterate
"""
from docopt import docopt
if __name__ == '__main__':
args = docopt(__doc__)
def iterate(n):
for i in range(1,n+1):
print(i)
... |
69eef85d325cfee2ed1a0625296c3f922fc11c5e | nukiska/solved_tasks | /big_n.py | 467 | 3.765625 | 4 | # Write a function that prints a text image of a capital letter N on (n) lines.
def big_n(n):
for i in range(n):
for j in range(n):
if i == 0 and j == n - 1:
print('|\\' + (n - 1) * ' ' + '|')
if 0 < i < (n - 1) and j == n - 1:
print('|' + i * ' ' + ... |
7c4c31f6f5844558da6d5a4a63373c4dfdae447f | aproulx232/Coding_Challenges | /longest_distinct_substring.py | 1,316 | 4.09375 | 4 | """Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb"."""
def sub_r(s, k):
def _sub_helper(s, k, m):
# print("string", s)
num_d... |
271694984dbdf95ef138b363e511e06405505618 | Raragyay/Snake | /snake/solver/path.py | 8,473 | 3.734375 | 4 | # coding=utf-8
"""
Definitions for PathSolver class, which is the path-finder for Greedy and Hamilton..
Exported methods in PathSolver are longest path to tail and shortest path to food.
"""
import random
import sys
from collections import deque
from snake.map import PointType, Direc
from snake.solver.base import Base... |
12cd64b6744467aa4ecf2737105e2cdbbc6004af | sawsuh/dotfiles | /desktop/.pok3rcolors.py | 293 | 3.75 | 4 | def color(hexstring):
hexlist = [hexstring[i:i+2] for i in range(0,6,2)]
red = round(int(hexlist[0],16)*6/255)
green = round(int(hexlist[1],16)*6/255)
blue = round(int(hexlist[2],16)*6/255)
print(red)
print(green)
print(blue)
colorcode = input("")
color(colorcode)
|
063006a182a074c86fb9a2720d7dd6285568604b | Delpire/daily-programmer | /Quicksort 8-25-2014/Quicksort.py | 602 | 3.78125 | 4 | from random import randint
def quicksort(array):
pivot = randint(0, len(array)-1)
S = []
G = []
for i in range(0, len(array)):
if i != pivot:
if array[i] < array[pivot]:
S.append(array[i])
else:
G.append(array[i])
if len(S) == 2:
if S[1] < S[0]:
S[0], S[1] = S[1], S[0]
elif len(S) > 1:
... |
1b0427634d5e3b9ac41cefbabf3323c6ef29e19f | jCrCaT/disaster_response | /data/process_data.py | 4,093 | 3.890625 | 4 | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''
DEF: Load data from csv file and merge the data from messages and categories
INPUT:
messages_filepath - Path where is the data related to messages on csv format... |
38781d742fed0862cecf31d4b0b847125fc2b872 | jeason15/Personal-Projects | /float_calculator.py | 2,256 | 4.15625 | 4 | ###################################
# float_calculator.py Joshua Eason
# 2/21/2019
# Calculates the binary values of
# floating point numbers using the
# IEEE 754-1985 Standard.
###################################
### Program still buggy with numbers less than 1 and greater than -1.
### Need to resolve issu... |
8d54ab8f1dc7d601e6d9de9013be9c771270c02e | UalwaysKnow/-offer | /offer/二叉树/二叉树镜像.py | 528 | 3.65625 | 4 | '''实质上是遍历问题'''
def method(root):
if root == None:
return False
stack = []
stack.append(root)
while stack:
currentNode = stack.pop(0)
currentNode.left,currentNode.right = currentNode.right,currentNode.left
if currentNode.right:
stack.append(currentNode.right)
if currentNode.left:
stack.append(current... |
823f234c2325c00013916f04ee0913df1d15e12a | onetotwothree/artificialStocks | /editse.py | 1,435 | 3.765625 | 4 | from datetime import datetime
import random
import os
import csv
import sqlite3
def main():
running = True
conn = sqlite3.connect('artificialStock.db', check_same_thread=False)
c = conn.cursor()
while running == True:
cmd = input("Enter command: ")
if cmd == 'delete':
... |
0fbe63dd21bd38166d7bcb9433a3e24ab104140a | CSJ0203/Python | /Downloads/으아악/pyhon/multistring.py | 3,199 | 3.84375 | 4 | #multistring.py
print("=" * 50)
print("My Program")
print("=" * 50)
a = "Apple is A Banna is B"
print(len(a))
print(a[4])
a = "Apple is A Banna is B Cheese is C Delete is D"
print(a[3])
print(a[7])
print(a[-2])
print(a[-1])
print(a[0]+a[1]+a[2]+a[3]+a[4])
print(a[0:5])
a = "20010331Rainy"
year = a[:4]
date = a[4:8]
... |
6a95d2c1bbc854189277893bbb50f970ff8ec4d3 | shivansh-max/Algos | /Arrays/Medium/MonotonicArray.py | 1,121 | 3.75 | 4 | class MonotonicArray:
def __init__(self):
pass
def check(self, array):
print(f"Array : {array}")
print(f"Monotonic : {self.checkHelper(array)}")
def checkHelper(self, array):
if len(array) < 1:
return True
status = True
asscending = self.firstCh... |
e28fbddfc2b9230e21d7764b87dd7a2e7fcac802 | BriskyGates/Epiphany- | /quicksort.py | 929 | 3.984375 | 4 |
list_before=[2,4,9,3,4,5,2,1,5,6,4,2,7,8,6,0]
def quickSort1(list_before):
if len(list_before)<2:
return list_before
midprivot=list_before[len(list_before)//2] # 以中间元素作为基准
left_part=[x for x in list_before if x<midprivot]
right_part=[y for y in list_before if y>midprivot]
standard_po... |
5a5c41bbcbd3f22e677b2134bfa925f03a329b28 | jnquintin/apachescan | /apachescan/analyzer/core.py | 5,545 | 3.5625 | 4 | """
Computes statistics about a set of requests
To reduce the memory foot print the number of request and
the size of the response are kept by groups.
The collections has a low memory foot print.
One integer for each possible value.
The computation of the most_common is small
O(n * log(k)) when keeping k elements.
T... |
382eb07590a8ac77c47a57c69fc9107442e30d57 | inarchus/EOS_Does_Python | /Day_1/general_day_1.py | 6,193 | 3.53125 | 4 | import math
import random
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
import datetime as dt
import string
from example_display import ExampleDisplay
def message_boxes():
messagebox.showinfo('This is the title.', 'This is the Message')
messagebox.showwarning('This is the title... |
7f5e5eb1101fc5a9041720b7e1d8b76516b60b98 | AP-Class-Activities/Final-Project-T-03 | /sale.py | 2,343 | 3.96875 | 4 | '''
This is a class defining the products that have been selled by the sellers and bought by the customers.
This class has access to the product class, date class, customer class and the seller class.
Usage:
1) Create a new sale:
s = Sale(product,seller,customer)
2) Print a sale information:
prin... |
9fbd9c35a72ffc0875dee8d7a975393c0c5a9740 | ineedthisforCPEN/projecteuler | /solutions/problem009/version002.py | 3,378 | 4.28125 | 4 | # Version-specific constants - EDIT THESE VALUES
VERSION_NAME = "Version002 - Hardcode shortcut"
VERSION_DESCRIPTION = """
Shortcut the bruteforce method by checking if the sum a + b + c is
divisible by one of the 16 known primitive pythagorean triples where
a, b, c < 100.
If no primitive triple matches to the sum, fa... |
1d83aec1a1d470da03d522cbbf4d1677d492f001 | RogerFabianRozoYepez/python-2 | /tarea2/tarea10.py | 492 | 3.75 | 4 | precio = int(input("Ingrese el valor unitario del articulo: "))
articulo = int(input("Ingrese el numero de articulos: "))
total= precio*articulo
if articulo <5:
print("Precio total a pagar es: ", total)
elif articulo >=5 and articulo<10:
rest = (precio*5/(100))*(articulo)
total1 = total-rest
pri... |
b85baf37d078fa4ee51efe234c3348469ee68fe0 | deone/tryouts | /fizzbuzz.py | 113 | 3.859375 | 4 | x = 15
if x % 3 == 0:
print "Fizz"
elif x % 5 == 0:
print "Buzz"
elif x % 15 == 0:
print "FizzBuzz"
|
fc7d90f9379ad58b2b54c365ca624bfa5db17a13 | kodeskolen/tekna_h20_intro | /dag2/kode/funksjoner2.py | 303 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 17:49:34 2020
@author: Marie
"""
def legg_sammen(ledd1, ledd2):
return ledd1 + ledd2
x = 1
y = 2
print(legg_sammen(x, y))
def maks(a, b):
if a>b:
størst = a
else:
størst = b
return størst
print(maks(-1, 4))
|
0bcc0cdd08e771aa4d407e95576646ab98ccad0b | sukantamajhi/Computer_graphics_Lab | /bres_circle.py | 1,210 | 3.890625 | 4 | # Bressenham's circle drawing algorithm
import matplotlib.pyplot as plt
def bres_circle(x0,y0,r):
x = 0
y = r
x_plt = []
y_plt = []
print(x,y)
d = 3-2*r
while(x<=y):
if (d<0):
x+=1
d = d+4*x+6
else:
x+=1
y-=1
... |
4d1c9b677ae05191d254e4c6b0bcc598fa275ee4 | simonhoch/python_basics | /03_introduicing_lists/3_10_evey_function.py | 619 | 4.09375 | 4 | french_towns = ['paris', 'strasbourg', 'wittersheim', 'mtp']
for town in french_towns :
print (town.title())
print (french_towns[0] + ' and ' + french_towns[-1] + ' stink')
print (sorted(french_towns, reverse=True))
print (french_towns)
french_towns.reverse()
print (french_towns)
french_towns.reverse()
print (french... |
cb93a0c2bc4dd71eddb70c1993ac52e372df20b3 | cmcconomy/adventofcode | /2017/day4/day4.py | 2,024 | 3.90625 | 4 | import unittest;
import re;
problem_num='1'
inputfile='input.txt'
#########
# Setup
#########
with open(inputfile) as f:
file_input_text = f.read()
#########
# Funcs
#########
def basic_split(input_text):
return [line for line in input_text.split('\n') if len(line)>0]
def is_valid(passphrase, check_anagram=F... |
67ff98a79f51a88ab6d4a3fadf92f5e0551b353e | King-Pie/ProjectEuler | /1-25/problem_5.py | 1,202 | 3.78125 | 4 | # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
# Solution from user Berdal on Project Euler forum
def smallest_divisible_number(n):
numbers = []
fo... |
2280a78673f3ba911d3b3fc07fcd6e17ea505671 | ayarem21/python_labs | /lab1/labt_4.py | 389 | 3.828125 | 4 | import math
def f2(x):
tmp = ((math.cos(x ** 2) ** 2) + x + 2 * math.sin(3 * x)) / -2
return tmp
def f1(x, a, b, c):
tmp = 0.5 * x - (((a * x - b) + c) * x - b) / x - 1
return tmp
x = float(input("Enter x: "))
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: ")... |
9e07366c2b425fa3457978e7e1eca5d571ce2672 | nonlining/Algorithms | /Heap and Priority Queues/job_queue.py | 2,442 | 3.5625 | 4 | # python2
from Queue import PriorityQueue
class JobQueue:
def read_data(self):
self.num_workers, m = map(int, raw_input().split(' '))
self.jobs = [int(s) for s in raw_input().split(' ')]
assert m == len(self.jobs)
def write_response(self):
for i in range(len(self.jobs)):
... |
315d5ad0a102f04553e41d3bbfe0dddc6c3832d0 | bzsaph/ip2pythonloginusingfile | /signup.py | 677 | 3.625 | 4 | import random
class signup:
"""docstring for login"""
def __init__(self):
g=input("email=")
y=input("you name=")
print("do you want to create you password if yes type 'yes' if you want to be genelated by system typ 'NO'")
checking=input("choose")
yes="yes"
no="NO"
if (checking==yes):
h=inpu... |
b2d71e3ac4322357978e08307c714252cd028d7b | afterCherry/leetcode- | /14.还没结束—最长公共前缀—经典题/常规思路—a串和b串求完的结果再去和c串求,如此迭代下去.py | 583 | 3.6875 | 4 | # 缺点:和C串求前缀的时候,会重新从第一个字符开始记录,增加不必要的计算
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
length=len(strs)
j=0
res=[]
i=1
while 1:
while i<length:
flag=1
if strs[i][j] != strs[0][j]:
flag=0
... |
7e7c042c2a2fdf2ebf2dd502d329d9b6929b9f93 | AlexEngelhardt-old/courses | /Data Structures and Algorithms/01 Algorithmic Toolbox/Week 4 - Divide-and-Conquer/assignment/1-binary_search/1-binary_search.py | 887 | 3.859375 | 4 | # Uses python3
import math
import sys
def binary_search(a, x, left=0, right=None):
if right is None:
right = len(a)-1
if left > right:
return -1
mid_key = math.floor(left + (right-left)/2)
if a[mid_key] == x:
return mid_key
elif a[mid_key] > x:
return binary_search... |
b9d8949c9562621591b92c3929cfb3d93b52dd59 | sgeniy/practic-6.9.1 | /rectangle_2.py | 499 | 3.765625 | 4 | from main import Rectangle, Square, Circle
rect_1 = Rectangle(5, 4)
rect_2 = Rectangle(10, 30)
square_1 = Square(5)
square_2 = Square(10)
circle_1 = Circle(3)
circle_2 = Circle(7)
figures = [rect_1, rect_2, square_1, square_2, circle_1, circle_2]
for figure in figures:
if isinstance(figure, Square)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.