blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
05189f24e379d4140a05e39036e0c84ae426cd45 | bakil/pythonCodes | /days between two dates course/days between two dates v3.py | 3,083 | 4.34375 | 4 | # Given your birthday and the current date, calculate your age
# in days. Compensate for leap days. Assume that the birthday
# and current date are correct dates (and no time travel).
# Simply put, if you were born 1 Jan 2012 and todays date is
# 2 Jan 2012 you are 1 day old.
# IMPORTANT: You don't need to solve t... |
7687eb1f8832c57fbb4f887533dda1e0bcc38b07 | tommycheung24/Crypto-Corgi-Company | /Project 4 Crypto Corgi Company.py | 8,138 | 4.25 | 4 | from cisc108 import assert_equal
def main():
"""
Main function that calls all the other functions and provides
an crypto experience
"""
#Asks if the user wants to encrpyt text or decrypt text
user_input = input("Do you want to encrypt or decrypt?")
#if the user typed "encrypt"
... |
8a3cb1d1a9524ef8ab023cfa6443cd0492a0867f | patriciavg1/course-content | /tutorials/W3D2_HiddenDynamics/solutions/W3D2_Tutorial2_Solution_df351917.py | 1,060 | 3.953125 | 4 | def markov_forward(p0, D):
"""Calculate the forward predictive distribution in a discrete Markov chain
Args:
p0 (numpy vector): a discrete probability vector
D (numpy matrix): the transition matrix, D[i,j] means the prob. to
switch FROM i TO j
Returns:
p1 (numpy vector): the predictive probabili... |
eb32a2a8a66389f6e8587864d81f0a26fcd23845 | sweetreprise/Flask-19.2 | /stories.py | 2,797 | 4.21875 | 4 | """Madlibs Stories."""
class Story:
"""Madlibs story.
To make a story, pass a list of prompts, and the text
of the template.
>>> s = Story(["noun", "verb"],
... "I love to {verb} a good {noun}.")
To generate text from a story, pass in a dictionary-like thing
of {prompt: ans... |
98f5c5fa7f2696546900839982cb7b9221ac31e4 | rohitg15/UMCPCrypto | /assignment1/crypto/vigenere_encryption.py | 850 | 3.515625 | 4 | import sys
# assuming inputs are bytearrays
def encrypt(message, key):
key_len = len(key)
message_len = len(message)
# divide message into blocks based on key length
mblocks = [message[i * key_len : (i + 1) * key_len] for i in range(message_len / key_len)]
# handle trailing bytes
if message_l... |
4d0d884069feab8394799711a00fdf7023bf129f | RenaLu/Team-design-software | /factorTrinomialsTestCases .py | 4,504 | 4.125 | 4 | ######################################################################################################
#Purpose: this program includes a wide variety of cases that tests the package factorTrinomialTool.py
#Programmers: Rena Lu, Pavneet Kapoor, Saad Haq, Alex Nelson
#Last Modified: May 13, 2014
#########################... |
cbffec6c1ec8fc2200385fbade3a3a75eb30e265 | drkndl/Coding-Practice | /Project Euler/collatz.py | 566 | 3.578125 | 4 | #Heads up, this program is painfully slow
import numpy as np
arr = np.arange(20,1000000,1)
print(arr)
#Took the array from 20 cuz there's no way the first 20 numbers have the longest Collatz sequence
def collatz(elem):
count=0
while elem>=16: #Took it till 16 cuz after that it's just 8,4,2,1 for all numbers
if e... |
cc639a171f2a93928e5c46f0482c487431cfbece | rahulvennapusa/PythonLearning | /LargestOddNumber.py | 546 | 4.03125 | 4 | counter = 0
largest_odd_number = 0
input_numbers = [None, None, None]
while counter <= 2:
x = input("Enter a number: ")
# line= sys.stdin
if type(int(x)) == int:
input_numbers[counter] = x
counter += 1
for numb in input_numbers:
# print(type(numb))
if isinstan... |
be33c5f2cbe612722fd2f54bb0c73ac9eef2acc4 | Eagalaivan/practice | /arrayminoperation.py | 1,237 | 3.671875 | 4 | def atobminop(a,b):
lena=len(a)
#lenb=len(b)
calc_boi=1
diff=0
min_op=0
for i in range(lena):
if(a[i]!=b[i]):
print(a[i],b[i])
diff = b[i]-a[i]
a[i]+=calc_boi
if(diff == b[i+1]-a[i+1]):
min_op+=1
els... |
811f57a5846faaabb970f047bc87a5b14b88b0f1 | NenadPantelic/GeeksforGeeks-Must-Do-Interview-preparation | /Trees/BinaryTreeSize.py | 566 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 17 14:09:24 2020
@author: nenad
"""
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
# count number of nodes in BT
def size(root):
if root is None:
return 0
#... |
d2131bd6229bff8f5d79313851dedc383305a54b | iFengZhao/Algorithms-1 | /剑指Offer/03-2-不修改数组找出重复的数字.py | 2,790 | 3.515625 | 4 | '''
题目:
在一个长度为n+1的数组里的所有数字都在1-n的范围内,所以数组中至少有一个数字是重复的,请找出数组中任意一个重复的数字,
但不能修改输入的数组,例如,如果输入长度为8 的数组 [ 2, 3, 5, 4, 3, 2, 6, 7 ] 那么对应的输出是重复的数字2或者3。
'''
# 方法一:创建一个长度为n+1的辅助数组,然后逐一把原数组的每个数字复制到辅助数组。如果原数组中被复制的数字是m,则把它复制
# 到辅助数组中下标为m的位置。这样很容易发现哪个数字是重复的。
# 空间O(n)
def duplicate1(arr):
if not isinstance(arr, list):
r... |
2a6de67a1fdb0424de38493103dc65e8d0227ec3 | skurmedel/wordsalad | /wordsalad/input/tokenisation.py | 2,054 | 4.09375 | 4 | import string
def split_germanic(text, strip={"\r"," ", "\n", "\t"}, whitespace=string.whitespace, punctuation=string.punctuation, start_words=[], sentence_end=".?!"):
"""Tries to split the input text as if it were natural language "germanic" text,
like english or german.
whitespace will be used as word s... |
987646752d203c14704a3c50c2d1ae62a07815f4 | sammiriche/datacode | /0.学习大纲/4.python算法.py | 320 | 3.875 | 4 | 1:疑难重点
不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)
a = 3
a += 3
最后 id(a)是会变得 但是list 使用append方法添加元素,id 不会变。
|
ff39187bf0d2692afb7dc19b6ae599656ee7be52 | nzwg1412/my_first_app | /first_app.py | 2,655 | 3.65625 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time
dt = pd.read_csv("treatmentpara.csv")
df = pd.read_csv("fractures.csv")
# st.title("streamlit demo")
# st.write("""s
# Hello *world!!*
# """)
# st.write("""
# Here are our dataset prepared for machine learning m... |
1f77c9d855262832e20b81b10042b9021909a226 | everettsouthwick/politics-bot | /modules/sql_init.py | 1,118 | 3.703125 | 4 | import sqlite3
class SQLInit:
def __init__(self):
self.conn = sqlite3.connect("main.db")
self.cur = self.conn.cursor()
self.cur.execute('''
CREATE TABLE IF NOT EXISTS `saves` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
... |
98bb5d881a32b12d55f4e64398e6d3a18ac7c370 | morepath/reg | /reg/context.py | 5,215 | 3.75 | 4 | import inspect
from types import MethodType
from .dispatch import dispatch, Dispatch, format_signature, execute
from .arginfo import arginfo
class dispatch_method(dispatch):
"""Decorator to make a method on a context class dispatch.
This takes the predicates to dispatch on as zero or more parameters.
:p... |
af39c1aa11505e4e4b58b6335f83d0e99f7fa61c | faqtoff/UCA-InformaticaGeneral | /PRACTICA5/hfj.py | 139 | 3.578125 | 4 | def estaEnLista(num,lst):
if num in lst:
return True
def main():
num=23
lst=[1,2,3,4]
estaEnLista(num,lst)
main()
|
d4c9b1976bc997ca4517e2659ba860e9234387ba | Lazizkhan1/Foundation | /R/R9.py | 249 | 3.703125 | 4 | arr = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
new = []
for i in arr:
i = list(i)
i.reverse()
new.append(i)
new.sort()
arr.clear()
for i in new:
i.reverse()
arr.append(i)
print(arr)
# [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
|
d7f76a587ccb4855a65fe10e8634f72ebac7a57c | Noufal21/732A74----Intro-to-python | /Lab 04/text_stats.py | 9,712 | 4.09375 | 4 | #!/usr/bin/env python3
import sys
import os
import string
from itertools import islice
from itertools import groupby
import operator
from collections import Counter
import string
output_file = False
wholeBooks = ""
out_file = ""
out_AsFile = False
WordCount = 0
UniqueWord = 0
def read_file(path):
with open(path) ... |
29874677cc805fd7b1bee5b761097e733b154801 | rimachinz/pythoncodes | /special pgms/polymorphism-overloading.py | 215 | 3.890625 | 4 | #function overloading
# def add(x,y):
# z = x + y
# return print(z)
#
# # add(2,3)
# add(2.3,5.4)
#operator overloading
def add(x,y):
z = x + y
return print(z)
add('a','b')
add(2.3,5.4) |
aacff2d0e648e0b867d12434a9e25df9d9e86875 | richkde2303/python_basic | /exercise/age_student.py | 383 | 3.96875 | 4 | from datetime import datetime as dt
print('태어난 년도를 입력하세요 : ')
student_birth = int(input())
current_year = dt.today().year
print(dt.today())
print(current_year)
age = current_year - student_birth + 1
print('나이는 : ', age)
if 15 <= age < 20:
print('고등학생')
elif 20 <= age <= 28:
print('대학생')
else:
print('학생이 ... |
96725f466967b7a09475cd1223d0d368a9e21042 | Ravi-Nikam/Python-Programs | /filter.py | 273 | 3.515625 | 4 | #filter only work with checking the condition
list1=[12,14,32,65,45]
list2=[21,41,22,6,25]
def age_check(age):
# return (age*18)
if age>18:
return True
else:
return False
ans=filter(age_check,list1)
for i in ans:
print(i)
|
b73be79b8bdc56aff424a63194bb2cd77fff433f | Piera/WB-Data-Structures-Algo | /CodingBat/sum3.py | 326 | 4.0625 | 4 | # Given an array of ints length 3,
# return the sum of all the elements.
# sum3([1, 2, 3]) # 6
# sum3([5, 11, 2]) # 18
# sum3([7, 0, 0]) # 7
def sum3(nums):
tot = 0
for i in range(len(nums)):
tot += nums[i]
print tot
return tot
# Can't resist the loop!
sum3([1, 2, 3]) # 6
sum3([5, 11, 2]) # 18
sum3([7, 0, 0... |
1990261c274c16fedd33a023a59098efb99f3acd | Keefetgy/cs1010s-finals-template | /CS1010S/cs1010s-nov14-template.py | 7,602 | 3.53125 | 4 | #!/usr/bin/env python3
## CS1010S Nov14 Template
## Question 1A
"""
Answer here.
"""
## Question 1B
"""
Answer here.
"""
## Question 1C
"""
Answer here.
"""
## Question 1D
"""
Answer here.
"""
## Question 1E
"""
Answer here.
"""
## Question 1F
"""
Answer here.
"""
# The following... |
b9dc40e92346d54f16c1612e1fda98ac65926ef4 | AccLoo0311/mit6.0001-notes-pset | /my_pset_code/ps1/ps1a.py | 622 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 21:56:14 2020
@author: zhenghaoyu
"""
#ps1a.py
annual_salary=float(input("Enter your annual salary:"))
portion_saved=float(input("Enter the percent of your salary to save, as a decimal:"))
total_cost=float(input("Enter the cost of your dream home... |
3cb18daa18054f3846eaf1e549cbcd71c154ea14 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2565/60602/281831.py | 849 | 3.90625 | 4 | def makeIntList(list):
count = 0;
while (count < len(list)):
list[count] = int(list[count]);
count += 1;
return list;
def quickSort(list):
if(len(list)>1):
count=1;
x=list[0];
leftList=[];
rightList=[];
while(count<len(list)):
if(int(li... |
f5198da7422704be4f4be5455c2c8607da8426e5 | Swati213/pythonbasic | /lapallin.py | 185 | 4.125 | 4 | a=input("enter a string")
l=list(map(lambda x:(x==" ".join(reversed(x))),a))
if(a==l):
print("string is pallindrome",a)
else:
print("string is not pallindrome",a)
|
8575954423b7affac17b9871ec2081dd9acf222a | xufengww/python | /advanced feature/triangles.py | 162 | 3.5 | 4 | # -*- coding: utf-8 -*-
def triangles():
L = [1]
while 1:
yield L
L = [1] + [L[i] + L[i+1] for i in range(len(L)-1)] + [1]
|
d040ac70d59007175aca50836666f56852dd6b7b | rajac2000/learnPython_1 | /hello.py | 166 | 3.921875 | 4 | print("Hello world!!")
print("Welcome to Python programming")
a=int(input("Enter first number : "))
b=int(input("Enter Second number : "))
print(a+b)
print ("A", "B") |
2e631023803e9fbcb016f837ce81a9e6f4139b50 | binarioGH/teachingprogramming | /for.py | 258 | 3.828125 | 4 | #-*-coding: utf-8-*-
name = input("Escriba su nombre: ")
vocales = ["a","e","i","o","u"]
contador_de_vocales = 0
for letra in name:
if letra.lower() in vocales:
contador_de_vocales += 1
print("En tu nombre hay {} vocales.".format(contador_de_vocales))
|
8013ee741fb86911c65c396a9e2b0a6bcee3dcb9 | PengInGitHub/Python-Practice | /sort/bubble_sort.py | 1,036 | 3.96875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 1 22:22:35 2018
@author: pengchengliu
"""
def bubble_sort(seq):
if len(seq) < 2:
return seq
# outter loop, iterate each num in seq
for i in range(len(seq)-1):
# inner loop, iterate each num in seq behind i
... |
4ed495e2d2f00631c6747835bdfd0d645c0d40ed | scohen40/wallbreakers_projects | /Leetcode/week_4/p0844_backspace_string_compare.py | 941 | 3.671875 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
return self.stack_soln(S, T)
def stack_soln(self, S: str, T: str) -> bool:
"""
Solution with stacks
Runtime: O(S+T) + O(min(S, T))
Space: O(S+T)
"""
stack_s = []
stack_t = []
... |
dbb151d5bb32d10031406035d7eeb60ccd321769 | lkuszal/licencjat | /playfair.py | 3,377 | 3.90625 | 4 | """ Playfair cipher aims to code text by bigrams, using table 5x5 containing whole alphabet (replacing J by I)
in given order"""
# Written by Lukasz Cholodecki as part of 2021 thesis
from pattern import MasterCipher
class Playfair(MasterCipher):
"""cipher and decipher keys are the same, init method converts given... |
04da3ae4927a1fda03b3ad2e17c1fdae9b0da041 | zhoujun-star/Learning-diary | /4.Radiobutton (选择按钮).py | 561 | 3.671875 | 4 |
import tkinter as tk
t=tk.Tk()
t.title('my home')
t.geometry('200x200')
var=tk.StringVar()
l=tk.Label(t,bg='yellow',width=20,text='you have seleced')
l.pack()
def print_selection():
l.config(text='you have seleced'+var.get())
r1=tk.Radiobutton(t,text='Option A',variable=var,relief='groove',value='A',... |
b21710b3c40fb3935857eacfb04f736ba3dad802 | ValneyFaria/FisicaIII | /ex_1_v1.py | 317 | 3.53125 | 4 | # !/usr/bin/python3
# coding: UTF-8
from math import sin, sqrt, tan, pi
k, l, m, g = 9.0e9, 0.5, 0.1e-3,9.8
temp = input("Enter the value of theta:")
theta = float(temp)
print(f'The value of theta is {theta}')
theta2 = (theta*pi)/180
q = sqrt(((4.*l**2)*(m*g)*(sin(theta2))**2)*(tan(theta2)/k))
print(f'q = {q}C') |
b9c8c3198ea3b91ca79b7666122aeba124f8d46b | blueones/LeetcodePractices | /mergetwosortedlists21.py | 947 | 4.09375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
beforeN = ListNode(0)
dummyN = beforeN
if l1 == None and l2 == None:
ret... |
cf9fa87af9f132b6e235e4327175d82ba6ecb5ca | rmodi6/scripts | /practice/Leetcode/3326_flood_fill.py | 998 | 3.765625 | 4 | # https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3326/
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
oldColor = image[sr][sc]
visited = [[False for j in range(len(image[0]))] for i i... |
3b707d43db6cc7427d859314446fe923a96e0720 | 7anya/tictactoe | /tictactoe/tictactoe.py | 4,850 | 3.921875 | 4 | """
Tic Tac Toe Player
"""
import copy
import math
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who ha... |
13b4bf0c1b75bc2419b934615e024666c1256bdd | Futureprogrammer1/Daily-python-exercise | /Python exercise 2.py | 241 | 4.0625 | 4 | #Bryan Ventura Ortiz - Chapter 2 - Exercise 2
#Enter your name and print
name = str(input('Enter your name: '))
print ('Hello ' + name )
Age= int(input("Enter your age:" ))
x = Age - 100
print ("you will be one hundrerd in " + str(x) + "Years" )
|
2f6dc72affbbd68f1b366581c340d1559fee3808 | AMEER-GITHUB/lecture2 | /lamda.py | 596 | 4.1875 | 4 | people=[
{"name":"Harry", "house": "Gryffindor"},
{"name":"Cho", "house": "Ravenclaw"},
{"name":"Draco", "house": "Slytherin"}
]
'''def f(person):
return person["name"]
'''
# here 'f' takes 'people' as its parameter.
# 'key' is a sort method optional paramete which is used to do custom sorting
# 'rever... |
f7cc951122ee7e7997e49e5c2a60fb4bfa1fde50 | yoga24/py-ds-algo | /chapter03/HotPotato.py | 623 | 3.578125 | 4 | import random
from structures.queue import Queue
def hot_potato(names, num):
game_queue = Queue()
for name in names:
game_queue.enqueue(name)
while game_queue.size() > 1:
for index in range(num - 1):
member = game_queue.dequeue()
game_queue.enqueue(member)
... |
f4c7c8018acaee2e8c681051ec96762ac41eb7bf | nn98/Algorithm | /src/BaekJoon/Simple_Implementation/P5235.py | 304 | 3.546875 | 4 | for _ in range(int(input())):
li = list(map(int, input().split()))[1:]
odd = even = 0
for n in li:
if n%2 == 1:
odd += n
else:
even += n
if odd == even:
print("TIE")
elif odd > even:
print("ODD")
else:
print("EVEN")
|
55e9d929cc326b670327eca3a252d8baf47613a2 | yywecanwin/PythonLearning | /day07/04.列表推导式.py | 820 | 3.859375 | 4 | # -*- coding: utf-8 -*-
# author:yaoyao time:2020/1/10
"""
列表推导式的格式:
列表名 = [x for x in range()函数]
每次循环都得一个数字,然后把x作为元素添加到列表中
在列表推导式中使用 if语句
列表名 = [x for x in range()函数 if 条件]
"""
list1 = [x for x in range(1,5)]
print(list1) # [1, 2, 3, 4]
list2 = [x+2 for x in range(1,5)]
print(list2) # [3, 4, 5, 6]
list... |
230db29fa5aa6fb2d579aadd6a971b32cdad5722 | gitcheng/gitcheng.github.io.old | /ipython_notebook/golden_ratio_and_fibonacci_numbers.py | 3,339 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# <h1>Golden Ratio and Fibonacci Numbers</h1>
# <codecell>
%matplotlib inline
# <codecell>
import numpy as np
import matplotlib.pyplot as plt
import math
# <codecell>
sqrt = math.sqrt
# <codecell>
phi = (sqrt(5)-1)/2
print phi
# <codecell>
... |
a576812adb73a15d11234d4ba6c9250de6eb202d | syo0e/Algorithm | /python/conceptNote/SelectionSort.py | 319 | 3.953125 | 4 | def SelectionSort(arr):
length = len(arr)
for i in range(length - 1):
minIdx = i
for j in range(i + 1, length):
if arr[j] < arr[minIdx]:
minIdx = j
arr[minIdx], arr[i] = arr[i], arr[minIdx]
return arr
arr = [3, 5, 2, 4, 6, 1]
print(SelectionSort(arr))
|
e11deafccfb6c38af6325eb9a765060467ca107a | sinoclover/python | /Web-scraping/Test.py | 648 | 3.546875 | 4 | from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
def getTitle(url):
# 排除URL错误和HTTP未响应的情况,将返回空对象
try:
html = urlopen(url)
except (HTTPError, URLError) as e:
return None
# 排除不存在的标签情况,即调用空对象的标签属性
try:
bsObj = Beautifu... |
794cc48f4a3afab49bee3a61a551cdca49a6ee98 | sandeep-skb/Data-Structures | /Python/Trees/reverse_level_order.py | 757 | 3.9375 | 4 | class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def reverseLevelOrder(node):
if node == None:
print("Node is empty, illegal input")
return
q = [node]
s = []
while(len(q) != 0):
tmp = q.pop(0)
if tmp.right != None:
q.append(tmp.right... |
77f295fa1dfa904e326f3801cda82b27ad5ae046 | amirafzali/coding-questions | /more/lowest-common.py | 401 | 3.578125 | 4 | def lowestCommonAncestor(self, root, p, q):
def search(root):
if root == p or root == q or not root:
return root
left = search(root.left)
right = search(root.right)
if left == p and right == q or left == q and right == p:
return root
if l... |
a807409aea1617cedddcf09b6c6223b56affe77b | Si047p/movie_trailer | /media.py | 650 | 4.0625 | 4 | """ Defines media types with their attributes
"""
class Movie():
"""Class stores the information related to a movie.
Attributes:
movie_title: The movie's title.
poster_image: URL to the movie's poster or box art.
trailer_youtube: URL to the movie's trailer on YouTube
"""
... |
deaa7307a6ed2b508c87f897c4cf22b45bc10d06 | AndersDuncan/statprog | /oblig4/assign6.py | 1,000 | 3.59375 | 4 | import numpy as np
import scipy.stats as st
readings = np.genfromtxt("csv/salmonella.csv", delimiter = ",")
interval = float(input("Please give your confidence interval. "))
if interval > 1:
interval = interval / 100
total = 0
for x in readings:
#Gives every element in the array an exponent of 2, for the ... |
00122d4f4f0fca064bdc987f823b7a151041cadb | sunshineonmyshoulders/python | /zumbis/lista 1/11.py | 278 | 3.859375 | 4 | """ Sabendo que str() converte valores numericos apra strings,
calcule quantos dígitos há em 2 elevado a um milhão"""
v = str(2 ** 1000000) # ** eleva um numero a alguma potência e transforma em string
print(len(v)) # len verifica o comprimento da string e imprime o valor |
fae08c96ab28fb5c5931825938eb7168bf999264 | janagood/My-Advent-of-Code-2020 | /aoc19.py | 4,841 | 3.84375 | 4 | '''
Advent of Code 2020 Day 19
Jana Goodman
Part 1: the patterns in the rules are 'almost' re expressions
Part 2: recursion in rules
In the test rules and challenge rules rule 000 points
directly to 8 and 11 in this order.
So every valid rule follows one of these patterns:
Rule 8 returns pattern like... |
213c24ab62996f4b69339e53696b8e365f81273d | Udhaya19/python-beginner | /practice_python/remove_duplicate.py | 348 | 4.09375 | 4 | def remove_duplicate():
user_list = []
result_list = []
for i in range(0, 8):
get_list_value = int(input("Enter the list value:"))
user_list.append(get_list_value)
print(user_list)
for i in user_list:
if i not in result_list:
result_list.append(i)
print(result... |
cfd49f357ac0eb1ccfa872054bdc2aba8574a653 | saumyaagrahari123/loop | /q23 table.py | 86 | 3.65625 | 4 | n=int(input("enter the number"))
i=1
while (i<=10):
print(n,"x","=",n*i)
i=i+1 |
64036c1580ae66aec969139869f762a9695e3fe3 | nnaeueun/Python_RaspberryPi | /1007/list/practice06.py | 554 | 3.625 | 4 | #1차부터 4차까지 치뤄지는 시험
#차수가 늘어날수록 반영비중이 10% 20% 30% 40% 늘어남
#합계
sList = list()#사용자가 입력한 값을 저장할 배열
sum = 0 #총 합을 저장할 변수 선언
for n in range(1,5): # 1부터 4까지 반복
print(n,end = " ")
score = int(input("차 시험 : "))#사용자로부터 숫자 받음
sList.append(score) #받은 점수를 배열에 저장
sum = int(sList[0]*0.1+sList[1]*0.2+sList[2]*0.3+sList[3]... |
da00384de380fbf82c6dcfc3024557aabcf08f98 | Touseef90/python-projects | /alphabaticorder.py | 445 | 3.515625 | 4 | s = 'azcbobobegghaklabcdef'
asciiValue = 97
newCount = 0
count = 0
index = 0
substr = ''
for x in range(0, len(s)):
if ord(s[x]) >= asciiValue:
count += 1
asciiValue = ord(s[x])
if count > newCount:
newCount = count
index = x
else:
count = 1
asciiValue = ord(s[x])
start = index + 1 - newCount
while... |
1c9ce93f818fc866bc2dab6873269a3daa7c104d | sajedgit/pythonTest | /ifelse.py | 290 | 4.125 | 4 | print(1<2<3)
if 5>9:
if 3>9:
print("one")
else:
print("111")
else:
print("222")
name="Korim"
if name=="sajed":
print("name is {}".format(name))
elif name=="Rahim":
print("name is {}".format(name))
elif name=="Korim":
print("name is {}".format(name))
|
d02ea981864d008f0400b96722199bb74188771d | ablade/CodingChallenge | /Python3/heap.py | 925 | 3.8125 | 4 |
def left(i):
return i << 1
def right(i):
return (i << 1)+ 1
def parent(i):
if i <= 1:
return 1
else:
return i >> 1
def max_heapify(array,lvi,index):
l = left(index)
r = right(index)
largest = index
if l < lvi and array[l] > array[largest]:
largest = l
if... |
a608556df2b601e324e430673910a452a47019ba | Kargina/Geekbrains-python-algorithms | /Lesson1/les_1_task_4.py | 652 | 4.0625 | 4 | # 4. Пользователь вводит две буквы.
# Определить, на каких местах алфавита они стоят,
# и сколько между ними находится букв.
a = input('Введите первый символ: ')
b = input('Введите последний символ: ')
print(f"Буква '{a}' находится на {ord(a)-96} месте в алфавите")
print(f"Буква '{b}' находится на {ord(b)-96} месте... |
1adcf977c14393ac62472c4547011a4b51339603 | Dilshada798/Dictationary | /qno2.py | 333 | 3.921875 | 4 | # Ek program likhiye jisse ki niche di hui dictionaries ek hi dictionary me aa jaaye jaise ki niche Expected result me diya gaya hain or jisski bhi keys same hai unki values add ho jai. Example :-
dict={"name":"pooja","marks":56}
key_name=input("enter the name")
if key_name in dict:
print("exist")
else:
print... |
6f25e2c1ec49fbc192fcf0910c672fad8f4412e3 | hexinping/PythonCode | /practice/py100lianxi/pyquestion13.py | 697 | 3.734375 | 4 | # -*- coding: UTF-8 -*-
'''
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
'''
def func1():
l =[]
for n in range(100,1000):
i = n / 100 #百位
j = n / 10 % 10 #十位
k = n % 10 #个位
... |
0aa11e4492d4dba9b8cef5d9177f4a58ab85df18 | iamasik/Python-For-All | /C 0-2/Code/Print Formating.py | 154 | 4.28125 | 4 | name = "Delwar Hossen"
age = 24
print("My Name IS {} And Age IS {}".format(name,age)) #python 3
#python 3.6
print(f"My Name Is {name} And Age Is {age}") |
7b42a3b4b12332af0f798a53b9f74915c10794b4 | Shmilyqjj/Shmily-py | /Python_Study/DataStructureAndAlgorithm/company_programming_test/others/Solutions.py | 6,375 | 4.03125 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
:Description: 其他公司 笔试编程题 及 实现
:Author: 佳境Shmily
:Create Time: 2020/3/22 0:18
:File: Solutions
:Site: shmily-qjj.top
"""
# def solution():
# """
# 有一张包含n行m列的方格纸,每个小方格都是一个基地(总共有n*m个基地)
# 现在要放置补给品,如果补给品落在小方格内或边界上则该基地获得了补给品
# 如果补给点在交界处,则被视为已为交界的单元格都提供了补给品(如果在两个格子的... |
5ead8768f62a2a01b8b4621d763481138c15139d | Ming-Yi-W/FirstAI | /Numpy/7、数组分割.py | 1,406 | 3.5625 | 4 | import numpy as np
'''
numpy.split 函数沿特定的轴将数组分割为子数组,格式如下:
numpy.split(ary,indices_or_sections,axis)
参数说明:
ary:被分割的数组
indices_or_sections:如果是一个整数,就用该数平均切分,
如果是一个数组,为沿轴切分的位置。
axis:沿着哪个维度进行切向,默认为0,横向切分,为1的时候,纵向切分
'''
print('一维数组')
a=np.arange(1,13)
#调用split函... |
ef21ac756d0876aff6729e8fcbb2a0df401bc28e | cyrsis/TensorflowPY36CPU | /_5_Math/5primeListOptimised2.py | 567 | 3.921875 | 4 | import time
primeList = []
primeList.append(1)
primeList.append(2)
def primeTest(testNum):
prime = True
for i in range(2,testNum,2):
if testNum % i == 0:
prime = False
return prime
def allPrimes(maxNum):
for i in range(3,maxNum,2):
if primeTest(i) == True:
... |
24e98804f28f44f3dc7bebdc9c71bf4811b7830c | tumbleweed-G/OpenFile_Python_Tumble | /Dicionario.py | 494 | 3.875 | 4 | import json
d1 ={
'Pessoa 1': {
'nome':'Luiz',
'idade': 25,
},
'Pessoa 2': {
'nome' :'Rose',
'idade': 30,
},
}
#Salva dados no arquivo principal, com dados do tipo json
d1_json = json.dumps(d1, indent = True)
with open('abc.txt', 'w+') as file:
fil... |
2888e18170c466a1af9f39b2aefdb83c57f32359 | lzz5235/Code-Segment | /Python/求星期天.py | 1,030 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 16 14:49:31 2014
题目内容:
根据下列信息计算在1901年1月1日至2000年12月31日间共有多少个星期天落在每月的第一天上?
a) 1900.1.1是星期一
b) 1月,3月,5月,7月,8月,10月和12月是31天
c) 4月,6月,9月和11月是30天
d) 2月是28天,在闰年是29天
e) 公元年数能被4整除且又不能被100整除是闰年
f) 能直接被400整除也是闰年
@author: lzz
"""
mondays=0
def getmonthdays(yea... |
46cc7bd9ff508c1d57a319f02dead3126d5bc77c | KiruthikaGopalsamy/GraduateTrainingProgram2018 | /Python/Day2.py | 1,505 | 3.8125 | 4 | <PROBLEM SET 02> SEPTEMBER 04,2018
SUBMITTED BY kiruthika.gopalsamy
#get first name and last name from user and print your full name
a=raw_input("enter your first name")
b=raw_input("enter your last name")
print("Full Name : %s%s"%(a,b))
# get ur full name, age as input from user and print first name and last n... |
5943f29054b324135094be958a3e19aaa5462711 | Shashank-117/Python-Projects | /Day 23-Turtle_Crossing/car_manager.py | 816 | 3.765625 | 4 | COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
import random
from turtle import Turtle
class CarManager():
def __init__(self):
self.all_cars = []
self.m = STARTING_MOVE_DISTANCE
def create(self):
chance = random.randint(1... |
b90f2ecd4f503881869361f60cc9546b48300e54 | sirelkhatim/Ciphers | /affine.py | 1,325 | 3.59375 | 4 | from ciphers import Cipher
import string
from helper import mod_inv
class Affine(Cipher):
"""Class that implements affine cipher method"""
def __init__(self):
self.alphabetList = list(string.ascii_uppercase)
self.m = len(self.alphabetList)
def encrypt(self,text,a,... |
c39a780738f99b9a348f8b417ec21ca10c4ca75b | LuisValgoi/python-playground | /dataConversion.py | 139 | 4.03125 | 4 | # Data Type Conversion
birth_year = input('Tell me your birth year: ')
age = 2020 - int(birth_year)
print(f'You are: {str(age)} years old') |
e4cc3fd5a785823246ed211783ee88a4143adfb7 | mws19901118/Leetcode | /Code/Palindrome Permutation.py | 594 | 3.53125 | 4 | class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
dict = {}
for x in s:
if x not in dict: #Count the number of appearance of each character.
dict[x] = 1
else:
... |
b783f8af04166a851297bc14ef59075f001699ee | towerjoo/CS-notes | /gae/lib/django/tests/modeltests/model_forms/models.py | 16,708 | 3.625 | 4 | """
36. Generating HTML forms from models
Django provides shortcuts for creating Form objects from a model class and a
model instance.
The function django.newforms.form_for_model() takes a model class and returns
a Form that is tied to the model. This Form works just like any other Form,
with one additional method: s... |
096b50d9dbf3bbe81ee4b42bc64d2de5632e70c1 | Xrai171/MailTaskGoshan | /MorozovGeorgy.py | 208 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 08 19:31:04 2017
@author: user
"""
lines = 0
FileName = input('Input file name \n')
print(FileName)
for line in open(FileName, 'r'):
lines += 1
print(lines) |
5df18b5485f784506bf8d15ea79710ca9df41476 | murdomoyse/dockerised-flask-nlp-app | /src/helpers/common_functions.py | 1,607 | 3.703125 | 4 | from typing import List
import os
def result_code_mappers(val) -> str:
"""Map result codes 0/1/2 to string explanations"""
m = {0: "passed", 1: "failed", 2: "human moderation required"}
return m[val]
def format_output_text(stringval) -> str:
"""Removes the unwanted characters in output text and prov... |
9bc35dfe3bef38f715841985f5e62c18b47cf483 | Gauravd1234/Trigonometric-graphs | /Trig_graphs.py | 501 | 3.796875 | 4 | from matplotlib import pyplot as plt
import numpy as np
from numpy import pi
print("\n")
print("What type of graph do you want?: ")
trig_type = input("S for sine, C for cosine and T for tangent: ")
if trig_type.lower() == "s":
x = np.linspace(0, 2*pi, 360)
y = np.sin(x)
elif trig_type.lower() == "c":
x =... |
9114e5f0ed9bba59e4e8844ac7ca552c526a0ef4 | louissock/Python-PPA | /wff/wff_lib.py | 6,809 | 3.53125 | 4 | """
Filename: wff_lib.py
Author: Sang Shin
Date: 09/12/2012
Core functions that are used in the we feel fine program
"""
#!/bin/env python
import sys
def feelings_frequency(feelings, content):
# Check each line of content for the feeling
# If the feeling is in the line of content, increase the fre... |
8963264fc2d26744fcf63b73a7ef45100cbc8f0c | Zrb1/functions_and_classes_assignment | /question2.py | 588 | 4.15625 | 4 | #########IMPORT LIBRARIES HERE IF NEEDED#######
################END IMPORTS####################
"""
Write a function that takes a list of integers as input and returns the sum of the even numbers in the list
minus the sum of the odd numbers in the list. The list may contain zeros and negative numbers. For example,
f([... |
ce2b94c6ea5446f1caabc0a1b09c5be1ee7ec60d | dnlwrn01/Python-Projects | /abstraction.py | 616 | 3.90625 | 4 |
#import abc mod
from abc import ABC, abstractmethod
#parent class
class payment(ABC):
def saleTotal(self, total):
print(f"Item Cost: {total}")
#abstract method
@abstractmethod
def calcTotal (self, total):
pass
#calculate and print
class taxCalc(payment):
def calcTotal (self, tota... |
174a14b98d95d23cf08d35c1b9aef2228c503d78 | DroidsYoureLookingFor77/PythonPortfolio2020CC | /Term 1/madlib/onedoesnotsimplywalkCC.py | 815 | 4.0625 | 4 | #This program was written by Connor Crowe
print("Remember, do no put a space before you answer!\n")
word1 = input("Type an action.")
word2 = input("Type a place.")
word3 = input("Type a color followed by a plural noun.")
word4 = input("Type a plural noun.")
word5 = input("Type a noun.")
word6 = input("Type an adjectiv... |
9f0aefd3212b63d9370539b0694b3eb185d2c024 | raphaellaxz/PolyUCourseworks | /COMP1001/Lab/2/4.py | 488 | 3.828125 | 4 | #stringSplit.py
# using the split() function to manipulate strings data.
# Lines that start with '#' are COMMENTS.
# They are not interpreted by Python.
myString = "TIGER, tiger, burning bright\nIn the forests of the night,\nWhat immortal hand or eye\nCould frame thy fearful symmetry?"
print(myString)
#separate word by... |
4dabd49a4f9ae2936dc4b71661de1c4c6c88c219 | PaolaCNacif/Actividad_06 | /Menu.py | 1,867 | 4.03125 | 4 | #Encoding:UTF-8
#Autor: Paola Castillo Nacif
#Menu entre la funcion insectos y la funcion calcular mayor
def calcularMayor():
mayor=0
numero=0
while numero!=-1:
numero=int(input("Inserte numero"))
n=numero
if n>mayor:
mayor=n
if mayor==0:
print("No hay datos ... |
6ebe7e6ded4eacbc96953981709dc3f4db6a203a | greatbriton42/mazecreator | /venv/MazeDefinition.py | 1,348 | 3.8125 | 4 | import random
class Maze:
def __init__(self, size: [], start, end):
self.size = size
self.start = start
self.end = end
self.top = [0 for i in range(self.size[0])]
self.middle = [[0 for i in range(self.size[1])] for i in range(self.size[0])]
self.bottom = [0 for i in... |
0b52e253448214f2f75599b724316a0d91c17f3a | mdjukic/repos | /q_python_scripts/if.py | 1,210 | 4.28125 | 4 |
from __future__ import print_function
from datetime import datetime
import os
import sys
def main(args):
# indentation of code within Python is very important, as it identifies code blocks to the interpreter
# - other programming languages use braces
# initialize a variable within user input of an integer v... |
84b5af720d32732e27b7d277c923baaaab75d63e | yzl232/code_training | /mianJing111111/Google/设计自动售货机.py | 1,935 | 3.5625 | 4 | # encoding=utf-8
'''
设计自动售货机
'''
#另外涉及一些dp的东西。 可以preprocess。 需要找的钱 。 以及多少个硬币。
'''
class drinks : id, price, name
class VendingMachine
- boolean takeMoney(Money money);
//Here item will contain type & quantity, no smart search required
//say user need half litere Coke.
- Item pickItem(Item item);
- boolean ... |
ce1dc49c351bf904299e5fdcfc147a111087177a | eagleliujun/leetcode | /N367.py | 712 | 3.9375 | 4 | """
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
"""
class Solution:
def isPerfectSquare(self, num: int) -> bool:
... |
2d2df62642e27fe9f0c65da71385b12ca7933672 | ehizman/Python_Projects | /src/turtle_graphics/turtle.py | 3,965 | 3.53125 | 4 | from turtle_graphics.direction import Direction
from turtle_graphics.pen import Pen
from turtle_graphics.pen_position import PenPosition
class Turtle:
def __init__(self):
self.__current_row_position = 0
self.__current_column_position = 0
self.__pen = Pen()
self.__direction = Direct... |
120ee586030d04463b841b3fdb0ef706ed145df3 | hellomansour/python_work | /Chapter 9/9-6_ice_cream_stand.py | 1,000 | 3.828125 | 4 | #9-6_ice_cream_stand.py
class Restaurant():
def __init__(self,name,cuisine_type):
self.name = name.title()
self.cuisine_type = cuisine_type.title()
self.number_served = 25
def describe_restaurant(self):
print("Restaurant name: " + self.name)
print("Cuisine type: " + self.cuisine_type)
print()
def op... |
f0ebf39e5d6f03a3bf9a77162e0628027127518d | aaronshan/start-deep-learn | /perceptron/AndExample.py | 1,180 | 3.65625 | 4 | # _*_ coding:utf-8 _*_
import Activator
from Perceptron import *
def get_train_data():
"""
:return: 返回and真值表的数据
"""
# 输入向量
input_vectors = [[1, 1], [1, 0], [0, 1], [0, 0]]
# 输入向量对应的真值[[1, 1] => 1, [1, 0] => 0, [0, 1] => 0, [0, 0] => 0]
labels = [1, 0, 0, 0]
return input_vectors, lab... |
a21e7d0d2b35ebc00c6f1fc0fec8c91b03323cf0 | sabrina-32-SUST/PythonLearning | /areaOfAShape.py | 774 | 4.1875 | 4 | #Area of a Shape
base = float(input("Enter Base = "))
height = float (input("Enter Height = "))
length = float (input("Enter Length = "))
width = float (input("Enter Width = "))
radius = float (input("Enter Radius = "))
angle = int(input("Enter Angle = "))
area = 0.5 *base*height
print("Area of Triangle : " , ar... |
e8c1cb0ed750040a5e13250c1e9f6cecb9584a35 | nicolageorge/idiomaticpython | /presentation/3 0 multiple exit points.py | 1,415 | 3.921875 | 4 | # Distinguishing multiple exit points in loops
# Donald Knuth came up with some structured equivalent
# need flag variable to say if something is found or not found
# the code could be returned/exited earlier when value is found, however this type of code is
# usually a portion of a bigger functionality thus can't be... |
6c3ade44ef64f3254a451cd4b8e5776e3c884baa | luvhalvorson/Leetcode-Python-Solutions | /problems/validate_binary_search_tree/solution.py | 621 | 3.828125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def help(root, minval, maxval):
... |
0b1e72f1ab711c9f31301df81664ed76f431649a | scottmo223/TravelingSalesmanProblem | /AddressDistances.py | 1,106 | 3.71875 | 4 | # Robert S Morales 000954923
class AddressDistances():
"""
Contains matrix of address distances, an index to address map, the indexes of
visited addresses, and the indexes of not visited addresses.
"""
def __init__(self):
self.addressDistanceMatrix = []
self.indexAddressMap = []
... |
809a35df9bc63857cfee6574caa2cce8fa865e33 | simula67/advanced-python-course-material | /instructor-github/day5/others/urllib/3_urllib.py | 332 | 3.53125 | 4 | import urllib
import urllib2
values = {'q' : 'python training in hyderabad'
}
data1 = urllib.urlencode(values)
#url = 'https://www.google.com/search?' + data
url = 'http://localhost/get.php'
#print url
req = urllib2.Request(url, data="n=100")
response = urllib2.urlopen(req)
the_page = response.read()
prin... |
4a9ed95e21cd5e94e2dc73b557bfb2a397ee624e | achinthagunasekara/puzzles_and_algorithms | /remove_comments/solution.py | 1,061 | 3.578125 | 4 | """ Solution """
# pylint: disable=invalid-name
import re
"""
// Remove comments from main.c file
// main.c contents:
int main()
{
// printf() displays the string inside quotation
printf("Hello, World!");
printf("foo"); /* More comments
And more comments
*/ return 0;
}
Expected output:
int main()
{
prin... |
0753f39d5d94c420a2e65db86555a8f31299b34c | MagdalenaSvilenova/Python-Fundamentals | /regex/furniture.py | 507 | 3.734375 | 4 | import re
data = input()
furniture = []
money = 0
pattern = r"^>>([a-zA-Z]+)<<([0-9]+\.?[0-9]+)!([0-9]+)$"
while not data == 'Purchase':
match = re.match(pattern, data)
if match:
name = match.group(1)
price = float(match.group(2))
quantity = int(match.group(3))
... |
afeab1992242f87ac21e65d7b0a462c8b79bcf73 | v2tka/gittt | /templates/fdsfdsfdsfdsfdsfds.py | 50 | 3.515625 | 4 | i=3
for n in range(0,10,3):
i=i+1
print(i) |
678ad8136eb7ffbdc22add36798cf069a57cc2e7 | wenyuwong1/biosys-analytics | /assignments/11-regex-dates/dates.py | 2,187 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Author : wwong3
Date : 2019-MAR-26
Purpose: Regular Expression Data Parsing
"""
import os
import sys
import re
# --------------------------------------------------
def main():
args = sys.argv[1:]
if len(args) != 1:
print('Usage: {} DATE'.format(os.path.basename(sys.argv[... |
201edc6b5e13506ff11e914928b295b6a0d267ce | fernandezfran/python_UNSAM | /ejercicios/Clase04/busqueda_en_listas.py | 1,554 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#### busqueda_en_listas.py
def buscar_u_elemento(lista, elemento):
"""
recibe una lista y un elemento
devuelve la posición de la última aparición de ese elemento en la lista o -1
si el elemento no pertenece a la lista
"""
pos = -1
for i... |
c225e57c2e2bda1899bbb735cb9a1a0f19e3d560 | tsmith328/AoC2015 | /Day22/Day22.py | 3,861 | 3.6875 | 4 | import sys
spells = {"missile": (53, 4, 0, None), "drain": (73, 2, 2, None), "shield": (113, 0, 0, "shield"), "poison": (173, 0, 0, "poison"), "recharge": (229, 0, 0, "recharge")}
effects = {"shield": (6, 7, 0, 0), "poison": (6, 0, 3, 0), "recharge": (5, 0, 0, 101)}
hp = 50
mana = 500
#The player
class Player(object)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.