blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2eccb0fe1805da5cf5d30cb42524bb40cf4a22c1 | stackpearson/cs-notes | /lambda_questions/fibonacciSimpleSum2.py | 2,805 | 4.1875 | 4 | def fibonacciSimpleSum2(n):
fib_numbers = generate_fibonacci(n)
print(fib_numbers)
fib_numbers = set(fib_numbers) # O(len(fib_numbers)) time and space
# loop for all numbers
for first in fib_numbers: # This is O(len(fib_numbers)) = O(log n) because fib numbers almost double each iteration
... |
589a82a73dda707a468a905449b7e5f50ea212f6 | ssmores/hackerrank | /thirtydaysofcoding/day06.py | 2,327 | 4.15625 | 4 | """30 days of coding for HackerRank.
Day 6: Let's Review
by AllisonP
Objective
Today we're expanding our knowledge of Strings and combining it with what we've already learned about loops. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given a string, S, of length N that is indexe... |
a82102d910f69fab9884705b1a3e1614d2119852 | zhangswings/py_pro | /com/pdsu/Class_control.py | 3,003 | 4.28125 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
'''
访问限制
'''
# 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,
# 在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问,所以,我们把Student类改一改:
class Student(object):
def __init__(self,name,score):
self.__name=name
self.__score=score
def print_score(self):
... |
92524194484ebe2da98a5fd35554d3bcc7aac678 | injulkarnilesh/python_tryout | /email_slicer.py | 304 | 3.609375 | 4 |
email = input("What is your email id? : ").strip();
at_ret_index = email.index("@")
user_name = email[:at_ret_index]
domain = email[at_ret_index + 1 : ]
output_message = "With {} as your email, you got user name {} and domain {}"
result = output_message.format(email, user_name, domain)
print(result)
|
7d6708b4775cdea1d794628df78266cf3c6c8174 | AhmetTuncel/CodeKata | /CodeKata/6_Rank/Replace_With_Alphabet_Position_Kata.py | 516 | 4.3125 | 4 | """
Welcome. In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. a being 1, b being 2, etc. As an example:
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def alphabet_position(text):
text ... |
232ab1268be20d5654fe5ae815a8342a5a20e7ef | samhenryowen/samhenryowen.github.io | /CS260/projects/runestone/ch5/ch5e3.py | 717 | 3.953125 | 4 | def binarySearch(alist, item):
if len(alist) == 0:
return False
else:
midpoint = len(alist) // 2
if alist[midpoint] == item:
return True
else:
if item < alist[midpoint]:
newlist = []
for _ in range(0,midpoint):
... |
08812460a49058e4230f76a481b4343b2e98641d | damiati-a/CURSO-DE-PYTHON | /Mundo 2/ex041.py | 471 | 3.90625 | 4 | # Classificando atletas
from datetime import date
atual = date.today().year
nasc = int(input('Qual o ano de nascimento? '))
idade = atual - nasc
print('O atleta tem {} anos'.format(idade))
if idade <= 9:
print('Classificação MIRIM')
elif idade <= 14:
print('Classificação INFANTIL')
elif idade ... |
bd31b1bb9a9381596417f9556f60b3b9ff817419 | jinshah-bs/Function_2 | /intro.py | 1,133 | 4.03125 | 4 | # print("Hello")
lists = [1, 5, 8, 0, 45]
sorte_list = sorted(lists, reverse=True)
# print(sorte_list)
# lists.sort()
# def addition(x, y, k):
# b = 11
# sum_num = x + y*k + b
# print(sum_num)
# print("b within the function is {}".format(b))
# return sum_num
#
# a = 10.0
# b = 3.0
# number = addi... |
73a30c551adfac21c631469ac9c402e7a92cc2db | ItanuRomero/Projeto-Interdisciplinar | /Projeto/Administrator.py | 5,331 | 3.734375 | 4 | from database import *
def initialize_administrator():
while True:
options = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
print('\nO que você gostaria de fazer?\n')
print('1 - Visualizar todas as categorias')
print('2 - Inserir nova categoria')
print('3 - Remover um... |
f8c2381c60e156221b084e78a7f9a2a8b6f3480a | alimat2244/read-file-course | /main.py | 253 | 3.640625 | 4 | # This is a sample Python script.
# written by Sadiat Adegbite
# Enter a file name you want opened
print("This program is written by Sadiat Adegbite")
textfile = open(r"C:\Users\alima\OneDrive\Documents\Fruits.txt",'r')
for i in textfile:
print(i, end="")
|
3183a2a59f2cf6455338f60f4a1819b21aede81d | glambertation/ToGraduate | /Leetcode/python/coins/300/378.py | 1,283 | 3.984375 | 4 | '''
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 1... |
a51999bdc3287955be104c3cb3346a14e3114b0d | oywc410/MYPG | /python3/入门/06字典/05字典内置函数&方法.py | 1,017 | 3.8125 | 4 | """
len(dict)
计算字典元素个数,即键的总数。
str(dict)
输出字典以可打印的字符串表示。
type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。
1 radiansdict.clear()
删除字典内所有元素
2 radiansdict.copy()
返回一个字典的浅复制
3 radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 radiansdict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5 key in dict
如果键在字典dict里返回... |
3e7606a2d13fe87fe7cd88a7c9cb39391a48a3b2 | ZJU-RoboCup/BotecBeast | /leju_lib_pkg/src/lejufunc/utils.py | 366 | 3.546875 | 4 | #coding=utf-8
def is_number(number):
try:
return float(number)
except:
return None
def judge_range_number(number, min, max):
number = is_number(number)
if number is not None:
if min <= number <= max:
return number
raise ValueError("参数错误, 应为数字类型, 范围为[{}, {}]".for... |
4aa4bdec0f7eae29b3d21139fed1657ae7538f5c | freakraj/python_projects | /whileraj_solu.py | 235 | 3.671875 | 4 | name =input("please enter your name : ")
# harshit
temp_var=""
i=0
while i<len(name):
if name[i] not in temp_var:
temp_var +=name[i]
print(f"{name[i]} : {name.count(name[i])}")
i +=1
|
139d48048b47406931482cb7d40147df15560118 | JenZhen/LC | /lc_ladder/Adv_Algo/dp/LC_377_Combination_Sum_IV.py | 1,581 | 3.671875 | 4 | #! /usr/local/bin/python3
# https://www.lintcode.com/problem/combination-sum-iv/description
# Example
# 给出一个都是正整数的数组 nums,其中没有重复的数。从中找出所有的和为 target 的组合个数。
#
# 样例
# 样例1
#
# 输入: nums = [1, 2, 4] 和 target = 4
# 输出: 6
# 解释:
# 可能的所有组合有:
# [1, 1, 1, 1]
# [1, 1, 2]
# [1, 2, 1]
# [2, 1, 1]
# [2, 2]
# [4]
# 样例2
#
# 输入: nums = ... |
90f258e25fd3f055850a61b3e820b0bcf98099e8 | alexisshaw/python2perl | /tests/toSubmit/demo09.py | 157 | 3.5625 | 4 | #!/usr/bin/python
__author__ = 'Alexis Shaw'
array = [5,4,3,2,1]
string = "Hello how are you"
print sorted(array)
print sorted([5,4,3,2,1])
print len(string)
|
50d6f4436dab9117a84c5537e73cde136fb74f1a | samaritanhu/swe_fall | /swe241p/Exercise2/InsertionSort.py | 1,187 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
# University of California, Irvine
# Master of Software Engineering, Donald Bren School of Information and Computer Science
# Created by: Xinyi Hu
# Date : 2020/10/09
# Contact : xinyih20@uci.edu
# Target : Realize InsertionSort
# Reference : The algorithm design manual
... |
09c0574e2383a2c68ddf850b4335469b18342da9 | idobleicher/pythonexamples | /examples/variable_scopes/global_scope_example_3.py | 692 | 4.28125 | 4 | #We only need to use global keyword in a function if we want to do
# assignments / change them. global is not needed for printing and accessing
#Any variable which is changed or created inside of a function is local, if it hasn’t been declared as a global variable.
#To tell Python, that we want to use the global varia... |
b9a0b0512e2a83a0a11e882b43083b270235f637 | bohdan167/My-Games | /Connect Four/Text Mode/model.py | 1,743 | 3.5625 | 4 | import numpy as np
ROW_COUNT = 6
COLUMN_COUNT = 7
def create_board():
board = np.zeros((ROW_COUNT, COLUMN_COUNT))
return board
def valid_move(board, move):
if (0 <= move <= 6) and board[0][move] == 0:
return True
else:
return False
def get_next_row(board, move):
r = len(board)... |
e3524ac737dda91438024c5103619196a8b2f61c | hsonetta/OCR | /Front_end/input.py | 1,898 | 3.515625 | 4 | """
Loads the desired input image, language model
and calls function to recognize text.
"""
import numpy as np
import streamlit as st
from PIL import Image
import cv2
from ocr_wrapper import detect_text, crop_img, recognize_text
from data import *
import easyocr
import time
@st.cache(suppress_st_warning=True)
def load... |
875c6f49e9ce07ab69ee36918cc6b3b4c2755c1e | gimquokka/problem-solving | /Programers/Lv_2/전화번호 목록/ref.py | 169 | 3.6875 | 4 | def solution(phone_book):
phone_book.sort()
for p1, p2 in zip(phone_book, phone_book[1:]):
if p2.startswith(p1):
return False
return True |
660851f5fcbceca5371134ab5c2d8b3bc4233e9b | charles161/python | /intersection.py | 195 | 4 | 4 | list1=input('Enter the space separated elements for list 1 : ').split(' ')
list2=input('Enter the space separated elements for list 2 : ').split(' ')
print(list(set(list1).intersection(list2)))
|
57453238c82722cbf17305333ab649ecc1414555 | roushan5mishra/HackerRank_Python | /timeConversion.py | 493 | 3.953125 | 4 | #!/bin/python
import sys
def timeConversion(s):
# Complete this function
temp1 = s[-2:]
temp2 = int(s[:2])
if temp1.upper() == 'PM':
if temp2 < 12:
temp2 +=12
elif temp2 == 12:
temp2 = 12
elif temp1.upper() == 'AM':
if temp2 < 12:
te... |
e83fcbe5590d069bd7e5dca9eeee31b5e7af9991 | GHubgenius/DevSevOps | /2.python/0.python基础/day12/代码/day12/01 昨日回顾.py | 1,704 | 3.640625 | 4 | '''
编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),
要求登录成功一次,后续的函数都无需再输入用户名和密码。
'''
# 可变类型,无需通过global引用,可直接修改
user_info = {
'user': None # username
}
# 不可变类型,需要在函数内部使用global对其进行修改
user = None
def login():
# 判断用户没有登录时,执行
# 登录功能
# global user
username = input('请输入账号: ').strip()
password = input('请输入密码: ').st... |
2d3cf1f1e3d3722b8daee2c85408c7d326589317 | shivasupraj/LeetCode | /107. Binary Tree Level Order Traversal II.py | 709 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
715ea88ed53d02f3f0962e26d583f9abaa3a0474 | setyo-dwi-pratama/python-basics | /21.fungsi_rekursi&lambda.py | 4,272 | 4.0625 | 4 | # FUNGSI REKURSI DAN LAMDBDA
print("===============1. FUNGSI REKURSI===============")
# Fungsi rekursi adalah fungsi yang memanggil dirinya sendiri secara berulang. Jadi di dalam tubuh fungsi kita memanggil fungsi itu sendiri
# CONTOH. Di dalam matematika, kita mengenal tentang faktorial. Faktorial adalah perkal... |
68ae40f164c2302c65e257be74c0933602170ae6 | jabhax/python-data-structures-and-algorithms | /OOP/Adapter.py | 2,334 | 4.28125 | 4 | # Design Patterns
'''
Adapter Pattern works as a bridge between two incompatible interfaces. This
pattern involves a single class, which is responsible for joining the
functionalities of Independent or Incompatible Interfaces. It converts the
interface of a class into another interface based on some requirement. The
p... |
f89ce38b0c9aa62878f4c946aa9cd42d5e513933 | sumeetmankar171/HTP | /archive/check_time_string.py | 966 | 3.578125 | 4 | __author__ = 'mlucas'
import sys
def check_time_str(time_str):
hour = time_str[0:2]
mins = time_str[2:4]
secs = time_str[4:6]
fsec = time_str[6:]
c_hour = hour
c_mins = mins
c_secs = secs
if int(secs) > 59:
c_secs = '00'
if int(mins) < 59:
c_mins = str(int... |
9b8faea2b631b28a1ca3a54f78bf42e2717e0f46 | originalhumanbeing/algorithm-training | /python/longest_palindrom.py | 1,050 | 4.21875 | 4 | # 앞뒤를 뒤집어도 똑같은 문자열을 palindrome이라고 합니다.
# longest_palindrom함수는 문자열 s를 매개변수로 입력받습니다.
# s의 부분문자열중 가장 긴 palindrom의 길이를 리턴하는 함수를 완성하세요.
# 예를들어 s가 토마토맛토마토이면 7을 리턴하고 토마토맛있어이면 3을 리턴합니다.
def is_palindrom(s):
return s == s[::-1]
assert (is_palindrom('토마토'))
assert (not is_palindrom('토마토마'))
def longest_palindrom(s):
... |
3d36c4de6c1a80327f8b4c982ee255b355d513a3 | prinned/prog | /palchk.py | 562 | 4.0625 | 4 | '''This program finds the largest palindrome which is a
product of two 3-digit numbers. E2018/'''
import math
def palchk(i): #checks whether i is a palindrome
ja = ""
for m in range(0,len(str(i))//2):
ja += str(i)[m] #ja = first half of number
jb = ""
for m in range(math.ceil(len(str(i))/2... |
edab1f6596c0790d81f3d0f70168a2ae50eb4bfd | danielsbezerra/python | /if-odd-even.py | 297 | 4.0625 | 4 | #!/bin/python3
N = int(input())
R = range(0,101)
if N in R:
if N%2 != 0: #odd
print("Weird")
elif N in range(2,5):
print("Not Weird")
elif N in range(6,21):
print("Weird")
elif N > 20:
print("Not Weird")
else:
print(f"{N} out of range(0,101)") |
f0725ac023a6653a29aabe9df21035016fd1ff1d | rhondaregister/Exercises | /countPairs/countPairs.py | 386 | 3.953125 | 4 | '''
A function to determine the number of pairs in an array.
'''
number_of_socks = 9
sock_colorways = [10, 20, 20, 10, 10, 30, 50, 10, 20]
def countPairs(n, ar):
pairs = []
count = 0
for i in ar:
if i in pairs:
pass
else:
pairs.append(i)
num = ar.count(i)
pair = int(num / 2)
count += pair
retu... |
ae566c005a8256a4f8db53cb1899c2fcfb4346b7 | linkeshkanna/ProblemSolving | /EDUREKA/Course.3/Case.Study.1.Programs/factorial.py | 429 | 4.28125 | 4 | class factorial:
def calculateFactorial(object, value1):
value = int(value1)
if value == 1:
return value
else:
return value * object.calculateFactorial(value - 1)
if __name__ == "__main__":
value = input("Please Enter a Number : ")
object = factorial()
f... |
c69814982c6636a3e910a8759b11f864cc9ea9df | KrishnadevAD/Python | /u6.py | 538 | 3.96875 | 4 | print("enter the first number")
firstNumber=int(input())
print("enter the second number")
SecondNumber=int(input())
print(str(firstNumber)+" + "+str(SecondNumber)+"= "+str(firstNumber+SecondNumber))
print(str(firstNumber)+"-" +str(SecondNumber)+"= "+str(firstNumber-SecondNumber))
print(str(firstNumber)+" * "+str... |
c06406f5666f6e0d64efa105ae2da1beb06e2212 | a-utkarsh/python-programs | /Numpy/slicing_indexing.py | 569 | 4.03125 | 4 | import numpy as np
a = np.arange(10)
print(a)
s = slice(2,7,2)
print (a[s])
# array to begin with
a = np.array([[1,2,3],[3,4,5],[4,5,6]])
print(a.ndim)
print ('Our array is:')
print (a)
print ('\n')
# this returns array of items in the second column
print ('The items in the second column are:')
print (a[...,2])
pri... |
32774ecded41feb3dc3e865f33b01f13a1685ed8 | PonMorin/CP3-Pon-Morin | /Lecture53_Pon_M.py | 128 | 3.75 | 4 | def vatCal(totalPrice):
result=totalPrice+(totalPrice*7/100)
return result
print(vatCal(int(input("Enter Number: "))))
|
a119b6f1537c49b603ba005b5c7119be0ed8cb4f | phatnguyenuit/Python | /dictionary.py | 858 | 3.890625 | 4 | #coding:utf-8
'''
dictionary dạng {key:value, key2:value2,....,key_n:value_n}
truy cập giá trị của dictionary
dictionary['key']
cập nhật giá trị của key bằng cách gán lại giá trị cho dictionary['key']
xoá del ten_dictionary[key]
hoặc del ten_dictionary để xoá tất cả
#dict.clear()
#dict.copy() return a copy
#dict.get(... |
e614847ff6c548d56322f1956604dd8a0a9ca53f | muhammadahsan21/100DaysOfLearningDataScience | /ThinkStats_Book/think_stats_exercise2_2.py | 1,648 | 3.84375 | 4 | import thinkstats_survey as survey
import think_Stats_First as first
def mean(number_list):
return float(sum(number_list)/len(number_list))
def variance(number_list):
mean_of_list=mean(number_list)
return mean(([(x-mean_of_list)**2 for x in number_list]))
def stddev(number_list):
variance_of_list=var... |
0c1dc3b9e4defb77ee0e1537a5f96e164b38016f | CDidier80/Code-Challenges-Algos-Interviews-Cool-Solutions | /challenges-and-interview-problems/WARM-UPS/are-you-playing-banjo/banjo.py | 620 | 4.3125 | 4 | # Create a function which answers the question "Are you playing banjo?".
# If your name starts with the letter "R" or lower case "r", you are playing banjo!
# The function takes a name as its only argument, and returns one of the following strings:
# name + " plays banjo"
# name + " does not play banjo"
# solution... |
ae300c15ef006d668905472f994081dccd259e90 | ZhanlinWang/hpc_work | /lec4/sqrtx.py | 443 | 3.703125 | 4 | #!/bin/python
'''
Module for approximating sqrt.
More ...
'''
'Why not come here'
from numpy import *
x = 100.
def sqrt2(x, debug=False):
'''
more details
'''
s = 1.
kmax = 100
tol = 1.e-14
for k in range(kmax):
if debug:
print "Before iteration %s, s = %20.15f" % (k,s)
s0 = s
s = 0.5 * (s + x/s)
delt... |
3e36dccfc4f5626851d9d45e2ccaf62a2246c88c | amirtha4501/Guvi | /AbsoluteBeginner/AbsoluteLearner5.py | 180 | 4.1875 | 4 | # Calculate circumference
import math
radius = float(input())
if radius >= 0:
circumference = 2 * math.pi * radius
print('%.2f' % circumference)
else:
print("Error") |
7616aafe667f56da41b7c7fc5a73bd8bbaba4bb4 | wrthls/bmstu-5sem | /AA/lab_01/print_matrix.py | 200 | 3.796875 | 4 |
def print_matrix(matrix):
for j in range(len(matrix)):
print(" ", end='')
for k in range(len(matrix[j])):
print(matrix[j][k], ' ', end='')
print()
print()
|
9218816be9ea8ac47eb870342bdfdc4c3af761bd | Raccoon987/aliev.me | /tree_git.py | 19,784 | 3.921875 | 4 |
''' create binary heap - list realization - acts like tree '''
class BinaryHeap:
def __init__(self, size):
self.heapList = [0]
self.currentSize = 0
self.maxSize = size #max number of elements in heap
# inserting element with it futher migration to the correct "binary heap" place
... |
91120deff3b5ec130c32d7088be70c042429101a | 13excite/other | /find_local_max.py | 944 | 3.53125 | 4 | import sys
my_list = []
for num in sys.stdin.read().split():
my_list.append(num)
def localMaxLst(lstIn):
if len(lstIn) == 0:
return [] # no results from empty list
lst = [] # init -- no results yet
m = lstIn[0] # the first element as the maximum...
candidate = True # ... candidate
... |
07d3da584c63240f89b1fd9a1387890548b3b3b2 | omatveyuk/interview | /bubble_sort.py | 816 | 4.34375 | 4 | """Bubble sort.
6 5 3 8 7 2
5 3 6 7 2 8
3 5 2 6 7 8
3 2 5 6 7 8
2 3 5 6 7 8
The big numbers bubble to the top. After the first pass through the list,
the biggest number will be all the way to the right. After the second pass,
the second highest number will be second from the right, and so on.
>>> bubble_sort([6, 5... |
429e29b039ca7de7ef998560c290100621386467 | arsamigullin/problem_solving_python | /leet/Design/add_and_search_word.py | 1,791 | 3.78125 | 4 | # this is my solution
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = dict()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.root
for ch in w... |
fa24009fdf0b7667851a18b06552003fb049a331 | terpator/study | /Условные операторы/domashka_2 - переделанное.py | 1,001 | 4.0625 | 4 | """
Есть девятиэтажный дом, в котором 4 подъезда. Номер подъезда начинается с
единицы. На одном этаже 4 квартиры. Напишите программу которая, получит
номер квартиры с клавиатуры, и выведет на экран, на каком этаже, какого
подъезда расположенна эта квартира. Если такой квартиры нет в этом доме, то
нужно сообщить об... |
13850bd3ff5bf2b980192a78a437934aaaca81a6 | leejongcheal/algorithm_python | /파이썬 알고리즘 인터뷰/ch9 스택, 큐/20.유효한 괄호.py | 614 | 3.75 | 4 | class Solution:
def isValid(self, s: str) -> bool:
stack = []
# 와 요런식으로 깔끔하게 ㅋㅋ
table = {
")":"(",
"}":"{",
"]":"["
}
for char in s:
if char not in table:
stack.append(char)
# 나는 not stack 을 따로 두었는데 이... |
51fef7a2a36a99f47e3b6dcd6ae07ba21cf8d375 | ulysses316/python-practicas | /gasolineras.py | 795 | 3.609375 | 4 | import requests
def distancia():
o=raw_input("Dame el punto de origen: ")
d=raw_input("Dame el destino deseado: ")
a=requests.get(params={"origins": o, "destinations":d}, url="https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&key=AIzaSyBfI7bob5KZFrPC4kQ-tzZzE63airiYsqU").json()
prin... |
b34c2cd48622c0cceae73eefef06892b6179b673 | git-vish/Soft-Computing-Lab | /BackProp_XOR_keras.py | 621 | 3.65625 | 4 | import numpy as np
import keras
# STEP-1: initializing data
xt = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
yt = np.array([[0], [1], [1], [0]])
# STEP-2: creating nn model
model = keras.models.Sequential()
model.add(keras.layers.Dense(32, input_dim=2, activation='relu'))
model.add(keras.layers.Dense(1, activation='si... |
cad0ad725150d9b3652ccdae0b0a0deb5475f4d9 | khadimniass/MesPremiersCodesPythons | /ordre.py | 368 | 3.828125 | 4 |
p=int(input("entrez le nombre premier p: "))
x=int(input("entrez l'entier x: "))
i=1;ord=0
while(True):
if(x**i%p==1):
ord=i
break
i+=1
print("ordre de ",ord)
def ordre(p,x):
p,x=int(p),int(x)
compteur,ordr=1,0
while(True):
if (x**compteur%p==1):
ordr=compteur
... |
6f7f39782c84bd72cc7e3509b1cdaf941b01c67d | Arocchi03/python_HWchallenge | /Python_homework/Python_challenge/PyPoll/main.py | 1,469 | 3.53125 | 4 | import csv
import os
Voter_ID = 0
County = 0
total_votes = 0
percentage_votes = []
num_votes = []
Candidate_list = []
Candidate_winner=[]
#Reading data
csvpath = os.path.join("PyPoll/Resources/election_data.csv")
with open (csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
... |
c9d875bd877e21f2eced12faeadc62176eed25ec | WGrace824/GenCyber-2016 | /CaesarCipher.py | 1,353 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 8 09:38:56 2016
@author: student
Caesar Cipher
1. Name your function with 2 parameters, a str and a int
2.
"""
def Caesar_Cipher(Message, shift):
Cipher = ""
for char in Message:
if ord(char) > 64 and ord(char) < 91:
if ord(char) + shift... |
93e6febe467806de50a08903c46e7d00df61185e | DmytroLopushanskyy/Lab3 | /json_parse/task2_json_parse.py | 1,661 | 3.828125 | 4 | import json
import copy
def decode_json(path):
""" (str) -> dict
Decode json file into a dictionary
"""
with open(path, 'r', encoding='UTF-8') as f:
decode_data = json.load(f)
return decode_data
def parse_json(data):
""" (dict) -> None
Parse dictionary with user input
"""
... |
db140a884a420eb0b53cd4d09ff462a6e1d96a2c | michlee1337/practice | /Fundamentals/stackQs2.py | 2,100 | 3.9375 | 4 | # implement stack through min heap priority q
class MinHeap():
def __init__(self):
self.heap = []
self.size = 0
# parent: (i-1)//2
# left child: (i*2)+1
# right Child: (i*2)+2]
def bubbleUp(self,i):
# while parent exists for this index
if i <= 0:
return... |
70f438ce30d9445b69fe0ce65638ec016bb4a284 | olivigora/tokyo-3 | /fibonacco numbers.py | 157 | 4.125 | 4 | def fibonacci(x):
a = [1]
for x in range(x):
a.append(a[x]+a[x-1])
print(a)
x = int(input("How many Fibonacci numbers do you want?: "))
fibonacci(x) |
a041e414b78ccd1acd3fb0c83f651f0f63ee784a | BorjaSuarezMoron/trabajo | /venv/diccionario2.py | 465 | 3.953125 | 4 | # -*- coding: utf-8 -*-
string_input = raw_input("Escriba ")
def prueba(string_input):
input_list = string_input.split() # splits the input string on spaces
# process string elements in the list and make them integers
print input_list
diccionario={}
for i in range(len(input_list)):
valor... |
140a585fe0be022403bfd60b71b687699f62f708 | RainMoun/nowcoder_program | /剑指offer/快速排序.py | 566 | 3.828125 | 4 | def quick_sort(num_lst, left, right):
if left >= right:
return
low = left
high = right
key = num_lst[low]
while left < right:
while left < right and num_lst[right] >= key:
right -= 1
num_lst[left] = num_lst[right]
while left < right and num_lst[left] <= ke... |
ab8f7eb116d786a06622703b548396a069a1720c | karan2808/Python-Data-Structures-and-Algorithms | /Stack/BinaryTreeInOrderTraversal.py | 1,047 | 3.953125 | 4 | class Solution:
def inorderTraversal(self, root):
result = []
stack = []
current = root
# while current is not none or stack is not empty
while current != None or len(stack) > 0:
# push all the left nodes onto stack
while current:
sta... |
20e53c74fa106387e9f986261cf15ebcc88fdd13 | JDavid121/Script-Curso-Cisco-Python | /145 tuple application.py | 213 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 25 22:42:13 2020
TUPLE APPLICATION
@author: David
"""
var = 123
t1 = (1,)
t2 = (2,)
t3 = (3,var)
t1,t2,t3 = t2,t3,t1
print(t1,t2,t3)
print(type(t1)) |
65920ef8856c5040e1098ea1f2bd6cc9dafa98d7 | RomanAleksejevGH/Python | /groupwork/booksmenu.py | 1,674 | 3.78125 | 4 | import books
newLib=books.library()
#newLib.info("Математика для тех, кто не открывал учебник")
def book_search():
get_book=input('\nВведите название книги:\n')
newLib.infoBook(get_book)
def author_search():
get_author = input('\nВведите имя автора:\n')
newLib.infoAuthor(get_author)
def book_by_letter(... |
55c83c1c2c1bbe4352cbfb8d98e569e84f8b5b4a | iainfraser188/funtions-lab-2 | /start_code/task_list.py | 2,188 | 4.0625 | 4 |
# As a user, to manage my task list I would like a program that allows me to:
# 1. Print a list of uncompleted tasks
# 2. Print a list of completed tasks
# 3. Print a list of all task descriptions
# 4. Print a list of tasks where time_taken is at least a given time
# 5. Print any task with a given description
##... |
36910b80d5248e8e4e30861f8677fdb30d77da2f | Tom-Harkness/projecteuler | /Python/utilityfunctions.py | 2,770 | 3.90625 | 4 | def isPrime(n):
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while (i*i<=n):
if n % i == 0:
return False
i += 2
return True
def isPentagonal(n):
return (24*n+1)**0.5 % 6 == 5
def isHexagonal(n):
ret... |
0b03c2f019a2f7d924107aae2a08d484db611155 | alexandermedv/Prof_python2 | /main.py | 2,146 | 3.5 | 4 | import csv
import re
import pandas as pd
import numpy as np
def lastname(contacts_list):
"""Обработка фамилии"""
result = []
for record in contacts_list:
pattern = "[\w]+"
words = re.findall(pattern, record[0])
if len(words) == 3:
record[0] = words[0]
recor... |
7e16019f837e72d25cee3c1f60f3017f5c4be478 | QuratulainZahid93/unit3 | /unit3_6.py | 2,076 | 4.3125 | 4 | # Invite some people to dinner.
guests = ['sherry', 'aney', 'maha']
name = guests[0].title()
print(name + ", please come to dinner.")
name = guests[1].title()
print(name + ", please come to dinner.")
name = guests[2].title()
print(name + ", please come to dinner.")
name = guests[1].title()
print("\nSor... |
7ccf45bad51f087f12dca35c502ceec801eb4799 | dalismo/python-challenge | /PyBank/main.py | 2,213 | 3.65625 | 4 | # modules to bring in
import os
import csv
# filepath
budget_csv = os.path.join('.','Resources','budget_data.csv')
# variables to store for counts, calcs and loop
total_months = []
total_net_gainloss = 0
total_gainloss = 0
prior_gainloss = 0
amount_gainloss = 0
amt_gainloss = []
difference = 0
difference_list = []
m... |
1286bf30879c0f24a8272c92d259c83023fc4427 | soyoonjeong/python_crawling | /2_currencycode_scrap.py | 865 | 3.5 | 4 | import os
import requests
from bs4 import BeautifulSoup
os.system("cls")
url = "https://www.iban.com/currency-codes"
print("Hello! Please choose select a country by number:")
result = requests.get(url)
soup = BeautifulSoup(result.text, "html.parser")
tds = soup.find_all("td")
names = []
codes = []
for index, td in e... |
8a13e4e6a312514c9a8ddb7b343bf705bb5bb037 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/bxxbub001/question4.py | 803 | 3.765625 | 4 | #marks
#B.Booi
#24 April
def marks():
fail = 0
thirds = 0
lower2 = 0
upper2 = 0
first = 0
numbers = input("Enter a space-separated list of marks:\n")
numb_list=numbers.split(" ")
#print(numb_list)
listlen = len(numb_list)
#print("length",listlen)
for x in range(listlen):
... |
ed3acfad76d2291a97a8d0bc5524f52da4f36627 | tswsxk/CodeBook | /Leetcode/SearchInsertPosition.py | 584 | 3.953125 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
head = 0
tail = len(nums) - 1
while head < tail - 1:
mid = (head + tail + 1) // 2
if nums[mid] == target:
return mid
elif nums[mid] < targ... |
790cb075ab683b4ad0c6be81acd1309f109d5545 | buptwxd2/leetcode | /Round_1/496. Next Greater Element I/solution_1.py | 679 | 3.640625 | 4 | class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
my_stack = []
my_dict = {}
for num in nums2:
while my_stack and my_stack[-1] < num:
top_num = my_stack.pop(-1)
my_dict[top_num] = num
my_st... |
fed9f9bd907c7e1bd3e70288915c20883e7f68f4 | rkarna/DSC510Summer2020 | /Jena_Binay_DSC510/week2_print_receipt.py | 1,099 | 4.09375 | 4 | #DSC 510
#Week 2 Programming Assignment 1.2
#Programming Assignment Week 2
#Author: Binay P Jena
#06/12/2020
from datetime import datetime
execution_date = datetime.now().strftime("%Y-%m-%d")
def _total_charges (length):
print("Transaction Details - ")
install_cost = length * 0.87
print("Installation Leng... |
5ba1efe224bdcd173eee72d3369ecb283e69d3ab | ScatterBrain-I/MCLAPython | /LectureWork/1d.Comments.py | 164 | 3.625 | 4 | import math
# Peter E Niemeyer
# 7/7/17
#
# this is to figure the volume of a cone
radius = 10
height = 44
volume = math.pi * (radius * radius) * (height/3)
print volume
|
42f4524ed8bfef1538b79246b27bf27f4f4be194 | dworakp/guessing-game | /guessing.py | 1,376 | 4.125 | 4 | import random
number=random.randint(1,100)
guesses = [0]
print("I've picked a random number from 1 to 100. Guess the number!")
print("If your guess is more than 10 away from my number, I'll tell you you're COLD")
print("If your guess is within 10 of my number, I'll tell you you're WARM")
print("If your guess is f... |
7ea611bce359960fd2f2ad160fd0bf62a0194ccb | Sanlador/School | /CS531/sudoku.py | 13,225 | 3.59375 | 4 | import numpy as np
import math
#reads file of sudoku puzzles and places them in arrays arranged by difficulty (file is specifically formatted prior to input)
def readPuzzleFile(file):
easy = []
medium = []
hard = []
evil = []
difficulty = {
"Easy": 1,
"Medium": 2,
"Hard": 3,
"Evil": 4
}
... |
d750a6b9e5d3f75dff0f0bfba73b76d70002901c | dsspasov/HackBulgaria | /week0/2-Python-harder-problems-set/problem30_test.py | 454 | 3.578125 | 4 | #problem30_test.py
import unittest
from problem30 import groupby
class TestGroupBy(unittest.TestCase):
def test_empty_list(self):
self.assertEqual({'odd':0, 'even':0}, groupby(lambda x: 'odd' if x % 2 else 'even', []))
def test_not_empty_list(self):
self.assertEqual({'odd':[1,3,5,9] , 'even':[2... |
4c13ba803a0fc414c94a3860e0d33fdfe813f0fe | DeanHe/Practice | /LeetCodePython/SmallestValueAfterReplacingWithSumOfPrimeFactors.py | 1,241 | 4.0625 | 4 | """
You are given a positive integer n.
Continuously replace n with the sum of its prime factors.
Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n.
Return the smallest value n will take on.
Example 1:
Input: n = 15
Output: 5
Explanation: Initially, ... |
96145aafa29063359becd3fc98fc932e78712204 | franceshoho/Aliens_Invasion | /ship.py | 1,500 | 3.890625 | 4 | import pygame
class Ship:
"""A class to manage the ship"""
def __init__(self, ai_game):
"""Initialize the ship and set its starting position"""
# get screen from ai_game
self.screen = ai_game.screen
# get settings from ai_game
self.settings = ai_game.settings
# g... |
0c240dc233f789d84b520990af063cb5b991a11b | Jill1627/lc-notes | /countAndSay.py | 1,173 | 3.671875 | 4 | """
问题:输出第n位count and say sequence - 注意count and say sequence的生成方式
思路:递归,算法设计如何从n-1到n
1. 考虑n=0,1的特殊情况
2. 初始:res, count = 1, prev = self.countAndSay(n - 1),还有prevNum
3. 在loop中,考察当前i(curNum)与prevNum的关系,更新count
4. 如果当前位与前一位相等,只需要count++
5. 如果当前位与前一位不等,更新答案,同时:reset count = 1,preNum = curNum
6. 最后一步,还要将prevNum加入答案
完成
"""
c... |
8acddf851481fec34d87ae05bddd319ddcc60fc6 | Zorro30/Udemy-Complete_Python_Masterclass | /Regular_expression/star_character.py | 147 | 3.96875 | 4 | import re
pattern = r"eggs(bacon)*"
if re.match(pattern, "eggsbaconbacon"):
print ("Match found!")
else:
print("Does not match!") |
c3be5862c916bf4bfb702841f79e77e3e4275560 | zx000ppze000/Pathon | /w1_lect_p2.py | 376 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 17 23:42:57 2018
@author: zhangx
"""
"""a = 0
while a<5:
print(a)
a += 1
"""
"""for n in range(5):
print(n)
"""
"""for n in range(0,10,2):
print(n)
"""
"""mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)
"""
mysum = 0
for i in range(5, 11, 2):
m... |
72a2b890d37e93beaf2b69f37a21cc79be259e4e | bsiranosian/brown-compbio | /CSCI1820/hw3/src/alignment_with_inversions.py | 7,902 | 3.609375 | 4 | #parameters
import argparse
parser = argparse.ArgumentParser(description="Script compute the optimal local alignment with inversions of two sequences. Takes input from two fasta sequences.")
parser.add_argument("fasta1", action="store", metavar="fasta1", help="The file name of the first fasta sequence")
parser.add_ar... |
d25d2a8a56754ad1a2fd8f056a628f5249f659bc | AlexKolchin/geekbrains | /Modules/math_ex.py | 545 | 3.921875 | 4 | import math
#1. Найти длину окружности с определенным радиусом
r = 100
print(2*r*math.pi)
#2. Найти площадь окружности с определённым радиусом
print((r**2)*math.pi)
print(math.pow(r, 2)*math.pi)
#3. По координатам 2-х точек определить расстояние между ними
x1 = 10
y1 = 10
x2 = 50
y2 = 100
l = math.sqrt((x1-x2)**2 + ... |
40db83c1e54636bc9b238468820fe26e4c124345 | lovroselic/Coursera | /String Algorithms/suffix_tree/suffix_tree V2.py | 2,993 | 3.71875 | 4 | # python3
#https://www.geeksforgeeks.org/generalized-suffix-tree-1/
import sys
NA = -1
#DEBUG = False
DEBUG = True
if DEBUG: test = open("sample_tests\\sample3", "r")
class Node:
__num__ = -1
def __init__(self, parentkey, pos = -1, substr = "", suffixlink = None):
self.parent = parentkey
sel... |
79e4ffa5d4cccf44de87b3d02d11dc8750fc867c | Gagan-453/Python-Practicals | /timedelta and programs.py | 2,505 | 4.28125 | 4 | #timedelta class of datetime module is useful to find durations like difference between two dates or finding the date after adding a period to an existing date
#Program to find future date and time from an existing date and time
from datetime import *
d1 = datetime(2016, 4, 29, 16, 45, 0) #Store the date and time in da... |
8e699ea99af07d3c2c1dd445a0e62ce45b653526 | azharul/misc_problems | /iterator.py | 674 | 4.28125 | 4 | #!/usr/bin/python
#Write Interleaving Iterator class which takes a list of Iterators as input and iterates one element at a time from each iterator until they are all empty
# interleaving iterators are also called Round Robin iterator
from itertools import islice, cycle
def roundrobin(*iterables):
"roundrobin('... |
3cc5925d3e66a1ef7bb5236e675589544dddaf9a | ajing/clusterVis | /TreeRebuilder.py | 4,417 | 3.5 | 4 | """
Rewrite file to make the node name simple, so graphviz can understand
Assumption: 1. node names are started with CHEMBL or ASD
2. only two kinds of statements contain node name: (1) node declaration (2) edge between nodes.
"""
import sys
def NodeNameExist(line):
if "CHEMBL" in line or ... |
606877c697359e4294811eb327f97ffcb8e89511 | castorfou/scikit-learn-mooc | /notebooks/cross_validation_ex_05.py | 3,664 | 4.03125 | 4 | #!/usr/bin/env python
# coding: utf-8
# # 📝 Introductory exercise for non i.i.d. data
#
# <div class="admonition note alert alert-info">
# <p class="first admonition-title" style="font-weight: bold;">Note</p>
# <p class="last">i.i.d is the acronym of "independent and identically distributed"
# (as in "independent an... |
434e11bf4a5f81fd9e2530f48082e0eb4ebf2d42 | Gustovus/PFB_problemsets | /Python_Problemsets/problemset4_factcount.py | 165 | 3.640625 | 4 | #!/usr/bin/env
import sys
findfact = sys.argv[1]
findfact = int(findfact)
count = 1
fact = 1
while count <(findfact+1):
fact *= count
count += 1
print(fact)
|
c1aa83cfc9e30f737dd1d88a74e36d89acf280fa | WillianComenalli/ImageSplicingDetection | /source/distanceMetrics.py | 485 | 3.5625 | 4 | '''
Created on 05 ott 2016
@author: lorenzocioni
Different matrics for evaluating distances bewteen eigenvalues
'''
import math
def linearDistance(a, b):
return abs(a - b)
def quadraticDistance(a, b):
return pow((a - b), 2)
def logarithmicDistance(a, b):
if abs(a - b) > 0:
return math.log(abs(a... |
e1faa3f2477a24537a5d7036514172a2c8580e55 | K7evin/Hello | /Hello.py | 136 | 3.875 | 4 | username = input("Hi, whats your name? ")
# Respond to the user: nice to meet you “username”
print("Nice to meet you, " + username)
|
0169cd5a80122e36468d2a439803a69b8e9d50dc | Yalfoosh/pizza | /src/yeast_prediction/preprocessing/dataset.py | 1,530 | 3.515625 | 4 | import csv
from pathlib import Path
from typing import List, Union
from .utils import fahrenheit_to_kelvin
def preprocess_raw_yeast_dataset(
source_path: Union[Path, str],
delimiter: str = "\t",
) -> List[List[Union[float, int]]]:
"""
Preprocesses a dataset in the form of a CSV file.
Args:
... |
e749cecbf7d6c6ded05510be93b75d4df5195615 | dixit5sharma/Individual-Automations | /Sudoku_Easy.py | 895 | 3.671875 | 4 | print("Input Sudoku - ")
with open("Files/SudokuFileEasy.txt","r") as f:
a=[]
for line in f:
print(line,end="")
a.append(list(map(int,line.split())))
loopContinue=True
while(loopContinue):
for i in range(9):
for j in range(9):
if a[i][j]==0:
... |
0b11a9816b1a01cefa52012d6dce688dd997f361 | ashrielbrian/coursera-algorithms-specialization | /01 Algorithmic Toolbox/03 Week 3/covering-segments-revised.py | 1,140 | 3.9375 | 4 | # Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
# Sort according to the end points of each segment in ascending order
sortedSegments = sorted(segments, key=lambda segment: segment.end)
requiredPoint = ... |
45f108190fc597c625059e02ab6e44a784d3aa41 | jhonatanmaia/python | /study/curso-em-video/exercises/029.py | 132 | 3.671875 | 4 | a=int(input('Enter the velocity: '))
if a>80:
b=(a-80)*7.0
print('You received a traffic ticket! Value $ {:.2f}'.format(b)) |
642e36b167d30ccdd0426370b18f8bcf80e86300 | James-Do9/Python-Mastering-Exercises | /exercises/11-Swap_digits/app.py | 292 | 4.1875 | 4 | #Complete the fuction to return the swapped digits of a given two-digit-interger.
def swap_digits(num):
left_num = str(num // 10)
right_num = str(num % 10)
return (right_num) + (left_num)
#Invoke the function with any two digit interger as its argument
print(swap_digits(13))
|
6d788d93336c264037107711ff97efaecaf37d90 | daniel-reich/ubiquitous-fiesta | /rMwssAueJjn9FmjZC_10.py | 253 | 3.578125 | 4 |
def number_pairs(txt):
txt = txt.split(' ')
numLis = txt[1:]
pair = 0
while len(numLis):
count = numLis.count(numLis[0])
pair += count//2
numLis = list(filter(lambda n: n !=numLis[0], numLis))
return pair
|
87fc7bbba277f7d2f4dea919746156af6d54aab4 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2618/60760/320294.py | 214 | 3.546875 | 4 | tests=int(input()) #找规律
lists=[]
all=[]
all.append(tests)
for i in range(tests):
a=int(input())
all.append(a)
lists.append(list(map(int,input().split(' '))))
all+=lists
res=sum(all)
print(res) |
0e2a43ed96efc6516f72956dc2c1d3cc3d5ffc59 | henrique17h/Aprendizado_Python | /desafio91.py | 1,544 | 3.65625 | 4 | from time import sleep
time = list()
dados = dict()
partidas = list()
while True:
dados.clear()
dados['Nome'] = str(input('Nome do jogador: '))
total = int(input(f'Quantos partidas {dados["Nome"]} jogou: '))
partidas.clear()
totGols = 0
for c in range(1, total+1):
partid... |
e21f6f0c0f7014a0d9ecb10370662a4ab7bd9714 | Shelkopryad/python_common | /counter.py | 283 | 3.546875 | 4 | words = input("Write:\n")
def replace(s):
return s.replace(".", "").replace(",", "").replace("!", "")
tmp = [x.lower() for x in replace(words).split()]
result = {}
for x in tmp:
if x not in result:
result[x] = 1
else:
result[x] += 1
print("\n", result) |
b8557b82dccf452688c8d4beabb48a4171f6d6d5 | likhitha5101/DAA | /Assignment-5/bruteforce.py | 326 | 3.859375 | 4 | def matchnuts(nuts,bolts):
n=len(nuts)
for i in range(0,n):
for j in range(0,n):
if(nuts[j]==bolts[i]):
nuts[i],nuts[j]=nuts[j],nuts[i]
print("Arranged order of nuts: ",nuts)
bolts=[5,2,1,4,9,8,6]
nuts=[1,4,6,8,9,5,2]
print("Order of Bolts: ",bolts)
print("Initial order of nuts: ",nuts)
matchnuts(nuts,b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.