blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
64f767701344bcea45ef4d2507b32b9f2f2bffbb | 0r0loo/D.S-Algo | /Python/doit_da_algo/chap01/print_starts1.py | 303 | 3.78125 | 4 | # *를 n개로 출력하되 w개마다 줄바꿈하기 1
print('*를 출력합니다.')
n = int(input('몇 개를 출력할까요? : '))
w = int(input('몇 개마다 줄바꿈을 할까여? : '))
for i in range(n):
print('*', end='')
if i % w == w - 1:
print()
if n % w:
print()
|
16ac4fcf657be4ad681a4676af25a31d8c346e99 | saviaga/Algorithm-Implementations | /traverse_tree/py/StackTraversal.py | 1,117 | 3.75 | 4 | class StackTraversal:
# Output after stack push
def preorderTraversal(self, root):
stack, cur = [], root
result = []
while cur or stack:
while cur:
stack.append(cur)
result.append(cur.val)
cur = cur.left
cur = stack.... |
8bc9566ce94446146efaff25b262b534a2cc65b1 | MihailBratanov/Kelly-s-py-workbook | /first.py | 1,857 | 3.78125 | 4 | #Url we shall be scraping from
base_url="https://www.lexico.com/en/definition/"
#imports of libraries we will use
from tkinter import *
import requests
import re
from bs4 import BeautifulSoup
#This is a function to remove the html tags from the definition
def cleanup(definition):
regex = "<.*?>"
final_de... |
537794df6dc4f0e2de7566ff852e07446a6bdd2d | manishshiwal/guvi | /vowel.py | 163 | 3.796875 | 4 | n=raw_input("enter the letter")
ab=['a','A','e','E','i','O','u','o','I','U']
b=1
for c in ab:
if(n==c):
print("vowel")
b=0
if(b==1):
print("consonant")
|
ce9b9e1faaf31244f2ec3aaa1e9fa1f09201b36f | addherbs/LeetCode | /Medium/39. Combination Sum.py | 1,271 | 3.53125 | 4 | # Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
#
# The same repeated number may be chosen from candidates unlimited number of times.
#
# Note:
#
# All numbers (including target) wil... |
6aaf1f801baea88a1a028a82477f8def1880df7b | SateehTeppala/Data | /Sorting Algorithams/Bubble Sort.py | 384 | 4.15625 | 4 | '''
Optimized Bubble Sort Algorithm
'''
def BubbleSort(a):
for i in range(len(a)):
for j in range(0,len(a)-i-1):
if a[j] > a[j+1]:
a[j],a[j+1] = a[j+1],a[j]
return a
if __name__ == "__main__":
a = [2,312,21,121,2,454,567,787,453,45,545,3,534,5,34]
data = BubbleSort... |
d36ec25fe459d3f97ae0d485e94d1e4374be1391 | aucan/LeetCode-problems | /287.FindtheDuplicateNumber.py | 1,430 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 21:23:43 2020
@author: nenad
"""
"""
Problem URL: https://leetcode.com/problems/find-the-duplicate-number/
Problem description:
Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (incl... |
ad53896a1b6391ac861c2f43c63352e0696cbd4a | nyuruk/words.py | /words.py | 2,890 | 3.609375 | 4 | # Generate words from simple rules.
import sys
import re
import random
import json
def from_rule(rule, parameters):
"""
Generates a word that matches the specified rules.
"""
if not rule or not parameters:
return None
# Find all parameters that are wrapped in {}
matches = re.finditer... |
895fd887deeb17e194103f89dad455000eaf0855 | jinglepp/python_cookbook | /03数字日期和时间/03.03数字的格式化输出.py | 2,113 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# 问题
# 需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。
# 解决方案
# 格式化输出单个数字的时候,可以使用内置的 format() 函数,
# 比如:
x = 1234.56789
print(format(x, '0.2f')) # 两位小数
# 1234.57
print(format(x, '>10.1f')) # 右对齐
# 1234.6
print(format(x, '<10.1f')) # 左对齐
# 1234.6
print(format(x, '^10.1f')) # 居中对齐
# 1234.6
print(fo... |
aabbc9cd21f5cc2a20aa1089610d7bef134ca5cb | AamodPaud3l/python_assignment_dec15 | /eqnsolve.py | 255 | 3.875 | 4 | #Program to solve a y = mx + c having various values of x
x_values = [1, 2.3, 5.6, 7, 78]
def solve_for_y(values):
m = 45
c = 0.5
for x in values:
y = m * x + c
print("For x={0}, y= {1:.2f}".format(x,y))
solve_for_y(x_values)
|
31af92bbb718ddd1060a54d49aee4e81685e92b0 | jgathogo/python_level_1 | /week4/problem8.py | 19,542 | 3.6875 | 4 | import os
import string
import sys
"""
Notes:
- Thumbs up!
- You probably ran out of time but consider using text alignment. It is a godsend for users.
"""
def main():
# 1000 most common English words
common_words = ["be", "and", "of", "a", "in", "to", "have", "too", "it", "I", "that", "for", "you", "he", "w... |
061714b286b1481edc102b893e83f05ebb88faf8 | giutrec/FablabDoorman | /www/datemanager.py | 498 | 3.734375 | 4 | #!/usr/bin/env python
from sys import argv
from datetime import datetime
format = "%Y-%m-%d %H:%M"
start_time = "16:00"
stop_time = "20:00"
now = datetime.today()
start_date_string = now.strftime("%Y-%m-%d ") + start_time
start_date = datetime.strptime(start_date_string, format)
stop_date_string = now.strftime("%Y-%m... |
7d01a498c8984d3674a549745126f0e498e4f350 | jgjefersonluis/python-pbp | /secao02-basico/aula22-valormaiormenor/main.py | 458 | 4.03125 | 4 | # Escreva um programa para exibir o maior e menor valor uma vez digitado pelo usuario
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
maior = a
if b > c and b > a:
maior = b
if c > b and c > a:
maior = c
menor = a
if b < c and... |
90fd936722b928db36e7f404309bb0c08dcb35a8 | svenkat19/snap | /benchmark/python/fib-recurs.py | 82 | 3.578125 | 4 | def fib(n):
if n <= 2: return n
return fib(n - 1) + fib(n - 2)
print(fib(35)) |
7451c0b64380a280e6d5943230bf1034e86f3cb2 | biomathcode/Rosalind_solutions | /Strings_and_lists.py | 980 | 3.703125 | 4 | """
Given: A string s of length at most 200 letters and 4 integers a, b, c and d
Return:The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.
"""
SampleText = "HumptyDumptysatonawallHumptyDumptyhada... |
98786b98b44e4c24374581dd374350bf992702c3 | hatlonely/leetcode-2018 | /python/119_pascals_triangle_ii.py | 295 | 3.84375 | 4 | #!/usr/bin/env python3
class Solution:
def getRow(self, n):
if n == 0:
return [1]
row = self.getRow(n - 1)
return [1] + [row[i] + row[i+1] for i in range(0, len(row) - 1)] + [1]
if __name__ == '__main__':
print(Solution().getRow(3), [1, 3, 3, 1])
|
c9e7b8d0917bf711109ccb13858b5c88fd4545d5 | yung-pietro/learn-python-the-hard-way | /EXERCISES/ex23.py | 1,532 | 4.1875 | 4 | import sys
script, input_encoding, error = sys.argv
#the argv's that the script requires
def main(language_file, encoding, errors):
#creates function, main, with three inputs, language_file, encoding, and errors. But where do these come from?
line = language_file.readline()
#not sure
if line:
#if... |
4049df6753bb05a3656ad534054b54c96af1119c | Barret-ma/leetcode | /567. Permutation in String.py | 1,411 | 3.828125 | 4 | # Given two strings s1 and s2, write a function to return true if s2 contains
# the permutation of s1. In other words, one of the first string's permutations
# is the substring of the second string.
# Example 1:
# Input: s1 = "ab" s2 = "eidbaooo"
# Output: True
# Explanation: s2 contains one permutation of s1 ("... |
7c1386e726f4867617ac9682657532da2425df07 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/returning_values.py | 1,324 | 4.25 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def area_triangle(base, height):
""" Calculate the area of triange by multipling `base` by `height` """
return base * height / 2
def get_seconds(hours, minutes, seconds):
""" Calculate the `hours` and `minutes` into sec... |
5f3fce4dec43a93460b56832074440249eae4b32 | mbuhot/mbuhot-euler-solutions | /python/problem-052.py | 577 | 3.734375 | 4 | #! /usr/bin/env python3
from itertools import count
description = '''
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digi... |
4fd5e020d013ebe4000749cee5b1ece25621c713 | bkyileo/algorithm-practice | /python/Longest Common Prefix.py | 736 | 3.84375 | 4 | __author__ = 'BK'
'''
Write a function to find the longest common prefix string amongst an array of strings.
Subscribe to see which companies asked this question
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if le... |
f728bda2423de4a317a3609c46f59a6e397b0745 | UniqueDavid/Python | /day6/demo-property.py | 552 | 3.859375 | 4 | #使用@property进行可以设置一个getter函数,即返回一个值
#使用score.setter可以设置相关的值,这里面第一个参数为self,第二个为value
class Student(object):
@property
def name(self):
return self.__name
@property
def score(self):
return self.__score
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('Score must be an int... |
50c659616892deecac7a0122bb08a52628386405 | Anishde85/Hacktoberfest21_Algo_Collection | /Python/binary-search.py | 263 | 3.84375 | 4 | def binary_search(arr, n):
st = 0
end = len(arr) - 1
while(st < end):
mid = (st+end)//2
if arr[mid] == n:
return True
elif arr[mid] < n:
end = mid-1
else:
st = mid+1
return False
|
6e93dd515d6e6390ab79034520c0290177b598f1 | adnan15110/DataCompressionWithAdvise | /context_tree/context_tree.py | 2,016 | 3.921875 | 4 |
class TrieNode:
# Trie node class
def __init__(self):
self.children = [] # can be improved by having a dict
self.data = 0
self.count=0
# isEndOfWord is True if node represent the end of the word
self.isEnd = False
class Trie:
# Trie data structure class
def __... |
09c1890b291b58e9b585818a888d448f48fb92fc | gqjuly/hipython | /helloword/2020_7_days/nine_class/c8.py | 677 | 3.625 | 4 |
from c9 import Human
"""
继承性:
避免我们定义重复的方法和变量
"""
class Student(Human):
def __init__(self, school, name, age):
self.school = school
# Human.__init__(self,name, age)
super(Student, self).__init__(name, age)
# self.__sorce = 0
def do_homework(self):
super(Student, self).... |
6658a8791cec18480fcca1661a942952f52cad72 | st-pauls-school/bio | /2012/q1/python/distinct-prime-factorisation.py | 1,060 | 3.734375 | 4 | def primes(ubound):
rv = [2]
candidates = [x for x in range(3,ubound+1,2)]
candidate = 2
while candidate < ubound**0.5:
candidate = candidates[0]
rv.append(candidate)
# this resizing of the lists is somewhat sub-optimal, considering re-writing, e.g. https://stackoverflow.... |
c6469d2a545f3249abcc3539f22bd2d7ae1d1af6 | gitPty/windows7 | /windows7/unit16/highs_lows.py | 1,283 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 21 19:14:04 2019
@author: Administrator
"""
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高气温
filename ='death_valley_2014.csv'
with open (filename) as f:
reader =csv.reader(f)
header_row =next(reader)
... |
96d86117bb5a578e1ad5f43ae51f4b4b2518a171 | Togas/algorithms | /sorting/insertionSort.py | 292 | 3.984375 | 4 | #sort in place
def insertionSort(array):
for i in range(1, len(array)):
j = i-1
while j >= 0:
if array[i] < array[j]:
array[i], array[j] = array[j], array[i]
j -= 1
i -= 1
else:
break
|
3317d6468880bb73ae91beb4dcba99c0f932f8ae | aming0518/PythonStudy | /替换和空格的消除.py | 262 | 4.3125 | 4 |
mystr="hello 123 hello 123"
print(mystr.replace("123","python"))#替换
print(mystr)
print(mystr.replace("123","python",1))#1,限制次数
print(" ab c ".strip())#前后去掉空格
print(" ab c ".rstrip())#去掉右边空格
print(" ab c ".lstrip())
|
19adc927fecadd9ad39523d8de8cfd702250500f | mindnhand/Learning-Python-5th | /Chapter19.AdvancedFunctionTopics/sumtree.py | 1,622 | 4.3125 | 4 | #!/usr/bin/env python3
#encoding=utf-8
#---------------------------------------------------------
# Usage: python3 sumtree.py
# Description: why recursive function
#---------------------------------------------------------
'''
recursion--or equivalent explicit stack-based algorithms we'll meet
shortly--can be requ... |
57269b576346b40c264a51748cdee321e490db65 | joybakes/HB-Exercise09 | /recursion.py | 1,932 | 4 | 4 | # Multiply all the elements in a list
def multiply_list(l):
total = 1 # Set total to 1
if l == []: # Set the base case, if our list is empty
return 1 # return 1
else: #if our list is not empty
total = l.pop() * multiply_list(l) # total is equal to last number in list * multiply_list(l)
ret... |
fb3a79f78c218ceece9e075baaa51b246b7fa92d | manjunatha-kasireddy/python | /python/practice/ifelse/for2.py | 630 | 3.96875 | 4 | ex = ["c-lang", "java", "python", "html", "javascript"]
for x in ex:
print(x)
for x in "java":
print(x)
for x in ex:
print(x)
if x == "python":
break
for x in ex:
if x == "html":
break
print(x)
for x in ex:
if x == "c-lang":
continue
print(x)
for x in range(6):
print(x)
... |
7f876fbd61655d286b2406f1d371e5e439e084b5 | eronekogin/leetcode | /2020/increasing_order_search_tree.py | 696 | 3.75 | 4 | """
https://leetcode.com/problems/increasing-order-search-tree/
"""
from test_helper import TreeNode
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
currNode, stack = root, []
newRoot = currRoot = None
while currNode or stack:
while currNode:
... |
687fb311b55c26b81a942481bdfd6e633dd32986 | nfu13026/FruitGuessingGame | /fruitGuessinggame v0.9.py | 4,127 | 4.21875 | 4 | #fruitGuessinggame
#Nathaniel Fu
#Version 0.9
import time
import sqlite3
import random
def randomFruit(): #This function is connected to a database in order to randomly select a fruit from a database which contains a list of fruit.
with sqlite3.connect("FruitDatabase(GitHub)/fruits.db") as db: #Here is t... |
0f1e6e52b35ccd27212dc7bf1a3566f404fb497b | luffyx25/msc-data-science | /INM430/Week01-part1.py | 2,725 | 3.984375 | 4 | # https://moodle.city.ac.uk/mod/page/view.php?id=1174260
import csv # imports the csv module
import sys # imports the sys module
# total rows
total = 0;
f = open('TB_burden_countries_2014-09-29.csv') # opens the csv file
# Exercises Part-1: Some elementary Python tasks
# 1. Count the number of rows in the ... |
b44c973d8ed585904175d4789ca16a361f5a06d7 | ds-ga-1007/assignment9 | /zk388/auxilary_functions.py | 2,576 | 4.03125 | 4 | '''
Created on Dec 3, 2016
@author: Zahra KAdkhodaie
'''
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from matplotlib.text import Text
'''Load the datasets. These datasets must be in the same folder as the code.'''
countries = pd.read_csv('countries.csv')
income = pd.read_... |
1f71d6171e834e059d77958f9f3adecc68e0c139 | MuhammadSaqib-Github/Python | /Assignment 2/Question #3.py | 473 | 3.703125 | 4 | lisT = [1 ,2 ,2 ,2 ,2 ,1 ,3 ,1 ,3 ,3 ,3 ,1 ,5 ,5 ,5 ,0 ]
occurence = 0
length = len(lisT)
for i in range(length):
counter=0
x=i
for j in range(length):
y=j
if (lisT[i]==lisT[j]):
if y-x==0 or y-x==1:
counter=counter+1
x+=1
... |
f3382d622452146775228c4068fb5363fe051bc6 | simrit1/asimo | /Chap 20/alice_words.py | 2,218 | 3.671875 | 4 | def text_to_words(the_text):
""" return a list of words with all punctuation removed
and all in lowercase """
my_substitutions = the_text.maketrans(
# If you find any of these
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\",
# Replace them by these
"abcdefghij... |
3386638160c393304e239e56634a3e6fa4ece679 | Sm0rter/Challenges | /Prefix Challenge.py | 516 | 3.71875 | 4 | # Variables
going = True
# Functions
def c_p(x, y, z, common):
if len(y) == 0 or len(x) == 0 or len(z) == 0 or x[0] != y[0] or y[0] != z[0] or z[0] != x[0]:
return common
return(c_p(x[1:], z[1:], y[1:], common + x[0]))
# Main Loop
while going == True:
string1 = input("Give me the first word. ")
... |
109e5f6759849f4d475ba9c18deb86cda6318887 | jaquelinepeluzo/Python-Curso-em-Video | /ex016.py | 130 | 4 | 4 | n1 = float(input('Digite um número: '))
print('O número digitado é {}, e sua porção inteira é: {}'.format(n1, int(n1)))
|
1858fd23d76c081809863899b8df4522cb193e7c | ellkrauze/stack_binary_search_tree | /Deck_Python_Errors.py | 1,404 | 3.8125 | 4 | from collections import deque
def main():
d = deque([])
while True:
input_line = input()
console_command = (input_line.split(' '))[0]
if console_command == 'push_front':
number = int(input_line.split(' ')[1])
d.appendleft(number)
print('ok... |
7c5f88c58541eee854c87a9cc0e870f18841a1a9 | JackDrogon/CodingEveryday | /code/2021/04/09/python-itertools-groupby.py | 319 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
def sortBy(score):
if score > 80:
return "A"
elif score >= 60:
return "B"
else:
return "C"
scores = [81, 82, 84, 76, 64, 78, 59, 44, 55, 89]
for m, n in itertools.groupby(scores, key=sortBy):
print(m, list(n))
|
7c6bc1e4689efab269a762cadb5e032096608c05 | Javiql/Estructura-de-Datos | /Tarea S1- EjerciciosPáginaWeb/Tarea ejercicio 12.py | 411 | 3.703125 | 4 | #Nombre: Javier Santiago Quiroz Lastre
#Aula: Software A1
#Ejercicio 12:Calcular la suma de los cuadrados de los primeros 100 enteros y escribir el resultado.
class Suma:
def Calcular(self):
i=1
suma=0
x=range(100)
for i in x:
suma=suma+i*i
print... |
3abd1af360dc1be946bad27a4d28a345da510258 | alice19-meet/yl1201718 | /extra/tictactoe | 2,895 | 3.765625 | 4 | class Board():
def __init__(self):
self.board = [[x for x in range(3*n-2, 3*n+1)] for n in range(1, 4)]
self.used_blocks = set()
def __str__(self):
board_output = ""
for row in self.board:
for number in row:
board_output += str(number) + " "
... |
a6ae9a6dc166c15ed59fe4e32f2f656255f00d9c | Muriithijoe/Password-Locker | /test.py | 3,149 | 3.578125 | 4 | import pyperclip
import unittest
from locker import User
from credential import Credential
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for user class behaviours
Args:
unittest.TestCase: class that helps in creating test cases
'''
def setUp(self):
'''
... |
63002814329cc2ec351da6089cdaab15b98ffbac | jaykooklee/practicepython | /if.py | 206 | 3.625 | 4 | if True:
print('참입니다.')
if True:
print('참입니다.')
if False:
print('참입니다.')
score = 80
if score > 80:
print('합격입니다.')
else:
print('불합격입니다.')
|
6590806b73eeb82243baf85d9581d33982806275 | wangkai997/leetcode | /2.两数相加.py | 1,290 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=2 lang=python3
#
# [2] 两数相加
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode((... |
c2facf5a64c35fba081ea370388df3855554f9bc | Alisson-JP/Programas-Basicos | /Python/Numero dobro e terça parte.py | 308 | 3.984375 | 4 | #Crie um algoritmo que leia um número real e mostre na tela o seu dobro e a sua terça parte.
numero = float(input(f'Por favor, digite um número qualquer: '))
dob = numero * 2
ter = numero / 3
print(f'Você digitou {numero}, o dobro deste valor corresponde a {dob}, já a terça parte é igual a {ter}.')
|
3394f0b8c6ac5dd84796cbe5b9a9506d5fa39ac1 | AllenKd/algorithm_practice | /second_stage/lowest_common_ancestor_in_a_binary_tree.py | 1,138 | 3.828125 | 4 | class Node:
# Constructor to create a new binary node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def find_path(root, target):
if not root:
return False
if root.key == target:
return [root.key]
left = find_path(root.left, tar... |
872ae32cf7837edf369ca2cc0988bb21c2ddc846 | AdityaDavalagar/sample | /address.py | 135 | 3.578125 | 4 | address = "1-3-33/221,domalaguda,hyderabad"
temp = ['-','/']
for i in temp:
address = address.replace(i," ")
print address
print temp |
8cb2276934fb11d7e2fbd6c3b5d8f18427484de0 | wellingtonlope/treinamento-programacao | /uri-online-judge/python3/iniciante/1153.py | 136 | 4.03125 | 4 | # -*- coding: utf-8 -*-
def fat(num):
if num == 1:
return 1
return fat(num-1) * num
n = int(input())
print(fat(n))
|
5e13a4066f53c3d50d324229aaa0b06ab20aa1a2 | A01376318/Mision_03 | /Trapecio.py | 745 | 3.625 | 4 | #Autor: Elena R.Tovar, A01376318
#Calcular área y perímetro midiendo base mayor, base menor y altura de trapecio isóceles
import math
#calcula area
def calcArea(ba,bb,h):
a=((ba+bb)/2)*h
return a
#calcula hipotenusa
def hipotenusa(ba,bb,h):
hip= math.sqrt((h**2)+(((ba-bb)/2)**2))
return hip
#... |
53a56961bbd744660847e6c553618b52ca689e2c | KarolloS/python-course | /Problem Set 2/p2_3.py | 972 | 3.828125 | 4 | # Monthly interest rate = (Annual interest rate) / 12.0
# Monthly payment lower bound = Balance / 12
# Monthly payment upper bound = (Balance x (1 + Monthly interest rate)12) / 12.0
#
# Write a program that uses these bounds and bisection search to find the smallest monthly payment to the cent
# such that we can pay o... |
8c8fcdc1b0ff0d40c191d7ba83d1050cb3ecb752 | sdawn29/cloud-training | /for_ex.py | 1,463 | 3.53125 | 4 | s = 'python'
for a in s:
print('a =', a)
b = 'java'
L = [10, 20, 30]
for b in L:
print('b =', b)
print('Now a and b =', a, b)
D = {'A': 10, 'B': 20}
for k in D:
print('k =', k)
line = '-' * 40
print(line)
for k in D.keys():
print('key =', k, 'value =', D[k])
print(line)
for v in D.va... |
e171dcc3bb0df770d740074336a213b9830156c0 | EmilianaAP/Movie_match | /Movie_searching.py | 738 | 3.75 | 4 | from imdb import IMDb
def movie_searching(username):
moviesDB = IMDb()
movie_name = input("Enter movie name: ")
movies = moviesDB.search_movie(movie_name)
print('Searching for movies:')
id = movies[0].getID()
movie = moviesDB.get_movie(id)
title = movie['title']
year = movie['year']
... |
b41eda9c8fc780a99da12561f0d9322c216ef98f | TPSGrzegorz/PyCharmStart | /KodolamaczKurs/Prace domowe/OOP_Stringify_Nested.py | 1,239 | 3.734375 | 4 | class Crew:
def __init__(self, members=()):
self.members = list(members)
def __str__(self):
return '\n'.join([str(x) for x in self.members])
class Astronaut:
def __init__(self, name, experience=()):
self.name = name
self.experience = list(experience)
def __str__(self... |
a4d8e795cef326feed9e6b68adde2d1c48c9c15b | ponpon88/python_lab | /20191202/s6-1.py | 480 | 3.640625 | 4 | def printmsg():
print("副程式", msg)
''' Main func '''
msg = 'Global Variable'
print("主程式", msg)
printmsg()
def printmsg2():
msg2 = "Local Variable"
print("副程式", msg2)
''' Main func '''
msg2 = 'Global Variable'
print("主程式", msg2)
printmsg2()
def printmsg3():
global msg3
msg3 = "Local Variable"
... |
3bd32cd2107d30ef41241ed246509fcdac4664fb | JhoanRodriguez/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/4-print_hexa.py | 82 | 3.546875 | 4 | #!/usr/bin/python3
for x in range(0, 99):
print("{:d} = 0x{:x}".format(x, x))
|
58234b08fdd28af355e999e81de9ec25af3bc4d5 | choijy1705/AI | /chap04/ex01_MSE.py | 656 | 3.765625 | 4 | # MSE(Mean Squared Error) : 손실함수
import numpy as np
def mean_squared_error(y, p):
return 0.5 * np.sum((y - p)**2)
# 예측 결과 : 2
p = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] # 2일 확률이 60프로 2라고 예측
y = [0,0,1,0,0,0,0,0,0,0] # One-Hot Encoding 방법으로 출력(실제값)
print(mean_squared_error(np.array(y), np.array(p)))... |
5e855b93dffb8f00d63b9012bfe9647542e25154 | sindridan/Python_2018 | /verkefni1.py | 5,024 | 3.6875 | 4 | #liður 1:
#break input into indices where the line breaks
#append into new sortedlist
#sort the list
def cdo(input):
sorts = input.split(" ") #seperates each word in string by spaces and lists them
sorts.sort()
newstr = " ".join(sorts) #create a unified string and form a space between every word
return... |
dd069a546b04f836997cc82d6a345e4edd62485b | mukesh-jogi/python_repo | /Sem-6/Threading/multithread-lock.py | 1,016 | 3.5625 | 4 | import threading
from time import sleep
class C1(threading.Thread):
def __init__(self,threadname): # Overriding Thread class(baseclass) __init__ method
threading.Thread.__init__(self)
self.threadname = threadname
def run(self): # Overriding Thread class(baseclass) run method
isacquired =... |
cd0ff3bc7246086f771b5f07ebbd8219990def13 | siarhiejkresik/Epam-2019-Python-Homework | /final_task/pycalc/calculator/precedence.py | 2,355 | 3.515625 | 4 | """
The operator precedence.
"""
from enum import IntEnum
class Precedence(IntEnum):
"""
The operator precedence according to the operator precedence in Python.
https://docs.python.org/3/reference/expressions.html#operator-precedence
"""
DEFAULT = 0
# Lambda expression
LAMBDA = 10 ... |
b10961fb09b913e29bc502ab39b3d20fbfb2bd78 | pptech-ds/PPTech-Recommender-System-1 | /main.py | 12,578 | 3.671875 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('dark')
# To understand recommender system I followed the tutorial from "https://stackabuse.com/creating-a-simple-recommender-system-in-python-using-pandas"
# Database used for this tuto comming from "http... |
78a3070b719c5521e36d241e9ad26ccb33817cfc | nlpclass-2018-II/python-and-nltk-intro-exercise-muhammadhsn23 | /number6.py | 263 | 3.890625 | 4 | import nltk
# nltk.download('punkt')
sentence = 'I am going to take the NLP class next semester'
tokens = nltk.word_tokenize(sentence)
i=0
for words in tokens: #iterate through all splitted words
print(len(words)) #print the number of characters in the words |
d64d339ab2800064a7882951c68885b4211d4de0 | cwmaguire/genetic_algorithms_book | /escape.py | 834 | 3.703125 | 4 | import turtle
def escaped(position):
x = int(position[0])
y = int(position[1])
return x < -35 or x > 35 or y < -35 or y > 35
def draw_bag():
turtle.shape('turtle')
turtle.pen(pencolor='brown', pensize=5)
turtle.penup()
turtle.goto(-35, 35)
turtle.pendown()
turtle.right(90)
tu... |
5a22bfda22239f3394726c7a3db7c855abfa1827 | 10GGGGGGGGGG/colouring_graphs | /colouring_graphs.py | 3,329 | 3.609375 | 4 | import networkx as nx
import matplotlib.pyplot as plt
# Python program for solution of M Coloring
# problem using backtracking
class Graph():
nodes = []
edges = []
matrix = []
colors = []
colorDB = ['red','aqua','lawngreen','yellow','pink','orange','gray','salmon','cornflowerblue','fu... |
40f51f018d8be8f7ecd3db8307d702172e5e89a2 | colons/euler | /common.py | 977 | 3.796875 | 4 | alphabet = 'abcdefghijklmnopqrstuvwxyz'
def factors(n):
d = 1
fs = set()
sqrt = int(n**0.5)
while d <= sqrt:
if n % d == 0:
f = n/d
fs.add(d)
fs.add(f)
d += 1
return fs
def is_prime(number):
if number == 1 or number < 0:
return F... |
5d6b386581014f5298f04084c7aff1de5fc9ecde | dAIsySHEng1/CCC-Senior-Python-Solutions | /2011/S1.py | 240 | 3.640625 | 4 | N = int(input())
count_t=0
count_s=0
for i in range(N):
l = input()
count_s+= l.count('s')+l.count('S')
count_t+= l.count('t')+l.count('T')
if count_s>count_t or count_s==count_t:
print('French')
else:
print('English')
|
299b6edb7758a4ab05596d2eeb7d4bf03bf17c0a | DDUDDI/mycode1 | /0515/member.py | 216 | 3.734375 | 4 | class Member:
def __init__(self, num, name, phone):
self.num = num
self.name = name
self.phone = phone
def info(self):
print('\t', self.num, '\t', self.name, '\t', self.phone) |
dff53a57170b4d59dab8100387c5b3c75d9d3037 | Durga944/loop | /loop_str.py | 62 | 3.6875 | 4 | str="durga"
a=0
while(a<len(str)):
print(str[a])
a=a+1 |
cf504822c44fcd06e39dcdd522c4f7b837b3783d | sankeerth/Algorithms | /String/python/leetcode/valid_palindrome_iii.py | 1,224 | 3.9375 | 4 | """
1216. Valid Palindrome III
Given a string s and an integer k, return true if s is a k-palindrome.
A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.
Example 1:
Input: s = "abcdeca", k = 2
Output: true
Explanation: Remove 'b' and 'e' characters.
Example ... |
c8d9a1670ea13fd076506f85844d3b756e20993d | yjkim0083/3min_keras | /02_ANN/ann_regression.py | 1,672 | 3.546875 | 4 | # 회귀 ANN 모델
from keras import layers, models
class ANN(models.Model):
def __init__(self, Nin, Nh, Nout):
# Prepare network layers and activation functions
hidden = layers.Dense(Nh)
output = layers.Dense(Nout)
relu = layers.Activation("relu")
# Connect network elements
... |
dc6a2550f33c59ad7aa31cc5e4369510fc9d1ab0 | shashank977/Leetcode-Algo | /max_ascending_subarr.py | 251 | 3.828125 | 4 | def maxAscendingSum(nums):
if not nums:
return 0
sum = maxSum = nums[0]
for i in range(1,len(nums)):
if nums[i]>nums[i-1]:
sum+=nums[i]
maxSum = max(maxSum, sum)
else:
sum = nums[i]
return maxSum
print(maxAscendingSum([100,10,1])) |
172860b768863338b0bdd06d35442ef47fa507c6 | smkamranqadri/python-excercises | /excercise-7.py | 189 | 3.890625 | 4 | # Question 7 (Chapter 8):
# Please generate a random float where the value is between 10 and 100 using Python math module.
# Hints:Use random.random() to generate a random float in [0,1]. |
576e69ea02f4a0b6810e9f3c7933928a4d2473ed | Covax84/Coursera-Python-Basics | /quadratic_equation.py | 429 | 3.734375 | 4 | # квадратное уравнение: ax² + bx + c
# дискриминант: D = b² - 4ac
# вывести корни в порядке возрастания
a = float(input())
b = float(input())
c = float(input())
d = b**2 - (4 * a * c)
if d > 0:
x = (-b - d ** 0.5) / (2 * a)
y = (-b + d ** 0.5) / (2 * a)
if x < y:
print(x, y)
else:
print(... |
1c98c2d9acb50ea6448a401592b60df27c5caf25 | kashyrskyy/web-dev-tutorial | /triangle class.py | 1,065 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[7]:
import math
class Triangle():
def __init__(self, a, b, c):
self.side1 = a
self.side2 = b
self.side3 = c
def perimeter(self):
return self.side1 + self.side2 + self.side3
def area(self):
return 1/4(sq... |
96cb9a7fbff2fca911b7d8721a98732cfa4dbfd4 | bl00p1ng/Python-Intermedio | /list_and_dicts.py | 618 | 3.796875 | 4 | def run():
my_list = [1, 'hello', True, 4.5]
my_dict = {"firstname": "Andrés", "lastname": "López"}
super_list = [
{"firstname": "Andrés", "lastname": "López"},
{"firstname": "Tony", "lastname": "Stark"},
{"firstname": "Peter", "lastname": "Parker"},
{"firstname": "Hana", "l... |
d6a7c68bd23074d006187b3facfd070e30cec55c | lucyluoxi90/LearningPython | /hello.py | 4,713 | 4.21875 | 4 | print("Hello World")
the_world_is_flat = 1
if the_world_is_flat:
print "Be careful not to fall off!"
#3.1.1
print 2+2
print 50-5*6
(50-5.0*6)/4
8/5.0
17/3 #int / int ->int
17/3.0 #int / float -> float
17//3.0 # explicit floor division discards the fractional part
17%3 # the % operator returns the remainder of the ... |
7a1fdb1c91a87980d9162885a03430f8403fd3f9 | Yue-Du/Leetcode | /33.py | 1,144 | 3.578125 | 4 | from typing import List
class Solution:
def search(self, nums: List[int], target: int) -> int:
if len(nums)==0:
return -1
left=0
right=len(nums)-1
med=(left+right)//2
while left+1 < right:
if nums[med] > nums[right]:
left=med
... |
5323f6abf6d0a793a622cfea5de075f2c3c309f4 | deshdeepakPandey/Assignment1 | /PrimeNumbers.py | 179 | 3.75 | 4 | Number=int(input("Enter Number: "))
for j in range(2,Number+1):
k=0
for i in range(2,j/2+1):
if(j%i==0):
k=k+1
if(k<=0):
print(j),
|
7e5d96030e051f76c183d7cd19c28d5e49ea7033 | nikkiwojo/TDD-Project | /test_ordering.py | 716 | 3.890625 | 4 |
# Writing a unit test (basic example)
# First - need to import unittest package
# Second - need to import class/functions from original code
# Second - set up a class that will define a bunch of functions to test original code
# Notice parameter for the class is unittest.TestCase
# See example below for what to put in... |
925ec04191841fd4c63bf0301ae6d732c870e3be | bgoonz/UsefulResourceRepo2.0 | /_PYTHON/DATA_STRUC_PYTHON_NOTES/python-prac/Overflow/_Learning/problems/problem_07_dictionary.py | 510 | 3.78125 | 4 | # DICTIONARY
#
# Write a function named "my_filter" that takes a dictionary as a parameter.
# Return another dictionary that consists of the key/value pairs from the
# argument where the value has a length less than or equal to 3. Use any
# construct that want to implement "my_filter".
#
# Test data follows.
# WRITE Y... |
a7a284ebe3d3a9484994d50ef7487bd6844e3961 | rishabhranawat/challenge | /leetcode/abbreviation.py | 1,065 | 3.609375 | 4 | class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
:type dictionary: List[str]
"""
self.abbrs = {}
for each in dictionary:
ab = self.getAbbreviation(each)
if(ab in self.abbrs):
self.abbrs[ab].add(each)
... |
86dd91ed439e368d155397eb44453f0e621f5d19 | naveenselvan/hackerranksolutions | /sWAP cASE.py | 245 | 3.78125 | 4 | def swap_case(s):
c=[]
e=''
for i in s:
c.append(i)
for j in c:
if(j.isupper()==True):
e+=j.lower()
else:
e+=j.upper()
return e
|
5415daf4ab0d250304964de3065412c4871390f8 | sanyapalmero/Advent-of-code-2018 | /Day2/main.py | 1,277 | 3.90625 | 4 | def find_checksum(list_id): #solution of part 1
temp = []
res1 = 0
res2 = 0
for line in list_id:
two_count = 0
three_count = 0
for letter in line:
temp.append(letter)
for letter in temp:
if temp.count(letter) == 2:
two_count = 1
... |
26b4192e8075364bae32c3ff6e3958b668ae1d42 | DonCastillo/learning-python | /0061_set_challenge.py | 169 | 3.515625 | 4 |
while True:
text = input("Enter a text here: ")
if text.casefold() == "quit":
break
else:
print(sorted(set(text).difference(set("aeiou")))) |
578e302c56d7408a4b4c0324c6510b459bc6c721 | rafaelperazzo/programacao-web | /moodledata/vpl_data/69/usersdata/168/36267/submittedfiles/jogo.py | 736 | 3.9375 | 4 | # -*- coding: utf-8 -*-
import math
cv=int(input('Digite o número de vitórias do Cormengo: '))
ce=int(input('Digite o número de empate do Cormengo: '))
cs=int(input('Digite o número de saldo de gols do Cormengo: '))
fv=int(input('Digite o número de vitórias do Flaminthians: '))
fe=int(input('Digite o número de empate d... |
b9cd36a78a7ef15e6e254e79b49a309e125acfcc | aretisravani/python6 | /arm.py | 107 | 3.53125 | 4 | a=int(raw_input())
b=a%10
c=a/10
d=c%10
e=c/10
x=b**3+d**3+e**3
if(x==a):
print("yes")
else:
print("no")
|
ad3fea33f8163877572f7ec99a8f80cbbbfb31ec | erjan/coding_exercises | /maximum_matrix_sum.py | 1,637 | 3.984375 | 4 | '''
You are given an n x n integer matrix. You can do the following operation any number of times:
Choose any two adjacent elements of matrix and multiply each of them by -1.
Two elements are considered adjacent if and only if they share a border.
Your goal is to maximize the summation of the matrix's elements. Retur... |
8d01098dc7941f59dc39ba84a3529327911039cb | emanuelgustavo/pythonscripts | /Introdução a Ciencia da Computação com Python - PII/w5_busca_binária/w5_Ex2_bubble_sort.py | 459 | 3.921875 | 4 | def bubble_sort(lista):
fim = len(lista)
first = True
for i in range(fim-1, 0, -1):
if first:
#print(lista)
first = False
for j in range(i):
a = lista[j]
b = lista[j+1]
if a > b:
lista[j] = b
... |
197123c26689787a9bb58d86e283513db68580e4 | rajathans/cp | /CodeChef/hs08test.py | 174 | 3.796875 | 4 | x,y = raw_input().split()
x = int(x)
y = float(y)
if ((x % 5) == 0):
if((y-x-0.5)>0):
print("%0.2f"%(y-x-0.5))
else:
print("%0.2f"%y)
else:
print("%0.2f"%y) |
3705242fe7cad024a763f6c429fc3ba67163a886 | rikoodb/agregador_de_editais | /projeto_parser_inovacao/spiders/testes/testes_db_usuario.py | 1,208 | 3.53125 | 4 | import os
import unittest
import sqlite3
from usuario.usuario import lista_usuarios
class test_db_usuario(unittest.TestCase):
def setUp(self):
self.conn = sqlite3.connect("mydatabase.db")
self.cursor = self.conn.cursor()
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS usua... |
950e0385dee010fc04faca4e3e15ecbeca7019de | bhaveshpatelquantiphi/python | /day 3/calc.py | 2,155 | 3.90625 | 4 | import logging
import datetime
# now = datetime.datetime.now()
logging.basicConfig(filename='example.log',level=logging.DEBUG)
# logging.debug('This message should go to the log file')
# logging.info('So should this')
def add(x,y):
"""
add (x(float), y(float))
Return (float) :addition of first and second nu... |
3c638aa8de7f0a0c6b8c2c25e54ec3fd4c279d9a | RajatPrakash/Python_Journey | /matplot_lib_oops.py | 459 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(10, 10)) # creating a simple figure
axes = figure.add_axes([0, 0, 1, 1])
x = np.linspace(0, 10, 100)
y = np.tan(x)
axes.plot(x, y, 'r--', label= 'Red Sine Wave #01')
axes.set_xlabel('Time')
axes.set_ylabel('Sine wave')
axes.set_title('My... |
0050ea4f21566b9cc4317cc0e818fc0ba4dd1939 | conniechen19870216/WorkNotes | /Ubuntu4Me/codes/python/calc1.py | 525 | 3.5625 | 4 | #!/usr/bin/python
#coding:utf-8
from __future__ import division
x = int(raw_input("please input x: "));
y = int(raw_input("please input y: "));
def jia(x, y):
return x+y
def jian(x, y):
return x-y
def cheng(x, y):
return x*y
def chu(x, y):
return x/y
def calc(x, o, y):
if o == '+':
return jia(x, y)
elif ... |
b5457cb06b80bdb700244192651108498099b7ce | stephanieeechang/PythonGameProg | /PyCharmProj/Codingame/Defibrillators.py | 835 | 3.5625 | 4 | '''
Q2 final project
Codingame - Easy Level - Defibrillators
'''
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
defibList = []
smallestD = 99999999
lon = input()
lon = float(lon.replace(',','.'))*math.pi/180
lat = input()
lat = float(lat.repl... |
675d86bb8c0c5dcbdbe80b66a4291e64fc3e3cc1 | bvsslgayathri-8679/pythonlab | /1_2.py | 65 | 3.703125 | 4 | n=int(input())
if n>=0:print("positive")
else:print("negative") |
69cd770f18c2af8d4ab1fbbf1be95fe8aacdb80c | codegician/Python-Scripts | /inheritance.py | 927 | 3.875 | 4 | class Parent():
def __init__(self, last_name, eye_color):
print("Parent Constructor Called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name - "+self.last_name)
print("Eye Color - "+self.eye_color)
class Child(Parent):... |
b2d205e7a7c6f7dd492b65eee3eed9ef78e0f82f | MarionMcG/python-fundamentals | /Lecture notes and demos/1review.py | 1,617 | 4.3125 | 4 | #Demos and notes from Week 1 of Python Fundamentals
#Reviewing the basics
#Is it Tuesday?? (Review of IF Statements)
import datetime
print()
print("Is it Tuesday???")
today = datetime.datetime.today()
dayofweek = today.weekday()
print ('Today = ',today)
print ('Day of Week =', dayofweek)
#If the day of the week equal... |
6b886f6ad60a72be720a57d5f257f931d4914ead | theshadman/CPSC231_Stuff | /T14and15/Tutorial_14.py | 1,222 | 3.75 | 4 | #from tkinter import*
import tkinter as tk
import time
'''
animation = Tk()
canvas = Canvas(animation, width=500, height=500)
canvas.pack()
canvas.create_line(50,50,150,150)
while True:
for x in range(50):
canvas.move(1,5,0)
animation.update()
time.sleep(0.05)
for x in range(50):
canvas.move(1,-5,0)
anima... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.