blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7693aea0be5dd70eeaa68f29475448a8a57e8623 | clairewkh/Python_Challenge | /PyPoll/main.py | 2,919 | 3.890625 | 4 | #Importing csv and os
import csv
import os
#Setting path of the csv and reading the csv file
path2 = os.path.join('Resources','election_data.csv')
with open (path2) as data2:
read2 = csv.reader(data2,delimiter = ",")
#Setting up holders to store values in the loop
tot_counts = 0
Khan_counts = 0
Correy... |
aeaf21b5dc3317a918c9301eb44faab33e4c43cf | michal-stoma/exercism-python | /grade-school/grade_school.py | 398 | 3.5 | 4 | class School(object):
def __init__(self, name):
self.name = name
self.roster = {}
def grade(self, grade):
return self.roster.get(grade, set())
def add(self, student, grade):
self.roster.setdefault(grade, set()).add(student)
def sort(self):
return ((key, tuple(s... |
8ebe4e6785c7ee87e0b54588645efd4df87c5d4d | Sengolda/python-tools | /pytools/valid_email.py | 223 | 3.703125 | 4 | import re
EMAIL_PATTERN = r"([\w\.-]+)@([\w\.-]+)(\.[\w\.]+)([\w\.]?)"
def check_email(email):
is_real_email = re.search(EMAIL_PATTERN, email)
if is_real_email:
return True
else:
return False
|
1b6c52d981ba9e5242239ca4c7abebcc58ddf783 | here0009/LeetCode | /Python/StoneGameII.py | 1,918 | 3.765625 | 4 | """
Alex and Lee continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alex and Lee take turns, with Alex starting first. Initially, M = 1.
On each player's... |
f6aa9da698de808415b102cda054b6cd9f001540 | miguelzeph/Python_Git | /2009_2010/06_Estudo_Matplotlib/Física_Ondas/interferencia destrutiva.py | 323 | 3.828125 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,100,0.001)
A=5
y1=A*np.sin(x)
y2=A*np.sin(x+np.pi)#coloquei uma fase de 180 para poder anular com a onda y1 , assim temos uma onda destruitiva
y=y1+y2
plt.plot(x,y,'ro',x,y1,'r-',x,y2,'b-',20)
plt.show(... |
1afcc800c7f4bdd3381bcedde69b7a984e0c3900 | ayhansevimli/python-fundamentals | /examples/else-002.py | 298 | 4.03125 | 4 | soru = input("Bir meyve adı söyleyin bana:")
if soru == "elma":
print("evet, elma bir meyvedir...")
if soru == "karpuz":
print("evet, karpuz bir meyvedir...")
if soru == "armut":
print("evet, armut bir meyvedir...")
else:
print(soru, "gerçekten bir meyve midir?") |
154abdee6be767f4a0b89e54ef25c07bb182b165 | agungsedayu/latihanGIT | /modul/tugas_sumtriangle.py | 1,524 | 3.8125 | 4 | def sum_of_triangle(n):
z = []
start = 1
for i in range(n):
for j in range(1,i+2):
if i < j:
print('[' + str(start)+']', end = ' ')
else:
print(start, end = ' ')
start +=1
z.append(start-1)
print('\n')
x = 0
... |
2c3594d1a4505d50918c8ff216d7d35ac298f611 | HadzhieV777/SoftUni_Fundamentals_2021 | /Data Types and Variables-Exercise/02. Chars to String.py | 196 | 4.1875 | 4 | # 02. Chars to String
char_one = input()
char_two = input()
char_three = input()
def char_to_string():
string_all = char_one + char_two + char_three
print(string_all)
char_to_string()
|
0180fd1747c2769f1b430a766b1634299863f91b | aki0601/NLP100ver2020 | /chapter_1/1-1.py | 128 | 3.703125 | 4 | a = 'パタトクカシーー'
odd_str = a[::2]
print(odd_str)
# Ref. https://www.headboost.jp/python-how-to-slice-strings/#122 |
0225d6b26584c52f271028b2736a561667114dd9 | furas/python-examples | /__scraping__/travel.padi.com/main.py | 971 | 3.796875 | 4 | #!/usr/bin/env python3
# date: 2019.11.30
# https://stackoverflow.com/questions/59113577/selenium-in-python-finding-an-element-via-relative-xpath
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get('https://travel.padi.com/s/liveaboards/caribbean/')
all_cards = driver.find_elements_by_xpath... |
b31ca0931532dda7925a152b0bd26535b23d4953 | NorthcoteHS/10MCOD-Dimitrios-SYRBOPOULOS | /user/classroll.py | 780 | 3.75 | 4 | """
prog: classroll.py
name: Dimitrios Syrbopoulos
Date: 01/05/2018
Desc: making a roll that tells who is on guinne pig duty
"""
#import random
import random
#the roll is the following names
roll = ['Jessica', 'Emily', 'Jordan', 'Kayley', 'Bruce', 'Michael', 'Everett', 'Lisa', 'Sam', 'Noah']
#created a veriable for the... |
d1b00deae0615a663ffc8fa7ec1fb76906d9c443 | easmah/topstu | /functions08/storingfunctions_as_modules.py | 731 | 4.34375 | 4 | """One advantage of functions is the way they separate blocks of code from your main program.
You can go a step further by storing your functions in a separate file called a module and then importing that module
into your main program. An import statement tells Python to make the code in a module available in the curre... |
78e4838780877aac53962a325d6489c628bb28c1 | jongiles/python_data_apy | /session_08_working_files/inclass_exercises/inclass_8.55.py | 599 | 3.578125 | 4 | # 8.55: First view, then concatenate the two DataFrames
# vertically.
import pandas as pd
df = pd.DataFrame({ 'a': [1, 2, 3],
'b': [2.9, 3.5, 4.9],
'c': ['yourstr', 'mystr', 'theirstr'] },
index=['r1', 'r2', 'r3'])
df2 = pd.DataFrame({ 'b': [4, 5, 6],
... |
230fe930d066a4a757c4e1702ecc21a04854bf43 | RavichandranJM/scripts | /python/medium.com/mprocess_ex.py | 405 | 3.609375 | 4 | #!/usr/bin/env python
import multiprocessing
def square(d):
print("square: ", d * d)
result = d * d
print(result)
def quad(d):
print("quad: ", d * d * d * d)
if __name__ == "__main__":
num = 7
result = None
t1 = multiprocessing.Process(target=square, args=(num,))
t2 = multiprocessing.Process(t... |
23469cae1a365d2cc768cdf868fc5a6232cb6f38 | ManuelCM21/Upeu-proyecto-21 | /AVANCE-Unidad_1/Ejercicios_10/Ejercicio10.py | 662 | 3.890625 | 4 | def estcondicional10():
#Definir variables y otros
print("--> EJERCICIO 10 <--")
paquete=0
#Datos de entrada
dinerox=int(input("Ingrese el dinero que recibirá: "))
#Proceso
if dinerox>=50000:
paquete=("una television, un modular, 3 pares de zapato, 5 camisas y 5 pantalones")
if dinerox<50000 and din... |
1878b1da75ac172531bb1697af8660b7bed16fb3 | Tej-Singh-Rana/Adhocnetworks-Workshop | /nlp_operation.py | 1,728 | 3.703125 | 4 | # Using NLP
import nltk
#nltk.download('all')
from urllib import request # for downloading data from url
from bs4 import BeautifulSoup # for souping
import time
import re # importing regular expression
# Pointing to URL
url='https://en.wikipedia.org/wiki/Machine_learning'
htmldata=request.urlopen... |
f08b2944524c87e846b8ad6fb93ccc899011caa4 | SnapWars/CodingWar | /david/sessions/2018/medium/865_smallest_subtree_with_all_the_deepest_nodes.py | 1,054 | 3.6875 | 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 subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
... |
75d6630d7512fc6db27d490ab48c7523a228fd0d | brittainhard/py | /cookbook/objects/encapsulation.py | 1,188 | 3.890625 | 4 | class Foo:
"""
Python is a consenting adult's language. No such thing as private and public
methods.
If this leads me away from doing this very natural thing, then its
definitely to be stopped. I know you didn't need to need. Needing. Needling
Fiddling.
"""
def __init__(self):
... |
2a2bab3fb36503bff755dd7d87d447a283ccc295 | MysteriousSonOfGod/py | /fileHandling.py | 1,067 | 3.53125 | 4 | import os
myFiles = ['Read.txt','test.txt']
# path = os.path.join('D:','\\Learning','Programming','Python')
path = os.getcwd()
for filename in myFiles:
path1 = os.path.join(path,filename)
print(path1)
print(os.path.split(path1))
#print(os.path.join('.\\',filename))
print('Directory Name is: ' + ... |
8e6496911752959d1c92d415369a9ad848dfd325 | Oshalb/HackerRank | /insertionp1.py | 417 | 4.03125 | 4 | # Insertion Sort Part 1
def insertion_sort(n, arr):
target = arr[-1]
idx = n - 2
while (target < arr[idx]) and (idx >= 0):
arr[idx + 1] = arr[idx]
print(*arr)
idx -= 1
arr[idx + 1] = target
print(*arr)
if __name__ == "__main__":
size_of_list = int(input())
list_t... |
0303f0bc2d341a626189df1ee3ab4f117855a61c | cliffgao2s/my-leetcode | /daily-practise/remove-element.py | 1,122 | 3.546875 | 4 | #https://leetcode-cn.com/problems/remove-element/
#关键是O1的 额外空间消耗
from typing import List
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
total = 0
#受限于空间,先将VAL全部替换到队尾
for index in ra... |
e950e2fd9ddce5c9a4eac9402021dd5dce87807a | Kontowicz/Daily-coding-problem | /day_045.py | 320 | 3.96875 | 4 | # Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability
# , implement a function rand7() that returns an integer from 1 to 7 (inclusive).
import random
def rand5():
return random.randint(1, 5)
def rand7():
return ((rand5()*5 + rand5() - 5) % 7) + 1
print(rand7()) |
ba862459f790fdb0d1309d873af02dc66807211c | cyroxx/erika3004 | /erika/erica_encoder_decoder.py | 924 | 3.59375 | 4 | import json
def transpose_dict(dictionary):
return {value: key for key, value in dictionary.items()}
class DDR_ASCII:
CONVERSION_TABLE_PATH = "./erika/charTranslation.json"
def __init__(self, *args, **kwargs):
"""read conversion table from file and populate 2 dicts"""
with open(self.CON... |
fc99e85a355e3b088b03366938f1f143072b372a | akshirapov/think-python | /11-dictionaries/ex_11_10_5.py | 1,343 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
This module contains a code for ex.5 related to ch.11.10 of
Think Python, 2nd Edition
by Allen Downey
http://thinkpython2.com
"""
def word_dict():
"""Make a dictionary of words."""
d = {}
with open('words.txt') as fin:
for line in fin:
d[line.strip()] = []... |
93a69f6035882d59122a073999195546e7a296ff | bella013/Python.questions.repeat | /questao7.py | 163 | 3.96875 | 4 | i = 0
maior = 0
while (i < 5):
i = i+1
num = int(input("Insira um número: "))
if(num>maior):
maior = num
print("O maior número é: ", maior)
|
4b6200e73cb70f1e2e175799abf6a6894cbde39a | jaehui327/PythonProgramming | /Lab0515/Lab03.py | 735 | 3.765625 | 4 | # 축약어 풀어쓰기
# 현대인들은 축약어를 많이 사용한다.
# 예를 들어서 "B4(Before)" "TX(Thanks)" "BBL(Be Back Later)" "BCNU(Be Seeing You)" "HAND(Have A Nice Day)"
# 와 같은 축약어들이 있다.
# 축약어를 풀어서 일반적인 문장으로 변환하는 프로그램을 작성하여 보자.
# 출력 결과
# 번역할 문장을 입력하시오: TX Mr. Park!
# Thanks Mr.Park!
dic = {"B4":"Before", "TX":"Thanks", "BBL":"Be Back Later", "BCNU":"Be... |
221eb474246e827c1dbfa3bb12c0ea70c1efa96c | pbarton666/virtual_classroom | /dkr-py310/docker-student-portal-310/course_files/begin_advanced/py_dict_2.py | 670 | 4.125 | 4 | #py_dict_2.py
my_dict = {'team': "Cubs", "town": "Chicago", "rival": "Cards"}
print("dict is: {}\n".format(my_dict))
default = None
#use popitem() to get some (unknown) item. Will crash if dict is empty.
if my_dict:
key, value = my_dict.popitem()
print("we've removed: {}\n".format(value))
print("dict is n... |
19d8dcecb23468821ce21abc175bfcb91a47c26d | Liuqian-12/my_python_study | /1 基础/字符串的查找与替换.py | 585 | 4.625 | 5 | hello_str = "hello world"
# 判断是否以指定字符串开始
print(hello_str.startswith("hello"))
# 判断是否以指定字符串结束
print(hello_str.endswith("world"))
# 查找指定字符串 (find:如果指定的字符串不在,会返回-1;index:会报错)
print(hello_str.find("llo"))
print(hello_str.find("abc"))
'''
print(hello_str.index("llo"))
print(hello_str.index("abc"))
'''
# 替换字符串 (replace方法... |
3f292207f0315bf5b255cc7065727f1a2b4bf4b1 | caozongliang/1805 | /12day/5题一.py | 291 | 3.734375 | 4 | str = '人生苦短,我用python,life is short'
a = str.count('p')
print('p的个数为:%d'%a)
b = str.count('l')
print('i的个数为:%d'%b)
c = str.rfind('s')
print(c)
str1 = str.upper()
print(str1)
str2 = str.lower()
print(str2)
str3 = str.title()
print(str3)
d = str[7:13]
print(d)
|
483cbf22fe287b21188cc96ed25764396d946022 | walymoss/pythoncourse | /functions.py | 92 | 3.640625 | 4 | def sayHello():
name = input("What's your name\n")
print("Hello ", name)
sayHello() |
2d7df997fec548bad060d05d237d7c59a948e6ea | saubhik/leetcode | /problems/beautiful_arrangement.py | 1,494 | 3.71875 | 4 | from unittest import TestCase
class Solution:
# Examples:
# n=3
# 1,2,3
# perm[i] is divisible by i.
# i is divisible by perm[i].
# There is at least 1 beautiful arrangement: 1, ..., n.
# Consider the reverse: 3, 2, 1. This is also beautiful.
# 1, 3, 2 or 2,... |
d741a787f92878ac49f36b4b137724ebc6df30cc | jackfriend/piglatin | /piglatin.py | 1,232 | 3.734375 | 4 | import sys
import re
def read_file(FILE_ONE):
with open(FILE_ONE, 'r') as file_one:
data = file_one.read()
return split_sentence(data)
def convert_file(FILE_ONE):
word_array = []
for word in FILE_ONE:
word = convert_word(word)
word_array.append(word)
return "".join(wo... |
c9de1c6162d050dd7248b3889ecfb7fea8d347e2 | JoelBondurant/RandomCodeSamples | /python/mathtool.py | 460 | 3.78125 | 4 | """
Starting collection of needed math utils.
"""
def pct(a, b, percent = True, asstr = False, ndigits = 4):
""" Percent difference function: Calculate the percent difference from a to b. """
result = 1.0 * (b - a) / a
if percent:
result *= 100.0
result = round(result, ndigits)
if asstr:
result = str(result) ... |
2cab5e6b6c314ae3764b8c8a12f1f04425b4545c | Dani7410/PythonLearning | /ListComprehension and Modules/1.ListCompExercises.py | 603 | 4.15625 | 4 | #Create a list of capital letters in the english alphabet
#--
alphabet = [chr(x) for x in range(65,91)]
print(alphabet)
print("-------------------")
#Create a list of capital letter from the english aplhabet,
# but exclude 4 with the Unicode code point of either 70, 75, 80, 85.
#--
CapitalL = [chr(x) for x in rang... |
6085e0ae6440293d2bb2ed25bbd45e7bf232e9d8 | mcs526/PythonProjects | /numberGame/number_game.py | 1,294 | 4.1875 | 4 | import random
def greeting():
print("Welcome to the Number Guess Game!")
print("You have 5 chances to correctly guess the number the computer is thinking of. \nGood luck!")
def game():
guess_count = 5
while(guess_count):
try:
guess = int(input("Guess a number between 1 and 100: "))
except NameError:
pri... |
ae5fa3dd2286dec1d490e16e279f67825375cdae | RadkaValkova/SoftUni-Web-Developer | /Programming Basics Python/06 Nested Loops More Exercises/Unique PIN Codes.py | 591 | 3.90625 | 4 | a = int(input())
b = int(input()) # не успявам да я направя
c = int(input())
for first_digit in range(1, a+1):
if first_digit % 2 != 0:
continue
counter = 0
number = 0
for second_digit in range(2, 7+1):
number = second_digit
if number % second_digit == 0:
... |
92e670812af1f1b40818d6db7cab3af50691e78d | dengyungao/python | /老男孩python全栈开发第14期/python基础知识(day1-day40)/字典+列表/python生成器.py | 854 | 4.0625 | 4 | '''
生成器函数让你可以声明行为类似迭代器的函数。它们让程序员能够以快速、简单和简洁的方式生成迭代器。
不妨举例解释这个概念。
假设你需要为前100000000个完美平方数求总和,从1开始。
使用列表推导很容易做到这一点,但问题是输入量很大时容易内存溢出,生成器则不会:
'''
import time
def 使用列表推导式():
t1 = time.time()
sum([i * i for i in range(1, 10000000)])
t2 = time.time()
time_diff = t2 - t1
print("It took {0} Secs to execute this method".fo... |
17a0d9b81dd3f3833b2c016831c7e4f7b6061026 | alexbnlee/python | /Coding Study/20180118-编码操作.py | 3,953 | 3.53125 | 4 | from blog_diy import *
blog.getTitle3()
def getTitle4(index=1, *t):
# 将得到的结果自动复制到剪贴板上
"为标题添加特殊样式的 HTML 代码 —— title 为名称 —— index 为锚点名称"
from Tkinter import Tk
r = Tk()
title = r.clipboard_get()
if len(t) > 0:
title = t[0]
s = '<div class="title_hh"><a name="A'+(str(index)).zfill(2)+'"></a><strong>' +... |
7707bdab57ee4eb5cf3b4f92f0d8fe82cb0a94f0 | ruigege66/PythonReptile | /Reptile3_PostAnlysis.py | 1,265 | 3.609375 | 4 | """
"""
from urllib import request,parse
#负责处理json格式的模块
import json
"""
大致流程:
(1)利用data构造内容,然后urlopen打开
(2)返回一个json格式的结果
(3)结果就应该是girl的释义
"""
baseurl = "https://fanyi.baidu.com/sug"
#存放迎来模拟form的数据一定是dict格式
data = {
#girl是翻译输入的英文内容,应该是由用户输入,此处使用的是硬编码
"kw":"girl"
}
#需要使用parse模块对data进行编码
data = parse.urlencode(... |
695d8c0f877c152c932563ef7ee8bdf914729424 | OnlyWangyn/algorithm | /plusone.py | 502 | 3.578125 | 4 | class Solution:
"""
@param: digits: a number represented as an array of digits
@return: the result
"""
def plusOne(self, digits):
left = len(digits)-1
while left>=0:
if digits[left]+1<10:
digits[left]=digits[left]+1
break
else:
... |
9d4618cc9fce7c4dbe23f15471250b375ae35a76 | YK0L0DIY/Python | /capicua.py | 237 | 3.734375 | 4 | import sys
num1=int(input("Indique um numero de 3 algarismos "));
numt1=int(num1*0.01);
numt2=num1-(int(num1*0.1)*10);
if numt1==numt2:
print("O numero "+str(num1)+" e capicua.");
else:
print("O numeor "+str(num1)+" nao e capicua.");
|
48d268dadeea93e9c3cc6730b1fd466725c37fe0 | usman-tahir/rubyeuler | /pernicious_numbers.py | 623 | 3.6875 | 4 | #!/usr/bin/env python
def population_count(n):
return sum([int(ones) for ones in bin(n) if ones == '1'])
def is_prime(n):
return False if n == 1 else not len([d for d in xrange(2,n) if n % d == 0])
def is_pernicious(n):
return is_prime(population_count(n))
# display the first 25 pernicious numbers
perni... |
41d2986b4413502423f1af487036cbf7aab68e61 | sneha-singh1/Python-Assignment | /Python-Assignment/day1/pattern.py | 737 | 4.0625 | 4 | #assign-pattern
line=int(input("Enter the lines"))
for i in range(0,line):
print("*"*i)
#reverse
#j=line
#for i in range(0,line):
# print("*" *j)
# j-=1
# break
#vansh ka code
a=int(input("Enter number of lines: "))
str="python"
for n in range(1,a):
print()
print(n... |
384b2ff73f9714e453b423fa5d2ca42f0f730172 | YanisKachinskis/python_basic_200120 | /lesson3/hw3.py | 658 | 4.40625 | 4 | # homework lesson: 3, task 3
"""
Реализовать функцию my_func(), которая принимает три позиционных аргумента,
и возвращает сумму наибольших двух аргументов.
"""
def my_func(num_1: int, num_2: int, num_3: int) -> int:
"""
Функция считает сумму двух наибольших чисел из трех.
:param num_1: int
:param num_... |
ac8fd15c282db1580044ae6154936c34c543d298 | sqrhussain/structure-in-gnn | /src/misc/separator.py | 1,113 | 3.8125 | 4 |
# A slightly modified version of James Allen's code, to split a list of numbers in the format [x1,...,xn]
# Source: https://gist.github.com/jlln/338b4b0b55bd6984f883
import pandas as pd
def splitDataFrameList(df,target_column,separator):
''' df = dataframe to split,
target_column = the column containing the ... |
b56fbf31fdbcf2714ee1daa847233b6dacf57719 | takenmore/Leetcode_record | /offer_jz/32.levelOrd.py | 2,038 | 3.828125 | 4 | '''
@description: 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
@param {type} Tree
@return: 层次遍历结果
'''
import collections
from typing import List
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
'''
队列实现的层次遍历
'''
class Solution:
# 逐行打印 保存
... |
e3ddc46bd471115d1d06c204e214f8efe91e4ad9 | zhangludada/m-learn | /notes/两个变量的矩阵运算.py | 229 | 3.625 | 4 | import numpy as np
#if a=x,b=3,y=2x+3 == [5,7,9]
#a为样本 1,2,3
#把a做成3*2的矩阵
a=[[1,1],[2,1],[3,1]]
a=np.mat(a)
#假设线性关系
x=[[2],[3]]
x=np.mat(x)
#矩阵dot(a,x)就是要求的y
y=np.dot(a,x)
print(y)
|
55e5633a1cb0d9e661d07efc146370c8516a90f2 | natasapan/python-exercises | /exer6.py | 162 | 3.9375 | 4 | num_str = input("Wright a number: ")
num_int = int(num_str)
prod_int = 1
x = 1
while x < num_int + 1:
prod_int = prod_int * x
x = x + 1
print (prod_int)
|
cfa308e8e6b13513d7a50856942bab213499e3af | kctoombs/CS8 | /lab02/lab02.py | 1,693 | 4.03125 | 4 | #lab02.py by Kenneth Toombs for CS8 lab02, 10/21/2013
#Some Example Python Functions
# Next define a function for the perimeter of a rectangle
# consumes: length, width
# produces: perimeter of the rectangle
# THIS ONE SHOULD PASS ITS TESTS ALREADY. IT IS HERE AS AN EXAMPLE
def perimRect(length,width):
"""
... |
e28ee8fdc0a69ca1370dac4c8cf71ba27eb98523 | pratimasakinala/python | /python/script.py | 2,030 | 4.15625 | 4 | # print("Welcome to Python!")
"""
import datetime
print(datetime.datetime.now())
from datetime import datetime
print(datetime.today().date())
from datetime import datetime as dt
print(dt.today().date())
"""
# string variable (single or double quotes. both work)
# name = "Pratima"
# print(name + " Sakinala")
# mul... |
45587eb24896c4af0df25aacdcdaca27da970d70 | mihirkelkar/languageprojects | /StInt/permutation_game/permutation_game.py | 875 | 3.546875 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import string
def increasing(lst):
if len(lst) == 1:
return True
for i in range(len(lst)-1):
if lst[i] > lst[i+1]:
return False
return True
mem = {}
def winner(lst):
tup = tuple(lst)
if tup in mem:
... |
47a1ce0ee508837a53b63384b14a254af8c73c93 | JoeFerrucci/Python-Playground | /Sorting/01 seqsearch2.py | 247 | 4 | 4 | def sequentialSearch(alist, item):
pos = 0
found = False
for cur in alist:
if cur == item:
found = True
return found
testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]
print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13)) |
d6e06b7717262fe1594a89c13ccbbe5a763b6651 | Sravaniram/Python-Programming | /Code Kata/Prime number or not.py | 176 | 3.546875 | 4 | n=raw_input()
r=0
if n.isdigit():
a=int(n)
for i in (2,a/2):
if(a%i)==0:
r=1
break
else:
r=0
if(r==0):
print "yes"
else:
print "no"
else:
print "invalid"
|
0497ce8fab8bae14d185c8c2c2fae2981db2733a | lagru/docstring-plot-bug-demo | /demo_module.py | 738 | 3.765625 | 4 | """Dummy module."""
def bar():
"""
Do nothing.
Returns
-------
out : None
Nothing.
Examples
--------
If I try to plot something
>>> import matplotlib.pyplot as plt
>>> plt.plot([1, 2, 3], [1, 2, 3])
>>> plt.show()
but end the docstring with a text line right... |
8b2464e225ee5fd25fd4e83b937f52012e118ee9 | uFitch/goit-python-homeworks | /Python-2/Homework_3/fibo.py | 461 | 4.03125 | 4 | def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print('Какой член ряда Фибоначчи хотите узнать?')
n = int(input())
print (fibonacci(n))
if __name__ == '__main__':
print("Файл fibo.py запускается напрямую")
else:
... |
f53b08a286eae58e4ddec10d5f393bfa0af5f2a0 | oudream/hello-fastai | /courses-py/deeplearning2/meanshift.py | 8,000 | 4.21875 | 4 |
# coding: utf-8
# # Clustering
# Clustering techniques are unsupervised learning algorithms that try to group unlabelled data into "clusters", using the (typically spatial) structure of the data itself.
#
# The easiest way to demonstrate how clustering works is to simply generate some data and show them in action. ... |
e5f07bcbeebd09645c92cd5a34ac2838e5b73382 | laxmikantra/books150 | /navigator.py | 958 | 3.53125 | 4 | from collections import MutableSequence
class Navigator(MutableSequence):
def __init__ (self, pages):
self.pages = list(pages)
self.index = 0
def __iter__ (self):
return self
def __next__ (self):
try:
item = self.pages[self.index]
e... |
055de4ce2950c98100eaf87e8e0e50bdb9ee2e3f | shivshankar-123/ATM-machine | /ATM-machine-data-fetching.py | 1,126 | 4.0625 | 4 | print("welcome to ABC bank")
pin=1011
chances=3
balance=50000
while chances !=0:
user_pin=int(input("enter the four digit number:"))
if user_pin!=pin:
chances-=1
print("wrong pin number")
print(f"you have {chances} chances left")
else:
user_choice=input("B: balance... |
4df80767b81dfbca2568436d4d44723c464a17f3 | maddiecousens/dicts-word-count | /wordcount.py | 526 | 3.71875 | 4 | # put your code here.
from sys import argv
def get_word_count(filename):
word_count = {}
with open(filename) as textfile:
for line in textfile:
line = line.rstrip()
words = line.split(" ")
for word in words:
word = word.strip(",.?!;:\"").lower()
... |
b8c77bbd98c638282a4c6cb6946ce7b4bc152bba | SeanLooXy/PHY407 | /Lab4/Lab4_Q3ab.py | 3,145 | 4.03125 | 4 | import numpy as np
import matplotlib.pyplot as plt
#Part a
#Text Exercise 6.10 a
#we can modify the number of loops to acheive different levels of accuracy
#in our case we achieved 10^-6 by setting the number of loops to 15
xa=1.0
numOfLoops = 15
for k in range(numOfLoops):
xa = 1 - np.exp(-2*xa)
print("value... |
a6be380af5d73e0739fc79f7a9839c3d91fafe1e | skobayashi009/self_taught_programmer | /challenge_12_2.py | 471 | 3.828125 | 4 | import math
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r**2
class Triangle:
def __init__(self, l, h):
self.l = l
self.h = h
def area(self):
return 1/2 * self.l * self.h
class Hexagon:
def __... |
e626b1bd6cc9c8287efe8ad6bd29644cb8d191a7 | arthuston/arthuston-demos | /spiral/spiral-python/spiral.py | 1,889 | 4.4375 | 4 | RIGHT = 0
DOWN = 1
LEFT = 2
UP = 3
MOVE_ROW = [0, 1, 0, -1]
MOVE_COL = [1, 0, -1, 0]
def past_limit(row, col, matrix):
"""
Check if row or col is outside range of the matrix.
:param row: row number
:param col: column number
:param matrix: the matrix
:return: true if row or column is out of mat... |
74187c508a514e42c3384edeee09bba8e1795590 | rebeccaaaaaaaaaaa/exercicios-python | /converter_metros.py | 366 | 3.96875 | 4 | # Faça um Programa que converta metros para centímetros.
class Initial():
def __init__(self):
self.metro = float(input('Digite o valor de metros'))
def Converter(self):
self.centimetro = self.metro * 100
print('O valor',self.metro,'corresponde a',self.centimetro)
mostrarResult... |
b6ac56a421147f28fd56cb2031c952c8775de338 | magda-zielinska/python-level1 | /bits.py | 309 | 3.765625 | 4 | # shifting bits
Var = 17
VarRight = Var >> 1
# = 17 // 2 → 8 (shifting to the right by one bit is the same as integer division by two)
VarLeft = Var << 2
# = 17 * 4 → 68 (shifting to the left by two bits is the same as integer multiplication by four - second bit = 2*2 = 4)
print(Var, VarRight, VarLeft)
|
ab16fd5424a96ebee7cc00febf447b51c8a7ac2b | YSreylin/HTML | /1101901079/Array/array11.py | 253 | 3.984375 | 4 | #write a python to remove a specified items using the index from an array
import array
array = array.array('i',[1,3,4,5,6,7])
print("The original array are:", array)
a = int(input("Enter the place number you want to delete:"))
array.pop(a)
print(array)
|
bee5df05a65c82caca2b2cbe5cef87a0b83b80b5 | atsuhisa-i/Python_study1 | /iterable8.py | 96 | 3.8125 | 4 | meat = {'beef': 199, 'pork': 99, 'chiken': 49}
for x in meat:
print(x, 'is', meat[x], 'yen') |
641cf1592e65c67717e8d84914f469cade88e2b5 | Delta-Ark/MarkovTextMimic_Prompter | /line_gen_train.py | 3,669 | 3.5 | 4 | #markov functions (by Allison Parrish)
import sys
import random
def build_model(tokens, n):
"Builds a Markov model from the list of tokens, using n-grams of length n."
model = dict()
if len(tokens) < n:
return model
for i in range(len(tokens) - n):
gram = tuple(tokens[i:i+n])
next_token = tokens[i+n]
if gr... |
0ce4cb68ef50d3433b58c9309600c769352bdb30 | hamdan-codes/python-basic-programs | /new life.py | 16,954 | 3.59375 | 4 | import tkinter as tk
import random
import time
class Game(tk.Tk):
board = []
new_tile_selection = [2, 2, 2, 2, 2, 2, 4]
score = 0
highscore = 0
scorestring = 0
highscorestring = 0
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
sel... |
abc3a1ee76961625dc05b2bcdea5ea6b99febc3b | IuryBRIGNOLI/tarefas130921 | /5.py | 261 | 3.828125 | 4 | p = input("Mostre a qual multiplicação resulta em 10 \n a-5x3\nb-2x5\nc-5x5")
if(p == "a" ):
print("Você errou")
elif(p == "b" ):
print("Você acertou")
elif( p == "c" ):
print("Você errou")
else:
print("Digite um das possibilidades") |
0bf8659ca44eca73773c945f25773125d49df67c | amdslancelot/stupidcancode | /questions/2nd_largest_element.py | 595 | 3.90625 | 4 | # Write a function that returns the seconds largest element in the array.
# For example, given the array [2, 5, 1, 10, 7, 9], the function should return 9.
# [2, 5, 1, 9, 9, 7]
# ^
# res = [9,5]
# [3,3,3]
import sys
def func(nums):
if len(nums) < 2:
exit(1)
res = [-sys.maxint, -sys.max... |
3c25cb3c9fe662c70dc1049f46db56687197913a | dylngg/weekly-programs | /week05/cantDecide.py | 1,380 | 4.125 | 4 | import random
# Get the options
choicesInput = input('Enter your choices: ')
choices = choicesInput.split(',')
favorites = choices
print('Here are your choices:', choices)
# Repeat until Decision has been made
while True:
# If you have more than one option
if len(favorites) > 1:
#Get Input and put it in a list
... |
132391d10cfd590eb6ae3ba83e05b7c0da90655f | lanvce/learn-Python-the-hard-way | /ex33.py | 549 | 3.890625 | 4 |
"""numbers=[]
def tryone(i,j):
while i>j:
print(f"At the top i is {j}")
numbers.append(j)
j=j+1
print("Numbers now:",numbers)
print(f"At the bottom i is {j}")
tryone(6,0)
print(numbers)
for num in numbers:
print(num)"""
numbers=[]
def trytwo(j):
for j in ran... |
2cf02dd041ef0a26d9ae204d9a01caebb5e3723e | Renier83/python | /PyBank/mini/Chainnumber.py | 422 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 8 06:54:47 2020
@author: renie
"""
user_play = "y"
start_number = 0
while user_play == "y":
user_number = int(input(" How many numbers?"))
for x in range(start_number, int(user_number) + start_number):
print(x)
start_number = s... |
fe10d7f11d6837e6dc46a353629bad7b54f26186 | deimelperez/150_Py_challenges | /055.py | 404 | 4.0625 | 4 | import random
rn = random.randint(1,5)
num = int(input("Guess a number between 1 and 5: "))
count = 0
while num != rn and count < 1:
count += 1
if num > rn:
num = int(input("Too high, guess again: "))
else:
num = int(input("Too low, guess again: "))
if num == rn:
print("You win!",rn,"=... |
9ed043925e29d19d09f8b848c57e519517e1bbed | enigdata/python-coding | /OOP/mro.py | 554 | 4.0625 | 4 | class A:
def __init__(self):
print('A')
super().__init__()
class B(A):
def __init__(self):
print('B')
super().__init__()
class X:
def __init__(self):
print('X')
super().__init__()
class Forward(B, X):
def __init__(self):
print('Forward')
... |
4020d1112e34f2427436a55fb22ad9417f0e5bac | sibyllwang/algorithm-benchmarking-analysis | /python_code/util.py | 2,941 | 3.796875 | 4 | import sys
import random
import time
"""
Shuffle an array.
Returns a permutation of the original. Original array remains intact.
"""
def shuffle(arr):
l = len(arr)
ret = list(arr) # make a copy of the original
for i in range(l**2):
j = random.randint(0, l-1)
k = random.randint(0, l-... |
a5aa0c124b076873c486900efff0ab966c5f70c3 | nahgnaw/data-structure | /exercises/graph/number_of_islands_ii.py | 2,752 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by wate... |
24f63740c7dd16ccfdb1c78b97a6463ee0bb7553 | optionalg/challenges-leetcode-interesting | /find-pivot-index/test.py | 2,431 | 4.15625 | 4 | #!/usr/bin/env python
##-------------------------------------------------------------------
## @copyright 2017 brain.dennyzhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File: test.py
## Author : Denny <http://brain.dennyzhang.com/contact>
## Tags:
## Description:
## ... |
e61617508493a067071ab3995c4cc1077f270489 | andreiteo/ierdna | /Edu/2DLists_Nested_loops.py | 350 | 4 | 4 | #!/usr/local/bin/python3
import sys
print(sys.version)
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
#aici specifici sa printeze indexul 0 pentru randul zero si apoi indexul 0 pentru coloana zero
print(number_grid[0][0])
print(number_grid[1][1])
for rows in number_grid:
for column i... |
a01fe698307db429324a2aca1036930e0ae2eb14 | frescosush/Project-Euler-Python- | /code/power digit sum.py | 332 | 3.515625 | 4 | n = 2 ** 1000
print(n)
numbers_list = []
for x in range(0,len(str(n))):
val = str(n)[x:x+1:1]
print(val)
numbers_list.append(val)
int_numbers_list = list(map(int, numbers_list))
print(int_numbers_list)
total = 0
for y in range(0,len(int_numbers_list)):
total = total + int_numbers_list[y]
pr... |
134cd9797a20be3becb35a619904fed7e1bad691 | tainenko/Leetcode2019 | /leetcode/editor/en/[1800]Maximum Ascending Subarray Sum.py | 1,434 | 3.90625 | 4 | # Given an array of positive integers nums, return the maximum possible sum of
# an ascending subarray in nums.
#
# A subarray is defined as a contiguous sequence of numbers in an array.
#
# A subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i
# where l <= i < r, numsi < numsi+1. Note that... |
e7a4fce1a1efce787eb09d76c619a17a46b973f0 | anirbanpalDSC/msds510 | /src/msds510/avenger.py | 6,747 | 3.5625 | 4 | """
This module initializes the object with a dictionary-based
record. If no records is provided, the instance attributes
are not set.
"""
import datetime as dt
class Avenger:
def __init__(self, record=None):
"""
:param record: record (dict): Dictionary-based record of Avenger data
"""
... |
2cca2fecc7a08ffe384320c4abc63e91c87d4c7a | j94wittwer/Assessment | /Informatik/E9/task_2.py | 3,571 | 3.65625 | 4 | from abc import ABC, abstractmethod
class Toy:
def __init__(self, name):
self.name = name
self.is_assembled = False
self.is_painted = False
self.is_wrapped = False
def is_complete(self):
return self.is_assembled and self.is_painted and self.is_wrapped
class Assembly... |
96ab7e029d42a5502f12e5e41313cb0e3f9234b9 | mauved/exercism-solutions | /python/hexadecimal/hexadecimal.py | 1,089 | 4.0625 | 4 | # Hexadecimal to decimal converter
# Written by Sofia Nieves
# Hexadecimal can only two digits
valid_digits = "0123456789ABCDEF"
def hexa(num_string):
# initiliazes our return value
decimal_sum = 0
# This stores the place value of the digit we're on
num_place = len(num_string) - 1
for n in num_s... |
7aa77daea76397883fe7673d7d4a709c9b4bb393 | amritat123/list_Questions | /negtive_element_output.py | 189 | 3.78125 | 4 | a=[1,3,5,6,3]
i=0
while i<len(a):
multi= -1*(a[i])
i=i+1
print(multi)
# in list output will come...
list=[1,2,3,4,5,]
i=0
j=[]
while i<len(list):
j.append(-list[i])
i+=1
print(j) |
4b37caad257e1615073bff81e8170cb448d46fbd | richardok24/Udemy | /Complete-Python-3-Bootcamp/Milestone Project - 2/Blackjack.py | 6,965 | 3.90625 | 4 | import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,'Queen':10, 'King':10, 'Ace... |
2f54dd8ca17dc9afe1c593654fa1e5895bff9a8e | valentalent/CodeForces | /Next_Round.py | 1,305 | 3.75 | 4 | """
Next Round
time limit per test3 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest r... |
d7ae5afab2e259631541b7ce180973f524ff627c | Mateushrb/URI-Online-Judge | /Python/Iniciante/1035 - Teste de Seleção 1.py | 417 | 3.703125 | 4 | # Entrada de dados
A, B, C, D = [int(x) for x in input().split()]
# Seleção
if B > C and D > A:
if C + D > A + B:
if C > 0 and D > 0:
if A%2==0:
print("Valores aceitos")
else:
print("Valores nao aceitos")
else:
print("Valores nao a... |
3930d64dc2b65e15321c674aca93fff4d8aa4d42 | majdalkilany/data-structures-and-algorithms-python | /data-structures-and-algorithms-python/data_structures_and_algorithms/challenges/depth_first_graph/depth_first_graph.py | 3,312 | 3.703125 | 4 | class Node:
def __init__(self, value, next_=None):
self.value = value
self.next = next_
class Stack:
def __init__(self, item=None):
self.top = item
def push(self, item):
if self.top == None:
self.top = Node(item)
else:
new_node = Node(item)
... |
386008a239548e19fbac36561df821df5462bbfe | GabrielBogo/pyference | /pyfer/functions.py | 5,210 | 3.84375 | 4 | import pandas as pd
import numpy as np
def specify(data, response, explanatory=None):
'''
Choose specific columns to feed the subsequent pipeline.
Parameters:
---------------
data: pd.DataFrame
response: string
One column of the dataframe to be the response variable.
explanatory: s... |
9310e7452996b54bf3227db2f53c778667f1e618 | felixtan/cracking-the-coding-interview | /dynamic_programming_and_memoization/magic_index/magic_index.py | 1,599 | 3.96875 | 4 | # O(logn)
#
# Let the sorted array arr contain distinct integers
#
# If arr[i] > i for some index i, then arr[j] > j for all j > i.
# It follows that a magic index cannot exist for any index >= i.
#
# On the other hand, assume that a magic index exists in arr.
# If arr[k] < k for some index k, then the magic index > k... |
c81a12b295e402141be1c16ee281c203bc744055 | NeilFC/Cloud9Test | /OpeningFileRead1.py | 203 | 4.15625 | 4 |
# Open the specified text file in read mode, reading it line-by-line into a list
f = open("printedit.txt", 'r').readlines()
# Loop through the lines of the original input
for line in f:
print line |
358b8c0d3ecd6a9420518b4ddb795d5754f0d8e0 | dimdred/Lynda | /Learning python/shell methods.py | 1,186 | 3.8125 | 4 | import os
import shutil
from os import path
from shutil import make_archive
from zipfile import ZipFile
def main():
# make a duplicate of an existing file
if path.exists("textfile.txt"):
# get the path to the file in the current directory
src = path.realpath("textfile.txt")
# separate ... |
ceded26ca11d3db9e91d1f217edfa73037f127de | OlgaLB/wierdeaux | /HoeWarmIsHetInDelft.py | 1,392 | 3.65625 | 4 | #!/usr/bin/env python3
# for ability to send HTTP requests
import requests
# for pulling data out of HTML file
from bs4 import BeautifulSoup
# for working with page source
import selenium
from selenium.webdriver.firefox.options import Options
# for exiting in case of exception
import sys
if __name__ == "__main__":
... |
b51c5ed37d6f50b9d59e3a216278dc8dfb1368ea | kiok46/Subset-Sum-Problem | /main.py | 4,095 | 3.578125 | 4 | import pandas
import datetime
import numpy
xl = pandas.ExcelFile("HouseHoldElectricity.xlsx")
data_frame = xl.parse(xl.sheet_names[0], skiprows=3)
def calculate_power(current_power, percentage_decrease):
"""
calculates the new power.
"""
required_power = current_power - (current_power * percentage_d... |
e35c12d8adc901bfad341fa36d9667e9a8251677 | turbobin/LeetCode | /排序/sort_colors.py | 1,530 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
75. 颜色分类(荷兰国旗问题)
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,
使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
输入: [1,1,2]
输出: [1,1,2]
"""
class Solution(object):
def sortColors(self, nums):
"""
思路1:最简单可以使用... |
2eda9b84bc2fe0f486ed699864742f649aaaa40b | nchikkam/projects | /py/sorting/selection.py | 342 | 3.8125 | 4 | from lib.util import swap
def selection_sort(a):
# swaps once with min_index
l = len(a)
for i in range(l):
min_index = i
for j in range(i+1, l):
if a[min_index] > a[j]:
min_index = j
swap(a, i, min_index)
a = [4, 5, 2, 6, 9, 10, 1, 3, 8, 7]
print(a)
sele... |
0bd1b4ff957f9859d0b0bd235a6be3bd6b601720 | tmuweh/python-essential | /func.py | 639 | 4.0625 | 4 | #!/usr/bin/env python3
import random
def isprime(n):
if n <= 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
#call prime
number = random.randrange(0, 100)
prime = isprime( number)
if isprime(number):
print("number {} is prime".... |
4858ee02bdcf671b88b15cd7d72e6d88fe2d3a70 | GuXipeng/python-exercise | /ex4.6.py | 614 | 3.828125 | 4 | #! /usr/bin/env python3
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any" ,kind,"?")
print("-- I'm sorry, we are all out of", kind)
for arg in arguments:
print(arg)
print("-" * 48)
keys = ... |
275b4020055fd5bd74157f27a87f51b6b959d471 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_53/1013.py | 2,720 | 3.890625 | 4 | class Snapper:
"""
Google Codejam problem 1:
Snappers are power intermediaries that control current.
Snappers may be ON or OFF, and may only change state when powered.
Snappers keep track of their connections, and connections must support
the function call is_on()
"""
def __ini... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.