blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8ab936ebb880310a33675c8faf9c325deba0d735 | TonyJenkins/python-workout | /06-pig-latin-sentence/pig_latin.py | 154 | 3.828125 | 4 | #!/usr/bin/env python3
def pig_latin(word):
if word[0] in 'aeiou':
return word + 'way'
else:
return word[1:] + word[0] + 'way'
|
e6b2fd430d1cfbcf71817cc0aea228da5c76517b | yeoeunhwang/python-works | /leetcode_problem/move_zeroes.py | 191 | 3.71875 | 4 | def move_zeroes(nums):
count = 0
for n in nums:
if n == 0:
nums.remove(0)
nums.append(0)
return nums
print(move_zeroes([1,0,2,3,0,4]))
|
c404d7892a14e457ca000f8f72b540ccb8d2f314 | hyelim-kim1028/lab-python | /LEC04/exception1.py | 2,139 | 3.90625 | 4 | """
error, exception: 프로그램 실행 중에 발생할 수 있는 오류
- exception 은 예외 (프로그램 실행 중 비정상적인 발생 -> 오류)
프로그램 실행중에 오류가 발생하면 해결 방법:
1) 오류가 발생한 코드 위치를 찾아서 오류가 발생하지 않도록 수정
2) 오류가 발생하더라도, 오류를 무시하고 프로그램이 실행될 수 있도록 프로그램을 작성
-> try 구문
"""
# Different types of errors
print(1)
# TYpical Error 1: nameerror: 변수나 함수등의 없는 이름을 사용하려고 할 때 ( ~ ... |
1d28e2e312043342856020926b0196cb5e8d0535 | venkateshpitta/python-exercism | /anagram/anagram.py | 199 | 3.765625 | 4 | from typing import List
def detect_anagrams(string: str, array: List[str]) -> List[str]:
return [x for x in array if x.lower() != string.lower() and sorted(x.lower()) == sorted(string.lower())]
|
3845f57d169ddefe7152a86b47545dabf77e7b0d | ryanfitch/Python_Mini_Projects | /Python-W3-Exercises/python-exercise37.py | 252 | 4.25 | 4 | # Write a Python program to display your details like name, age,
# address in three different lines.
name = input("Give me your name: ")
age = input("Give me your age: ")
address = input("Give me your address: ")
print(name)
print(age)
print(address)
|
9d7f5c5e56b17e1eec9d4aff5456cbf8259beb9b | glaubersabino/python-cursoemvideo | /world-02/exercice-055.py | 435 | 3.859375 | 4 | # Exercício 055
# Faça um programa que leia o peso de cinco pessoas.
# No final, mostre qual foi o maior e o menor peso lidos.
maior = 0
menor = 0
for c in range(0, 5):
peso = float(input('Qual o peso da pessoa {}? '.format(c + 1)))
if peso > maior:
maior = peso
if c == 0:
menor = peso
... |
3be1451c533dc8121e909b7f40def217dcf7f4a6 | AishwaryaBhaskaran/261644_Daily-commits-Python | /str.py | 470 | 4.25 | 4 | #Write a python program to check the user input abbreviation.If the user enters "lol", print "laughing out loud".If the user enters "rofl", print "rolling on the floor laughing".If the user enters "lmk", print "let me know".If the user enters "smh", print "shaking my head"
str=input()
if str=="lol":
print("laughing... |
e9fe4f39fbde4a99afa41aa24b8dc086374f4246 | Frankiee/leetcode | /graph_tree_dfs/backtracking/131_palindrome_partitioning.py | 976 | 4 | 4 | # [Backtracking]
# https://leetcode.com/problems/palindrome-partitioning/description/
# 131. Palindrome Partitioning
# History:
# 1.
# Feb 12, 2019
# 2.
# Dec 1, 2019
# Given a string s, partition s such that every substring of the partition
# is a palindrome.
#
# Return all possible palindrome partitioning of s.
#
#... |
27f371dcc889c5fd98e1554e238eb07e4a9e789e | bshankar/hackerrank | /src/strings/super_reduced_string.py | 540 | 3.71875 | 4 | # https://www.hackerrank.com/challenges/reduced-string/problem
def super_reduced_string(s):
s_list = list(s)
is_reduced = True
while is_reduced:
i = 0
is_reduced = False
while i < len(s_list) - 1:
if s_list[i] == s_list[i + 1]:
del s_list[i]
... |
e8914afce49f32ee9cda85de26036d1ff93dcdcb | vrushti-mody/Leetcode-Solutions | /Valid_Perfect_Square.py | 400 | 3.859375 | 4 | # Given a positive integer num, write a function which returns True if num is a perfect square else False.
# Follow up: Do not use any built-in library function such as sqrt.
class Solution:
def isPerfectSquare(self, num: int) -> bool:
num=num**0.5
print( num)
num=str(num)
if num[l... |
962aa75fea71466930e04b124dcc696a65409d75 | AKondro/ITSE-1329-Python | /CC5/CC5-Ex11/code.py | 250 | 3.796875 | 4 | fhand= open("mbox-short.txt")
records = 0
for record in fhand:
if record.startswith("From "):
split_record = record.split()
print(split_record(1))
records += 1
print("There were",records,"lines in the file with From as the first word") |
f4ce6a373b70c3c56465564c46fa80e64a138529 | poojataksande9211/python_data | /python_tutorial/excercise/winning_random_guessing_game1.py | 551 | 3.9375 | 4 | # win_num=45
import random
win_num=random.randint(1,100)
guess=1
guess_num=input("enter a no between 1 to 100")
guess_num=int(guess_num)
game_over=False
while not game_over:
if guess_num == win_num:
print(f"YOU WIN,and you guess a no in {guess} times")
game_over=True
else:
if gu... |
fbe376a3ac1cf002051bb73614d2ea1f2347ccb6 | sakkugupta/python | /pattern-1.py | 192 | 3.953125 | 4 | '''for i in range (1,6):
for j in range(1,6):
print('*',end='\t')
print()'''
for i in range (1,6):
for j in range (5,0,-1):
print('*',end="\t")
print()
|
3877046cb608fbeeab852d02116bb28ef8ad8f75 | prcopt/Python-Course-May2021 | /S02Q02.py | 2,607 | 4.4375 | 4 | """
EXERCISE SET S02Q02
- Using the starting and ending values of your car’s odometer,
and the measure of fuel consumed,
calculate the number of stops one should make for refuelling
while travelling from Bangalore to Goa,
a distance of 560 kms.
2 methods are pro... |
52a286f663ed2b7a704bd80414b5b6c64516f6c2 | moliming0905/Python | /Spider/getBaiduTiebaInfo.py | 1,582 | 3.703125 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import urllib
import urllib2
def loadPage(url,filename):
"""
作用:根据URL发送请求,获取服务器响应文件
url:需要爬取的url地址
filename:处理的文件名
"""
print "Download "+filename
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/5... |
b0ae29eb0766073101e56dc15b5bc208a04d47dc | oeeen/algorithm-practice | /boj/1110.py | 285 | 3.640625 | 4 | def func(n):
if (n < 10):
return n * 10 + n
else:
return (n%10) * 10 + (n//10 + n%10)%10
def main():
n = int(input())
current = func(n)
count = 1
while (current != n):
current = func(current)
count += 1
print (count)
main() |
f548eb1636d968bc0821c463aa9f82c40a6c78be | Batman001/leetcode_in_python | /dp/longest-common-sub-sequence.py | 715 | 3.71875 | 4 | # -*- coding:utf-8 -*-
def longest_common_sub_sequence(text1: str, text2: str) -> int:
"""
查找两个字符串的最长公共序列
:param text1: 字符串1
:param text2: 字符串2
:return: 最长公共序列的长度
"""
m = len(text1)
n = len(text2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m + 1):
... |
cd21e72989f60548f6b3485aa6a86ef885e9876e | navyakanu/30-Days-Of-Code | /Day8/Solution.py | 442 | 3.859375 | 4 | n = int(input())
phone_book = {}
for i in range(0,n):
print("Enter the name and number to add to phone book in the format name number")
name, id = input().split()
phone_book[name] = id
while 1:
temp = ''
print("Enter the name to search number for")
name = input()
if name == temp:
bre... |
03e6ab07c9c80cc13ef3883f02c492ff6c4b700a | iamksir/studyEveryDay | /first/study_list.py | 919 | 3.96875 | 4 | #list一种有序的集合
classmates = ['zhangsan','lisi','wangwu']
print(classmates)
#用索引访问list中每一个位置的元素
print(classmates[0])
print(classmates[-2])
#超出索引报'indexError'
#print(classmates[4])
#用len()获取list元素的个数
a = len(classmates)
print(a)
#lisr是一个可变的有序表,可以用append()追加元素到末尾
classmates.append('zhouliu')
print(classmates)
#通insert()... |
93cdd20bada04e8c46cbc75b20499bbcfb5e4e3b | hemangandhi/derpspace | /pythons/divesh/8_queens.py | 817 | 3.546875 | 4 | def intersect(x1,y1,x2,y2):
return x1 == x2 or y1 == y2 or abs(x1 - x2) == abs(y1 - y2)
def solve_queens_h(curr_sol,ind):
if ind == len(curr_sol):
return curr_sol
while curr_sol[ind] < len(curr_sol):
if not any(intersect(ind,curr_sol[ind],i,curr_sol[i]) for i in range(ind)):
gue... |
1ab6a912927cd0f3254fdf875455c1638b3fa8e9 | Abhishek532/Python-Practice-Programs | /Table of a number using FOR.py | 138 | 4.15625 | 4 | a = int(input("Enter a number : "))
n = int(input("Enter number of multiples :"))
for i in range(1,n+1):
print(a,"x",i,"=",a*i)
|
e96d043129788ccd284059aebdd28d9369ae1ee4 | eewf/SoftUni-Fundamentals-Tasks | /Sum of chars.py | 142 | 3.96875 | 4 | n = int(input())
total = 0
for i in range(n):
symbol = input()
char = ord(symbol)
total += char
print(f"The sum equals: {total}")
|
ebc162d4ea3b927eaa416b6c108df42c230e2b5b | JackM400/Text_Adventure_Test | /TextAdventureTest.py | 2,953 | 3.953125 | 4 | import time
import random
def GameInrto():
print('You awake in a overgrown grotto')
time.sleep(2)
print('You dont know who you are.......')
time.sleep(3)
print('or how you got here')
time.sleep(1)
print('In front of you you see two caves.\n')
time.sleep(1)
print('In one cave lies a... |
9e9957995bf4f555d0ee02970fcb46ac5aedf664 | heyhello89/openbigdata | /03_Data Science/1. Collection/1. CSV Handle/2.csv_read_row_column.py | 773 | 3.625 | 4 | import csv
def get_cvs_colInstance(col_name):
col_instance=[]
col_index=data[0].index(col_name)
for row in data[1:]:
col_instance.append(row[col_index])
return col_instance
def print_row(col_instance, type="int"):
if type == "int":
list(map(int, col_instance))
elif type == "... |
0c78fe580eb76e1bca6d4a6c41d505636075f820 | harsha1223/Data-Structure-using-python | /Graph/InsertionOperation/AddEdgeusingAdjacencyMatrix.py | 1,565 | 3.859375 | 4 | def add_node(v):
global node_count
if (v in nodes):
print("The node already present in the graph")
else:
node_count = node_count + 1
nodes.append(v)
for n in graph:
n.append(0)
temp = []
for i in range (node_count):
temp.appe... |
f96084792065b949edbac63b313119f6d65d0ea7 | slavishtipkov/Python | /Fundamentals/collections/dics.py | 1,412 | 4.15625 | 4 |
#dict
# delimited by { and }
# key-value pairs comma separated
# corresponding keys and values joined by colon
# the KEY obj must be immutable
# the VALUE obj can be mutable
# dict() constructor accepts:
# iterable series of key-value 2-tuples
# keyword arguments - requires keys... |
297f7aff8303af116c57510859338dfafd0a3c07 | damnmicrowave/cs102 | /homework01/vigenere.py | 1,635 | 3.734375 | 4 | def encrypt_vigenere(plaintext: str, key: str) -> str:
"""
>>> encrypt_vigenere("PYTHON", "A")
'PYTHON'
>>> encrypt_vigenere("python", "a")
'python'
>>> encrypt_vigenere("ATTACKATDAWN", "LEMON")
'LXFOPVEFRNHR'
"""
key = [key[i % len(key)] for i in range(len(pl... |
3dccc499d2dd2d6126caebdbbd4a7188437a8b6b | Robbie-Cook/COSC470-Assignment-1 | /decisionTree.py | 8,070 | 3.65625 | 4 | import numpy as np
"""
Class which defines a value,classification pair
"""
class Data:
def __init__(self, values, classification=None):
assert type(values) is list
self.values = values
self.classification = classification
def __str__(self):
return "Values: {}, Class: {}".forma... |
62a9bb7dd2e4f975819b93255d653186065d88b1 | Percygu/my_leetcode | /排序专题/堆排序/heap_sort.py | 2,522 | 3.796875 | 4 | '''
以小顶堆为例
0
1 2
3 4 5 6
7 8
'''
# 对数组里的第i个元素向下调整堆-----使堆为小顶堆
def heap_down(arr,size,i):
t = i
left,right = 2 * i +1, 2 * i +2 # 左右孩子的下标
if left < size and arr[left] < arr[t]: # 当前节点值比左孩子值大,t 变为做孩子下标 ,此时的t是左孩子和跟中的最小者
... |
1c42e473e5ad2f19ec8dc7a1b3fc8a77143481db | jackharv7/Python-2 | /PyParagraph/paragraph.py | 1,028 | 3.703125 | 4 | import re
import os
path_to_dir = os.path.dirname(os.path.abspath(__file__))
file_descriptor = os.path.join(path_to_dir, "paragraph2.txt")
sent_count = -1
letter_count = 0
count = 0
with open(file_descriptor) as inputfile:
text = inputfile.read()
for letters in text:
if not letters.isalpha():
... |
3f6e89e6379d8e22795a2593a94a46139e5dd0b9 | sam-kumar-sah/Leetcode-100- | /79s. Word_search.py | 1,430 | 3.953125 | 4 | //79. Word Search
'''
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent
cell, where "adjacent" cells are those horizontally or vertically
neighboring. The same letter cell may not be used more than once.
Example:
board =
[
['A','B',... |
38d2c3eba95e4a3cc4d626dad56710a01bdcdbd1 | ticotheps/practice_problems | /edabit/hard/remove_smallest/remove_smallest.py | 4,452 | 4.3125 | 4 | """
THE MUSEUM OF INCREDIBLY DULL THINGS
A museum wants to get rid of some exhibitions. Katya, the interior architect,
comes up with a plan to remove the most boring exhibitions. She gives them a
rating, and removes the one with the lowest rating. Just as she finishes rating
the exhibitions, she's called off to an imp... |
703d30f905866f41f09f8364b2415f64dc90c4da | calebperkins/algorithms | /algorithms/tries.py | 1,430 | 3.71875 | 4 | class TrieMap(object):
"""A map based on a prefix tree."""
def __init__(self):
self.chars = {}
self.value = None
def __contains__(self, key):
trie = self
for c in key:
if not c in trie.chars:
return False
trie = trie.chars[c]
... |
865a8712c325a49be0b61c568a1f9a339844adbf | xxxxgrace/COMP1531-19T3 | /Labs/lab08/19T3-cs1531-lab08/encapsulate.py | 1,056 | 4.15625 | 4 | # Author: @abara15 (GitHub)
# I added functions that get the name and birth year because we don't want to directly access self.name and self.birth_year.
# Also imported datetime to get the current year and find the correct age.
import datetime
class Student:
def __init__(self, firstName, lastName, birth_ye... |
898005b5a09860c2ee9f8dfa021620f80c8d66e5 | PanPapag/A-Complete-Python-Guide-For-Beginners | /Python_Basics/Programming_in_Python/update_variables.py | 208 | 4.09375 | 4 | x = 5 # initialize x
print(x)
x = x + 1 # update x
print(x)
x += 2 # increment x by 2 (same as x = x + 2)
print(x)
x -= 1 # decrement x by 1 (same as x = x - 13)
print(x)
|
f533326c5ccd902cc0ee60e1082384cc87e23834 | Risauce/Pre2015Code | /CSCI 127/Practicum Stuff/Practicum 1/william-roberts.py | 678 | 3.734375 | 4 | import statistics
theList = [1,2]
print(str(statistics.median(theList)))
print(str(statistics.median_low(theList)))
charList = ["You", "may", "say", "I'm", "a", "dreamer"]
def count_characters(theList):
count = 0
for i in theList:
for ch in i:
count +=1
return count
... |
25eb17bc02f6ef500d3418de6bdebeeed823d210 | NeilWangziyu/Leetcode_py | /permution.py | 718 | 3.78125 | 4 | def permute(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def swap(i, j, nums):
x = nums.copy()
tem = x[i]
x[i] = x[j]
x[j] = tem
return x
res = [nums]
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
... |
f4ac2a2339195fe99bc3dcd4ebfa01417638f51d | AdamZhouSE/pythonHomework | /Code/CodeRecords/2609/58585/318980.py | 162 | 3.703125 | 4 | a=int(input())
b=input()
c=input()
if a==3 and b=='6 2' and c=='1 2 1 3 4 2':
print(4)
print(10)
print(1)
else:
print(a)
print(b)
print(c) |
afd7c8c1d27f0b954c7f29812e2a6bca563bd3a0 | ecedavis/CodingChallenges | /src/day18.py | 484 | 3.875 | 4 | from collections import deque
class Solution:
# Write your code here
def __init__(self):
self.q=deque()
self.s=[]
def pushCharacter(self, ch):
#stack
self.s.append(ch)
def enqueueCharacter(self, ch):
#queue
self.q.append(ch)
... |
1bdc7697c49876c818fb384f0995e86fd91d2b0b | udhayprakash/PythonMaterial | /python3/11_File_Operations/04_zipping_files/b_tar_files/a_writing_tar_files.py | 651 | 3.703125 | 4 | """
Purpose: Working with tar files
"""
import os
import tarfile
os.makedirs("files", exist_ok=True)
os.chdir("files")
# creating files
open("fileOne.txt", "w").write("This is first line")
open("fileTwo.txt", "w").write("This is second line")
open("fileThree.txt", "w").write("This is third line")
# Creating new ar... |
99bf7f8a9843c586fb247feb827a3937f413fa34 | Boot-Camp-Coding-Test/Tips | /[노태윤]/Python Tips/Counter.py | 862 | 3.71875 | 4 | # Counter
from collections import Counter
# element의 갯수를 dictionary 형태로 반환
a = [1,1,2,3,2,1,2,3,4,5,2,3,3]
b = [4,5,3,1,2,3,2,4,5,3,1,6,1]
a = Counter(a)
b = Counter(b)
print(a) # Counter({2: 4, 3: 4, 1: 3, 4: 1, 5: 1})
print(b) # Counter({3: 3, 1: 3, 4: 2, 5: 2, 2: 2, 6: 1})
# dictionary 형태이므로 python set operati... |
06f2c277588b436488ed92345f58e82ddf15d1bd | erjan/coding_exercises | /itresume/Разница между произведением и суммой цифр.py | 655 | 3.890625 | 4 |
'''
Дано целое число n. Найти разницу
между произведение и суммой цифр в записи числа n.
'''
class Answer:
def subtractProductAndSum(self, n):
m = list(str(n))
m = [int(i) for i in m]
t = 1
for i in m:
t = t*i
s = sum(m)
return... |
e7a51034ec0edcfd1ae37c07b8bef855c5694d5f | CircularWorld/Python_exercise | /month_01/day_06/homework_06/homework_06.py | 567 | 3.9375 | 4 | '''
6. 将列表中整数的十位不是3和7和8的数字存入另外一个列表
list03 = [135, 63, 227, 675, 470, 733, 3127]
结果:[63, 227, 3127]
提示:将数字转换为字符串进行处理
'''
list03 = [135, 63, 227, 675, 470, 733, 3127]
# for i in range(len(list03)):
# list03[i] = str(list03[i])
list03 = [str(list03[i]) for i in range(len(list03))]
print(list03)
list_result = ... |
ccba60662c36d5bb9ab97fc048412b75e213afa6 | ATrui/Projects | /Arithmetic_arranger/arithmetic_arranger.py | 1,203 | 3.734375 | 4 | def arithmetic_arranger(problems, solution=False):
if len(problems) > 5:
return "Error: Too many problems."
operators = ["+", "-"]
line_1 = ""
line_2 = ""
line_3 = ""
line_4 = ""
for i, problem in enumerate(problems):
n1, op, n2 = problem.split(" ")
# Check for errors
if op not in oper... |
a4907c94a7280d1a6898aa6afac8e080c5300dc6 | jinurajan/Datastructures | /LeetCode/stack_and_queue/perfect_squares.py | 1,019 | 3.734375 | 4 | """
Perfect Squares
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
Example 1... |
a78afc2f159b596f1e0e17cc27008e11751319e7 | ScrappyCocco/TheColonistsItalian | /validator/main.py | 574 | 3.703125 | 4 | #!/usr/bin/env python3
import sys
from CSVValidator import CSVValidator
print("Starting script...")
if len(sys.argv) > 2:
print("Passed more than 1 arguments! You must pass only the filename! "
"(if necessary pass it as \"filename\" with quotes")
elif len(sys.argv) == 2:
if sys.argv[1].endswith(".... |
2942eac4521b7c77cae4afe56647faa44531efb3 | SilentWraith101/course-work | /lesson 03/capitalize points and name.py | 1,160 | 3.828125 | 4 | #input
firstname = str(input("Enter your first name: "))
lastname = str(input("Enter your last name: "))
position = str(input("Enter the position you finished in words: "))
points = 0
prizemoney = 0
#checking thier position and giving them the correct amount of points
if position.lower() == 'first':
print("you have... |
54c836cd916772ce56f7332d5409be1c646974b4 | foshay/cs325 | /hw1/qsort.py | 670 | 3.765625 | 4 | def sort(a):
if a == []:
return []
else:
pivot = a[0]
left = [x for x in a if x < pivot]
right = [x for x in a[1:] if x >= pivot]
return [sort(left)] + [pivot] + [sort(right)]
def sorted(t):
if t == []:
return []
else:
return sorted(t[0]) + [t[1]] ... |
7db7db628f827b981386467b07d320b68977f555 | janishsiroya/Janish_Basics_Python | /src/google-python-exercises/8.jpg/datastruc.py | 1,604 | 3.875 | 4 | #list*********************************************************************
shoplist = ['apple','banana','flower','carrot']
shop = ['ha']
print shop
print shoplist
print len(shoplist)
shoplist.append('berry')
print shoplist
print 'the items are'
for i in shoplist:
print i
a = shoplist[0]
del shoplist[0]
print shopli... |
791626b2f47a9663025ff40b2667cd262864c462 | VSerpak/AIND | /AIND-Sudoku-reviewed/Tests/solution_1.py | 8,352 | 3.6875 | 4 |
# coding: utf-8
# In[1]:
grid3 = '9.1....8.8.5.7..4.2.4....6...7......5..............83.3..6......9................'
# In[2]:
rows = 'ABCDEFGHI'
cols = '123456789'
# In[3]:
def cross(a, b):
return [s+t for s in a for t in b]
# In[4]:
boxes = cross(rows, cols)
# In[5]:
assignments = []
# In[6]:
def... |
633bbc1ef431a5539df27f486fa11c6291930898 | 1505069266/python- | /组的概念和定义/list.py | 802 | 3.8125 | 4 | arr = [1, 2, 3, 4, 5, 6]
print(type(arr))
arr.append('ddd')
print(arr)
arr1 = [[1, 2], [3, 4], 5]
print(arr1)
print(arr1[0][1])
newMoon = ['新月打击', '苍白之瀑', '月之降临', '月神冲刺']
print(newMoon[0])
print(newMoon[0:])
hero = newMoon + ['点燃', '虚弱']
print(hero)
# 元组
yuan = (1, 2, 3, 4, 5)
print(yuan[2])
print(yuan + ... |
680e15e98660f23973a2366c4ae0c44e19d46a3a | Lukhanyo17/Intro_to_python | /Week3/column.py | 132 | 4.09375 | 4 | um = int(input("Enter a number: "))
if (num > -6) and (num < 2) :
for i in range(num, num + 41, 7):
print("%2d" % i)
|
0a04a1e5c3c631f6d0bc5d15c45eae9279c175fa | joswha/interviewpreparation | /leetcode/7.py | 330 | 3.734375 | 4 | def reverse(x):
"""
:type x: int
:rtype: int
"""
if x < 0:
x = str(x)
x = x[1:]
x = -1 * int(x[::-1])
if x < -2 ** 31:
return 0
return x
x = str(x)
x = int(x[::-1])
if x >= 2 ** 31:
return 0
return x
a = 1534236469
print(r... |
4df7d3458420e646c340adb0a60f29fdfbb6be95 | fernado1981/python_ | /POO/List_set_dic/List_set_dict.py | 767 | 4.125 | 4 | tuple = {1, 2, 3, 4, 5, 6, 7, 8, 9}
numero = ["uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve"]
print(tuple)
# conversion de set tuple a lista tuple
tuple = list(tuple)
# modificar el array tuple
count = 1
for i in range(len(tuple)):
if tuple[i] == count:
tuple[i] = numero[i]
... |
f884be3644e1e7cd8001b09d5b872ee11515b386 | ash2osh/Algorithmic-Toolbox | /week3_greedy_algorithms/2_maximum_value_of_the_loot/fractional_knapsack.py | 1,241 | 3.703125 | 4 | def get_optimal_value(capacity, weights, values):
result = 0.
remainingCapacity = capacity
prices = []
for i in range(0, len(weights)):
prices.append(values[i] / weights[i])
for _ in range(0, len(weights)):
# get max values and weights
maxPrice = max(prices)
maxIndex... |
b93272d89c441aac1ccca69e4dd82ca1c1481785 | r3sult/My-AI-Experiment | /sample/scratch/kmeans-3.py | 5,047 | 3.515625 | 4 | """
created by : ridwanbejo
deskripsi : contoh implementasi algoritma K-Means untuk clustering data
"""
# library yang dibutuhkan untuk clustering k-means
import math
import collections
import copy
import numpy as np
import matplotlib.pyplot as plt
# fungsi - fungsi yang terlibat dalam perhitungan clustering k-mea... |
29465b8a5795d088e2c2ad1982917d18703b2ee6 | Aasthaengg/IBMdataset | /Python_codes/p02546/s625626401.py | 361 | 3.5 | 4 | #!/usr/bin/env python3
import sys
import collections as cl
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
target = input()
if target[-1] == "s":
print(target+"es")
... |
2cee21ad7586d43a85c06f20ae9d3ee6566afa94 | minsuk-heo/coding_interview_2021 | /Arrays_and_Strings/is_palindrome.py | 440 | 4.28125 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward. For example, 121 is palindrome while 123 is not.
"""
def isPalindrome(x: int) -> bool:
x_str = str(x)
if len(x_str) == 1:
return True
if x_str[0] == "-":
... |
bde2361c9a9861f15e92b7f1895849f0b047a817 | cheung1/python | /Class_Dog.py | 430 | 4.03125 | 4 |
#class className:
# methods
#define a class
#Class Dog
class Dog:
#defina a method
#dog is barking
def bark(self):
print 'Wang...Wang..Wang...'
def run(self):
print 'dog is running '
#create a dog
doggie = Dog()
#invoke a methon of Dog
doggie.bark()
doggie.run()
#add proper... |
d8a209acfc51284ec30e8025aa43edfb2048f721 | marb61a/Course-Notes | /Artificial Intellingence/Python/Notebooks/PyImageSearch University/Deep Learning 105/minivggnet/minivggnet_cifar10.py | 5,492 | 3.625 | 4 | # USAGE
# python minivggnet_cifar10.py --output output/cifar10_minivggnet_with_bn.png
# The text version of the tutorial is available at the following address
# https://www.pyimagesearch.com/2021/05/22/minivggnet-going-deeper-with-cnns/
# VGGNet was first introduced in a 2014 paper which can be found the following ad... |
f60aa0ba9586451a7beeabc096211e196784834e | udhayprakash/PythonMaterial | /python3/14_Code_Quality/04_unit_tests/b_using_unittest_module/e_Calculator/tests/test_addition.py | 880 | 3.796875 | 4 | """
Purpose: Testing addition functionality in calculator
"""
import sys
import unittest
# import os
# print(os.listdir('..'))
sys.path.insert(0, "..")
from calculator import addition
# for each_path in sys.path:
# print(each_path)
class TestSuiteAddition(unittest.TestCase):
def test01(self):
self.... |
4c493528f683bc0188dc1ec2ce2e7a0e0eee99de | Bjarturblaer/M | /yfirferð/yfirferð.py | 2,299 | 4.15625 | 4 | # Breytur
# int float str type print + * / // % input
# x = 2
# x += 2 # x+2
# x *= 2 # x = x*2
# name = input("Your name: ")
# print("Your name is "+name)
# # Boolean
# # if true/false ops and& or|
#x = True
#y = False
#if x:
# print("Yes")
#elif x:
# print("Yes 2")
#else:
# print("No")
# == > < >= <=... |
c42103f846cb3f58392731c8cf94f2155545605a | ErikVasquez/DataStructure | /U4/RadixSort.py | 1,279 | 3.515625 | 4 | #Delgado Vasquez Erik No.Control 17211515
from math import log10
from random import randint
import random
def listaAleatorios(n):
global alist
alist = [0] * n
for i in range(n):
alist[i] = random.randint(0, 1000)
return alist
def get_digit(number, base, pos):
return (number // base... |
0e7528eb69b8264d2fa29960b00057958b5bcde1 | coderlubo/Web_base | /01_多任务编程/01_多进程(重点).py | 1,435 | 3.609375 | 4 | # 李禄波
# 2021/2/4 下午4:34
import time
import multiprocessing
import os
def dance():
# 获取子进程id
print("子进程 my_dance id:", os.getpid())
# 获取父进程id
print("dance父进程:", os.getppid())
# 获取进程名
print("dance的进程名是:", multiprocessing.current_process())
for i in range(5):
time.sleep(1)
p... |
31b33e242eba231a1fe570511f4bb2c133659519 | prabhupant/python-ds | /data_structures/array/min_product.py | 1,118 | 4.125 | 4 | # Use these facts -
# If there are even number of negative numbers and no zeros,
# then the min product is the product of all except the max
# negative value
# If there are odd number of negative numbers and no zeros,
# the result is simply the product of all
# If there is a zero and all other are positive, then th... |
f73581df48bcdc074777d9c4291586ea518b3e7a | Dylan-Lebedin/Computer-Science-1 | /Labs/mobiles.py | 9,597 | 3.984375 | 4 | """
file: mobiles.py
language: python3
author: CS.RIT.EDU
author: Dylan Lebedin
description: Build mobiles using a tree data structure.
date: 10/2015, 11/2019
purpose: starter code for the tree mobiles lab
"""
############################################################
# ... |
2d8a9a5b2f4028dc196001d2cc6a87978592be34 | wcl19940217/python-projects | /head_sort.py | 1,608 | 3.765625 | 4 | import math
def print_tree(array):
index = 1
depth = math.ceil(math.log2(len(array)))
print(depth)
sep = ' '
for i in range(depth):
offset = 2 ** i
print(sep * (2**(depth-i-1)-1), end='')
line = array[index:index+offset]
for j, x in enumerate(line):
prin... |
61643131644eeece0e9b753ad224ea6f3c4105ab | Kushal1412/Competitive-Programming-and-Interview-Prep | /LeetCode/Python/0700_Search_in_a_Binary_Search_Tree_#1.py | 636 | 3.84375 | 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 searchBST(self, root: TreeNode, target: int) -> TreeNode:
if not root:
return
... |
983680a21e9980539d0e8674b93df4e2cd39c004 | gnurenga/python-learn | /unittest/add_ing_v2.py | 1,589 | 4.5 | 4 | """This is a program to add verb+ing form.
1. For word end with `e` drop `e`
2. For word ends in consonent-vowel-consonent
double the last letter
3. For other words just add `ing` at the end
The issue found in the previous version is fixed
in this version. In order to understand Unittest
this code is written
"""
d... |
9781a2621cd2920e2d2a4a64c517f768608221a4 | MatthewBell1/RandomCodes | /Email Slicer.py | 338 | 3.984375 | 4 | # Email splicer
ind = 0
email = input("")
for i in range(0,len(email)):
ind += 1
if email[i] == "@":
print("Your username is", email[0:ind-1], "and the domain is", email[ind:len(email)])
break
elif ind == len(email):
print("Invalid email address")
break
else:
... |
c492b964ceac09e356483d6bf0c70ce7c198f2e6 | chrisleo34/FSDI-111-Class-1-Assignment-1 | /lab 1/calc.py | 1,360 | 3.625 | 4 | """
Author: Christian Astarita
Title: Symple Python
"""
# global vars
# functions
def print_separator():
print('_' * 30)
def print_menu():
print_separator()
print('Python Calc')
print_separator()
print("[1] Sum")
print("[2] Subtract")
print("[3] Multiply")
... |
0d6a2edb536e7ac5bcc40d273f4ecc807511adad | zachleong/sddchallenges | /semiprime.py | 2,559 | 4.5 | 4 | #run with python 3
from primepriv import isprime #importing my isprime function from another file
import math
#Testing if input is valid or not
while True:
try:
lower = int(input("lower range: "))
upper = int(input("upper range: "))
#if the user puts in valid numbers
if upper > 0 and lower > 0 and upper > ... |
dc1a668a8f0c7a3f882c97f6913f2dd36a49c436 | smanurung/dcal | /Event.py | 661 | 3.5 | 4 | class Event:
def __init__(self,name,place,start,end,desc):
self.name = name
self.place = place
self.start = start
self.end = end
self.desc = desc
def getName(self):
return self.name
def setName(self,newname):
self.name = newname
def getPlace(self):
return self.place
def getStart(self):
return... |
07d6d3873250b66c0d36e96ac46edc18ac285240 | 233-wang-233/python | /day15/15day_7.py | 1,682 | 4 | 4 | from abc import ABCMeta,abstractmethod
class Employee(metaclass=ABCMeta):
'''员工(抽象类)'''
def __init__(self,name):
self.name=name
@abstractmethod
def get_salary(self):
'''结算月薪(抽象方法)'''
pass
class Manger(Employee):
'''部门经理'''
def get_salary(self):
return ... |
15d1858b6174d37aee723b8b6abd9acf237f7f71 | patrickspencer/instacart | /src/generate_full_orders.py | 1,710 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
generate_full_orders.py
~~~~~~~~~~~~~~~~~~~~~~~
The `orders` table does not include information about the individual products
that go into each order. `orders` records the relationship between a user and
the order.
The tables `orders_prior` and `orders_train` relate the individual product... |
d7cf96036bf83ecba6f37927bd76ba2ed9d9c184 | mareced/predavanje_9 | /if_else.py | 297 | 3.625 | 4 | ime = "Franci"
if ime == "Miha":
print("Pozdravljeni, Miha!")
elif ime == "Franci":
print("Pozdravljen, Franci!")
else:
print("Pozdravljen, neznanec")
starost = 30
if starost > 25:
print("star si več kot 25")
elif starost >=18:
print("Odrasel si")
else:
print("Mlad si") |
296c64a89468abd68a4d705b5ec73f12e177c1bf | vlschilling/python-data-structures | /avg2.py | 211 | 4.09375 | 4 | numlist = list()
while (True):
usrinp = raw_input("Enter a number: ")
if usrinp == "done" : break
value = float(usrinp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print "Average:", average
|
fa6d29893080689c31e394963213b7c65a0409d4 | marko37/Fisica-Computacional | /cellular_automaton.py | 3,036 | 3.953125 | 4 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
import sys, hashlib
def dec_to_any_base(n, base, width=0):
"""Convert from decimal to any base and return an array.
width : The minimum number of elements in the returned array,
with zero-padding if necessary.
"... |
c65f358380f0189717032666991f396bde4c06ec | rakeshsukla53/interview-preparation | /Rakesh/matrix_arithmetic/rotate in place algorithm.py | 515 | 3.765625 | 4 |
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
matrix[::] = zip(*matrix[::-1])
class Solution:
def rotate(self, A):
n = len(A)
for i in range(n/... |
e3adaf17f1f3a6b440e392e727f653a0398b623e | palak-ag/CS-Algorithms-and-Programs-that-every-programmer-should-know | /BinarytoDecimal.py | 183 | 4.09375 | 4 | num=int(input("enter the binary number"))
decimal=0
i=0
while(num!=0):
r=num%10
decimal=decimal+r*(pow(2,i))
num=num//10
i=i+1
print("the decimal number is:",decimal)
|
5ebf849519abc4b919e27560586d6787cc5819be | Lisandro79/DataScience | /Python/Arrays/IncrementArbitraryPrecisionInt_5-2.py | 1,499 | 3.9375 | 4 | import numpy as np
# takes as input an array representing a non-negative integer
# E.g.: <1, 2, 9>
# returns an array representing that integer + 1
# E.g. <1, 3, 0>
# Brute force approach:
# - loop through the array, transform each element into a string and concatenate each char
# - transform the string into an int
... |
2fe9ce908c4ad01543016767f06f958bfad8c5f4 | roger-pan/python-labs | /03_more_datatypes/2_lists/03_06_product_largest.py | 1,056 | 4.28125 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Find the largest number in the list.
Print the results.
CHALLENGE: Calculate the product of all of the numbers in the list.
(you will need to use "looping" - a concept common to list operations
that we haven't looked at yet. See if you can figure it ou... |
191ab119c5c5f5e5dc57a289a5287bfca27a026e | dwhickox/NCHS-Programming-1-Python-Programs | /Chap 4/NamePrgmFixed.py | 399 | 4.03125 | 4 | #David Hickox
#Mar 11 17
#Name slice prgm
#variables
# name = my name
print("Welcome to the name program")
name = "David William Hickox"
if "z" in name:
print("You have a unique name")
else:
print('You do not have a z in your name')
print("Intials =\t"+name[0]+name[6]+name[14])
print("First name:\t"+name[:5... |
639f45413a682919f66028c789751a71427d511a | MoisesFlores-1/HIP_HW | /REGISTER.py | 1,564 | 4.46875 | 4 | sales_tax = .95
#sales tax is defined here and can be changed
price = int(input ("Enter Price: ") )
result = 0
#The user inputs the price of the item here.
while (price > 0) :
#As long as the price is greater than 0,
# then the program will loop until 0 is the input from the user
price = float(input("Enter Pric... |
bd58595a5dd0ff91851693e55e072e2522ed64fc | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4000/codes/1636_869.py | 293 | 3.625 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Use as mensagens de erro para corrigir seu código.
valor = float(input("Qual o valor: "))
if (valor>=200):
preco = valor - (5/100) * valor
else:
preco = valor
print(round(preco, 2)) |
513a2392be1b2e8a3a9638440f844ddee740bddd | shadd-anderson/Exercism-Exercises | /python/anagram/anagram.py | 346 | 3.875 | 4 | def find_anagrams(word, candidates):
anagrams = []
word = word.lower()
for candidate in candidates:
lower_candidate = candidate.lower()
if word == lower_candidate:
continue
else:
if sorted(word) == sorted(lower_candidate):
anagrams.append(candi... |
bcd2b9c5004fccf9c92b62ea86b6c3a9f320ab45 | ninja-programming/python-basic-series | /writing_file_examples.py | 775 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 4 10:39:53 2021
@author: mjach
"""
'''
how to write in a file with write() and writelines() function
'''
# with open('writing_my_file.txt', 'w') as my_writing_file:
# #writing_file = my_writing_file.writelines('we are learning python basic.')
# writing_file = my_... |
3b4a1e6058e0eedc97517e9dce35522854bb1323 | weijuwei/python_new | /排序算法/bubbleSort.py | 382 | 4.15625 | 4 | # 冒泡排序
def bubble_sort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-1,i,-1):
if arr[j] < arr[j-1]:
arr[j],arr[j-1] = arr[j-1],arr[j]
return arr
if __name__ == "__main__":
arr = [55, 23, 53, 36, 56, 10, 28, 100, 59, 98, 78]
print("排序前:",arr)
arr1 = b... |
bbc04b31245b9834bc4276b54b3cf1131b45eef8 | mcardia98/2019-Network-Security-Internship-Scripts | /log_parser.py | 5,122 | 3.578125 | 4 | '''
Sensitive information replaced with XXXX
Takes a .csv as input and outputs a .csv with information that the network security team can
use to determine health of various elements
'''
import csv
from datetime import datetime
#for formatting purposes to make the output csv look pretty
def add_rows(num_rows,... |
bd3d0a51ea1128fd564e2d50ec9865791303ff3c | thcborges/estrutura-de-dados-com-python3 | /Algoritmos_e_Estrutura_de_Dados/deque_collections.py | 311 | 3.984375 | 4 | from collections import deque
def show(d):
for i in d:
print(i, end=' ')
print()
d = deque()
d.append(1) # adiciona do lado direito
d.appendleft(2) # adiciona do lado esquerdo
d.append(3)
d.appendleft(4)
show(d)
print(d.pop())
show(d)
print(d.popleft())
show(d)
d.remove(1)
show(d)
|
22a2bcc93cd372798d25252aa09e2da75d198adc | Deeachain/Nowcoder-Leetcode | /剑指/字符流中第一个不重复的字符.py | 918 | 4.09375 | 4 | # -*- coding:utf-8 -*-
"""
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,
第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
"""
class Solution:
# 返回对应char
def __init__(self):
self.s = ''
def FirstAppearingOnce(self):
# write code here
result = []
for i in self.s... |
55c3452133a3d517f5fda64b1950c27da3dfbd94 | tBuLi/symfit | /examples/global_fitting.py | 1,882 | 3.609375 | 4 | """
A minimal example of global fitting in symfit.
Two datasets are first generated from the same function.
.. math::
f(x) = a * x^2 + b * x + y_0
All dataset will share the parameter :math:`y_0`, which measures the background,
but :math:`a` and :math:`b` will be unique for each. Additionally, dataset 2
will con... |
dfdbeff2c17f0cf239fb3ba8fe38aad7b0a2d23f | jmeza44/SevenAndHalf | /Principal.py | 501 | 3.578125 | 4 | # Clase Main de ejecución
from Recursos import iniciar_juego, mostrar_menu_princ, recibir_eleccion_num
if __name__ == "__main__":
while True: # Ciclo de ejecución del algoritmo (Solo termina al seleccionar la opción 3 en el menú principal)
mostrar_menu_princ()
eleccion = recibir_eleccion_num(3)
... |
f44c0f080765fc7b21ae6d5b344cdd3d78f59ece | DarkstarIV/Mini-Python-Projects | /Time Telling/main.py | 220 | 4.03125 | 4 | import datetime
e = datetime.datetime.now()
print ("Current date and time = %s" % e)
print ("Today's date: = %s/%s/%s" % (e.month, e.day, e.year))
print ("The time is now: = %s:%s:%s" % (e.hour, e.minute, e.second)) |
d7757cf6382fa7c5f42a385258b62e138b9e3e7a | neilshah101/daily-practise | /weekly_journal/week_2/day4/json activity /activity1-writning-to-a-json-file.py | 204 | 3.75 | 4 | import json
name = input("enter the name : ")
age = input("enter the age: ")
with open("person.json" ,"w") as file_object:
person = {"name": name , "age" : age}
json.dump(person,file_object)
|
f8e630194a54eeeee7cb1508b01d9de5c1e443dd | Alpha-W0lf/w3resourcePracticeProblems-Python | /Basic Part 1 Exercises/basic part 1 exercise 17-1.py | 569 | 4.15625 | 4 | # Write a Python program to test whether a number is within 100 of 1000 or 2000.
given = int(input("Enter a number: "))
range = 100
number1 = 1000
number2 = 2000
lowerBound1 = number1 - range
upperBound1 = number1 + range
lowerBound2 = number2 - range
upperBound2 = number2 + range
if given >= lowerBound1 and given... |
44eb7cd0e4bfcca8b85da7033a9547e14702a5f6 | KobiBeef/learnpythonthehardway | /ex39_test.py | 1,751 | 4.25 | 4 | import hashmap
# creata a mapping of state to abbbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'New York', 'NY')
hashmap.set(states, 'Michigan', 'MI')
# create a basic set of states and some cities... |
d247392051fbfc30e84eab8f65b9ee0e4c19c212 | stefansilverio/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 538 | 4.1875 | 4 | #!/usr/bin/python3
"""
This function prints out text
Returns:
text to stdout
"""
def text_indentation(text):
"""prints text to stdout
Returns text
"""
sym_list = ['.', ':', '?', ]
string = ""
if isinstance(text, str) is not True:
raise TypeError("text must be a string")
for i in te... |
f05c7da6e54cd7315cf0ca20618f3405b4051212 | devscheffer/SenacRS-Algoritmos-Programacao-1 | /01 - 2019-03-28 - Estacionamento lista/Task - 01.py | 6,865 | 3.71875 | 4 | # Trabalho - Estacionament
# Autor: Gerson Scheffer
menu = '''
=================
Menu
=================
1- Registrar entrada
2- Registrar saida e pagamento
3- Relatorio
4- Mapa
Escolha: '''
#List
list_lp = [] #license plate dos carros
list_box_car = [] #Box usado pelo carro
list_hin = [] #Horario ... |
42eb3c018504a8478d33b37cd40d4af0d664029e | artemschabanov/domash | /task_3_3.py | 117 | 3.6875 | 4 | x = input ("ввведите строку")
f =len(x)
if(f>10):
print(x[0:-1],"!!!")
elif(f<10):
print(x[1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.