blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
da048197d6ef72449ddd0032171b27538992b650 | realonbebeto/Mock-Data | /gen_address.py | 642 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 20:29:48 2020
@author: mistageek
"""
import random
def gen_address():
street_names = ["Main", "1st", "2nd", "3rd", "U. Highway", "Ken. Avenue", "T Mboya", "Valley Rd", "H. Sellasie", "Ring Rd"]
cities = ["Nairobi", "Mombasa", "Eldoret", ... |
4e098ee6b650cfb3ed5ab3844f0a3edb115adb7e | flaviu2001/University-Projects | /Semester 1/Fundamentals of Programming/Seminars/2019-10-01/2.py | 146 | 3.59375 | 4 | def sleepIn(weekday, vacation):
return vacation or not weekday
def tobool(x):
return x == 'yes'
print(sleepIn(tobool(input()), tobool(input()))) |
92481bceee6a45a6e9dfe9ed45e5679268decc5a | Rodrigo-Antonio-Silva/ExerciciosPythonCursoemVideo | /Ex007/ex007.py | 264 | 3.640625 | 4 | A = input('\33[33mNome de Aluno:\33[m ')
n1 = float(input('\33[33mValor de X:\33[m '))
n2 = float(input('\33[33mValor de Y:\33[m '))
m = (n1 + n2) / 2
print('\33[31mAluno(a): {}, média entre {} e {} é igual a {:.2f}.\33[m'.format(A, n1, n2, (n1 +n2)/2))
|
38373dd26ea7849262a013fce185c83590d332e5 | serenastater/Data-Analysis | /plotting_with_df.py | 1,518 | 3.921875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
values = np.array([1, 3, 2, 4, 1, 6, 4])
example_df = pd.DataFrame({
'value': values,
'even': values % 2 == 0,
'above_three': values > 3
}, index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# Change False to True for thi... |
d5fe4c6116170ce4229ecc34ab1aaeac9d8c228b | duanluyun/SolutionsOfLeetCode | /147. Insertion Sort List.py | 657 | 3.875 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = dummy = ListNode(0)
wh... |
3ce49daf3e6db4a59e057f5f6eee621381f64e5d | matia02/prueba | /adivina_numero.py | 670 | 3.921875 | 4 |
number_to_guess = (6+2)
print("Este juego se llama Adivina el numero,Cuentas de tres oportunidades")
user_number = int(input("Adivina el numero: "))
if number_to_guess == user_number:
print("Has ganado")
else:
print("Has fallado, intentalo otra vez")
number_user_1 = int(input("Adivina el número: "))... |
6b6d1ee9cedd16a27c82a68cc2aae7709572c541 | yyassif/codinginterviewquestions | /algorithms/124. Binary Tree Maximum Path Sum.py | 798 | 3.796875 | 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 maxPathSum(self, root: TreeNode) -> int:
self.max_sum =float('-inf')
def rec(node):
... |
c2fdfb56f32d1ac88bbade5479675bbc71cbf914 | CecileSerene/google-2.0 | /vectorial/functions.py | 759 | 3.609375 | 4 | import collections
def term_frequency(term, vocab_full):
"""
Occurrences of term in the full vocabulary
"""
occurrences = collections.Counter(vocab_full) # get occurrences of each term
return occurrences[term]
def term_frequency_in_index(term_id, document_id, index):
"""
Occurrences of ... |
08cdb9bb4a085d616074a4bfbf7bd66f82f5bc1f | Alpha00790/Python_OOP_0 | /OOP.py | 1,912 | 4.125 | 4 | class Person:
def __init__(self,person_name):
self.name = person_name
def get_name(self):
return self.name
a_person = Person("Shaikat")
b_person = Person("Alpha")
print(a_person.get_name())
print(b_person.get_name())
class Person:
def __init__(self,person_name,date_of_b... |
1793322158b68413eebc26019efa9629b8126c81 | manhducpham/phamducmanh-fundamental-c4e21 | /session3/homework/serious_ex3b.py | 461 | 3.84375 | 4 | from random import randint, choice
words_list = ['champion', 'victory', 'destroy', 'event']
words_num = len(words_list)
n = randint(0, words_num - 1)
word = words_list[n]
chars = list(word)
chars_len = len(chars)
for i in range(chars_len):
t = choice(chars)
print(t, end = " ")
chars.remove(t)
print()
gue... |
5b07144c63aef3841a381b7e210bdab85c2858ba | srczhou/ProficientPython | /sum_root_to_leaf_binary_tree.py | 1,260 | 4.0625 | 4 | #!/usr/bin/env python3
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __repr__(self):
return '%s <- %s -> %s' % (self.left and self.left.data, self.data,
sel... |
c1db1a2125e0c87fc0b10d8d3c7ee41e07cad3ed | hegde10122/python_training | /numpy/numpy6.py | 2,700 | 4.4375 | 4 | '''
INDEXING AND SLICING of ndarrays
'''
import numpy as np
arr = np.arange(10)
print(arr)
print(arr[5:8]) #index 8 is not included ---only 3 elemnts at index 5,6,7
arr[5:8] = 19
print(arr)
'''
If you assign a scalar value to a slice, as in arr[5:8] = 19, the value is propagated (or broadcasted henceforth)
to the ... |
2d334a2820c0c4fb40a2068b6a63e56edcb084ed | ZhaoYuxuan-BIT/Python_100test | /5.py | 113 | 3.8125 | 4 | #!/usr/bin/env python
#coding:utf8
l = []
for i in range(3):
j = int(raw_input())
l.append(j)
l.sort()
print l
|
d782769a00216720682b82d3afea5f5548a3f439 | ananyapoc/CPSC230 | /CPSC230/APochiraju_ICA02/divisible.py | 82 | 3.8125 | 4 |
if(a%7 == 0 and a%3==0):
print("divisible")
else:
print("not divisible")
|
4a972ecaca8f95271fa71f33ade6b320ad51c532 | zhyrnov/Mikhaylo | /homework7_1.py | 1,742 | 3.875 | 4 | # Написать программу реализующую хранилище информации о пользователях.
# Разбить логику по модулям: storage (функции get, add, get_storage), main (взаимодействие с пользователем)
#1.add
#2.get
#3.get_all
#>>1
#Email: Elias@mail.ru
#Login: eliasmir
#1.add
#2.get
#3.get_all
#>>2
#email: Elias@mail.ru
#Email: Elias@mail... |
45a7af67611c93ceb54dd5a74e87b2c3f8575fcc | wesenu/mit_6.00.1x | /pset2/pset2.py | 4,933 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 22:26:25 2018
@author: dileepn
MIT 6.00.1x: PSET2
"""
def creditBalance(balance, annualInterestRate, monthlyPaymentRate, t):
""" This function computes the balance of a credit card at the end of
't' years.
Inputs:
... |
897fb7b25ff1c36126a3d924b0e973e8414bdf80 | asishraz/banka_sir_notes | /ch_3/5.py | 182 | 4.09375 | 4 | #wap to print the sum of all the numbers from A to B
a = 0
A = int(input("enter any number: "))
B = int(input("enter any number: "))
for i in range(A,B+1):
a = a + i
print(a) |
8e56fa9cabdcb148c77cf430556a53fc40d874ed | didate/python-crash-course-book | /chap_7/input.py | 185 | 4.1875 | 4 | message = input('What is your name : ')
age = input('How old are you ? ')
if 18 <= int(age):
print(message + ', You are adult')
else:
print(message + ', You are very younger')
|
993a5a46bb411272e6c31187f52a4aa0e5ddcc1f | Wrangler416/afs210 | /week4/hash/hashing.py | 1,715 | 3.6875 | 4 | class HashTable:
def __init__(self):
self.size = 10
self.slots = [None] * self.size
self.data = [None] * self.size
self.count = 0
def hashFunction(self,key):
return key % self.size
def rehashFunction(self,key):
return key // self.size
# Insert your ... |
016888c6b67155b477739011c315bc041a0a486b | probabilistic-numerics/probnum | /src/probnum/utils/argutils.py | 1,951 | 3.6875 | 4 | """Utility functions for argument types."""
import numbers
from typing import Optional
import numpy as np
from probnum.typing import DTypeLike, ScalarLike, ShapeLike, ShapeType
__all__ = ["as_shape", "as_numpy_scalar"]
def as_shape(x: ShapeLike, ndim: Optional[numbers.Integral] = None) -> ShapeType:
"""Conver... |
843990527a847c642b85542e036eee404cee8a59 | nodepress0508/codingworkspace | /lc94.py | 4,004 | 3.71875 | 4 | """
94. Binary Tree Inorder Traversal
Given the root of a binary tree, return the inorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,3,2]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,... |
3ae969b0e2790b515f0f1504b6a475fd9956095e | GrimmeryGonsa/DSA-PYTHON | /Recusrion/CheckListIsSorted.py | 403 | 3.796875 | 4 | def isSorted(arr, i):
if len(arr) == 1:
return True
if i == 1:
return arr[1] > arr[0]
if arr[i] > arr[i - 1]:
return isSorted(arr, i - 1)
return False
n = int(input("Enter the list's length"))
arr = []
for i in range(n):
arr.append(int(input("Enter element " + str(i))))
so... |
70a22db10bc12dc52e66ad0f526d22505a2f676f | gabriellaec/desoft-analise-exercicios | /backup/user_230/ch150_2020_04_13_20_04_35_667279.py | 112 | 3.734375 | 4 | import math
def calcula_pi(n):
x=0
i=1
while i<=n:
x=6/(i**2)
pi=x**(1/2)
return pi
|
b932b50defa078fba0d7c32a5de78afbc375e029 | awamay/codeasylums-winter-19 | /day3-9.py | 433 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 18:41:45 2019
@author: awani
"""
def check(n):
c=0
d = int(len(n)/2)
for i in range(0,d):
if n[i]!=n[-i-1]:
c=1
if c==1:
return False
else:
return True
q = ["nhu","abhba","baaab","abs... |
b38be88d3c9f40877f48adc960ec4ec9f56a4da1 | ytf513/python_code | /file/fileopen_read.py | 244 | 3.515625 | 4 | #list.txtļݵlist2.txt
#ļ֮ǰȴдļ֮ǰҲȴ
with open("list.txt",'rb') as file1:
temp=file1.read()
with open("list2.txt","wb") as file2:
file2.write(temp)
|
485048346617a693a14458802b559e5f85acaef9 | zdyxry/LeetCode | /hash_table/0409_longest_palindrome/0409_longest_palindrome.py | 649 | 3.59375 | 4 | class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
if s is None or len(s) == 0:
return 0
dic = dict()
for c in s:
if dic.get(c) is None:
dic[c] = 1
else:
... |
9f695497154b4947762b376e733d69e265531e2f | eloydrummerboy/Socratica | /10_Random_Walk.py | 1,780 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 23:17:22 2017
@author: eloy
"""
import random
def random_walk(n):
"""Return coordinates after 'n' block random walk."""
x = 0
y = 0
for i in range(n):
step = random.choice(['N','S','E','W'])
if step == 'N':
y = y + 1
... |
362693d502c6801cda40644bea01cd71d84dae60 | PECNAS/Facebok | /myTree.py | 1,110 | 3.828125 | 4 | class Tree:
def __init__(self, data, right=None, left=None):
self.left = left
self.right = right
self.data = data
def add_leaf(self, leaf, tree):
if tree:
if leaf > tree.data:
if tree.right:
self.add_leaf(leaf, tree.right)
else:
tree.right = Tree(leaf)
else:
if tree.... |
132144546345410651ed848ff9921fe9c0d51401 | HarshMule20/Python_Practices | /array/append.py | 120 | 3.671875 | 4 | from array import *
arr1=array('i',[5,8,3,5,7])
arr1.append(29)
for i in range(len(arr1)):
print(arr1[i],end=" ")
|
01f28878b69ea60ad374d16c2bab4fd34d20adb8 | huang15n/654pythonDataAnalysis | /crawler.py | 2,242 | 3.625 | 4 | from urllib.request import urlopen # this is python3
from bs4 import BeautifulSoup
import csv
import re
""" this to define the crawler for the links that specified the category of ebay"""
class Crawler:
fieldnames_for_csv = ['item_description', 'item_price', 'item_shipping','total_price']
def crawl_to_pages... |
5fdd136461a4903cb8793eb0329f7a3758eb6824 | Aasthaengg/IBMdataset | /Python_codes/p03067/s221830643.py | 213 | 3.765625 | 4 | import math
from datetime import date
def main():
line = input().split()
a = int(line[0])
b = int(line[1])
c = int(line[2])
if c >= min(a, b) and c <= max(a, b):
print("Yes")
else:
print("No")
main()
|
07a301ef7cd5bfed91bb3f78657a942bf2bfd590 | Ayashy/PythonLearningProjects | /HackerRank/LarrysArray.py | 808 | 3.515625 | 4 |
def solve(A):
sets=[]
sets.append(A)
findPerms(sets,A)
sortedA=sorted(A)
print(sets)
if sortedA in sets:
return True
else:
return False
def findPerms(sets,A):
for i in range(len(A)-2):
new_array= rotate(A,i)
if new_array not in sets:
sets.ap... |
788d3eeb0f23fe898b99d4d06141d83374a5a1dc | TheTony/CompMeth_Tony | /Homework3Prob1Factorial.py | 746 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 24 12:35:47 2017
@author: Le
"""
import numpy as np
import math
n=input("Please enter value for n: ")
m=float(n)
o=int(n)
def factorial(m):
if m == 0:
return 1
else:
return m*factorial(m-1)
def factorial(o):
if o == 0:
... |
d9a3f01b4f7c4ef3f72f07f348e0927238aedda9 | hamzboy99/TICT-ICT-V1O | /practice exercise/Les 2/Practice_exercise 2.4.py | 211 | 3.546875 | 4 | uurloon = eval(input('Wat verdien je per uur: '))
aantaluur = eval(input('Hoeveel uur heb je gewerkt: '))
salaris = uurloon * aantaluur
print (str(aantaluur) + ' uur werken levert ' + str(salaris) + ' Euro op')
|
e61930d1a99ddbeacd41478f386d57f5b5c21759 | linda-jemni/Python-Linda-Jemni | /jour2/fonction2.py | 180 | 3.625 | 4 | def aire(a,b):
air= a*b
return air
def perimetre (a,b):
perimetr = (a+2)/2
return perimetr
a = int(input("a ?"))
b = int(input("b ?"))
print(aire (a,b))
print(perimetre(a,b)) |
4ab4c3056fd4eef1bb596232ebf098b9882c82e2 | avikejriwal/Project_Euler | /p12.py | 559 | 3.671875 | 4 | #nth triangle number can be computed by n(n+1)/2
import math
n = 1
k = 1
def isSquare(n):
root = int(math.sqrt(n))
if root**2 == n:
return True
else:
return False
while k < 500:
k = 0
N = n*(n+1)/2
for j in range(1,int(math.sqrt(N))):
if N % j == 0:
k += 1... |
efe4707ee2385f897e8d1b0e2b5b50b11ae76098 | sikattin/python_100knock | /src/chapter1/08_decrypt_encrypt.py | 1,276 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""準備運動 08.
与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.
英小文字ならば(219 - 文字コード)の文字に置換
その他の文字はそのまま出力
この関数を用い,英語のメッセージを暗号化・復号化せよ.
"""
import re
def clipher(target_str: str) -> str:
"""文字列の暗号・復号化を行い、処理後の文字列を返す.
:param target: 対象文字列
"""
result_str = ''
for target_char in target_str:... |
f30f82affb4ab191f6150315c38ba4653b9eeae1 | dfbq91/HackerRank | /InterviewPreparationKit/OtherInterviewTasks/string_rotation.py | 308 | 4.1875 | 4 | #!/usr/bin/python3
# Using dictionaries
def string_rotation(str1, str2):
str1, str2 = list(str1), list(str2)
str1.sort()
str2.sort()
print(str1, str2)
for c1, c2 in zip(str1, str2):
if c1 != c2:
return False
return True
print(string_rotation('abcde', 'cdeab'))
|
c161866326941efac9f2424ca5a3127a7b531e44 | gmg0829/pythonLearninng | /basic/listDemo.py | 1,060 | 3.828125 | 4 | hello = (1, 2, 3)
li = [1, "2", [3, 'a'], (1, 3), hello]
li.append("pytaya")
li.insert(0,'balabala')
li.pop()
li.pop(0)
li.remove('2')
#访问元素
print(li[3],li[-2])
#切片访问
#格式: list_name[begin:end:step]begin 表示起始位置(默认为0),end 表示结束位置(默认为最后一个元素),step 表示步长(默认为1)
print(li[0:2],li[:2])
print(li[0:3:2])
#嵌套访问
print(li[-2][1])
#删除元... |
d63046467224787556a092ed65ee6cbeeb823bc0 | RUC-CompThinking18/exploratory-programming-2-nnshah70 | /Explorartory 2.py | 492 | 4.21875 | 4 | def countPositive(numbers):
positiveCount = 0
for number in numbers:
if number > 0:
positiveCount += 1
return positiveCount
input_num = input("Enter a list of numbers comma seprated:")
#list_num = [12,-34,54,-12,2334,34,-323,23,-23]
#str_num = '1233435423232'
if type(input_num) == list... |
01946e73514ef3c753336fd60b5b78a64f5b9faa | vesssz/Fundamentals | /Text_processing/6e.Replace_repeating_chars.py | 138 | 3.84375 | 4 | string = input()
newstring = ""
newstring += string[0]
for i in string:
if newstring[-1] != i:
newstring += i
print(newstring) |
ebb22143506cab88533a37d5b19d390969ae4bb7 | PavelFilonov/LearningPython | /task1/first.py | 1,293 | 3.625 | 4 | def getIndexFirstMaxElement(lst):
index = 0
value = lst[index]
for i in range(1, len(lst)):
if lst[i] > value:
index = i
value = lst[i]
return index
def getIndexLastMinElement(lst):
index = 0
value = lst[index]
for i in range(1, len(lst)):
if lst[... |
626fba25ad44dc43ffdf5a19cf03235c7a419ddf | priyanka-111-droid/100daysofcode | /Day045/live_website.py | 1,987 | 3.5625 | 4 | from bs4 import BeautifulSoup
import requests #to get hold of data from particular url
response=requests.get(url="https://news.ycombinator.com")
# print(response.text) prints entire html code
yc_web_page=response.text
soup=BeautifulSoup(yc_web_page,"html.parser")
# print(soup.title)
#use inspect in chrome developer ... |
21667f98eaabbb5f19fffdec24aa130543fc3015 | rupnarainP/python | /Shelve.py | 1,262 | 3.890625 | 4 | import shelve
# with shelve.open("ShelveTest") as fruit:
# fruit['orange'] = "a sweet, orange, citrus fruit"
# fruit['apple'] = "good for making cider"
# fruit['lemon'] = "a sour, yellow, citrus fruit"
# fruit['grape'] = "a small, sweet fruit growing in bunches"
# fruit['lime'] = "a sour, green cit... |
fec55683dd0c74dceeb957bead74a43ad65bb8b5 | yukitj/RobotServer | /sql学习/dic2list.py | 131 | 3.609375 | 4 | item = {'ip':['1','2','3','4','no','on','yes']}
lst = list(item)
lst2=item['ip']
lst3 = lst+lst2
print(lst)
print(lst2)
print(lst3) |
181b8a48cf7122b519dc28fb117d0d463c447c66 | qmnguyenw/python_py4e | /geeksforgeeks/python/hard/5_5.py | 3,383 | 4.0625 | 4 | How to find longitude and latitude for a list of Regions or Country using
Python
**Geopy** is a Python 2 and 3 client for several popular geocoding web
services. Geocoding is the process to identify geographic coordinates like
latitude and longitude of a given city/country/address. This is very useful
durin... |
c29dab745cc71e3a1e95113f50e329caa5d1685d | rperezl-dev/S10-POO | /operacionesConNumeros.py | 3,530 | 3.984375 | 4 | from os import system as pantalla_win
from operaciones_numeros.basico import Basico
from operaciones_numeros.intermedio import Intermedio
class OperacionesConNumeros:
def __init__(self):
pass
def menu(self):
pantalla_win('cls')
opc = 0
ope_basica = Basico()
ope_interme... |
52d7abdcc61ed4d1ff9c32ee5282ac79927af75b | s6beihme/ProgPraktikum | /Exercise sheet 1/Exercise_12.py | 1,204 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 17:26:26 2018
@author: Benjamin Ihme
"""
#
from numpy import *
n=51
x=linspace(0,1,n)
y=linspace(0,1,n)
L=zeros((n,n))
L[0,:]= y*(y-1)
iter=70
for _ in range(iter):
for i in range(1,n-1):
for j in range(1,n-1):
Lt=... |
b9ee08f0f11f3421b3d2ff0e878be9bae3aaee43 | GongFuXiong/leetcode | /topic9_hash_table/T973_kClosest/interview.py | 2,532 | 3.640625 | 4 | '''
973. 最接近原点的 K 个点
我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。
(这里,平面上两点之间的距离是欧几里德距离。)
你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
示例 1:
输入:points = [[1,3],[-2,2]], K = 1
输出:[[-2,2]]
解释:
(1, 3) 和原点之间的距离为 sqrt(10),
(-2, 2) 和原点之间的距离为 sqrt(8),
由于 sqrt(... |
0a7efb346700a3caca8fce2c356ced6dd1c45318 | IDReaper/Coursework | /csc 120/change.py | 809 | 4.09375 | 4 | # change.py
# A program to calculate the value of some change in dollars
def main():
print "Change Counter"
print
print "Please enter the count of each coin type."
quarters = input("Quarters: ")
dimes = input("Dimes: ")
nickels = input("Nickels: ")
pennies = input("Pennies: ")
total = qu... |
a2350e0c59636af2172640782fb4d14f125f9e6f | Bogdan1726/CursorLectures | /exceptions_logging/ex1.py | 147 | 4.15625 | 4 |
while True:
str_1 = input()
if not str_1.isdecimal():
print("str is not decimal")
continue
a = int(str_1)
print(a) |
fc52bd37b74943b0247fc6fcfaf1f5fe5817ce55 | afahad0149/How-To-Think-Like-A-Computer-Scientist | /Chap 5 (CONDITIONALS)/exercise/num6(grade).py | 440 | 3.859375 | 4 | def find_grade (marks):
if (marks >= 75):
return "First"
elif (marks >= 70):
return "Upper Second"
elif (marks >= 60):
return "Second"
elif (marks >= 50):
return "Third"
elif (marks >= 45):
return "F1 Supp"
elif (marks >= 40):
return "F2"
else:
return "F3"
scores = [83, 75, 74.9, 7... |
c17644fbdbba76da0ff1aada5b30e2ddcf7e0a95 | hf-hf/Python3-Study | /Day1/Number.py | 640 | 4.3125 | 4 | """
isinstance 和 type 的区别在于:
type()不会认为子类是一种父类类型。
isinstance()会认为子类是一种父类类型。
注意:在 Python2 中是没有布尔型的,它用数字 0 表示 False,用 1 表示 True。
到 Python3 中,把 True 和 False 定义成关键字了,但它们的值还是 1 和 0,它们可以和数字相加。
"""
a, b, c, d = 20, 5.5, True, 4+3j
print(type(a), type(b), type(c), type(d))
a = 111
print(isinstance(a, int))
class A:
pa... |
2692ee6854399cbe4c413a5d3503aede9213de3c | raysmith619/Introduction-To-Programming | /exercises/introduction/blazing_intro/my_while.py | 167 | 3.859375 | 4 | # my_while.py 27Dec2021 crs - exercise while statement
print("my_while")
i = 1
max = 10
while i < max:
print("i:", i, "max(", max, ")")
i = i + 1
|
da963a861ca0e1e3e3696bb146347fc2e3000e5b | Lyasinkovska/python_learning | /bookstore/draft.py | 4,994 | 3.5 | 4 | '''def maxMultiple(divisor, bound):
return bound//divisor*divisor
print(maxMultiple(3, 10))
def circle_of_numbers(n, firstNumber):
if firstNumber < n/2:
return (2*firstNumber+n)//2
else:
return (2*firstNumber - n)//2
print(circle_of_numbers(13, 2))
def lateRide(n):
return n//60//10+... |
e4f22ae6ff69cef251eadf154f95fec521b71738 | p-verburg/advent_of_code_2019 | /navigation/orbit_map.py | 5,430 | 3.671875 | 4 | class Body:
def __init__(self, name):
self._name = name
self._orbit_center = None
self._orbit_depth = 0
self._satellites = []
def get_name(self):
return self._name
def get_orbit_center(self):
return self._orbit_center
def get_orbit_depth(self):
... |
7fd680548aaa1f6b734d0290ed2bd8dd745aceb2 | 0x000613/Outsourcing | /Python/2020-06-12-기본문법/factorial.py | 112 | 3.5 | 4 | def factorial_for(n):
ret = 1
for i in range(1, n+1):
ret *= i
return ret
factorial_for(10) |
f79216a852f10b8e4387e52788c50327b83161bb | opentracing/basictracer-python | /basictracer/recorder.py | 1,424 | 3.5625 | 4 | import threading
from abc import ABCMeta, abstractmethod
import six
class SpanRecorder(six.with_metaclass(ABCMeta, object)):
"""SpanRecorder is a simple abstract interface built around record_span.
"""
@abstractmethod
def record_span(self, span):
"""After the call to finish(), each BasicSpan... |
add29e17213d7eb64c2da0c2ac4f181470292b7b | arunkandappan/Rutgers-CS440-IntroAI | /Assignment 2 - Probabilistic Search/MazeSearch.py | 730 | 3.5 | 4 | import numpy as np
import random
SIZE = 5
class MazeSearch:
def __init__(self):
self.maze = np.zeros((SIZE, SIZE), dtype=np.float64)
for i in range(0, SIZE):
for j in range(0, SIZE):
self.maze[i,j] = random.choice([0.2, 0.4, 0.6, 0.9])
self.probability_containi... |
2fe77cc6becc6d51561eeae61a3d7b618f2a0d1f | durgacodez03/Hello_python | /otp_digit.py | 282 | 3.515625 | 4 | import math
import random
def generateOTP():
digit = "0123456789"
OTP = ""
for i in range(6):
OTP += digit[math.floor(random.random()*10)]
return OTP
if __name__ == "__main__":
print("Otp of lenght 6 is :", generateOTP())
|
747891d8b9dd44541c75368696f244948beff9df | Fongyitao/PythonS2 | /_01_基础篇/05_day/02_字符串格式化输出.py | 436 | 3.8125 | 4 | #__author: Fong
#date_: 2017/11/8 23:37
name = input("name:")
age = int(input("age:"))
salary = input("salary:")
if salary.isdigit(): # 判断是不是正整数
print("is digit")
int(salary)
else:
exit("must digit") # 输入的不是digit程序就结束
msg = """
--------info of %s--------
Name:%s
Age:%s
Salary;%s
You will be retired in %... |
5c96c5b864dcfa45055608b78e3ccfb029ca4504 | Miguel-Bit-Debug/Curso-em-Video-Python | /ex073.py | 636 | 4 | 4 | time = ('Palmeiras', 'Santos', 'Flamengo', 'Internacional',
'Atlético', 'Goiás', 'Botafogo', 'Bahia', 'São Paulo',
'Corinthias', 'Grêmio', 'Athletico-PR', 'Ceará SC',
'Fortaleza', 'Vasco da Gama', 'Fluminense',
'Chapecoense', 'Cruzeiro', 'CSA', 'Avaí')
print('-='*30)
print(f'Lista de tim... |
df5a29417c0f4c0fcc618618156c689ac1bf42e7 | royeectu/python-exercise | /tuples/15_tuple_length.py | 103 | 3.875 | 4 | # Write a program to find the length of a tuple
my_tuple = (1, 2, 3, 4, 5, 6, 7)
print(len(my_tuple))
|
3b205bcab8e78af2f973fee71269fb5b2b59fc82 | mahavivo/Python | /Python-cookbook-2nd/cb2_20/cb2_20_2_exm_4.py | 336 | 3.71875 | 4 | def area():
what_is_area = "Area of the rectangle"
def compute_area(self):
return self.x * self.y
def scale_both_sides(self, value):
ratio = math.sqrt((1.0*value)/self.area)
self.x *= ratio
self.y *= ratio
return property(compute_area, scale_both_sides, None, what_is_area... |
70538cb6587021e512e6c8d6b04f415859151a87 | eceusc/project-tic-tac-toe | /session_1_exercise.py | 924 | 4.28125 | 4 | import random
def draw_board(board):
# This function prints out the board that it was passed and should not return anything
#HINT: the parameter board should hold a list that holds the position of 'X's and 'O's
return
def input_player_letter():
#Ask the player if they want to be 'X' or 'O'
#Return... |
2cd2dfaed29ff6f4711fbda0968c3151bfbd43e0 | minisparrow/acm | /step1/00_list/leetcode2_addTwoNumbers.py | 1,838 | 3.875 | 4 | # -*- coding: utf-8 -*-
# leetcode 2: https://leetcode-cn.com/problems/add-two-numbers/
# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You ... |
54ff4c0b576a10b6fb200b4f75c2008fc8d6d7dd | internetonfire/iof-tools | /BGPpysim/util/EventScheduler.py | 2,665 | 3.703125 | 4 | #!/usr/bin/python
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it w... |
2b91c55cb7aad821d1eeb1a0dd47c6b9da0d16c4 | ABDULLAHFUAD/pdsnd_github | /main.py | 8,178 | 4.375 | 4 | import time
import pandas as pd
import numpy as np
# some comments are here
# some comments are here
# some comments are here
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month ... |
f4809190df0bb42c6bd91951491da585b955b8a0 | turbo00j/python_programming | /continue.py | 437 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 27 23:04:00 2019
@author: jaideep
"""
ans='yes'
while ans=='yes':
n=int(input("Enter an integer:"))
if n<=0 or n>=100:
print("please enter the numbers less than 100 and more than 0:")
continue
else:
for i in range(1,21):
pr... |
00f4c57273c174be36eec4432924b3429220c128 | dorisakpovwa/python-challenge | /PyBank/Resources/mainpay_edit1.py | 1,700 | 3.515625 | 4 | import os
import csv
#set the variables
bankdata = 'budget_data.csv'
totalmonths = 0
netprofit = 0
greatestI = ["", 0]
greatestD = ["", 9999999999999999999]
#set path to read file
with open(bankdata, "r") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csvheader = next(csvreader)
#initialize list
... |
8ea44901c01f113fe1b007886ebd673e500bebab | nbuonin/project_euler | /pe_003.py | 1,292 | 3.875 | 4 | """
Project Euler Problem #3
"""
from math import sqrt
def prime_tester(n):
for i in range(2, int(sqrt(n)) + 1):
if (n % i == 0):
return False
return True
def prime_generator(n):
"""Returns a list all primes less than n.
Implements the sieve of Eratosthenes algo"""
ints = [T... |
b0c54bd10f3b053d4e90d477fd71774721ce110f | raunaklakhwani/Algorithms | /Threading/EvenOdeeThread.py | 1,773 | 3.84375 | 4 | import threading
from math import ceil
from random import random
from Queue import Queue
from threading import Lock
count = 0
lock = Lock()
class Odd(threading.Thread):
def __init__(self, name, size, objQueue):
threading.Thread.__init__(self, name=name)
self.size = size
self.objQueue = obj... |
6b78ddfa7d6732fcde870c1db4678bde44b3c9b0 | Aserdiuk2/PythonFlow | /HW1.py | 1,362 | 3.609375 | 4 | __author__ = 'aserdiuk2'
"""Implement your own _uniq function.
first arg is collection.
function returns new collection of uniq items
Usage of Set data structures is forbidden."""
l = [9, 6, 7, 4, 8, 3, 5]
def good_order(l):
return(sorted(l))
print(list(good_order(l)))
"""Implement your own _filter funct... |
b813d24d88c4d5feb44c4ee0f899cc7cc82f007b | james-hadoop/JamesPython | /james_process/test.py | 149 | 3.625 | 4 | import time
x = 0
sum=0
print(time.strftime('%H:%M:%S'))
while x<500000000:
x+=1
sum+=x
print(time.strftime('%H:%M:%S'))
print(sum)
|
f8df1538261627d60e529c4c37a9d9484aa64c8c | MaxCosmeMalasquez/Ejercicios-Python- | /example2.19.py | 374 | 3.6875 | 4 | print("Price for call ")
print("Time for call")
w = int(input())
print("Day of week in numbers")
x =int(input())
print("Turn")
y = int(input())
if x == 7 and w >= 5 and :
print("Price of talk is " + str(w + w*0.03))
elif x != 7 and y==1:
print("Price of talk is " + str(w+w*0.15))
elif x!= 7 and y == 2 :
... |
02a9f1197d74118a0125b5f5f03756483350574d | Ricky-Hu5918/Python-Lab | /Dijkstras's_algorithm.py | 3,165 | 3.890625 | 4 | '''Dijkstra/'s algorithm'''
'''狄克斯特拉算法的伪代码
def find_lowest_cost_node(costs):
lowest_cost = float("inf")
lowest_cost_node = None
for node in costs: #遍历所有节点
cost = costs[node]
if cost < lowest_cost and node not in processed: #如果当前节点的开销更低且未处理过
lowest_cost = cost #就将其视为开销最低的节点
... |
2cd6b0c87393ee67f7d029aa47c890aa004ee062 | aspp-apac/pelita | /pelita/player/team.py | 26,871 | 3.625 | 4 |
import collections
from functools import reduce
from io import StringIO
import random
from . import AbstractTeam
from .. import datamodel
class Team(AbstractTeam):
""" Simple class used to register an arbitrary number of (Abstract-)Players.
Each Player is used to control a Bot in the Universe.
SimpleT... |
6e8e1fc9aa2d7a9dfe3df5281fc0bdc8ec68b4e1 | cgi0911/LeetCodePractice | /Others/Fibonacci/fibonacci_dp.py | 1,685 | 3.984375 | 4 | import time
def fibRecursive(n):
"""
:type n: int
:return: Fibonacci(n)
:rtype: int
"""
if (n <= 1):
return n
else:
return (fibRecursive(n - 1) + fibRecursive(n - 2))
def _fibMemorization(n, lookup):
"""
:type n: int
:return: Fibonacci(n)
:rtype: int
... |
b1115cca6e7c3cf051c2e6b06a7a292354792fec | ag94e/challenge-python-01 | /src/main.py | 1,399 | 3.96875 | 4 | # Resolve the problem!!
PALINDROMES = [
'Acaso hubo buhos aca',
'A la catalana banal atacala',
'Amar da drama',
]
NOT_PALINDROMES = [
'Hola como estas',
'Platzi',
'Oscar',
]
def is_palindrome(palindrome):
newPal = palindrome.replace(' ', '').lower() ## Generate the palindrome to lower ca... |
804b06e22221f4a1a714ccf6a1bbb6be0e1279a2 | ioanajoj/Artificial-Intelligence | /Subgraphs (EA)/Application.py | 694 | 3.59375 | 4 | """
9. Subgraphs (EA)
Consider an undirected graph G(V , E) with 2n nodes ( V is the set of nodes, and
E is the set of edges). Partitionate the set of nodes in two disjoint sets V 1 and V 2,
each containing exactly n nodes, in such a way that between any two nodes of the subgraphs
determined by the ... |
a9b6e452f99f4fd57df28b9344920a57918bba0f | 5l1v3r1/Cracking-the-Coding-Interview | /arraysAndStrings/removeDuplication.py | 692 | 4.21875 | 4 | # Design an algorithm and write code to remove the duplicate characters in a string without using any additional bu er
from collections import OrderedDict
# use hit list
def removeDup1(s):
hit = [False for i in range(256)]
result = ''
for char in s:
if hit[ord(char)] == False:
hit[ord(c... |
e9c916feef77e6aec19aad644082592f0fb247f2 | yatengLG/Sorting-Algorithm-python | /Sorts/Insertion_Sort.py | 1,242 | 3.734375 | 4 | # -*- coding: utf-8 -*-
# @Author : LG
"""
基本思想:
在要排序的一组数中,假定前n-1个数已经排好序,现在将第n个数插到前面的有序数列中,使得这n个数也是排好顺序的。如此反复循环,直到全部排好顺序。
过程:
平均时间复杂度:
O(n2)
未完成
"""
def Insertion_Sort(datas):
for i in range(1, len(datas)): # 初始假定第一个数据为有序,后续数据均为无序
for j in range(i):
current... |
6de82c53acf30965a92b88365a2cf03ef354f9b1 | Chandrahas-Soman/Data_Structures_and_Algorithms | /Python/Strings/palindrome.py | 220 | 3.953125 | 4 | # Palindrome
# palindrome string is one which reads tthe same when it is reversed.
# space = O(1) time = O(n)
def is_palindromic(s):
# note that s[~i] = s[-i - 1]
return all(s[i] == s[~i] for i in range(len(s) // 2))
|
438519d3eec354f58ea4f6f5b894cf3308e3d354 | Mikhail-Gl96/optimization-methods | /vergazova 2 variant gotovoe.py | 4,029 | 4.03125 | 4 | import math
# import matplotlib.pyplot as plt
# from matplotlib import mlab
# начальные условия
x0 = float(1)
y0 = float(0.69314718056)
# отрезок [x0, b], где x0 = 1, b = 2
b = float(2)
# шаг
h = float((b - x0)/10)
f = lambda x, y: math.e**(float(y)/float(x))
ilist = [0, 10, 1]
print(ilist)
xlist = [... |
a0c7dc11e94c70de567d5c5d9e60b80d46d6a134 | ElkinAMG/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 472 | 4.28125 | 4 | #!/usr/bin/python3
'''
This module contains the function `text_indentation`
for printing with indentation.
'''
def text_indentation(text):
'''This function prints with indentation.
- text {str} will be printed with indentations'''
if not isinstance(text, str):
raise TypeError('text must be a str... |
654e515a92ca00d444f54bc0d2a2b0cde1b1b5d2 | pirokaka/lab1_done | /lab1.py | 436 | 3.71875 | 4 | #1
n = int(input("Введите трёхзначное число: "))
if n >= 100 and n <= 999:
s = str(n)
f = False
for i in range(len(s)):
if s[i] == "0" or s[i] == "9":
f = True
if f == True:
print("Цифры 0 или 9 есть в числе.")
else:
print("Цифр 0 и 9 в числе нет.")
else:
prin... |
6cf83b5641f8046a34be3ef2808bf9b37df57f2c | GabrielSalazar29/Exercicios_em_python_udemy | /Exercicios Seção 04/ex025.py | 317 | 3.78125 | 4 | """
Leia um valor de área em acres e apresente-o convertido em metros quadrados. A
fórmula de conversão é: M = A * 4048.58, sendo M a área em metros quadrados e A
a área em acres.
"""
aa = float(input("Digite uma área em acres: "))
am = aa * 4048.58
print(f"A área digitada em metros quadrados é:{am} m2")
|
b7208190423ca8c16a0e687cb130a63087620952 | iisdd/Courses | /莫烦强化学习/Sarsa_ex1/RL_brain.py | 2,748 | 3.515625 | 4 | """
sarsa的特点,q_predict是用s_对应的a_算的,而不是s_中使Q最大的a_
agent决策
This part of code is the Q learning brain, which is a brain of the agent.
All decisions are made in here.
"""
import numpy as np
import pandas as pd
class RL(object):
def __init__(self,action_space,learning_rate=0.01,reward_decay=0.9,e_greedy=0.9)... |
6d1e59240df9346344a5d7066be6480e0a2cf894 | mattlisle/computer-vision | /corner_detector.py | 610 | 3.65625 | 4 | '''
File name: corner_detector.py
Author:
Date created:
'''
'''
File clarification:
Detects corner features in an image. You can probably find free “harris” corner detector on-line,
and you are allowed to use them.
- Input img: H × W matrix representing the gray scale input image.
- Output cim... |
561b53348ad0c8237cfdfd9964029384ea968b63 | starwriter34/EGN3214 | /Assignment 02/Assignment 2.py | 1,035 | 4.03125 | 4 | '''
Chris Oakley
Interpolation
08/31/2020
EGN3214 - Assignment 2
Variables:
xp = list of rain fall in hours
fp = list of rain fall in inches
i = throw away variable for hours
plural = logic for hours or hour depending on the amout of time entered
'''
import numpy as np
xp = [0, 1, 2, 5, 7, 8, 10, 12, 15]
fp = [0, 0... |
d89e5c0ca226f253951a8cfd51ad24d6b5da9419 | mishiwalker/python-labs | /03_more_datatypes/3_tuples/03_12_list_to_tuple.py | 206 | 4.25 | 4 | '''
Write a script that takes a list and turns it into a tuple.
'''
def convert(list_):
return tuple(list_)
list_ = [item for item in input("Please give me a list: ").split()]
print(convert(list_))
|
9ce65c972f12fc49fd63da58ef2f288271d23406 | harita1309/WTLABPython | /wordfrequency.py | 104 | 3.78125 | 4 | s = input("Enter a string: ")
l = list(s.split())
d = {}
for i in l:
d[i]=l.count(i)
print(d)
|
689f785611acb1c998febb25525b7181d1310c97 | yennanliu/CS_basics | /leetcode_python/Array/third-maximum-number.py | 5,308 | 4 | 4 | """
414. Third Maximum Number
Easy
Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Example 1:
Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The th... |
d9696d1d571c63a1d8437ab5ee0ff610e6848c0b | ultraasi-atanas/MIT-6.00.1x-Exercises | /MIT6.00.1x-Week2-BinarySearch.py | 603 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 24 14:43:09 2020
@author: Atnaas Kozarev
"""
# Guess the Square Root of X using binary search
x = 10000
margin_of_error = 0.01
numGuesses = 0
low = 1.0
high = x
guess = (high + low)/2.0
while abs(guess**2 - x) >= margin_of_error:
print('low ... |
de6d088dec9b8532102dc188819f5a1a4adc75d2 | GeekyTim/PiClock | /code/pir_gpio.py | 1,118 | 3.5625 | 4 | import threading
from time import time, sleep
import RPi.GPIO as GPIO
class PIR(threading.Thread):
"""
Detects whether there has been movement around the clock, and turns the matrix off if there has not been any
"""
def __init__(self, pirpin, nomovementforseconds):
self.__pin = pirpin
... |
9ffcc7778b94b354094609dc2b00d9fbffea4e6a | buglenka/python-exercises | /ReplaceWords.py | 2,374 | 4.3125 | 4 | #!/usr/local/bin/Python3.7
"""Replace Words
In English, we have a concept called root, which can be followed
by some other words to form another longer word - let's call this
word successor. For example, the root an, followed by other, which
can form another word another.
Now, given a dictionary consisting of man... |
ad8b1aab62871c25b34de89e8878a585677fe91e | gnasherx/Ciphers | /PlayfairCipher.py | 3,017 | 3.5 | 4 | from collections import deque
import numpy as np
matrix_size = 5 ** 2
input_string = ''
def find_repeater(string):
my_list = []
my_list.append(string[0])
for i in range(1, len(string)):
if string[i] in my_list:
return False
else:
my_list.append(string[i])
retur... |
c693e63e28f4ffc5837041bd9d30332c747a647b | tejamupparaju/LeetCode_Python | /leet_code102.py | 1,736 | 3.890625 | 4 | """
102. Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15... |
35f1cab05a63baa1a52a7086ff73c96719b3afdd | xingyazhou/Data-Structure-And-Algorithm | /BinarySearch/findMin.py | 1,467 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 8 21:27:15 2020
153. Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exis... |
7e14a7bf68a8d9046652a519d996765566c4134e | geekhub-python/strings-Client-Z | /10.py | 181 | 4.09375 | 4 | #!/usr/bin/env python3
text = input("Enter string: ")
my_list = text.split("h")
n_list = []
n_list.append(my_list[0])
n_list.append(my_list[-1])
text = "".join(n_list)
print(text)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.