blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
9772f3f6b0cf72deb0d46838263bbab91cb52ea4 | TypAnna/GruProgDD1331 | /Övning2/uppg4CheckDuplicates.py | 672 | 4.09375 | 4 | #Checks if a list contains duplicates.
def check_for_duplicates(aList):
aList.sort() #sorts the list (and changes it!)
for i in range(len(aList) - 1):
if aList[i] == aList[i+1]:
print("duplicate found!")
break #exits the for-loop
#--------- end of if-statement --------
... |
9f560389591ee629b0f5aac7447e530c72414d66 | TypAnna/GruProgDD1331 | /Övning3/uppg3Taylor.py | 927 | 4.09375 | 4 | import math
#Returns an approximatio of sin(x) using Taylor serier
def approxSin(x):
sign = 1
term = x
div = 1
total = x
limit = 1e-10
#continue adding terms as long as ther are big enough
while abs(term) > limit:
sign *= -1 #the sign alternates for each term
term = term*x*x... |
516f8bc5ddd1e0ff76756c4b0f57f8d09e40d44b | TypAnna/GruProgDD1331 | /Övning3/metodExempel.py | 489 | 3.875 | 4 | # name = "Abba" #these constants would be global
# age = 72
def sayHi(name, x):
age = x + 10
print("Hi " + name +", in 10 years you will be", age, "years old." )
#this x, name, and age only lives inside this function!
def main():
#all of these three work!
sayHi("Steffe", 60)
aName = "Annie"
... |
220d030db8e813ff831d77f042c2813d9af83f77 | TypAnna/GruProgDD1331 | /Övning4/uppg4StigandeList.py | 565 | 4.21875 | 4 | #recursive method that checks if a list is in increasing order
def isListIncreasing(aList):
if len(aList) == 1: #base case
#a list with one element is always in increasing order
return True
#check if the first two elements of the list are in order
isFirstTwoInOrder = aList[0] <= aList[1]
... |
6b887b63ceb0645b175068f6395142c64e4575ba | Retchut/MNUM-2020-2021 | /exams/2018/5.py | 497 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 16:53:52 2021
@author: Retch
"""
import math
a = 2 #miro
#a = 1 #meu
def f(x):
return (x-a)**2 + x**4
def aurea(x1,x2):
B = (math.sqrt(5)-1)/2
A = B**2
while(abs(x2-x1) > 0.000001):
x3 = x1 + A*(x2-x1)
x4 = x1 + B... |
b94fef21e5deb24431707d1cfed200d824578029 | njain512/mileStone_02 | /NehaJain_Milestone_02.py | 1,659 | 4.125 | 4 | #!/bin/python3
import random
from tkinter import *
root = Tk()
root.title("Password Generator")
print('Welcome to Password Generator')
print('Note: More than 8 characters for password is stronger!')
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*().,?0123456789'
fullname = Entry(root, width=4... |
afae92c197fc810b4837251d1a31cc8fdfa8dabf | CalvinWu4/CSCI-141 | /Lab11/vlc.py | 2,989 | 3.546875 | 4 | """
file: vlc.py
description: main program to generate variable length code output
language: python3
author: Calvin Wu, cwx7054@rit.edu
date: 11/23/2015
"""
from rit_lib import *
from array_heap import *
from math import *
class symbol(struct):
_slots = ((str,'name'),(int,'freq'),(str,'codeword'))
class node(str... |
7f9a1f729b68457169a66224c444dfcc702c6105 | CalvinWu4/CSCI-141 | /HW8/slList.py | 8,295 | 3.84375 | 4 | """
File: slList.py
Purpose: rit_object-based single-linked list for CS141 LECTURE.
Author: ben k steele <bks@cs.rit.edu>
Author: sean strout <sps@cs.rit.edu>
Language: Python 3
Description: Implementation of a single-linked list data structure.
"""
from slNode import *
from rit_lib import *
from testLinkSort impo... |
6f6ed57c3771115123dd38c6df3dd63243f501e5 | CalvinWu4/CSCI-141 | /new.py | 645 | 3.875 | 4 | # import turtle
#
# def drawSquares(length,depth):
# turtle.speed(10)
# if depth<=0:
# return
# count=4
# while count>0:
# turtle.forward(length)
# turtle.left(90)
# drawSquares(length/2,depth-1)
# turtle.right(180)
# count-=1
#
# drawSquares(100,3
# ... |
7cd9183ae4ae528a612d08c7e11c808efbaf4aaa | CalvinWu4/CSCI-141 | /Lab4/tiny_turtle.py | 3,087 | 3.984375 | 4 | """Calvin Wu"""
from turtle import *
####################################################################
# The "tt" names are a specified public interface.
# STUDENT: complete the definitions for the stubbed functions.
####################################################################
def ttEvaluateReverse(progra... |
4736850ed92082917f3d78bdc3f134dcc7caaf5a | dixoncox/6.00.1x | /9.14/ps1/PS1.1.py | 711 | 4.125 | 4 | # Counting Vowels (10 points possible)
# Assume s is a string of lower case characters.
# Write a program that counts up the number of vowels contained in the string s.
# Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.
# For example, if s = 'azcbobobegghakl', your program should print:
# Number of vowels: 5
#
# LOGIC:... |
92c2f9a52fd6b85796269f962fcaced27591686d | dixoncox/6.00.1x | /1.15/ps3.2.py | 542 | 4 | 4 | def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
result = True
for i in sec... |
e5ba8950ad749f293448959ddbd4066521bb82a3 | dixoncox/6.00.1x | /1.15/ps1.3.py | 407 | 4.0625 | 4 | #s = 'azcbobobegghakl'
s = 'abcbcd'
#Longest substring in alphabetical order is: beggh
currentString = s[0]
longestString = s[0]
for i in range(1,len(s)):
if s[i] >= s[i-1]:
currentString += s[i]
else:
currentString = s[i]
if len(currentString) > len(longestString):
longestString = c... |
3f88c2daaa6e103ed006358ab90ba782e3ddaa84 | tqa236/discrete-optimization | /knapsack/solver_test.py | 2,873 | 3.609375 | 4 | import unittest
from solver import (knapsack_solver, maximum_value, parse_input,
parse_or_tools_input)
class Test(unittest.TestCase):
def test_homemade(self):
file_location = "data/ks_4_0"
with open(file_location, "r") as input_data_file:
input_data = input_data_fi... |
8ae1d9b0f99162c68aba9000b961bb5e82273375 | campbel94/python-challenge | /PyBank/PyBank_main.py | 2,745 | 3.96875 | 4 | # Main Bank
# Dependant Modules
import csv
import os
# Set path for file
budget_path = os.path.join('Resources', 'budget_data.csv')
# Open the csv
with open(budget_path) as budget_file:
budget_reader = csv.reader(budget_file, delimiter=",")
# Read the header row first (skip this part if there is no header)
... |
1087c74d462353e4234a37f1a9d3744b58bd3a53 | erikkrasner/math-hacks | /squarefree.py | 1,130 | 3.875 | 4 | #!/usr/bin/env python
import sys
# Appx. 1-hour hack that generates squarefree words of arbitrary length,
# inspired by a late-night Wikipedia crawl that led me to
# http://en.wikipedia.org/wiki/Squarefree_word
# For words of length n the runtime is O(n log n).
# the infinite squarefree word is generated by taking th... |
8eb1a9c1faeb8976e155da52f2b3704c223e4893 | gvassallo/LeetCode | /143-ReorderList.py | 788 | 3.765625 | 4 | # Given a singly linked list L: L0→L1→…→Ln-1→Ln,
# reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
#
# You may not modify the values in the list's nodes, only nodes itself may be changed.
class Solution:
def reorderList(self, head: ListNode) -> None:
if not head or not head.next:
return head
sel... |
75b9bd79966385f7e5e562a94290db9151c55c94 | gvassallo/LeetCode | /088-MergeSortedArray.py | 777 | 4.03125 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
... |
3d9f57fc30d96924b091608f455e28469ec0d2d3 | gvassallo/LeetCode | /033-SearchInRotatedArray.py | 1,074 | 3.6875 | 4 | # 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).
# You are given a target value to search. If found in the array return its index,
# otherwise return -1.
class Solution:
def search(self, nums: List[int], target: int... |
5f7672776ffd746c8648772fd43f19d7e5447c7a | gvassallo/LeetCode | /034-SearchRange.py | 978 | 3.9375 | 4 | # Given an array of integers sorted in ascending order, find the starting and ending
# position of a given target value.
# Your algorithm's runtime complexity must be in the order of O(log n).
# If the target is not found in the array, return [-1, -1].
# For example, Given [5, 7, 7, 8, 8, 10] and target value 8, retu... |
f439947eca9172ad3823fed5194346a4764de636 | gvassallo/LeetCode | /056-MergeIntervals.py | 1,035 | 3.953125 | 4 | # Given a collection of intervals, merge all overlapping intervals.
#
# For example,
# Given [1,3],[2,6],[8,10],[15,18],
# return [1,6],[8,10],[15,18]
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __repr__(self):
return '['+ str(self.start) + '... |
e5830b143e5a3ad7005d2fc129d25d76ad87c823 | gvassallo/LeetCode | /438-FindAllAnagramsInAString.py | 861 | 3.625 | 4 | # Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
#
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
#
# The order of output does not matter.
class Solution:
def findAnagrams(self, s: str, p: str)... |
acef7f9c4fc4b8c3e61d64371f235d9f4219409e | gvassallo/LeetCode | /404-SumOfLeftLeaves.py | 583 | 3.78125 | 4 | # Find the sum of all left leaves in a given binary tree.
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
if root is None:
return 0
return self.helper(root, False)
def helper(self, root, is_left):
if root.left is None and root.right is None:
if... |
53fcafd4f3f770178f7dbcea372f7d0d8ee81040 | gvassallo/LeetCode | /206-ReverseLinkedList.py | 451 | 3.96875 | 4 | # Reverse a singly linked list.
#
# Example:
#
# Input: 1->2->3->4->5->NULL
# Output: 5->4->3->2->1->NULL
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return head
nex = head.next
curr = head
head.next = None
while nex is n... |
f2545d3c55d0dcc193f431d995b0eb374b9bb47e | ajunior/cp | /g4m3/p0002.py | 326 | 3.5625 | 4 | producers, expected = map(int, input().split())
collected = 0
for i in range(producers):
collected += int(input())
if (collected >= expected):
print("NADA PREOCUPANTE")
elif (collected >= expected - 5):
print("POUCO PREOCUPANTE")
else:
print("MUITO PREOCUPANTE")
# Complexity - Time: O(n); Space: ... |
f47cf751080276c959bfa671400a8e8c2f9168de | ScoobyLuffyDoo/PythonClasses | /Students/Students.py | 898 | 4.125 | 4 | # Formating Student Details
class Student:
SchoolName ="Blha High"
# A default Constructor
def __init__(self,Name,Surname,Age,StudentID):
self.Name = Name
self.Surname = Surname
self.Age = Age
self.StudentID = StudentID
# Summery of the student
def StudentDetails(sel... |
cebaec84aab78cf4bbd10d3e95ecfef7c309c9f0 | mageshz/Lyrics-downloader | /lyric.py | 1,710 | 3.796875 | 4 | #-------------------------------------------------------------------------------------------------
#Name :Lyrics Downloader
#Author : Vijetha PV
#Description :Just double click on the lyric.py , enter the name and artist of the song
#and automatically saves the lyrics in the file you specify
#Requirement Python 2.7.x d... |
76f057fc4cf9ff4bb72afb2fdcd17bd04f7df83c | AishwaryaVS/SL-Lab | /program2.py | 194 | 4.125 | 4 | mydictionary = {
"name": "Archie",
"identity": "Student",
"age": 17
}
print(mydictionary)
key = mydictionary["name"]
value = mydictionary.get("name")
print("Key is",key)
print("Value is",value)
|
97696a7de3d41c3ceb376e18e19fd5fd87de5064 | fairylin/python_web | /2-1/web8/mongo_demo.py | 2,762 | 3.5 | 4 | """
注意需要首先安装pymongo 这个库
pip install pymongo
安装后可以通过 pymongo 来链接使用mongodb
"""
import pymongo
# 链接 mongo 数据库, 主机是本机, 端口是默认端口
client = pymongo.MongoClient("mongodb://localhost:27017")
print('连接数据库成功', client)
# 设置要使用的数据库(名称)
mongodb_name = 'web8'
# 直接这样就可以创建(如果不存在)并使用这个数据库了
db = client[mongodb_name]
# 插入数据
# ===
# m... |
485e33e998bf3d949a3089137a50e8c8a6551054 | TechnoSavage/Testing_scripts | /lightbudget.py | 16,560 | 3.625 | 4 | #!/usr/bin/python
""" Script to make light budget calculations for permitted cable lengths for a
given TAP or appropriate TAP for current link. """
from decimal import Decimal, getcontext
def menu():
""" High level menu for available options. """
option = raw_input("""\nWhat would you like to do:
1 -... |
a0bb10e26cae0d65496252ce05bc94c6b536dfd6 | bartoszstepak/Python_2019-2020 | /Zestaw_13.py | 5,048 | 3.578125 | 4 | class Sudoku:
def __init__(self, size=4):
self.size = size
self.count = 0
if size == 4:
self.file = open("solutions.txt", "w")
if size != 4 and size != 6:
raise ValueError("Not supported size - 4 and 6 are allowed")
def check_grid(self, grid):
... |
e5c145e53bc8750d888282cbc30b02db2021e6b5 | smeehan12/LifeOfAParticle_2019 | /HandsOn/DoubleTriangular/ClairesMysteryGenerator.py | 450 | 3.703125 | 4 | import random
print("Starting Claire's Tracker Generator")
def generateAngleObservations(n):
p = 42
x = []
for i in range(n):
x.append(2 * p * random.uniform(0,1) - p)
return x
def getRandomAngleCoulombScatter():
p = 10
return 2 * p * random.uniform(0,1) - p
def generateAngle(... |
547c87b6c4bb15f4dd0de2152171ce5bb7e83e7a | isabella232/pyalgs | /pyalgs/algorithms/strings/substring_search.py | 3,110 | 3.515625 | 4 | from abc import ABCMeta, abstractmethod
class SubstringSearch(object):
__metaclass__ = ABCMeta
@abstractmethod
def search_in(self, text):
pass
class BruteForceSubstringSearch(SubstringSearch):
def __init__(self, pattern):
self.pattern = pattern
def search_in(self, text):
... |
cf1e153086ddffb382fd1afc905cfab6dc6c7de2 | isabella232/pyalgs | /pyalgs/algorithms/commons/selecting.py | 604 | 3.5 | 4 | from pyalgs.algorithms.commons.util import is_sorted, less
class BinarySelection(object):
@staticmethod
def index_of(a, x, lo=None, hi=None):
if not is_sorted(a):
raise ValueError('array must be sorted before running selection')
if lo is None:
lo = 0
if hi is N... |
5795dfd4f78d39c168f3510c28616532fa3302d4 | i-rahman/AI-Classification-Clustering-Election-Data | /clustering_kmeans_agnes/kmeans_agnes.py | 4,095 | 3.625 | 4 | import numpy as np
import math
import random
class K_MEANS:
def __init__(self, k, t):
# k_means state here
# Feel free to add methods
# t is max number of iterations
# k is the number of clusters
self.k = k
self.t = t
def distance(self, centroids, datapoint):
... |
ad143867fbdaaccf39002b34064e15d5fa2ecfb0 | medioman22/Bidirectional_Interface | /Bidirectional_interface/Haptics/Interface/src/utils.py | 3,495 | 3.609375 | 4 | # -*- coding: utf-8 -*-
# Author: Cyrill Lippuner
# Date: October 2018
import datetime # Time package
import math # Math package
class Utils():
"""The utils of the application."""
def timeDifSeconds(self, star... |
b21a5002281d97055baa2a50a4df707484299e34 | aupadhyaya-bellevue/csd-310 | /module_9/pysports_update_and_delete.py | 2,921 | 3.5 | 4 | # Name: Abhishek Upadhyaya
# Module 9 - Assignment 9.3
# Import MySQL modules
import mysql.connector
from mysql.connector import errorcode
# Define database configurations
config = {
"user": "pysports_user",
"password": "MySQL8IsGreat!",
"host": "127.0.0.1",
"database": "pysports",
"raise_on_warni... |
f3a811d6602b6d6154731e1da8e7c0c664f3a2d4 | doston12/hacker-rank-solutions | /the captains room.py | 296 | 3.890625 | 4 | # the captain's room
n = int(input())
rooms = input().split()
unique_rooms1 = set()
unique_rooms2 = set()
for x in rooms:
if x not in unique_rooms1:
unique_rooms1.add(x)
else:
unique_rooms2.add(x)
print(list(unique_rooms1.difference(unique_rooms2))[0])
|
ac402fb97711fe6a80bec52486340b21b7ef6a2e | doston12/hacker-rank-solutions | /itertools combinations.py | 353 | 3.671875 | 4 | # example for using itertools combinations
from itertools import combinations
string, k = input().split()
k = int(k)
characters = list(string)
characters.sort()
for i in range(1, k+1):
res = list(combinations(characters, i))
for i in res:
temp = ''
for x in i:
temp = t... |
3a47800f3826fcfa2f07162ac8df83da5a3e7ba7 | doston12/hacker-rank-solutions | /collections_deque.py | 594 | 3.8125 | 4 | # collections deque - memory and access efficient datastructure, retrieve data from both ends
# at O(1)
from collections import deque
n = int(input())
deq = deque()
for i in range(n):
x = input()
if x.find(' ') > 0:
method_name, number = x.split()
if method_name == 'append':
... |
6b73e2d171a866f74374f7ce1206d972b2e6e8fc | iulidev/code | /split_join.py | 1,104 | 4.3125 | 4 | # Splitting and joining strings (Divizare si imbinare stringuri)
text = 'Learning Python is fun'
# Generam lista de caractere din string
list_of_chars = [x for x in text]
print('Lista de caractere este:', list_of_chars)
# Splitting (divizare) a unui string in substringuri pe baza unui separator
# implicit separatorul... |
93044f26f245e893375af8ba126f51657c14fb23 | iulidev/code | /passing_primitive_variables.py | 1,305 | 4.3125 | 4 | # Passing primitive variables to functions as parameters
# Primitive variables = variabile de tipurile de baza (int, float, str, boolean)
# Basic data types variables (variabilele cu date de baza, primitive : int, str, float, boolean) - sunt immutable
# O functie poate modifica o variabila avand tip immutable doar daca... |
2fcfa4538e7db509cc52795ac01ccee5c2649e73 | 7201krap/COURSERA_Introduction-to-Tensorflow | /2week_ex6.py | 1,038 | 3.796875 | 4 | # Normalization 의 중요성
'''
Before you trained, you normalized the data, going from values that were 0-255 to values that were 0-1. What would be the impact of removing that? Here's the complete code to give it a try. Why do you think you get different results?
'''
import tensorflow as tf
print(tf.__version__)
mnist =... |
81fdda7a92fc78aeb9249b95342b320f8c2d2729 | imijan/PythonApplication4 | /PythonApplication4/PythonApplication4.py | 692 | 3.828125 | 4 | d = int(input('Введите длину стен: '))
e = int(input('Введите ширину стен: '))
p1 = (d + e) * 2
print(p1)
print('Введите высоту стены')
p2 = int(p1 * int(input('')))
print(p2)
print('Площадь деврных и оконных проемов')
o1 = (int(input()) * int(input()))
d1 = (int(input()) * int(input()))
pp = o1 + d1
print(pp)
print(... |
7284ea76760f3f1c58504782ae66329a76452360 | devluke88/blackjack-final | /main.py | 3,116 | 3.984375 | 4 | import random
from replit import clear
from art import logo
def get_a_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
generated_card = random.choice(cards)
return generated_card
def sum_of_cards(cards_list):
if sum(cards_list) == 21 and len(cards_list) == 2:
result = 0
ret... |
386204bb6f4eabb61d6e30b6ef34f12c449a5694 | Mohammad-Mouadi/tasks | /task1-TidyNumber/TidyNumberGenerator.py | 2,231 | 4.1875 | 4 | def is_valid_integer(str_num):
try:
int(str_num)
return True
except ValueError:
return False
def generate_greatest_tidy_number(str_number):
int_number = 0
if is_valid_integer(str_number):
int_number = int(str_number)
else:
raise Exception("Invalid input")
... |
81a6e9ef4aa60115b0db55437f3797a690de3bbd | Lera87/homework1 | /einstein_task.py | 1,014 | 4.1875 | 4 | print("This is a puzzle favored by Einstein. You will be asked to enter a three digit number, where the hundred's digit"
"differs from the one's digit by at least two. The procedure will always yield 1089")
input_number = input('Give me a number --> ')
if len(input_number) == 3 and abs(int(input_number[0]) - int(i... |
c1620ee98ce34b01a4b5a10a2c97757bfeb99401 | Lera87/homework1 | /22 task.py | 1,007 | 4.4375 | 4 | import random
#Случайным образом программа выбирает целое число от 1 до 10 и предлагает пользователю его угадать.
# Пользователь вводит число, а программа проверяет его и, если пользователь не угадал, то говорит больше или меньше.
# После чего опять просит угадать. И так пока пользователь не угадает выбранное число.
... |
1c2dd66966a9ad3782b168246f697aa02969e170 | tiu1234/cs505algo | /CS501WK12.py | 4,864 | 3.59375 | 4 | import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \tDistance from Source")
for node in range(self.V):
... |
0c1e6b545f3924930b8e0a5a67b33e12fe4711d3 | Scott-Thompson-MasterLink/cse210-student-hide-and-seek | /hide_and_seek/game/hider.py | 1,267 | 4.21875 | 4 | import random
class Hider:
"""an instance of hider, will watch seeker and keep track of distance
Attributes:
location(int): a number between 1-1000
distance(list of ints): list of the distances that occured previously
"""
def __init__(self):
'''constructor
... |
0c7d4889af373167eaa85967c2dcab4d06bd26d1 | ilseum/AtBSwP | /chapter5/fantasy_game.py | 783 | 3.875 | 4 | def display_inventory(inventory):
total_items = 0
print("Inventory:")
for key, value in inventory.items():
print(f"{value} {key}")
total_items += value
print(f"\nTotal number of items: {total_items}")
def add_to_inventory(inventory, add_items):
for item in add_items:
try:
... |
8efbdcd323eca7b15aee1de78da302abd8a6fe01 | qq763253009/Fluent-Python | /第三章字典和集合/3-8.py | 193 | 3.734375 | 4 | '''
集合论
'''
# 利用集合去重:
l = [1,1,2,3,1,1,1,2,3]
print(set(l))
A = [1,2,3,4,5]
B = [2,3,4,5,6]
# 找到AB交集的个数
print(len(set(A)&set(B)))
'''
OUT:
{1, 2, 3}
4
''' |
0f4092648a69b0e901b238a1e9673be3b694319b | qq763253009/Fluent-Python | /第二章序列构成的数组/2-1.py | 895 | 3.828125 | 4 | '''
列表的推导和可读性:
把一个字符串变成unicode的码位列表
'''
symbols = '!@#$%^&*()'
# 方式一:
codes = []
for symbol in symbols:
codes.append(ord(symbol))
print (codes)
# 方式二:
print([ord(symbol) for symbol in symbols])
'''
关于可读性的探讨:
任何学过Python的人,都能够迅速的明白方式一里的for循环的用法,
这里我们使用for循环来构造一个列表。
但是当你对「列表推导」有所了解之后,
你也可以一眼看明白方法二,
相对于方法一来说,方法... |
dd09f13d5df2d6a1c9ed5a7e3e163a001fc78467 | dylan-codesYT/AdventOfCode2020 | /day2.py | 879 | 3.59375 | 4 | import csv
# part1
with open('input2.csv') as data:
reader = csv.reader(data, delimiter=' ')
validCount = 0
for row in reader:
quota, letter, pw = row[0], row[1][0], row[2]
# get the range
# 'a-b'
i = quota.index('-')
lower = int(quota[:i])
upper = int(quota[i+1:])
count = 0
for character in pw:
... |
0adfbba1fc1c738f8d7309996c7e46a952b21aa4 | mossblaser/phd_thesis | /figures/space_filling_curves_comparison.py | 3,798 | 3.90625 | 4 | #!/usr/bin/env python
"""
Generate distortions for various space filling curves mapping a 1D space to a
2D space.
"""
from math import ceil, log, sqrt
def _hilbert(level, angle=1, s=None):
"""Generator of points along a 2D Hilbert curve.
This implements the L-system as described on
`http://en.wikipedia.or... |
3b79abb1a3c446572ca12f363bd46c9edd069d2c | zhendler/itstep_homework | /data_packing.py | 1,224 | 3.671875 | 4 | import json
class Book():
def __init__(self, name, year, publisher, genre, author, price, review):
self.name = name
self.year = year
self.publisher = publisher
self.genre = genre
self.author = author
self.price = price
self.review = review
de... |
3bcdf6ac893ce98fc018b3e4e4238f1605f7cf1a | jhancock1975/basic-python-stats | /monty-hall.py | 1,579 | 3.78125 | 4 | from random import randint
N = 1000
def simulate(N):
K = 0;
for i in range(N):
# hide the prize
doors = []
prizeDoor = randint(0,2)
for i in range(2):
if i == prizeDoor:
doors.append('p')
else:
doors.append(' ')
# choose the door
chosenDoor = randint(0... |
5c20e897dc78438a48bdecca1bcc164088078729 | tomkooij/AdventOfCode | /aoc2015/day2.1.py | 483 | 3.640625 | 4 | # adventofcode.com
# day 2.1
INPUTFILE = 'input/input2'
total = 0
with open(INPUTFILE) as f:
lines = f.readlines()
for line in lines:
x, y, z = line.split('x')
l = int(x)
w = int(y)
h = int(z)
# the example is wrong! add the AREA of the smallest size
area = ... |
b87cecf9f47145c9af7aa37076f0f633e2e209e7 | tomkooij/AdventOfCode | /aoc2016/day1b.py | 872 | 3.53125 | 4 | from collections import deque
move_funcs = deque([lambda x, y, n: (x, y+n), # north
lambda x, y, n: (x+n, y), # east
lambda x, y, n: (x, y-n), # south
lambda x, y, n: (x-n, y)]) # west
direction = {'L': 1, 'R': -1}
def find_second_visit(commands):
... |
a15ce26e23abcb4a600497da71c379a9e8e0fad5 | tomkooij/AdventOfCode | /aoc2016/day3.py | 266 | 3.78125 | 4 | def check_triangle(x, y, z):
return x + y > z and x + z > y and y + z > x
with open('input/input3.txt') as f:
n = 0
for line in f.readlines():
x, y, z = map(int, line.split())
if check_triangle(x, y, z):
n += 1
print(n)
|
ccc9a80b1b6e3117ae52f9497e0ad00ea2e63cf1 | kzalyalutdinova/labsinformatics2020 | /lab4_zalyalutdiniva.py | 1,910 | 3.5 | 4 | # Игра "Civilization 6"
class unit:
name = "name"
movement = 0
health = 0
status = "Alive"
def move (self, n):
if self.movement >= n:
self.movement -= n
def check_health(self):
if self.health <= 0:
self.status = "Dead"
class military_unit (unit):
... |
3ded6483fe69fc2a409c688bd7474dc29e7f9130 | MAPSuio/spring-challenge17 | /MAPS_days/vegarsti.py | 502 | 3.96875 | 4 | from datetime import date, timedelta as td
start_date = date(2000, 1, 1) # format is year, month, day
end_date = date(2017, 3, 9)
number_of_days = end_date - start_date
MAPS_days = 0
def sum_digits(i):
return sum(int(d) for d in str(i))
for i in range(number_of_days.days + 1):
today = start_date + td(days=... |
8655d75d616399c5c1c97cb3a2b26cd513cee802 | ganesh2583/Python-Data_Science | /twitterSentimentScript.py | 1,395 | 3.625 | 4 | import sys
import csv
import tweepy
from textblob import TextBlob
# Read the argument. This will the twitter search word
tweetToBeSearched=sys.argv[1]
# Twitter app Consumer Key and Consumer Secret
consumer_key = 'RPbZlqCZUrYwP6t1FIrI5hvfb'
consumer_secret = 'wF37kEMfLJmqKlmpMwQ9f5KbP51Us9ycGApJYpjg9ceKaZBQ... |
972a74e6a42f5aca3624b5d5af3c7d5b87312bbf | Nelocage/algorithm | /Python代码/函数装饰器.py | 2,690 | 3.921875 | 4 | #问题
#某些时候想为多个函数,统一添加某种功能,又不想在每个函数内添加完全相同的代码
#装饰器类似于包裹函数(wrap),在原函数上添加新的功能。并且替代原函数,
#*args,可以传入不固定参数
def sum(a,b):return a+b
#若是不定长数字相加,则需使用*args参数
def sum1(*args):
sum=0
for x in args:
sum+=x
return sum
import time
def add(a,b):
print(a+b)
#最基本的装饰器
#给现有函数增加一个记录程序运行时间的功能
def timer(... |
f2dc241a9d7da4bcfa7d09f2605eefb7310d066b | Nelocage/algorithm | /Python代码/多线程进程协程.py | 8,399 | 4.03125 | 4 | #问题描述
#多线程
#要同时下载多个文件,并保存
#解决方法
#使用标准库threading.Thread创建线程
from threading import Thread
import timeit # 计算每部所有的时间,跨平台精度使用timeit.default_timer()
from collections import deque
import queue #线程安全的队列
import time
a=deque() #线程内部共有同一个地址空间
#第一种使用线程的方法
def v_print(number):
print(number)
... |
9fdd8499a054b18f29185b1ce1474f6dd04d4986 | fumdiali/python_projects | /matchmakr.py | 1,353 | 4.28125 | 4 | print("Welcome to MatchMakr!")
print("---------------------")
#Gender selection
print("Please select your gender:")
print("Male:1")
print("Female:2")
#Get user choice
sex = input("> ")
#Determine gender
if sex == 1:
print("You are Male..")
#for Python3..throws error
#choice = input("Select your preferenc... |
f1120ca5822c8d9779cffab8b5d15cb8882dd9a5 | fumdiali/python_projects | /my_projects/my_house.py | 1,496 | 4.03125 | 4 | # simple maze,console-game
import time
print("*******************")
print(" ~ My House ~ ")
print("*******************")
print(" __________||__ ")
print(" / \ ")
print(" / ___ \ ")
print(" | ___ |_| | ")
print(" |______| |_______| ")
print("")
def comeIn():
entrance... |
48da6c1b4d4ec04f17ca63996b0226ce6b37adf1 | fumdiali/python_projects | /flip_mod.py | 468 | 4.15625 | 4 | # simple module that reverses the order of given input
## Written by Patrick C. Diali Jan 2017
import time
def flip():
print("\t*"*5)
print("\t\tWelcome To Flipper!")
print("\t*"*5)
print("Type any group of xters(words,letters,numbers)and press ENTER: ")
name = input()
try:
flipped =... |
e7ee4e7a01636a8ce13f904d2e076904b78941aa | stbka/pythonchallenge | /4_PhpCalculation.py | 462 | 3.53125 | 4 | #!/usr/bin/env python
import re
import time
from urllib import urlopen
URL="http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="
#NOTHING_NUM="12345"
NOTHING_NUM="62743"
def solution_1(url, num):
while True:
result = urlopen(url + num).read()
#re_obj = re.match("(?<=and the next nothing is )\d+", r... |
980e1307e2f1cb50c2e6df76aa1e64d9bafa8f0f | yuvakurakula/Binary-Search-4 | /Medianof2SortedArray.py | 2,197 | 3.546875 | 4 | class Solution:
# M is length of nums1, N is length of nums2
# Time Complexity - O(max(M, N))
# Space Complexity - O(M+N)
def findMedianSortedArrays1(self, nums1, nums2):
pointer1 = 0
pointer2 = 0
n1 = len(nums1)
n2 = len(nums2)
array = []
while pointer1 <... |
e451395e9129c58a71c0a2e8a60d0f8714523d3b | AspetDavoodi/Homework-REP | /Sorting algorithms/Quick sort.py | 873 | 3.875 | 4 | def quickSort(alist):
quickSortguide(alist,0,len(alist)-1)
def quickSortguide(arr,first,last):
if first<last:
splitpoint = partition(arr,first,last)
quickSortguide(arr,first,splitpoint-1)
quickSortguide(arr,splitpoint+1,last)
def partition(arr,first,last):
pivot = arr[first]
left ... |
4a4c9f410886509c60e2138fc57678cd483411d2 | Aleti-Prabhas/geekforgeeks | /sum_of_digits_palindrome.py | 571 | 3.765625 | 4 | #User function Template for python3
class Solution:
def isDigitSumPalindrome(self,N):
sum=0
while(N>0):
p=N%10
sum=sum+p
N=N//10
dupli=str(sum)
dupli2=dupli[::-1]
if(dupli==dupli2):
return 1
else:
return 0
... |
4c7dae8469fa36f1e4c6ce27cb717a8e8a73acbd | Aleti-Prabhas/geekforgeeks | /kth_digit.py | 453 | 3.609375 | 4 | #User function Template for python3
class Solution:
def kthDigit(self, A, B, K):
s=A**B
dupli=str(s)
p=len(dupli)
return dupli[p-K]
# code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int (input ())
for _ in ran... |
933823b9b31f33df44ad2796a0a4040e8b6878cf | BIGduzy/TCTI-V2ALDS1 | /Week2/Exercise5.py | 1,256 | 3.609375 | 4 | import random
x = 0
y = 0
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def quick_sort(a, low = 0, high = -1):
global x
if high == -1:
high = len(a) - 1
if low < high:
swap(a, low, random.randint(low, high))
m = low
for j in range(low + 1, high+1):
... |
406d5a73acc0792ebccde2855860c8de2a77ab26 | BIGduzy/TCTI-V2ALDS1 | /Week4/Exercise3.py | 1,819 | 3.515625 | 4 | pascal = {
0: {0: 1},
1: {0: 1},
2: {0: 1},
3: {0: 1},
4: {0: 1},
5: {0: 1},
6: {0: 1},
}
def B(n, k):
global pascal
if n in pascal and k in pascal[n]:
return pascal[n][k]
if k > n + 1:
raise ValueError("k can not be > n + 1")
if k == ... |
f03ae4581ca5337700f57328f01a309c711e9865 | BIGduzy/TCTI-V2ALDS1 | /Week1/Exercise2.py | 572 | 4 | 4 | def get_numbers(s):
"""
Description
gets all numbers in a string
:param s: string, the string with numbers
:return: List, the list with all numbers
"""
numbers = []
cur_number = ''
for i in s:
if i.isdigit():
cur_number += i
elif cur_numb... |
32870898956af27e0f97e94b1341a4563822a8ec | falbro/hacktober18 | /km ke mil.py | 237 | 3.78125 | 4 | # Input kilometer
kilometer = float(input("Masukkan nilai dalam kilometer: "))
# Faktor konversi
fak_konv = 0.621371
# Konversi ke mil
mil = kilometer * fak_konv
print('%0.2f kilometer sama dengan %0.2f mil' %(kilometer,mil))
|
bd66132d8ddca717aba11cd238b2ceee93491847 | Saqib438/Chapter-02-19B-098-SE | /Saqib Sarfaraz, 19B-098-SE, Section B.py | 5,514 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#the sum of first five integers
1+2+3+4+5
# In[2]:
#the average of sara(age23), mark(age19) and fatima age(32)
a=(23+19+32)/3
print("average age is :",a )
# In[3]:
#the number of times 73 goes into 403
403//73
# In[4]:
#2 to the power 10th
2**10
# In[5]:
... |
4ba83797f53d5f8214017f27322675b32f1d9107 | donzepedro/Pylessons | /1lesson.py | 825 | 3.765625 | 4 | phones = ["Phone xs", "Samsung S8 Plus","lg is shit","sony erricson",1,2]
#print(phones)
#print(len(phones))
phones.append('some new brand')
#print(phones)
phones.append("Phone xs")
#print(phones.count('Phone xs'))
#{
# some code here
# and litile bit more code
#}
NewPhones={"Iphone Xr", "xiaomi mi10",... |
a5b91495b0b3499a7ce593c18690c7777fd471c8 | hudecekfilip/WorkLogwithDB | /entry_tasks.py | 2,991 | 3.578125 | 4 | import datetime
import os
from database import Entry
class EntryTasks:
def add_new_entry(self):
self.task_name = self.task_username()
self.task_username_2(self.task_name)
self.task_date = self.date_of_the_task()
self.date_of_the_task_2(self.task_date)
self.task_title = self... |
dde78d950ec060ce27e29c922532ca0b74503328 | sahilsapolia/MyPythonCourse | /ch06-functions/vargs.py | 640 | 3.765625 | 4 | def print_stars(count):
print("*"*count)
#print_stars()
print_stars(20)
def slice_list(list_to_slice,*upper_bounds):
"""Returns slice of list if upper bound is valid"""
list_to_return = []
for upper_bound in upper_bounds:
if (len(list_to_slice) > upper_bound):
print('slicing...')
... |
550912d1e5ff5e642efeebd66de187098ea7515c | sahilsapolia/MyPythonCourse | /ch03/which_season.py | 1,139 | 4.15625 | 4 | print('Welcome to which session program')
month_string = input("Input the month number (e.g. January==1): ")
day_string = input("Input the day of the month (e.g. 19): ")
month = int(month_string)
day = int(day_string)
if month == 1 or month == 2 or month == 3:
season = 'winter'
elif month == 4 or month == 5 or m... |
6cfe36341c1787332c7025889bdd41229feb7a60 | sahilsapolia/MyPythonCourse | /ch04/range.py | 144 | 3.65625 | 4 | some_range = list(range(0,100,3))
message = 'There are {} numbers between 0 and 100 when counting by 3'
print(message.format(len(some_range))) |
1956ed1947194cdabdbe9b7623a93989d5740407 | anoyo-lin/algorithm | /geeksforgeeks/fibonacci_search.py | 1,225 | 3.90625 | 4 | #!/usr/bin/python3 #pseudo code
class fib_search(sorted_list, target):
def __init__(self):
self.n = sorted_list.length()
self.target = target
self.array = sorted_list
def __fib__(self):
fib_m_2 = 0
fib_m_1 = 1
fib_m = fib_m_2 + fib_m_1
while fib_m < self.... |
b3f1f19ed41b90d698944f42196745f2f6e5fdd7 | mohammaddanish85/Python-Coding | /String.py | 945 | 4.3125 | 4 | # This Program demonstrate the use of String data type.
str= "Welcome to the World of Python" # In this, statement can be stored in double quotes.
str1= 'Welcome to World of Python (2nd type)' # In this, statement can be stored in single quotes.
str... |
b290c6203ef47956bd156c009f4c8c14bc745514 | saumonarticho/Project-Euler | /Problem 4.py | 263 | 4.09375 | 4 | #Finds the largest palindrome made from the product of two 3-digit numbers
def Palindrome():
for x in range(100,1000):
for y in range(x,1000):
string = str(x*y)
if string[::-1] == string:
print(string)
|
2f24a2e30a1c716ce177ff238f7a33045c3cd023 | rmgard/python_deep_dive | /fifthSection/starArgs.py | 879 | 3.90625 | 4 | a, b, *c = 10, 20, 'a', 'b', 'c'
def func1(a, b, *args):
print(a)
print(b)
print(args)
# My average function...
def my_avg(*args):
count = len(args)
total = sum(args)
try:
mu = total/count
except ZeroDivisionError:
mu = 'You are finding the average of nothing!'
return m... |
bf8f96a166da7b0d0087d4004c2892c1c7f792ca | rmgard/python_deep_dive | /thirdSection/objMutability.py | 654 | 3.65625 | 4 | ''' numbers in python are immutable
Strings are immutable
Tuples are immutable
Frozen Sets
User-defined classes
Mutable:
lists
sets
dictionaries
user-defined classes
'''
# Tuples are immutable:
# elements cannot be deleted, inserted, or replaced
# in the below case, both the co... |
2f4291e7801858514618f989c84c9bf226e1c934 | rmgard/python_deep_dive | /fourthSection/booleanPrecedenceShortCircuit.py | 1,339 | 4.21875 | 4 | '''
not(A or B) == not(A) and (not B)
not(A and B) == not(A) or (not B)
not(x < y) == x >= y
not(x <= y) == x > y
Operator Precedence:
()
< > <= >= == != in is
not
and
or
'''
''' Short circuiting:
If we have X or Y, and X is True, then Y does not need to be calculated
... |
b0a38dc9892cc2f212e1c9534c96b6535be04b5e | rmgard/python_deep_dive | /seventhSection/memoizationDecoratorApp.py | 1,249 | 3.78125 | 4 | ''' Decorators can modify the behavior of another fn
'''
def fib(n):
print('Calculating fib({0})'.format(n))
return 1 if n < 3 else fib(n-1) + fib(n-2)
class Fib:
def __init__(self):
self.cache = {1: 1, 2: 1}
def fib(self, n):
if n not in self.cache:
print('Calculating... |
5162aeb497c0caf82537f47ebeabef71d4ca409c | rmgard/python_deep_dive | /seventhSection/closureAppPt2.py | 1,175 | 3.921875 | 4 | def counter(initial_value=0):
def inc(increment=1):
nonlocal initial_value
initial_value += increment
return initial_value
return inc
def counter(fn):
cnt = 0
def inner(*args, **kwargs):
nonlocal cnt
cnt += 1
print('{0} has been called {1} times'.format(f... |
929602aa68c4fd5c0b2d1ec07ac536aec8e08020 | jjgomera/tuenti-challenge-2 | /6_Cross-stitched_fonts.py | 2,178 | 3.953125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Challenge 6: Cross-stitched fonts
#Materials for cross-stitching are quite simple: cloth, a needle and thread. There are many kinds of fabrics for cross-stitching, all of them available in different resolutions or counts. The count (ct) is the number of pixels (or stitches)... |
8dce4e99aedde145317aad8ec98255511285f2c1 | mnickey/Thinkful | /Bicycles/customers_class.py | 811 | 4.0625 | 4 | class Customers(object):
"""docstring for Customers"""
def __init__(self, cust_name, cust_funds):
super(Customers, self).__init__()
self.cust_name = cust_name
self.cust_funds = cust_funds
self.garage = []
# Method to see if the customer can buy a bike
def can_buy(self, bike):
""" Returns true if the cust... |
a7288bb8e3e61baa375856bbcd6a5b1bcbc98d75 | kiritka-jain/My-programs | /repeated_string.py | 698 | 4.09375 | 4 | string_to_repeat = input()
substring_lenght_considered = int(input())
string_length = len(string_to_repeat)
count = 0
total = 0
if string_to_repeat == 'a':
print(substring_lenght_considered)
elif 'a' not in string_to_repeat:
print(count)
else:
for char in string_to_repeat:
if char == 'a':... |
647b9f87eddfb8d4a441118ca26f312e0597cdab | kiritka-jain/My-programs | /taum_and_b'day.py | 499 | 3.796875 | 4 | def cost_calculator(black,white,black_cost,white_cost,conversion_cost):
total_cost = black*(min(black_cost,(white_cost+conversion_cost)))+white*(min(white_cost,(black_cost+conversion_cost)))
return total_cost
total_test_cases = int(input())
for _ in range(total_test_cases):
black,white = list(map(i... |
184f9a2fc77c7e0da5db34c0c867f03855318508 | kiritka-jain/My-programs | /string_construction.py | 268 | 3.71875 | 4 | from collections import Counter
def string_construction(string):
unique_char = Counter(string)
return (len(unique_char))
total_strings = int(input())
for _ in range(total_strings):
string = input()
print(string_construction(string))
|
ec777de6f593f31aee171bef82f1585470e91ec2 | kiritka-jain/My-programs | /min_max_numpy.py | 338 | 3.59375 | 4 | import numpy
n,m = map(int,input().split()) #n*m dimension of array
aray = []
for index in range(n):
a,b = map(int,input().split())
aray.append(a)
aray.append(b)
ary = numpy.array(aray)
reshape_array = numpy.reshape(ary,(n,m))
min_along_axix = (numpy.min(reshape_array,axis=1))
print(numpy.max(min_... |
a23059122fbc473f79c8bcb717ab1d886360838f | lancaster2001/python-collection | /properties of strings 4.py | 686 | 3.90625 | 4 | carry_on = ("no")
if carry_on == ("no"):
revision_notes = input("input your revision notes")
carry_on = ("are you done?")
time_found = 0
found = ""
test_string = ""
input_word = ("variable")
for index in range (0 ,len(revision_notes) - 3):
test_string = test_string + revision_notes[ind... |
c3ae80976c13204d0382268db46ed33e7fe3208a | lancaster2001/python-collection | /textbook 4.8.py | 330 | 4 | 4 | alphbet = [26]
for index in range (0, 25):
alphbet[index] = input("enter letter")
string = "computer"
for index in range == (0, string.len - 1):
string2 = string[index]
for index2 in range ==(0, alphabet - 1):
if string2 == alphabet[index2]:
location = location + (",",index... |
7d8a81b0dd76d7d41b2d5ca129ddc75e6b9cb3c4 | lancaster2001/python-collection | /multiple if statements.py | 615 | 4.09375 | 4 | month = input("please enter a month number")
if month == "1" then
print("January")
elif month == "2" then
print("February")
elif month == "3" then
print("March")
elif month == "4" then
print("April")
elif month == "5" then
print("May")
elif month == "6" then
print("June")
elif month == "7" th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.